public async Task AddFinishedModel_WithCorrectData_ShouldSuccessfullyAdd() { // Arrange var context = ApplicationDbContextInMemoryFactory.InitializeContext(); var groupRepository = new EfDeletableEntityRepository <Product_Group>(context); var productRepository = new EfDeletableEntityRepository <Product>(context); var finishedModelsRepository = new EfDeletableEntityRepository <Finished_Model>(context); var groupService = new GroupService(groupRepository); var prodcutService = new ProductService(productRepository, groupService); var cloudinaryService = new FakeCloudinary(); var finishedModelsService = new FinishedModelService(finishedModelsRepository, prodcutService, groupService, cloudinaryService); var seeder = new DbContextTestsSeeder(); await seeder.SeedUsersAsync(context); await seeder.SeedGroupAsync(context); var user = new ApplicationUser { Id = "abc", FirstName = "Nikolay", LastName = "Doychev", Email = "*****@*****.**", EmailConfirmed = true, }; var fileName = "Img"; IFormFile file = new FormFile( new MemoryStream(Encoding.UTF8.GetBytes("This is a dummy file")), 0, 0, fileName, "dummy.png"); var finishedModel = new AddFinishedModelInputModel { Id = "abc1", Description = "Some description test 1", ImagePath = file, TypeProject = TypeProject.Classic.ToString(), Name = "Model 1", }; // Act AutoMapperConfig.RegisterMappings(typeof(AddFinishedModelInputModel).Assembly); var result = await finishedModelsService.AddFinishedModelAsync(finishedModel, user.Id.ToString()); var actual = context.Finished_Models.FirstOrDefault(x => x.Product.Name == "Model 1"); var expectedName = "Model 1"; var expectedDescription = "Some description test 1"; var expectedTypeOfProject = TypeProject.Classic.ToString(); // Assert AssertExtension.EqualsWithMessage(expectedName, actual.Product.Name, string.Format(ErrorMessage, "AddFinishedModel returns correct Name")); AssertExtension.EqualsWithMessage(expectedDescription, actual.Description, string.Format(ErrorMessage, "AddFinishedModel returns correct Power")); AssertExtension.EqualsWithMessage(expectedTypeOfProject, actual.TypeProject.ToString(), string.Format(ErrorMessage, "AddFinishedModel returns correct TypeOfProject")); }
private static async Task RunFileEnumTest(ADLSAdapter adapter) { using (adapter.CreateFileQueryCacheContext()) { List <string> files1 = await adapter.FetchAllFilesAsync("/FileEnumTest/"); List <string> files2 = await adapter.FetchAllFilesAsync("/FileEnumTest"); List <string> files3 = await adapter.FetchAllFilesAsync("FileEnumTest/"); List <string> files4 = await adapter.FetchAllFilesAsync("FileEnumTest"); // expect 100 files to be enumerated Assert.IsTrue(files1.Count == 100 && files2.Count == 100 && files3.Count == 100 && files4.Count == 100); // these calls should be fast due to cache var watch = Stopwatch.StartNew(); for (int i = 0; i < files1.Count; i++) { Assert.IsTrue(files1[i] == files2[i] && files1[i] == files3[i] && files1[i] == files4[i]); await adapter.ComputeLastModifiedTimeAsync(files1[i]); } watch.Stop(); Assert.Performance(10, watch.ElapsedMilliseconds, "Cached file modified times"); } }
public void TestMethod_Update_NullEntity_Throws() { ICollaborationService service = _unityContainer.Resolve <ICollaborationService>(); Action act = () => service.Update(null); AssertExtension.AssertInnerThrows <NullReferenceException>(act, "Nessuna eccezione di ritorno. Era attesa una NullReferenceException"); }
public async Task TestImportsRelativePath() { // the corpus path in the imports are relative to the document where it was defined. // when saving in model.json the documents are flattened to the manifest level // so it is necessary to recalculate the path to be relative to the manifest. var corpus = this.GetLocalCorpus("notImportantLocation"); var folder = corpus.Storage.FetchRootFolder("local"); var manifest = new CdmManifestDefinition(corpus.Ctx, "manifest"); var entityDeclaration = manifest.Entities.Add("EntityName", "EntityName/EntityName.cdm.json/EntityName"); folder.Documents.Add(manifest); var entityFolder = folder.ChildFolders.Add("EntityName"); var document = new CdmDocumentDefinition(corpus.Ctx, "EntityName.cdm.json"); document.Imports.Add("subfolder/EntityName.cdm.json"); document.Definitions.Add("EntityName"); entityFolder.Documents.Add(document); var subFolder = entityFolder.ChildFolders.Add("subfolder"); subFolder.Documents.Add("EntityName.cdm.json"); var data = await ManifestPersistence.ToData(manifest, null, null); Assert.AreEqual(1, data.Entities.Count); var imports = data.Entities[0]["cdm:imports"].ToObject <List <Import> >(); Assert.AreEqual(1, imports.Count); Assert.AreEqual("EntityName/subfolder/EntityName.cdm.json", imports[0].CorpusPath); }
public async Task TestAvoidRetryCodes() { AdlsTestHelper.CheckADLSEnvironment(); var adlsAdapter = AdlsTestHelper.CreateAdapterWithSharedKey(); adlsAdapter.NumberOfRetries = 3; var corpus = new CdmCorpusDefinition(); corpus.Storage.Mount("adls", adlsAdapter); var count = 0; corpus.SetEventCallback(new EventCallback { Invoke = (status, message) => { if (message.Contains("Response for request ")) { count++; } } }, CdmStatusLevel.Progress); await corpus.FetchObjectAsync <CdmDocumentDefinition>("adls:/inexistentFile.cdm.json"); Assert.AreEqual(1, count); }
private static async Task RunFetchAllFilesAsyncTest(SymsAdapter adapter) { await SymsTestHelper.CleanDatabase(adapter, databaseName); string createDatabaseRequest = TestHelper.GetInputFileContent(testSubpath, testName, "createDatabase.json"); await adapter.WriteAsync($"{databaseName}/{databaseName}.manifest.cdm.json", createDatabaseRequest); string tableName1 = "symsTestTable1"; string createTableRequest1 = TestHelper.GetInputFileContent(testSubpath, testName, "createTable1Request.json"); await adapter.WriteAsync($"{databaseName}/{tableName1}.cdm.json", createTableRequest1); string tableName2 = "symsTestTable2"; string createTableRequest2 = TestHelper.GetInputFileContent(testSubpath, testName, "createTable2Request.json"); await adapter.WriteAsync($"{databaseName}/{tableName2}.cdm.json", createTableRequest2); IList <string> databases = await adapter.FetchAllFilesAsync("/"); Assert.IsTrue(string.Equals(DatabasesManifest, databases[0])); IList <string> entities = await adapter.FetchAllFilesAsync($"{databaseName}/"); Assert.IsTrue(entities.Count == 2); Assert.IsTrue(string.Equals($"{tableName1}.cdm.json", entities[0])); Assert.IsTrue(string.Equals($"{tableName2}.cdm.json", entities[1])); await SymsTestHelper.CleanDatabase(adapter, databaseName); }
protected async Task PostAndGetShouldReturnSameEntity(UniverseEntity entity) { var uri = new Uri(this.BaseAddress); const string entitySetName = "UniverseEntity"; await this.ClearRepositoryAsync(entitySetName); var ctx = WriterClient(uri, ODataProtocolVersion.V4); ctx.AddObject(entitySetName, entity); await ctx.SaveChangesAsync(); // get collection of entities from repository ctx = ReaderClient(uri, ODataProtocolVersion.V4); DataServiceQuery <UniverseEntity> query = ctx.CreateQuery <UniverseEntity>(entitySetName); var entities = await Task.Factory.FromAsync(query.BeginExecute(null, null), (asyncResult) => { return(query.EndExecute(asyncResult)); }); var beforeUpdate = entities.ToList().First(); AssertExtension.DeepEqual(entity, beforeUpdate); // clear repository await this.ClearRepositoryAsync(entitySetName); }
public void AddJob_Post_Test() { // Act var uow = new UnitOfWorkFakeFactory().Uow.Object; var paramUser = new JobModel() { StarterDate = new DateTime(2000, 1, 15), EndDate = new DateTime(2001, 1, 16), IsNotActualJob = true, Texts = new List <TextModel>() { new TextModel() { Language = uow.LanguagesRepository.Get().ToList()[0], Value = "NewSkillCat.fr" }, new TextModel() { Language = uow.LanguagesRepository.Get().ToList()[1], Value = "NewSkillCat.en" } } }; var expected = paramUser.ToDto(uow.LanguagesRepository.Get().ToList()); expected.Id = uow.SkillCategoriesRepository.Get().Count() + 1; var nbJobs = uow.JobsRepository.Get().ToList().Count; var result = new IntroductionController(uow).AddJob(paramUser) as RedirectToRouteResult; // Assert Assert.IsNotNull(result); Assert.AreEqual(result.RouteValues["Action"], nameof(IntroductionController.ShowJobs)); Assert.AreEqual(nbJobs + 1, uow.JobsRepository.Get().Count()); AssertExtension.PropertyValuesAreEquals(expected, uow.JobsRepository.Get().Last()); }
public void DeleteHobbyTest() { // Arrange var uow = new UnitOfWorkFakeFactory().Uow.Object; var controller = new IntroductionController(uow); var expectedList = new List <Hobby>(uow.HobbiesRepository.Get().ToList()); var idToRemove = expectedList.Last().Id; expectedList.RemoveAll(x => x.Id == idToRemove); // Act var result = controller.DeleteHobby(idToRemove) as RedirectToRouteResult; // Assert Assert.IsNotNull(result); Assert.AreEqual(result.RouteValues["action"], nameof(IntroductionController.ShowHobbies)); AssertExtension.CompareIEnumerable(expectedList, uow.HobbiesRepository.Get().ToList(), (x, y) => x.Id == y.Id && x.Content == y.Content && AssertExtension.CompareIEnumerable(x.Texts, y.Texts, (a, b) => a.Language == b.Language && a.Value == b.Value) ); }
public void DeleteGraduationTest() { // Arrange var uow = new UnitOfWorkFakeFactory().Uow.Object; var controller = new IntroductionController(uow); var expectedList = new List <Grade>(uow.GradesRepository.Get().ToList()); var idToRemove = expectedList.Last().Id; expectedList.RemoveAll(x => x.Id == idToRemove); // Act var expected = new GraduationsModel { Graduations = expectedList }; var result = controller.DeleteGraduation(idToRemove) as RedirectToRouteResult; // Assert Assert.IsNotNull(result); Assert.AreEqual(result.RouteValues["action"], nameof(IntroductionController.ShowGraduations)); AssertExtension.CompareIEnumerable(expected.Graduations, uow.GradesRepository.Get().ToList(), (x, y) => x.ObtainingDateTime == y.ObtainingDateTime && x.Id == y.Id && AssertExtension.CompareIEnumerable(x.Texts, y.Texts, (a, b) => a.Language == b.Language && a.Value == b.Value) ); }
public void DeleteJobTest() { // Arrange var uow = new UnitOfWorkFakeFactory().Uow.Object; var controller = new IntroductionController(uow); var expectedList = new List <Job>(uow.JobsRepository.Get().ToList()); var idToRemove = expectedList.Last().Id; expectedList.RemoveAll(x => x.Id == idToRemove); // Act var result = controller.DeleteJob(idToRemove) as RedirectToRouteResult; // Assert Assert.IsNotNull(result); Assert.AreEqual(result.RouteValues["action"], nameof(IntroductionController.ShowJobs)); AssertExtension.CompareIEnumerable(expectedList, uow.JobsRepository.Get().ToList(), (x, y) => x.StarterDate == y.StarterDate && x.EndDate == y.EndDate && x.Id == y.Id && AssertExtension.CompareIEnumerable(x.Works, y.Works, (a, b) => a.Id == b.Id) && AssertExtension.CompareIEnumerable(x.Texts, y.Texts, (c, d) => c.Language == d.Language && c.Value == d.Value) ); }
public void AddWork_Post_Test() { // Act var uow = new UnitOfWorkFakeFactory().Uow.Object; const int jobId = 1; var paramUser = new AddWorkModel() { JobId = jobId, Texts = new List <TextModel>() { new TextModel() { Language = uow.LanguagesRepository.Get().ToList()[0], Value = "NewJob.fr" }, new TextModel() { Language = uow.LanguagesRepository.Get().ToList()[1], Value = "NewJob.en" } } }; var expected = paramUser.ToDto(uow.JobsRepository.Get().ToList(), uow.LanguagesRepository.Get().ToList()); expected.Id = uow.WorksRepository.Get().Count() + 1; var nbWorks = uow.WorksRepository.Get().ToList().Count; var result = new IntroductionController(uow).AddWork(paramUser) as RedirectToRouteResult; // Assert Assert.IsNotNull(result); Assert.AreEqual(result.RouteValues["Action"], nameof(IntroductionController.ShowJobs)); Assert.AreEqual(nbWorks + 1, uow.WorksRepository.Get().Count()); AssertExtension.PropertyValuesAreEquals(expected, uow.WorksRepository.Get().Last()); }
public void DeleteSkillCategoryTest() { // Arrange var uow = new UnitOfWorkFakeFactory().Uow.Object; var controller = new IntroductionController(uow); var expectedList = new List <SkillCategory>(uow.SkillCategoriesRepository.Get().ToList()); var idToRemove = expectedList.Last().Id; expectedList.RemoveAll(x => x.Id == idToRemove); // Act var result = controller.DeleteSkillCategory(idToRemove) as RedirectToRouteResult; // Assert Assert.IsNotNull(result); Assert.AreEqual(result.RouteValues["action"], nameof(IntroductionController.ShowSkills)); AssertExtension.CompareIEnumerable(expectedList, uow.SkillCategoriesRepository.Get().ToList(), (x, y) => x.DisplayPriority == y.DisplayPriority && x.Id == y.Id && AssertExtension.CompareIEnumerable(x.Skills, y.Skills, (a, b) => a.Id == b.Id && a.KnowledgePercent == b.KnowledgePercent) && AssertExtension.CompareIEnumerable(x.Texts, y.Texts, (c, d) => c.Language == d.Language && c.Value == d.Value) ); }
public void AddingItems_AfterClear_ShouldSynchronizeItems() { var sourceGameWorld = new NotifyPropertyChangedTestGameWorld { RandomIntProperty = 5 }; var sourceSynchronizerRoot = new SourceSynchronizerRoot(sourceGameWorld); sourceGameWorld.Players.Clear(); var targetSynchronizerRoot = new TargetSynchronizerRoot <NotifyPropertyChangedTestGameWorld>(sourceSynchronizerRoot.WriteFullAndDispose()); sourceGameWorld.Players.Add("player1", new NotifyPropertyChangedTestPlayer { Name = "player1", Health = 100, Level = 30 }); sourceGameWorld.Players.Add("player2", new NotifyPropertyChangedTestPlayer { Name = "player2", Health = 44, Level = 1337 }); targetSynchronizerRoot.Read(sourceSynchronizerRoot.WriteChangesAndDispose().SetTick(TimeSpan.FromMilliseconds(10))); NotifyPropertyChangedTestGameWorld targetGameWorld = targetSynchronizerRoot.Reference; AssertExtension.AssertCloneEqual(sourceGameWorld, targetGameWorld); }
public void PostAndGetShouldReturnSameEntity(UniverseEntity entity) { var uri = new Uri(this.BaseAddress); const string entitySetName = "UniverseEntity"; this.ClearRepository(entitySetName); var ctx = WriterClient(uri, ODataProtocolVersion.V4); ctx.AddObject(entitySetName, entity); ctx.SaveChangesAsync().Wait(); // get collection of entities from repository ctx = ReaderClient(uri, ODataProtocolVersion.V4); DataServiceQuery <UniverseEntity> query = ctx.CreateQuery <UniverseEntity>(entitySetName); IAsyncResult asyncResult = query.BeginExecute(null, null); asyncResult.AsyncWaitHandle.WaitOne(); var entities = query.EndExecute(asyncResult); var beforeUpdate = entities.ToList().First(); AssertExtension.DeepEqual(entity, beforeUpdate); // clear repository this.ClearRepository(entitySetName); }
public void AddGraduation_Post_Test() { // Act var uow = new UnitOfWorkFakeFactory().Uow.Object; var paramUser = new GraduationModel() { ObtainingDateTime = new DateTime(2010, 9, 1), Texts = new List <TextModel>() { new TextModel() { Language = uow.LanguagesRepository.Get().ToList()[0], Value = "Graduation.fr" }, new TextModel() { Language = uow.LanguagesRepository.Get().ToList()[1], Value = "Graduation.en" } } }; var expected = paramUser.ToDto(uow.LanguagesRepository.Get().ToList()); expected.Id = uow.GradesRepository.Get().Count() + 1; var nbGrades = uow.GradesRepository.Get().ToList().Count; var result = new IntroductionController(uow).AddGraduation(paramUser) as RedirectToRouteResult; // Assert Assert.IsNotNull(result); Assert.AreEqual(result.RouteValues["Action"], nameof(IntroductionController.ShowGraduations)); Assert.AreEqual(nbGrades + 1, uow.GradesRepository.Get().Count()); AssertExtension.PropertyValuesAreEquals(expected, uow.GradesRepository.Get().Last()); }
private static void RunSymsCreateAdapterPathTest(SymsAdapter adapter) { string databaseName = "testDB"; string corpusPathDatabases1 = "/"; string corpusPathDatabases2 = DatabasesManifest; string corpusPathDatabases3 = $"/{DatabasesManifest}"; string adapterPathDatabases = $"https://{adapter.Endpoint}/databases?{ApiVersion}"; Assert.IsTrue(string.Equals(adapterPathDatabases, adapter.CreateAdapterPath(corpusPathDatabases1))); Assert.IsTrue(string.Equals(adapterPathDatabases, adapter.CreateAdapterPath(corpusPathDatabases2))); Assert.IsTrue(string.Equals(adapterPathDatabases, adapter.CreateAdapterPath(corpusPathDatabases3))); string entityName = "testEntityName"; string corpusPathEntity = $"{databaseName}/{entityName}.cdm.json"; string adapterPathEntity = $"https://{adapter.Endpoint}/databases/{databaseName}/tables/{entityName}?{ApiVersion}"; Assert.IsTrue(string.Equals(adapterPathEntity, adapter.CreateAdapterPath(corpusPathEntity))); string corpusPathEntities = $"{databaseName}/{databaseName}.manifest.cdm.json/entitydefinition"; string adapterPathEntities = $"https://{adapter.Endpoint}/databases/{databaseName}/tables?{ApiVersion}"; Assert.IsTrue(string.Equals(adapterPathEntities, adapter.CreateAdapterPath(corpusPathEntities))); string relationshipName = "testRelationshipName"; string corpusPathRelationship = $"{databaseName}/{databaseName}.manifest.cdm.json/relationships/{relationshipName}"; string adapterPathRelationship = $"https://{adapter.Endpoint}/databases/{databaseName}/relationships/{relationshipName}?{ApiVersion}"; Assert.IsTrue(string.Equals(adapterPathRelationship, adapter.CreateAdapterPath(corpusPathRelationship))); string corpusPathRelationships = $"{databaseName}/{databaseName}.manifest.cdm.json/relationships"; string adapterPathRelationships = $"https://{adapter.Endpoint}/databases/{databaseName}/relationships?{ApiVersion}"; Assert.IsTrue(string.Equals(adapterPathRelationships, adapter.CreateAdapterPath(corpusPathRelationships))); }
public async Task ADLSWriteClientIdLargeFileContentsNoEmptyFileLeft() { AdlsTestHelper.CheckADLSEnvironment(); string filename = "largefilecheck_CSharp.txt"; string writeContents = new string('A', 100000000); ADLSAdapter adapter = AdlsTestHelper.CreateAdapterWithClientId(); adapter.Ctx = new ResolveContext(null, null); adapter.Ctx.FeatureFlags.Add("ADLSAdapter_deleteEmptyFile", true); try { await adapter.WriteAsync(filename, writeContents); } catch (Exception e) { } try { await adapter.ReadAsync(filename); } catch (Exception e) { Assert.IsTrue(e.Message.Contains("The specified path does not exist")); } }
public async Task TestLoadingAndSavingDateAndTimeDataTypes() { var cdmCorpus = TestHelper.GetLocalCorpus(testsSubpath, nameof(TestLoadingAndSavingDateAndTimeDataTypes)); // Load the manifest and resolve it var manifest = await cdmCorpus.FetchObjectAsync <CdmManifestDefinition>("local:/default.manifest.cdm.json"); var resolvedManifest = await manifest.CreateResolvedManifestAsync("resolved", null); // Convert loaded manifest to model.json var modelJson = await ManifestPersistence.ToData(resolvedManifest, null, null); // Verify that the attributes' data types were correctly persisted as "date" and "time" Assert.AreEqual("date", modelJson.Entities[0]["attributes"][0]["dataType"].ToString()); Assert.AreEqual("time", modelJson.Entities[0]["attributes"][1]["dataType"].ToString()); // Now check that these attributes' data types are still "date" and "time" when loading the model.json back to manifest // We first need to create a second adapter to the input folder to fool the OM into thinking it's different // This is because there's a bug that currently prevents us from saving and then loading a model.json under the same namespace cdmCorpus.Storage.Mount("local2", new LocalAdapter(TestHelper.GetInputFolderPath(testsSubpath, nameof(TestLoadingAndSavingDateAndTimeDataTypes)))); var manifestFromModelJson = await cdmCorpus.FetchObjectAsync <CdmManifestDefinition>("local2:/model.json"); var entity = await cdmCorpus.FetchObjectAsync <CdmEntityDefinition>(manifestFromModelJson.Entities[0].EntityPath, manifestFromModelJson); // Verify that the attributes' data types were correctly loaded as "date" and "time" Assert.AreEqual(CdmDataFormat.Date, (entity.Attributes[0] as CdmTypeAttributeDefinition).DataFormat); Assert.AreEqual(CdmDataFormat.Time, (entity.Attributes[1] as CdmTypeAttributeDefinition).DataFormat); }
public void Venue_VenueServiceApi_GetSeatAttributesByVenue_IfSuccess_Works() { const string venueId = "3456"; var seatAttributes = new List <SeatAttribute> { new SeatAttribute(), new SeatAttribute() }; executorMock .Setup(x => x.ExecuteApiWithWrappedResponse <List <SeatAttribute> >( It.IsAny <string>(), It.IsAny <RequestMethod>(), null, null, null, true)) .Returns(() => new ApiResult <List <SeatAttribute> >( seatAttributes, TestHelper.GetSuccessResponse(), It.IsAny <ApiContext>(), It.IsAny <Context>(), It.IsAny <Request>())); var result = GetSeatAttributes(new SDK.Venue.Models.Venue { internalId = venueId }); executorMock.Verify(mock => mock.ExecuteApiWithWrappedResponse <List <SeatAttribute> >( It.Is <string>(x => x.Contains(venueId)), It.IsAny <RequestMethod>(), null, null, null, true), Times.Once); AssertExtension.EnumerableAreEquals(seatAttributes, result.ToList()); }
public async Task AddAnswerToComment_WithCorrectData_ShouldSuccessfullyAdd() { // Arrange var context = ApplicationDbContextInMemoryFactory.InitializeContext(); var groupRepository = new EfDeletableEntityRepository <Product_Group>(context); var productRepository = new EfDeletableEntityRepository <Product>(context); var fireplaceRepository = new EfDeletableEntityRepository <Fireplace_chamber>(context); var suggestItemsReposotory = new EfDeletableEntityRepository <SuggestProduct>(context); var commentsRepository = new EfDeletableEntityRepository <Comment>(context); var groupService = new GroupService(groupRepository); var prodcutService = new ProductService(productRepository, groupService); var cloudinaryService = new FakeCloudinary(); var sugestItemsRepositoryService = new SuggestProdcut(suggestItemsReposotory); var emailSender = new FakeEmailSender(); var fireplaceService = new FireplaceService(fireplaceRepository, groupService, prodcutService, cloudinaryService, sugestItemsRepositoryService); var commentServices = new CommentService(commentsRepository, prodcutService, fireplaceService, emailSender); var seeder = new DbContextTestsSeeder(); await seeder.SeedUsersAsync(context); await seeder.SeedGroupAsync(context); await seeder.SeedCommentsAsync(context); // Act AutoMapperConfig.RegisterMappings(typeof(CreateCommentInputModel).Assembly); var result = commentServices.CreateAnswer("Тестов отговор", "comId1"); var expected = "Тестов отговор"; var actual = context.Comments.SingleOrDefault(c => c.Id == "comId1").Answer; // Assert AssertExtension.EqualsWithMessage(actual, expected, string.Format(ErrorMessage, "CreateAnswer")); }
public void Venue_VenueServiceApi_UpsertStandardAttributeByTitle_IfSuccess_ReturnsUpdated() { var attribute = new StandardAttribute { description = "desc", title = "title", intention = "" }; executorMock .Setup(x => x.ExecuteApiWithWrappedResponse <StandardAttribute>( It.IsAny <string>(), It.IsAny <RequestMethod>(), It.IsAny <object>(), null, null, true)) .Returns(() => new ApiResult <StandardAttribute>( attribute, TestHelper.GetSuccessResponse(), It.IsAny <ApiContext>(), It.IsAny <Context>(), It.IsAny <Request>())); var result = UpsertStandardAttributeByTitle(attribute); executorMock.Verify(mock => mock.ExecuteApiWithWrappedResponse <StandardAttribute>( It.IsAny <string>(), It.IsAny <RequestMethod>(), It.IsAny <object>(), null, null, true), Times.Once); AssertExtension.SimplePropertyValuesAreEquals(attribute, result); }
public async Task ShouldSupportDerivedComplexTypeAsync() { var settings = new CreatorSettings() { NullValueProbability = 0.0 }; var uri = new Uri(this.BaseAddress); var entitySetName = "ComplexTypeTests_Entity"; // clear respository await this.ClearRepositoryAsync("ComplexTypeTests_Entity"); var rand = new Random(RandomSeedGenerator.GetRandomSeed()); // post new entity to repository var baseline = InstanceCreator.CreateInstanceOf <ComplexTypeTests_Entity>(rand, settings); await PostNewEntityAsync(uri, entitySetName, baseline); int id = baseline.ID; var actual = (await GetEntitiesAsync(uri, entitySetName)).Where(t => t.ID == id).First(); AssertExtension.DeepEqual(baseline, actual); await UpdateEntityAsync(uri, entitySetName, actual, data => { data.ComplexType = InstanceCreator.CreateInstanceOf <ComplexTypeTests_ComplexType>(rand, settings); }); var afterUpdate = (await GetEntitiesAsync(uri, entitySetName)).Where(t => t.ID == id).First(); AssertExtension.DeepEqual(actual, afterUpdate); }
public void Venue_VenueServiceApi_GetVenues_IfSuccess_ReturnsVenues() { var venues = new List <SDK.Venue.Models.Venue> { new SDK.Venue.Models.Venue(), new SDK.Venue.Models.Venue() }; executorMock .Setup(x => x .ExecuteApiWithWrappedResponse <List <SDK.Venue.Models.Venue>, VenuesResponse, VenuesResponseContent>( It.IsAny <string>(), It.IsAny <RequestMethod>(), null, null, null, true)) .Returns(() => new ApiResult <List <SDK.Venue.Models.Venue> >( venues, TestHelper.GetSuccessResponse(), It.IsAny <ApiContext>(), It.IsAny <Context>(), It.IsAny <Request>())); var result = GetVenues(); executorMock.Verify(mock => mock.ExecuteApiWithWrappedResponse <List <SDK.Venue.Models.Venue>, VenuesResponse, VenuesResponseContent>( It.IsAny <string>(), It.IsAny <RequestMethod>(), null, null, null, true), Times.Once); AssertExtension.EnumerableAreEquals(venues, result.ToList()); }
public void TestLoadingAndSavingEndpointInConfig() { // Mount from config var config = TestHelper.GetInputFileContent(testSubpath, nameof(TestLoadingAndSavingEndpointInConfig), "config.json"); var corpus = new CdmCorpusDefinition(); corpus.Storage.MountFromConfig(config); Assert.Null(((ADLSAdapter)corpus.Storage.FetchAdapter("adlsadapter1")).Endpoint); Assert.AreEqual(AzureCloudEndpoint.AzurePublic, ((ADLSAdapter)corpus.Storage.FetchAdapter("adlsadapter2")).Endpoint); Assert.AreEqual(AzureCloudEndpoint.AzureChina, ((ADLSAdapter)corpus.Storage.FetchAdapter("adlsadapter3")).Endpoint); Assert.AreEqual(AzureCloudEndpoint.AzureGermany, ((ADLSAdapter)corpus.Storage.FetchAdapter("adlsadapter4")).Endpoint); Assert.AreEqual(AzureCloudEndpoint.AzureUsGovernment, ((ADLSAdapter)corpus.Storage.FetchAdapter("adlsadapter5")).Endpoint); try { var configSnakeCase = TestHelper.GetInputFileContent(testSubpath, nameof(TestLoadingAndSavingEndpointInConfig), "config-SnakeCase.json"); var corpusSnakeCase = new CdmCorpusDefinition(); corpusSnakeCase.Storage.MountFromConfig(configSnakeCase); Assert.Fail("Expected RuntimeException for config.json using endpoint value in snake case."); } catch (Exception ex) { String message = "Endpoint value should be a string of an enumeration value from the class AzureCloudEndpoint in Pascal case."; Assert.AreEqual(message, ex.Message); } }
public virtual void CreateAndDeleteLinkToDerivedNavigationPropertyOnBaseEntitySet() { // clear respository this.ClearRepository("InheritanceTests_Vehicles"); Random r = new Random(RandomSeedGenerator.GetRandomSeed()); // post new entity to repository var car = InstanceCreator.CreateInstanceOf <Car>(r); var vehicle = InstanceCreator.CreateInstanceOf <MiniSportBike>(r, new CreatorSettings() { NullValueProbability = 0.0 }); DataServiceContext ctx = WriterClient(new Uri(this.BaseAddress), ODataProtocolVersion.V4); ctx.AddObject("InheritanceTests_Vehicles", car); ctx.AddObject("InheritanceTests_Vehicles", vehicle); ctx.SaveChangesAsync().Wait(); ctx.SetLink(car, "SingleNavigationProperty", vehicle); ctx.SaveChangesAsync().Wait(); ctx = ReaderClient(new Uri(this.BaseAddress), ODataProtocolVersion.V4); var cars = ctx.CreateQuery <Vehicle>("InheritanceTests_Vehicles").ExecuteAsync().Result.ToList().OfType <Car>(); var actual = cars.First(); ctx.LoadPropertyAsync(actual, "SingleNavigationProperty").Wait(); AssertExtension.PrimitiveEqual(vehicle, actual.SingleNavigationProperty); this.ClearRepository("InheritanceTests_Vehicles"); }
private static async Task RunSpecialCharactersTest(ADLSAdapter adapter) { var corpus = new CdmCorpusDefinition(); corpus.Storage.Mount("adls", adapter); corpus.Storage.DefaultNamespace = "adls"; try { var manifest = await corpus.FetchObjectAsync <CdmManifestDefinition>("default.manifest.cdm.json"); await manifest.FileStatusCheckAsync(); Assert.AreEqual(1, manifest.Entities.Count); Assert.AreEqual(2, manifest.Entities[0].DataPartitions.Count); Assert.AreEqual( "TestEntity-With=Special Characters/year=2020/TestEntity-partition-With=Special Characters-0.csv", manifest.Entities[0].DataPartitions[0].Location); Assert.AreEqual( "TestEntity-With=Special Characters/year=2020/TestEntity-partition-With=Special Characters-1.csv", manifest.Entities[0].DataPartitions[1].Location); } catch (Exception e) { Assert.Fail(e.Message); } }
public void TestMethod_DeleteAsync_NullEntity_Throws() { IMessageService service = _unityContainer.Resolve <IMessageService>(); Action act = () => service.Delete(null); AssertExtension.AssertInnerThrows <NullReferenceException>(act, "Nessuna eccezione di ritorno. Era attesa una NullReferenceException"); }
public async Task TestGetProject_WithExistingProjectName_ShouldReturnProject() { // Arrange var context = ApplicationDbContextInMemoryFactory.InitializeContext(); var groupRepository = new EfDeletableEntityRepository <Product_Group>(context); var productRepository = new EfDeletableEntityRepository <Product>(context); var projectRepository = new EfDeletableEntityRepository <Project>(context); var groupService = new GroupService(groupRepository); var prodcutService = new ProductService(productRepository, groupService); var cloudinaryService = new FakeCloudinary(); var projectService = new ProjectService(projectRepository, cloudinaryService, prodcutService, groupService); var seeder = new DbContextTestsSeeder(); await seeder.SeedUsersAsync(context); await seeder.SeedGroupAsync(context); await seeder.SeedProjectAsync(context); // Act AutoMapperConfig.RegisterMappings(typeof(DetailsProjectViewModel).Assembly); var expected = context.Projects.SingleOrDefault(finishedModel => finishedModel.Product.Name == "Проект 1"); var actualResult = projectService.GetByName <DetailsProjectViewModel>("Проект 1"); // Assert AssertExtension.EqualsWithMessage(expected.Product.Name, actualResult.Name, string.Format(ErrorMessage, "GetProject with name, returns name")); AssertExtension.EqualsWithMessage(expected.TypeProject.ToString(), actualResult.TypeProject, string.Format(ErrorMessage, "GetFinishedModel with name, returns Type Of Project")); AssertExtension.EqualsWithMessage(expected.TypeLocation.ToString(), actualResult.TypeLocation, string.Format(ErrorMessage, "GetFinishedModel with name, returns Type Of Location")); AssertExtension.EqualsWithMessage(expected.Description, actualResult.Description, string.Format(ErrorMessage, "GetProject with name, returns description")); AssertExtension.EqualsWithMessage(expected.ImagePath, actualResult.ImagePath, string.Format(ErrorMessage, "GetProject with name, returns ImagePath")); }
public void UpsertPromotion_Successful() { if (!VerifyPromoCodeTestsEnabled()) { Assert.Ignore(); } var upsertBasketResult = (Basket.Models.Basket)null; Coupon coupon; try { (upsertBasketResult, coupon) = PrepareUpsertPromotionRequest( configuration["Basket:TestReferences:0"], configuration["Basket:ValidPromoCode"]); var basketDetails = service.UpsertPromotion(upsertBasketResult.Reference, coupon); Assert.Null(upsertBasketResult.Coupon); AssertExtension.AreObjectsValuesEqual(coupon, basketDetails.Coupon); Assert.NotNull(basketDetails.AppliedPromotion); } finally { service.ClearBasket(upsertBasketResult?.Reference); } }