public void FromDto_Transaction() { using (var testDbInfo = SetupUtil.CreateTestDb()) { //Arrange Mock <ILog> mockLog = new Mock <ILog>(); RepositoryBag repositories = SetupUtil.CreateMockRepositoryBag(testDbInfo.ConnectionString, mockLog.Object); DateTime timestamp = DateTime.Now; long? sourceAccountId = 1; long? destAccountId = 3; Money transferAmount = 123.45; string memo = "memo"; TransactionDto transactionDto = new TransactionDto() { Id = 1, Timestamp = timestamp, SourceAccountId = sourceAccountId, DestinationAccountId = destAccountId, TransferAmount = transferAmount.InternalValue, Memo = memo }; //Act Transaction transaction = DtoToModelTranslator.FromDto(transactionDto, repositories); //Assert Assert.Equal(timestamp, transaction.Timestamp); Assert.Equal(sourceAccountId, transaction.SourceAccountId); Assert.Equal(destAccountId, transaction.DestinationAccountId); Assert.Equal(transferAmount, transaction.TransferAmount); Assert.Equal(memo, transaction.Memo); } }
public async Task Data_Post_With_DataCreation() { Guid guid = new Guid("609efc9d-4496-4f0b-9d20-808dc2c1876d"); TestDataUtil.PrepareInstance("tdd", "custom-validation", 1337, guid); string token = PrincipalUtil.GetToken(1337); HttpClient client = SetupUtil.GetTestClient(_factory, "tdd", "custom-validation"); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); HttpRequestMessage httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, "/tdd/custom-validation/instances/1337/609efc9d-4496-4f0b-9d20-808dc2c1876d/data?dataType=default") { }; HttpResponseMessage response = await client.SendAsync(httpRequestMessage); string responseContent = await response.Content.ReadAsStringAsync(); Assert.Equal(HttpStatusCode.Created, response.StatusCode); DataElement dataElement = JsonConvert.DeserializeObject <DataElement>(responseContent); httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, $"/tdd/custom-validation/instances/1337/609efc9d-4496-4f0b-9d20-808dc2c1876d/data/{dataElement.Id}") { }; response = await client.SendAsync(httpRequestMessage); responseContent = await response.Content.ReadAsStringAsync(); Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Contains("\"enhetNavnEndringdatadef31\":{\"orid\":31,\"value\":\"Test Test 123\"}", responseContent); TestDataUtil.DeleteInstanceAndData("tdd", "custom-validation", 1337, guid); }
public async Task ValidateAttachment_ValidData() { TestDataUtil.DeleteInstance("tdd", "custom-validation", 1337, new System.Guid("16314483-65f3-495a-aaec-79445b4edb0b")); TestDataUtil.PrepareInstance("tdd", "custom-validation", 1337, new System.Guid("16314483-65f3-495a-aaec-79445b4edb0b")); string token = PrincipalUtil.GetToken(1337); HttpClient client = SetupUtil.GetTestClient(_factory, "tdd", "custom-validation"); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); string url = "/tdd/custom-validation/instances/1337/16314483-65f3-495a-aaec-79445b4edb0b/data/b862f944-3f04-45e3-b445-6bbd09f65ad5/validate"; HttpRequestMessage httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, url); HttpResponseMessage response = await client.SendAsync(httpRequestMessage); string responseContent = await response.Content.ReadAsStringAsync(); TestDataUtil.DeleteInstance("tdd", "custom-validation", 1337, new System.Guid("16314483-65f3-495a-aaec-79445b4edb0b")); List <ValidationIssue> messages = (List <ValidationIssue>)JsonConvert.DeserializeObject(responseContent, typeof(List <ValidationIssue>)); Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Empty(messages); }
public async Task Proceess_Get_OK() { TestDataUtil.PrepareInstance("tdd", "endring-av-navn", 1337, new Guid("26133fb5-a9f2-45d4-90b1-f6d93ad40713")); string token = PrincipalUtil.GetToken(1337); HttpClient client = SetupUtil.GetTestClient(_factory, "tdd", "endring-av-navn"); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); HttpRequestMessage httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, "/tdd/endring-av-navn/instances/1337/26133fb5-a9f2-45d4-90b1-f6d93ad40713/process") { }; HttpResponseMessage response = await client.SendAsync(httpRequestMessage); TestDataUtil.DeleteInstance("tdd", "endring-av-navn", 1337, new Guid("26133fb5-a9f2-45d4-90b1-f6d93ad40713")); string responseContent = await response.Content.ReadAsStringAsync(); ProcessState processState = (ProcessState)JsonConvert.DeserializeObject(responseContent, typeof(ProcessState)); Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal("Task_1", processState.CurrentTask.ElementId); }
public void ListAccountCommand_Options() { using (var testDbInfo = SetupUtil.CreateTestDb()) { Mock <ILog> mockLog = new Mock <ILog>(); AccountRepository repo = new AccountRepository(testDbInfo.ConnectionString, mockLog.Object); AccountStateRepository stateRepo = new AccountStateRepository(testDbInfo.ConnectionString, mockLog.Object); //Id will be 1 repo.Upsert(new Data.Models.AccountDto() { AccountKind = AccountKind.Source, CategoryId = 2, Description = "Description", Name = "Name", Priority = 10 }); stateRepo.Upsert(new Data.Models.AccountStateDto() { AccountId = 1, Funds = 10, IsClosed = false, Timestamp = DateTime.Today }); //Id will be 2 repo.Upsert(new Data.Models.AccountDto() { AccountKind = AccountKind.Category, CategoryId = null, Description = "", Name = "Category", Priority = 5 }); stateRepo.Upsert(new Data.Models.AccountStateDto() { AccountId = 2, Funds = 100, IsClosed = false, Timestamp = DateTime.Today }); //Id will be 3 repo.Upsert(new Data.Models.AccountDto() { AccountKind = AccountKind.Category, CategoryId = null, Description = "", Name = "Category2", Priority = 5 }); stateRepo.Upsert(new Data.Models.AccountStateDto() { AccountId = 3, Funds = 50, IsClosed = false, Timestamp = DateTime.Today }); CommandInterpreter interpreter = new CommandInterpreter(SetupUtil.CreateMockRepositoryBag(testDbInfo.ConnectionString, mockLog.Object, repo, stateRepo), BudgetCliCommands.BuildCommandLibrary()); ICommandAction action; bool success = interpreter.TryParseCommand("list accounts -n Name -c Category -d Description -y Source -p (4,6) -f (90,110)", out action); Assert.True(success); Assert.IsType <ListAccountCommand>(action); ListAccountCommand command = (ListAccountCommand)action; Assert.Equal("Name", command.NameOption.GetValue("N/A")); Assert.Equal("Description", command.DescriptionOption.GetValue("N/A")); Assert.Equal(2L, command.CategoryIdOption.GetValue("N/A")); Assert.Equal(AccountKind.Source, command.AccountTypeOption.GetValue(AccountKind.Sink)); Range <long> expectedPriorityRange = new Range <long>(4, 6, false, false); Range <Money> expectedFundsRange = new Range <Money>(90, 110, false, false); Assert.Equal(expectedFundsRange, command.FundsOption.GetValue(null)); Assert.Equal(expectedPriorityRange, command.PriorityOption.GetValue(null)); } }
public async void NaboVarselEndToEndTest() { /* SETUP */ string instanceOwnerPartyId = "1337"; Instance instanceTemplate = new Instance() { InstanceOwner = new InstanceOwner { PartyId = instanceOwnerPartyId, } }; SvarPaaNabovarselType svar = new SvarPaaNabovarselType(); svar.ansvarligSoeker = new PartType(); svar.ansvarligSoeker.mobilnummer = "90912345"; svar.eiendomByggested = new EiendomListe(); svar.eiendomByggested.eiendom = new List <EiendomType>(); svar.eiendomByggested.eiendom.Add(new EiendomType() { adresse = new EiendommensAdresseType() { postnr = "8450" }, kommunenavn = "Hadsel" }); string xml = string.Empty; using (var stringwriter = new System.IO.StringWriter()) { XmlSerializer serializer = new XmlSerializer(typeof(SvarPaaNabovarselType)); serializer.Serialize(stringwriter, svar); xml = stringwriter.ToString(); } #region Org instansiates form with message string instanceAsString = JsonConvert.SerializeObject(instanceTemplate); string xmlmelding = File.ReadAllText("Data/Files/melding.xml"); string boundary = "abcdefgh"; MultipartFormDataContent formData = new MultipartFormDataContent(boundary) { { new StringContent(instanceAsString, Encoding.UTF8, "application/json"), "instance" }, { new StringContent(xml, Encoding.UTF8, "application/xml"), "skjema" }, { new StringContent(xmlmelding, Encoding.UTF8, "application/xml"), "melding" } }; Uri uri = new Uri("/dibk/nabovarsel/instances", UriKind.Relative); /* TEST */ HttpClient client = SetupUtil.GetTestClient(_factory, "dibk", "nabovarsel"); string token = PrincipalUtil.GetOrgToken("dibk"); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); HttpResponseMessage response = await client.PostAsync(uri, formData); response.EnsureSuccessStatusCode(); Assert.True(response.StatusCode == HttpStatusCode.Created); Instance createdInstance = JsonConvert.DeserializeObject <Instance>(await response.Content.ReadAsStringAsync()); Assert.NotNull(createdInstance); Assert.Equal(2, createdInstance.Data.Count); #endregion #region end user gets instance // Reset token and client to end user client = SetupUtil.GetTestClient(_factory, "dibk", "nabovarsel"); token = PrincipalUtil.GetToken(1337); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); string instancePath = "/dibk/nabovarsel/instances/" + createdInstance.Id; HttpRequestMessage httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, instancePath); response = await client.SendAsync(httpRequestMessage); string responseContent = await response.Content.ReadAsStringAsync(); Instance instance = (Instance)JsonConvert.DeserializeObject(responseContent, typeof(Instance)); Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal("1337", instance.InstanceOwner.PartyId); Assert.Equal("Task_1", instance.Process.CurrentTask.ElementId); Assert.Equal(2, instance.Data.Count); #endregion #region end user gets application metadata httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, "/dibk/nabovarsel/api/v1/applicationmetadata"); response = await client.SendAsync(httpRequestMessage); responseContent = await response.Content.ReadAsStringAsync(); Application application = (Application)JsonConvert.DeserializeObject(responseContent, typeof(Application)); Assert.Equal(HttpStatusCode.OK, response.StatusCode); #endregion #region Get Message DataElement // In this application the message element is connected to Task_1. Find the datatype for this task and retrive this from storage DataType dataType = application.DataTypes.FirstOrDefault(r => r.TaskId != null && r.TaskId.Equals(instance.Process.CurrentTask.ElementId)); DataElement dataElementMessage = instance.Data.FirstOrDefault(r => r.DataType.Equals(dataType.Id)); httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, instancePath + "/data/" + dataElementMessage.Id); response = await client.SendAsync(httpRequestMessage); responseContent = await response.Content.ReadAsStringAsync(); Melding melding = (Melding)JsonConvert.DeserializeObject(responseContent, typeof(Melding)); Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal("Informasjon om tiltak", melding.MessageTitle); #endregion #region Get Status httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, $"{instancePath}/process"); response = await client.SendAsync(httpRequestMessage); responseContent = await response.Content.ReadAsStringAsync(); ProcessState processState = (ProcessState)JsonConvert.DeserializeObject(responseContent, typeof(ProcessState)); Assert.Equal("Task_1", processState.CurrentTask.ElementId); #endregion #region Validate instance (the message element) httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, $"{instancePath}/validate"); response = await client.SendAsync(httpRequestMessage); responseContent = await response.Content.ReadAsStringAsync(); List <ValidationIssue> messages = (List <ValidationIssue>)JsonConvert.DeserializeObject(responseContent, typeof(List <ValidationIssue>)); Assert.Empty(messages); #endregion // TODO. Add verification of not able to update message and check that statues is updated #region push to next step httpRequestMessage = new HttpRequestMessage(HttpMethod.Put, $"{instancePath}/process/next"); response = await client.SendAsync(httpRequestMessage); responseContent = await response.Content.ReadAsStringAsync(); Assert.Equal(HttpStatusCode.OK, response.StatusCode); #endregion #region Get Status after next httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, $"{instancePath}/process"); response = await client.SendAsync(httpRequestMessage); responseContent = await response.Content.ReadAsStringAsync(); processState = (ProcessState)JsonConvert.DeserializeObject(responseContent, typeof(ProcessState)); Assert.Equal("Task_2", processState.CurrentTask.ElementId); #endregion #region GetUpdated instance to check pdf httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, instancePath); response = await client.SendAsync(httpRequestMessage); responseContent = await response.Content.ReadAsStringAsync(); instance = (Instance)JsonConvert.DeserializeObject(responseContent, typeof(Instance)); IEnumerable <DataElement> lockedDataElements = instance.Data.Where(r => r.Locked == true); Assert.Single(lockedDataElements); #endregion #region Get Form DataElement dataType = application.DataTypes.FirstOrDefault(r => r.TaskId != null && r.TaskId.Equals(processState.CurrentTask.ElementId)); DataElement dataElementForm = instance.Data.FirstOrDefault(r => r.DataType.Equals(dataType.Id)); httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, instancePath + "/data/" + dataElementForm.Id); response = await client.SendAsync(httpRequestMessage); responseContent = await response.Content.ReadAsStringAsync(); SvarPaaNabovarselType skjema = (SvarPaaNabovarselType)JsonConvert.DeserializeObject(responseContent, typeof(SvarPaaNabovarselType)); Assert.Equal(HttpStatusCode.OK, response.StatusCode); #endregion #region Update Form DataElement string requestJson = JsonConvert.SerializeObject(skjema); StringContent httpContent = new StringContent(requestJson, Encoding.UTF8, "application/json"); httpRequestMessage = new HttpRequestMessage(HttpMethod.Put, instancePath + "/data/" + dataElementForm.Id) { Content = httpContent }; response = await client.SendAsync(httpRequestMessage); responseContent = await response.Content.ReadAsStringAsync(); Assert.Equal(HttpStatusCode.Created, response.StatusCode); #endregion #region push to next step httpRequestMessage = new HttpRequestMessage(HttpMethod.Put, $"{instancePath}/process/next"); response = await client.SendAsync(httpRequestMessage); responseContent = await response.Content.ReadAsStringAsync(); // Expect conflict since the form contains validation errors that needs to be resolved before moving to next task in process. Assert.Equal(HttpStatusCode.Conflict, response.StatusCode); #endregion #region Validate data in Task_2 (the form) httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, $"{instancePath}/validate"); response = await client.SendAsync(httpRequestMessage); responseContent = await response.Content.ReadAsStringAsync(); messages = (List <ValidationIssue>)JsonConvert.DeserializeObject(responseContent, typeof(List <ValidationIssue>)); Assert.Single(messages); #endregion #region Update Form DataElement with missing value skjema.nabo = new NaboGjenboerType(); skjema.nabo.epost = "*****@*****.**"; requestJson = JsonConvert.SerializeObject(skjema); httpContent = new StringContent(requestJson, Encoding.UTF8, "application/json"); httpRequestMessage = new HttpRequestMessage(HttpMethod.Put, instancePath + "/data/" + dataElementForm.Id) { Content = httpContent }; response = await client.SendAsync(httpRequestMessage); responseContent = await response.Content.ReadAsStringAsync(); Assert.Equal(HttpStatusCode.Created, response.StatusCode); #endregion #region push to confirm task httpRequestMessage = new HttpRequestMessage(HttpMethod.Put, $"{instancePath}/process/next"); response = await client.SendAsync(httpRequestMessage); responseContent = await response.Content.ReadAsStringAsync(); Assert.Equal(HttpStatusCode.OK, response.StatusCode); #endregion #region Get Status after next httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, $"{instancePath}/process"); response = await client.SendAsync(httpRequestMessage); responseContent = await response.Content.ReadAsStringAsync(); processState = (ProcessState)JsonConvert.DeserializeObject(responseContent, typeof(ProcessState)); Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal("Task_3", processState.CurrentTask.ElementId); #endregion #region push to end step httpRequestMessage = new HttpRequestMessage(HttpMethod.Put, $"{instancePath}/process/next"); response = await client.SendAsync(httpRequestMessage); responseContent = await response.Content.ReadAsStringAsync(); Assert.Equal(HttpStatusCode.OK, response.StatusCode); #endregion #region Get Status after next httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, $"{instancePath}/process"); response = await client.SendAsync(httpRequestMessage); responseContent = await response.Content.ReadAsStringAsync(); processState = (ProcessState)JsonConvert.DeserializeObject(responseContent, typeof(ProcessState)); Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Null(processState.CurrentTask); Assert.Equal("EndEvent_1", processState.EndEvent); #endregion TestDataUtil.DeleteInstanceAndData("dibk", "nabovarsel", 1337, new Guid(createdInstance.Id.Split('/')[1])); }
public void TestGetLatestStateByAccountId_WithDate() { using (var testDbInfo = SetupUtil.CreateTestDb()) { //Arrange Mock <ILog> log = new Mock <ILog>(); AccountRepository accountRepo = new AccountRepository(testDbInfo.ConnectionString, log.Object); AccountStateRepository repo = new AccountStateRepository(testDbInfo.ConnectionString, log.Object); AccountDto account = new AccountDto() { AccountKind = Enums.AccountKind.Category, Description = String.Empty, Name = "account", Priority = 5, CategoryId = null }; bool isInsertSuccessful = accountRepo.Upsert(account); DateTime state1Timestamp = DateTime.Today; AccountStateDto accountState = new AccountStateDto() { AccountId = account.Id.Value, Funds = (new Money(100)).InternalValue, IsClosed = false, Timestamp = state1Timestamp }; isInsertSuccessful &= repo.Upsert(accountState); DateTime state2Timestamp = state1Timestamp.AddDays(-10); AccountStateDto accountState2 = new AccountStateDto() { AccountId = account.Id.Value, Funds = (new Money(500)).InternalValue, IsClosed = false, Timestamp = state2Timestamp }; isInsertSuccessful &= repo.Upsert(accountState2); DateTime state3Timestamp = state1Timestamp.AddDays(-20); AccountStateDto accountState3 = new AccountStateDto() { AccountId = account.Id.Value, Funds = (new Money(800)).InternalValue, IsClosed = false, Timestamp = state3Timestamp }; isInsertSuccessful &= repo.Upsert(accountState3); //Act AccountStateDto a = repo.GetLatestByAccountId(account.Id.Value, state3Timestamp); AccountStateDto b = repo.GetLatestByAccountId(account.Id.Value, state3Timestamp.AddDays(5)); // half way between 3 and 2 AccountStateDto c = repo.GetLatestByAccountId(account.Id.Value, state2Timestamp); AccountStateDto d = repo.GetLatestByAccountId(account.Id.Value, state2Timestamp.AddDays(5)); //Half way between 2 and 1 AccountStateDto e = repo.GetLatestByAccountId(account.Id.Value, state1Timestamp); AccountStateDto f = repo.GetLatestByAccountId(account.Id.Value, state1Timestamp.AddDays(5)); //5 days in future //Assert Assert.True(isInsertSuccessful); Assert.Equal(800, new Money(a.Funds, true)); Assert.Equal(800, new Money(b.Funds, true)); Assert.Equal(500, new Money(c.Funds, true)); Assert.Equal(500, new Money(d.Funds, true)); Assert.Equal(100, new Money(e.Funds, true)); Assert.Equal(100, new Money(f.Funds, true)); } }
public void TestRemoveAllStatesByAccountId() { using (var testDbInfo = SetupUtil.CreateTestDb()) { //Arrange Mock <ILog> log = new Mock <ILog>(); AccountRepository accountRepo = new AccountRepository(testDbInfo.ConnectionString, log.Object); AccountStateRepository repo = new AccountStateRepository(testDbInfo.ConnectionString, log.Object); AccountDto account = new AccountDto() { AccountKind = Enums.AccountKind.Category, Description = String.Empty, Name = "account", Priority = 5, CategoryId = null }; bool isInsertSuccessful = accountRepo.Upsert(account); DateTime state1Timestamp = DateTime.Now; AccountStateDto accountState = new AccountStateDto() { AccountId = account.Id.Value, Funds = (new Money(100)).InternalValue, IsClosed = false, Timestamp = state1Timestamp }; isInsertSuccessful &= repo.Upsert(accountState); DateTime state2Timestamp = state1Timestamp.AddDays(-1); AccountStateDto accountState2 = new AccountStateDto() { AccountId = account.Id.Value, Funds = (new Money(500)).InternalValue, IsClosed = false, Timestamp = state2Timestamp }; isInsertSuccessful &= repo.Upsert(accountState2); DateTime state3Timestamp = state1Timestamp.AddDays(-2); AccountStateDto accountState3 = new AccountStateDto() { AccountId = account.Id.Value, Funds = (new Money(800)).InternalValue, IsClosed = false, Timestamp = state3Timestamp }; isInsertSuccessful &= repo.Upsert(accountState3); //Act List <AccountStateDto> allStatesBeforeRemove = repo.GetAllByAccountId(account.Id.Value); bool isSuccessful = repo.RemoveAllByAccountId(account.Id.Value); List <AccountStateDto> allStatesAfterRemove = repo.GetAllByAccountId(account.Id.Value); //Assert Assert.True(isInsertSuccessful); Assert.True(isSuccessful); Assert.Equal(3, allStatesBeforeRemove.Count); Assert.Empty(allStatesAfterRemove); } }
public void TestGetChildAccountIds_NoChildren() { using (var testDbInfo = SetupUtil.CreateTestDb()) { //Arrange Mock <ILog> log = new Mock <ILog>(); AccountRepository repo = new AccountRepository(testDbInfo.ConnectionString, log.Object); AccountDto account = new AccountDto() { AccountKind = Enums.AccountKind.Category, Description = String.Empty, Name = "account", Priority = 5, CategoryId = null }; bool isInsertSuccessful = repo.Upsert(account); AccountDto other1 = new AccountDto() { AccountKind = Enums.AccountKind.Category, Description = String.Empty, Name = "other1", Priority = 5, CategoryId = null }; bool isOtherInsertSuccessful = repo.Upsert(other1); AccountDto unrelated = new AccountDto() { AccountKind = Enums.AccountKind.Category, Description = String.Empty, Name = "unrelated", Priority = 5, CategoryId = null }; bool isUnrelatedInsertSuccessful = repo.Upsert(unrelated); AccountDto other2 = new AccountDto() { AccountKind = Enums.AccountKind.Category, Description = String.Empty, Name = "other2", Priority = 5, CategoryId = null }; bool isOther2InsertSuccessful = repo.Upsert(other2); //Act var childIds = repo.GetChildAccountIds(account.Id.Value); //Assert Assert.True(isInsertSuccessful); Assert.True(isOtherInsertSuccessful); Assert.True(isOther2InsertSuccessful); //make sure it's empty Assert.NotNull(childIds); Assert.False(childIds.Any()); } }
public async Task Instance_Post_WithNæringOgSkattemelding_ValidateOkThenNext() { // Gets JWT token. In production this would be given from authentication component when exchanging a ID porten token. string token = PrincipalUtil.GetToken(1337); // Setup client and calls Instance controller on the App that instansiates a new instances of the app HttpClient client = SetupUtil.GetTestClient(_factory, "tdd", "sirius"); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); HttpRequestMessage httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, "/tdd/sirius/instances?instanceOwnerPartyId=1337"); HttpResponseMessage response = await client.SendAsync(httpRequestMessage); string responseContent = await response.Content.ReadAsStringAsync(); Instance instance = JsonConvert.DeserializeObject <Instance>(responseContent); Assert.Equal(HttpStatusCode.Created, response.StatusCode); Assert.NotNull(instance); Assert.Equal("1337", instance.InstanceOwner.PartyId); // Get Data from the main form HttpRequestMessage httpRequestMessageGetData = new HttpRequestMessage(HttpMethod.Get, "/tdd/sirius/instances/" + instance.Id + "/data/" + instance.Data[0].Id); HttpResponseMessage responseData = await client.SendAsync(httpRequestMessageGetData); string responseContentData = await responseData.Content.ReadAsStringAsync(); Skjema siriusMainForm = (Skjema)JsonConvert.DeserializeObject(responseContentData, typeof(Skjema)); // Modify the prefilled form. This would need to be replaced with the real sirius form siriusMainForm.Permisjonsopplysningergrp8822 = new Permisjonsopplysningergrp8822(); siriusMainForm.Permisjonsopplysningergrp8822.AnsattEierandel20EllerMerdatadef33294 = new AnsattEierandel20EllerMerdatadef33294() { value = "50" }; XmlSerializer serializer = new XmlSerializer(typeof(Skjema)); using MemoryStream stream = new MemoryStream(); serializer.Serialize(stream, siriusMainForm); stream.Position = 0; StreamContent streamContent = new StreamContent(stream); streamContent.Headers.ContentType = MediaTypeHeaderValue.Parse("text/xml"); streamContent.Headers.ContentDisposition = ContentDispositionHeaderValue.Parse("attachment; filename=data-element.xml"); HttpResponseMessage putresponse = await client.PutAsync("/tdd/sirius/instances/" + instance.Id + "/data/" + instance.Data[0].Id, streamContent); // Add Næringsoppgave.xml string næringsppgave = File.ReadAllText("Data/Files/data-element.xml"); byte[] byteArray = Encoding.UTF8.GetBytes(næringsppgave); MemoryStream næringsoppgavestream = new MemoryStream(byteArray); StreamContent streamContentNæring = new StreamContent(næringsoppgavestream); streamContentNæring.Headers.ContentDisposition = ContentDispositionHeaderValue.Parse("attachment; filename=data-element.xml"); streamContentNæring.Headers.ContentType = MediaTypeHeaderValue.Parse("text/xml"); HttpResponseMessage postresponseNæring = await client.PostAsync("/tdd/sirius/instances/" + instance.Id + "/data/?datatype=næringsoppgave", streamContentNæring); DataElement dataElementNæring = (DataElement)JsonConvert.DeserializeObject(await postresponseNæring.Content.ReadAsStringAsync(), typeof(DataElement)); // Add skattemelding.xml string skattemelding = File.ReadAllText("Data/Files/data-element.xml"); byte[] byteArraySkattemelding = Encoding.UTF8.GetBytes(skattemelding); MemoryStream skattemeldingstream = new MemoryStream(byteArraySkattemelding); HttpContent streamContentSkattemelding = new StreamContent(skattemeldingstream); streamContent.Headers.ContentType = MediaTypeHeaderValue.Parse("text/xml"); streamContent.Headers.ContentDisposition = ContentDispositionHeaderValue.Parse("attachment; filename=data-element.xml"); HttpResponseMessage postresponseskattemelding = await client.PostAsync("/tdd/sirius/instances/" + instance.Id + "/data/?datatype=skattemelding", streamContentNæring); DataElement dataElementSkattemelding = (DataElement)JsonConvert.DeserializeObject(await postresponseskattemelding.Content.ReadAsStringAsync(), typeof(DataElement)); // Validate instance. This validates that main form has valid data and required data string url = "/tdd/sirius/instances/" + instance.Id + "/validate"; HttpResponseMessage responseValidation = await client.GetAsync(url); string responseContentValidation = await responseValidation.Content.ReadAsStringAsync(); List <ValidationIssue> messages = (List <ValidationIssue>)JsonConvert.DeserializeObject(responseContentValidation, typeof(List <ValidationIssue>)); Assert.Empty(messages); // Handle first next go from data to confirmation HttpRequestMessage httpRequestMessageFirstNext = new HttpRequestMessage(HttpMethod.Put, "/tdd/sirius/instances/" + instance.Id + "/process/next"); HttpResponseMessage responseFirstNext = await client.SendAsync(httpRequestMessageFirstNext); string responseContentFirstNext = await responseFirstNext.Content.ReadAsStringAsync(); ProcessState stateAfterFirstNext = (ProcessState)JsonConvert.DeserializeObject(responseContentFirstNext, typeof(ProcessState)); Assert.Equal("Task_2", stateAfterFirstNext.CurrentTask.ElementId); // Validate instance in Task_2. This validates that PDF for nærings is in place HttpResponseMessage responseValidationTask2 = await client.GetAsync(url); string responseContentValidationTask2 = await responseValidationTask2.Content.ReadAsStringAsync(); List <ValidationIssue> messagesTask2 = (List <ValidationIssue>)JsonConvert.DeserializeObject(responseContentValidationTask2, typeof(List <ValidationIssue>)); Assert.Empty(messagesTask2); // Move process from Task_2 (Confirmation) to Task_3 (Feedback). HttpRequestMessage httpRequestMessageSecondNext = new HttpRequestMessage(HttpMethod.Put, "/tdd/sirius/instances/" + instance.Id + "/process/next"); HttpResponseMessage responseSecondNext = await client.SendAsync(httpRequestMessageSecondNext); string responseContentSecondNext = await responseSecondNext.Content.ReadAsStringAsync(); ProcessState stateAfterSecondNext = (ProcessState)JsonConvert.DeserializeObject(responseContentSecondNext, typeof(ProcessState)); Assert.Equal("Task_3", stateAfterSecondNext.CurrentTask.ElementId); // Delete all data created TestDataUtil.DeleteInstanceAndData("tdd", "sirius", 1337, new Guid(instance.Id.Split('/')[1])); }
private void worker_DoWork(object sender, DoWorkEventArgs e) { try { SetProgressBar(60); SetLabel("Initializing components"); //this.LoadUserAppData(); SetProgressBar(100); SetLabel("Getting user information"); //GlobalService.User = "******"; //GlobalService.DbTable = "TB_hk950097"; /*if (domain == "kmhk.local") * GlobalService.DbTable = "TB_" + AdUtil.GetUserIdByUsername(GlobalService.User, "kmhk.local"); * else * { * string id = AdUtil.GetUserIdByUsername(GlobalService.User, domain); * * string tb = id == "as1600048" ? "hk070022" * : id == "as1600049" ? "hk110017" * : id == "as1600050" ? "hk040015" * : id == "as1600051" ? "hk160002" * : id == "as1600053" ? "hk950330" * : id == "as1600054" ? "hk110023" * : id == "as1600055" ? "hk120027" * : id == "as1600056" ? "hk140005" : ""; * * GlobalService.DbTable = "TB_" + tb; * * string name = id == "as1600048" ? "Chow Chi To(周志滔,Sammy)" * : id == "as1600049" ? "Ling Wai Man(凌慧敏,Velma)" * : id == "as1600050" ? "Chan Fai Lung(陳輝龍,Onyx)" * : id == "as1600051" ? "Ng Lau Yu, Lilith (吳柳如)" * : id == "as1600053" ? "Lee Miu Wah(李苗華)" * : id == "as1600054" ? "Lee Ming Fung(李銘峯)" * : id == "as1600055" ? "Ho Kin Hang(何健恒,Ken)" * : id == "as1600056" ? "Yeung Wai, Gabriel (楊偉)" : ""; * * GlobalService.User = name; * }*/ //List<string> list = new List<string>(); //list.Add(GlobalService.User); //EmailUtil.SendNotificationEmail(list); GlobalService.User = GlobalService.User.Trim(); try { SetLabel("Synchronizing data"); SharedUtil.AutoDeleteData(); Stopwatch sw = new Stopwatch(); sw.Start(); GlobalService.DepartmentFolder = SetupUtil.GetDepartmentFolder(GlobalService.User); sw.Stop(); Debug.WriteLine("Get Department Folder: " + sw.Elapsed); sw.Reset(); sw.Start(); GlobalService.DivisionMemberList = SystemUtil.DivisionMember(GlobalService.User); sw.Stop(); Debug.WriteLine("Get Division Memeber: " + sw.Elapsed); sw.Reset(); sw.Start(); GlobalService.DepartmentMemberList = SystemUtil.DepartmentMember(GlobalService.User); sw.Stop(); Debug.WriteLine("Get Department Member: " + sw.Elapsed); sw.Reset(); sw.Start(); GlobalService.SystemGroupList = GroupUtil.SystemGroupList(); GlobalService.CNGroupList = GroupUtil.CnGroupList(); GlobalService.VNGroupList = GroupUtil.VnGroupList(); GlobalService.JPGroupList = GroupUtil.JpGroupList(); sw.Stop(); Debug.WriteLine("Get System Group: " + sw.Elapsed); sw.Reset(); sw.Start(); GlobalService.CustomGroupList = GroupUtil.CustomGroupList2(GlobalService.User); sw.Stop(); Debug.WriteLine("Get Custom Group: " + sw.Elapsed); sw.Reset(); sw.Start(); GlobalService.AllUserList = UserUtil.AllUserList(); GlobalService.CnUserList = UserUtil.CnUserList(); GlobalService.VnUserList = UserUtil.VnUserList(); GlobalService.JpUserList = UserUtil.JpUserList(); sw.Stop(); Debug.WriteLine("Get All User: "******"Initialize attachment list: " + sw.Elapsed); sw.Reset(); sw.Start(); GlobalService.ExtraSystemGroupList = GroupUtil.ExtraSystemGroupList(); sw.Stop(); Debug.WriteLine("Get Extra System Group: " + sw.Elapsed); sw.Reset(); sw.Start(); GlobalService.NoticeList = MessageUtil.GetNoticeList(); sw.Stop(); Debug.WriteLine("Get Notice list: " + sw.Elapsed); GlobalService.IsPasswordInput = false; sw.Reset(); sw.Start(); GlobalService.DiscList = DiscUtil.PopulateDiscList(); sw.Stop(); Debug.WriteLine("Populate Disc List: " + sw.Elapsed); sw.Reset(); sw.Start(); GlobalService.Division = SystemUtil.GetDivision(GlobalService.User); sw.Stop(); Debug.WriteLine("Get Division: " + sw.Elapsed); sw.Reset(); sw.Start(); GlobalService.AppsList = SystemUtil.AppsList(); sw.Stop(); Debug.WriteLine("Get Application list: " + sw.Elapsed); sw.Reset(); sw.Start(); GlobalService.DocumentList = new List <lists.DocumentList>(); sw.Stop(); Debug.WriteLine("Initialize Document List: " + sw.Elapsed); sw.Reset(); sw.Start(); GlobalService.ContactList = ContactUtil.ContactList(); sw.Stop(); Debug.WriteLine("Load Contact List: " + sw.Elapsed); GetSystemVersion(); UpdateCommon(); SharedUtil.UpdateEmptyShared(); SharedUtil.UpdateShared(); Login(); //DataUtil.SyncDataToServer(); } catch (Exception ex) { Debug.WriteLine(ex.Message + ex.StackTrace); } } catch (ArgumentException ex) { File.WriteAllText(@"D:\Error.txt", ex.Message + ex.StackTrace); MessageBox.Show(ex.Message + ex.StackTrace); } }
public void TestAddAccountActionExecute_PastState() { using (var testDbInfo = SetupUtil.CreateTestDb()) { //Arrange Mock <ILog> mockLog = new Mock <ILog>(); AccountRepository repo = new AccountRepository(testDbInfo.ConnectionString, mockLog.Object); AccountStateRepository accountStateRepo = new AccountStateRepository(testDbInfo.ConnectionString, mockLog.Object); RepositoryBag repositories = SetupUtil.CreateMockRepositoryBag(testDbInfo.ConnectionString, mockLog.Object, repo, accountStateRepo); AccountDto account1 = new AccountDto() { Id = null, AccountKind = AccountKind.Sink, Name = "account1", Priority = 123, Description = "account1 description", CategoryId = null }; UpsertAccount(account1, repositories); DateTime state1Timestamp = DateTime.Today.AddDays(-100); AccountStateDto accountState = new AccountStateDto() { AccountId = account1.Id.Value, Funds = (new Money(100)).InternalValue, IsClosed = false, Timestamp = state1Timestamp }; accountStateRepo.Upsert(accountState); DateTime state2Timestamp = DateTime.Today.AddDays(-500); AccountStateDto accountState2 = new AccountStateDto() { AccountId = account1.Id.Value, Funds = (new Money(200)).InternalValue, IsClosed = false, Timestamp = state2Timestamp }; accountStateRepo.Upsert(accountState2); DetailAccountCommand action = new DetailAccountCommand("detail account account1", repositories); action.NameOption.SetData("account1"); action.DateOption.SetData(state1Timestamp.AddDays(-1)); //Latest state should be at timestamp2 ReadDetailsCommandResult <Account> result = null; Mock <ICommandActionListener> mockListener = new Mock <ICommandActionListener>(); mockListener.Setup(x => x.OnCommand(It.IsAny <ReadDetailsCommandResult <Account> >())).Callback <ReadDetailsCommandResult <Account> >((y) => { result = y; }); //Act bool successful = action.TryExecute(mockLog.Object, new [] { mockListener.Object }); //Assert Assert.True(successful); Assert.NotNull(result); Assert.Equal(account1.Id, result.Item.Id); Assert.Equal(200, result.Item.CurrentState.Funds); } }
public void TestDeleteAccountActionExecute_WithListeners() { using (var testDbInfo = SetupUtil.CreateTestDb()) { //Arrange Mock <ILog> mockLog = new Mock <ILog>(); AccountRepository repo = new AccountRepository(testDbInfo.ConnectionString, mockLog.Object); AccountStateRepository accountStateRepo = new AccountStateRepository(testDbInfo.ConnectionString, mockLog.Object); RepositoryBag repositories = SetupUtil.CreateMockRepositoryBag(testDbInfo.ConnectionString, mockLog.Object, repo, accountStateRepo); AccountDto accountDto = new AccountDto() { AccountKind = Data.Enums.AccountKind.Sink, CategoryId = null, Description = "test account", Name = "Test Account", Priority = 5 }; bool isInsertSuccessful = repo.Upsert(accountDto); long accountId = accountDto.Id.Value; int accountCountBeforeDelete = repo.GetAll().Count(); AccountStateDto stateDto = new AccountStateDto() { AccountId = accountId, Funds = 0, Timestamp = DateTime.Now, IsClosed = false }; isInsertSuccessful &= accountStateRepo.Upsert(stateDto); int stateCountBeforeDelete = accountStateRepo.GetAll().Count(); DeleteAccountCommand action = new DeleteAccountCommand("rm account \"Test Account\"", repositories); action.AccountName.SetData("Test Account"); action.IsRecursiveOption.SetData(false); Mock <ICommandActionListener> mockListener = new Mock <ICommandActionListener>(); mockListener.Setup(x => x.OnCommand(It.Is <DeleteCommandResult <Account> >(a => a.IsSuccessful && a.DeletedItems.Count() == 1 && a.DeletedItems.First().Name.Equals("Test Account")))).Verifiable(); List <ICommandActionListener> listeners = new List <ICommandActionListener>(); listeners.Add(mockListener.Object); //Act bool successful = action.TryExecute(mockLog.Object, listeners); int accountCountAfterDelete = repo.GetAll().Count(); int stateCountAfterDelete = accountStateRepo.GetAll().Count(); bool isClosed = accountStateRepo.GetLatestByAccountId(accountId).IsClosed; //Assert Assert.True(isInsertSuccessful); Assert.True(successful); Assert.Equal(1, accountCountBeforeDelete); Assert.Equal(1, accountCountAfterDelete); Assert.Equal(1, stateCountBeforeDelete); Assert.Equal(2, stateCountAfterDelete); Assert.True(isClosed); mockListener.VerifyAll(); } }
public void TestAccountPropertyValues() { using (var testDbInfo = SetupUtil.CreateTestDb()) { //Arrange Mock <ILog> mockLog = new Mock <ILog>(); AccountRepository repo = new AccountRepository(testDbInfo.ConnectionString, mockLog.Object); AccountStateRepository stateRepo = new AccountStateRepository(testDbInfo.ConnectionString, mockLog.Object); long id; string name = "Test Account"; long priority = 7; long? categoryId = null; string description = "description"; AccountKind accountKind = AccountKind.Source; Money initialFunds = 123.45; DateTime timestamp = DateTime.Now; AccountDto accountDto = new AccountDto() { Name = name, Priority = priority, Description = description, CategoryId = categoryId, AccountKind = accountKind, }; repo.Upsert(accountDto); id = accountDto.Id.Value; AccountStateDto stateDto = new AccountStateDto() { AccountId = id, Funds = initialFunds.InternalValue, IsClosed = false, Timestamp = timestamp, }; stateRepo.Upsert(stateDto); RepositoryBag repositories = SetupUtil.CreateMockRepositoryBag(testDbInfo.ConnectionString, mockLog.Object, repo, stateRepo); //Act Account account = new Account(accountDto.Id.Value, accountDto.Name, accountDto.CategoryId, accountDto.Priority, accountDto.AccountKind, accountDto.Description, timestamp, repositories); var propertyValues = account.GetPropertyValues().ToList(); AccountState state = DtoToModelTranslator.FromDto(stateDto, repositories); //Assert Assert.Equal(7, propertyValues.Count); Assert.Equal(id, propertyValues.First(x => x.Property.Equals(Account.PROP_ID)).Value); Assert.Equal(name, propertyValues.First(x => x.Property.Equals(Account.PROP_NAME)).Value); Assert.Equal(description, propertyValues.First(x => x.Property.Equals(Account.PROP_DESCRIPTION)).Value); Assert.Equal(accountKind, propertyValues.First(x => x.Property.Equals(Account.PROP_ACCOUNT_KIND)).Value); Assert.Equal(null, propertyValues.First(x => x.Property.Equals(Account.PROP_CATEGORY)).Value); Assert.Equal(priority, propertyValues.First(x => x.Property.Equals(Account.PROP_PRIORITY)).Value); Assert.Equal(state, propertyValues.First(x => x.Property.Equals(Account.PROP_CURRENT_STATE)).Value); } }
public void TestGetAccounts() { using (var testDbInfo = SetupUtil.CreateTestDb()) { //Arrange Mock <ILog> log = new Mock <ILog>(); AccountRepository repo = new AccountRepository(testDbInfo.ConnectionString, log.Object); AccountStateRepository stateRepo = new AccountStateRepository(testDbInfo.ConnectionString, log.Object); AccountDto parent = new AccountDto() { AccountKind = Enums.AccountKind.Category, Description = String.Empty, Name = "parent", Priority = 5, CategoryId = null }; bool isParentInsertSuccessful = repo.Upsert(parent); AccountDto testAccount = MakeAccount("Test Account"); AccountDto accountWithDescription1 = MakeAccount("AccountWithDescription1", description: "this is a description"); AccountDto accountWithDescription2 = MakeAccount("AccountWithDescription2", description: "descending"); AccountDto accountPriority10 = MakeAccount("AccountWithPriority10", priority: 10); AccountDto accountPriority1 = MakeAccount("AccountWithPriority1", priority: 1); AccountDto childAccount1 = MakeAccount("child1", categoryId: parent.Id); AccountDto childAccount2WithDescription = MakeAccount("child2", categoryId: parent.Id, description: "description"); AccountDto closedAccount = MakeAccount("closed", priority: 100); AccountDto fundedAccount = MakeAccount("funded", priority: 100); AddAccounts(repo, testAccount, accountWithDescription1, accountWithDescription2, accountPriority10, accountPriority1, childAccount1, childAccount2WithDescription, closedAccount, fundedAccount); SetAccountState(stateRepo, parent, 0, false); SetAccountState(stateRepo, testAccount, 0, false); SetAccountState(stateRepo, accountWithDescription1, 0, false); SetAccountState(stateRepo, accountWithDescription2, 0, false); SetAccountState(stateRepo, accountPriority10, 0, false); SetAccountState(stateRepo, accountPriority1, 0, false); SetAccountState(stateRepo, childAccount1, 0, false); SetAccountState(stateRepo, childAccount2WithDescription, 0, false); SetAccountState(stateRepo, closedAccount, 0, true); SetAccountState(stateRepo, fundedAccount, 1000.00, false); //Act int numMatchingTestAccountName = repo.GetAccounts(nameContains: "Test Account").Count(); int numMatchingChildName = repo.GetAccounts(nameContains: "child").Count(); int numMatchingDescription = repo.GetAccounts(descriptionContains: "desc").Count(); int numMatchingCategoryId = repo.GetAccounts(categoryId: parent.Id).Count(); int numInPriorityRange1To5 = repo.GetAccounts(priorityRange: new Range <long>(1, 5)).Count(); int numInPriorityRange6To15 = repo.GetAccounts(priorityRange: new Range <long>(6, 15)).Count(); int numInPriorityRange0To4 = repo.GetAccounts(priorityRange: new Range <long>(0, 4)).Count(); int numExcludingClosed = repo.GetAccounts(includeClosedAccounts: false).Count(); int numIncludingClosed = repo.GetAccounts(includeClosedAccounts: true).Count(); int numFunded = repo.GetAccounts(fundsRange: new Range <Money>(999.00, 1001.00)).Count(); //Assert Assert.Equal(1, numMatchingTestAccountName); Assert.Equal(2, numMatchingChildName); Assert.Equal(3, numMatchingDescription); Assert.Equal(2, numMatchingCategoryId); Assert.Equal(7, numInPriorityRange1To5); Assert.Equal(1, numInPriorityRange6To15); Assert.Equal(1, numInPriorityRange0To4); Assert.Equal(9, numExcludingClosed); Assert.Equal(10, numIncludingClosed); Assert.Equal(1, numFunded); } }
public async void NsmKlareringsportalenEndToEndTest() { /* SETUP */ string instanceOwnerPartyId = "1337"; Instance instanceTemplate = new Instance() { InstanceOwner = new InstanceOwner { PartyId = instanceOwnerPartyId, } }; ePOB_M svar = new ePOB_M(); svar.DeusRequest = new Deusrequest(); svar.DeusRequest.clearauthority = "Sivil"; svar.DeusRequest.nationallevel = "1"; string xml = string.Empty; using (var stringwriter = new System.IO.StringWriter()) { XmlSerializer serializer = new XmlSerializer(typeof(ePOB_M)); serializer.Serialize(stringwriter, svar); xml = stringwriter.ToString(); } #region Org instansiates form with message string instanceAsString = JsonConvert.SerializeObject(instanceTemplate); string boundary = "abcdefgh"; MultipartFormDataContent formData = new MultipartFormDataContent(boundary) { { new StringContent(instanceAsString, Encoding.UTF8, "application/json"), "instance" }, { new StringContent(xml, Encoding.UTF8, "application/xml"), "epob" }, }; Uri uri = new Uri("/nsm/klareringsportalen/instances", UriKind.Relative); /* TEST */ HttpClient client = SetupUtil.GetTestClient(_factory, "nsm", "klareringsportalen"); string token = PrincipalUtil.GetOrgToken("nsm"); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); HttpResponseMessage response = await client.PostAsync(uri, formData); string responsestring = await response.Content.ReadAsStringAsync(); response.EnsureSuccessStatusCode(); Assert.True(response.StatusCode == HttpStatusCode.Created); Instance createdInstance = JsonConvert.DeserializeObject <Instance>(await response.Content.ReadAsStringAsync()); Assert.NotNull(createdInstance); Assert.Single(createdInstance.Data); #endregion #region end user gets instance // Reset token and client to end user client = SetupUtil.GetTestClient(_factory, "nsm", "klareringsportalen"); token = PrincipalUtil.GetToken(1337, 4); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); string instancePath = "/nsm/klareringsportalen/instances/" + createdInstance.Id; HttpRequestMessage httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, instancePath); response = await client.SendAsync(httpRequestMessage); string responseContent = await response.Content.ReadAsStringAsync(); Instance instance = (Instance)JsonConvert.DeserializeObject(responseContent, typeof(Instance)); Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal("1337", instance.InstanceOwner.PartyId); Assert.Equal("Task_1", instance.Process.CurrentTask.ElementId); Assert.Single(instance.Data); #endregion TestDataUtil.DeleteInstanceAndData("nsm", "klareringsportalen", 1337, new Guid(createdInstance.Id.Split('/')[1])); }
public void ListAccountCommandActionKind() { ListAccountCommand action = new ListAccountCommand("ls accounts", SetupUtil.CreateMockRepositoryBag(string.Empty, null)); Assert.Equal(CommandActionKind.ListAccount, action.CommandActionKind); }
public async void ComplexProcessApp() { // Arrange string instanceGuid = string.Empty; string dataGuid; try { string token = PrincipalUtil.GetToken(1); HttpClient client = SetupUtil.GetTestClient(_factory, org, app); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); #region Start Process // Arrange Instance template = new Instance { InstanceOwner = new InstanceOwner { PartyId = instanceOwnerId.ToString() } }; string expectedCurrentTaskName = "Task_1"; // Act string url = $"/{org}/{app}/instances/"; HttpResponseMessage response = await client.PostAsync(url, new StringContent(template.ToString(), Encoding.UTF8, "application/json")); response.EnsureSuccessStatusCode(); Instance createdInstance = JsonConvert.DeserializeObject <Instance>(await response.Content.ReadAsStringAsync()); instanceGuid = createdInstance.Id.Split('/')[1]; dataGuid = createdInstance.Data.Where(d => d.DataType.Equals("default")).Select(d => d.Id).First(); // Assert Assert.Equal(expectedCurrentTaskName, createdInstance.Process.CurrentTask.ElementId); #endregion #region Upload invalid attachment type // Act url = $"/{org}/{app}/instances/{instanceOwnerId}/{instanceGuid}/data?dataType=invalidDataType"; response = await client.PostAsync(url, null); // Assert Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); #endregion #region Move process to next step // Arrange string expectedNextTask = "Task_2"; url = $"/{org}/{app}/instances/{instanceOwnerId}/{instanceGuid}/process/next"; // Act response = await client.GetAsync(url); List <string> nextTasks = JsonConvert.DeserializeObject <List <string> >(await response.Content.ReadAsStringAsync()); string actualNextTask = nextTasks[0]; // Assert Assert.Equal(expectedNextTask, actualNextTask); // Act response = await client.PutAsync(url, null); // Assert response.EnsureSuccessStatusCode(); #endregion #region Upload form data during Task_2 // Arrange url = $"/{org}/{app}/instances/{instanceOwnerId}/{instanceGuid}/data/{dataGuid}"; // Act response = await client.PutAsync(url, null); // Assert: Upload for data during step 2 Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); #endregion #region Validate Task_2 before valid time // Arrange url = $"/{org}/{app}/instances/{instanceOwnerId}/{instanceGuid}/validate"; // Act response = await client.GetAsync(url); string responseContent = await response.Content.ReadAsStringAsync(); List <ValidationIssue> messages = (List <ValidationIssue>)JsonConvert.DeserializeObject(responseContent, typeof(List <ValidationIssue>)); Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Single(messages); Assert.Equal(ValidationIssueSeverity.Error, messages[0].Severity); #endregion #region Validate Task_2 after valid time // Arrange url = $"/{org}/{app}/instances/{instanceOwnerId}/{instanceGuid}/validate"; // Act Thread.Sleep(new TimeSpan(0, 0, 12)); response = await client.GetAsync(url); responseContent = await response.Content.ReadAsStringAsync(); messages = (List <ValidationIssue>)JsonConvert.DeserializeObject(responseContent, typeof(List <ValidationIssue>)); Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Empty(messages); #endregion #region Complete process //Arrange url = $"/{org}/{app}/instances/{instanceOwnerId}/{instanceGuid}/process/completeProcess"; // Act response = await client.PutAsync(url, null); ProcessState endProcess = JsonConvert.DeserializeObject <ProcessState>(await response.Content.ReadAsStringAsync()); // Assert response.EnsureSuccessStatusCode(); #endregion } finally { // Cleanup TestDataUtil.DeleteInstanceAndData("tdd", "complex-process", 1000, new Guid(instanceGuid)); } }
public void TestTransactionPropertyValues() { using (var testDbInfo = SetupUtil.CreateTestDb()) { //Arrange Mock <ILog> mockLog = new Mock <ILog>(); AccountRepository accountRepo = new AccountRepository(testDbInfo.ConnectionString, mockLog.Object); AccountStateRepository accountStateRepo = new AccountStateRepository(testDbInfo.ConnectionString, mockLog.Object); RepositoryBag repositories = SetupUtil.CreateMockRepositoryBag(testDbInfo.ConnectionString, mockLog.Object, accountRepo, accountStateRepo); var accountDto1 = new AccountDto() { Name = "source", Priority = 5, AccountKind = AccountKind.Sink }; accountRepo.Upsert(accountDto1); var accountDto2 = new AccountDto() { Name = "dest", Priority = 5, AccountKind = AccountKind.Sink }; accountRepo.Upsert(accountDto2); accountStateRepo.Upsert(new AccountStateDto() { AccountId = 1, IsClosed = false, Funds = 0, Timestamp = DateTime.Now }); accountStateRepo.Upsert(new AccountStateDto() { AccountId = 2, IsClosed = false, Funds = 0, Timestamp = DateTime.Now }); Account account1 = DtoToModelTranslator.FromDto(accountDto1, DateTime.Today, repositories); Account account2 = DtoToModelTranslator.FromDto(accountDto2, DateTime.Today, repositories); long id = 1; DateTime timestamp = DateTime.Now; long? sourceAccountId = accountDto1.Id.Value; long? destAccountId = accountDto2.Id.Value; Money transferAmount = 123.45; string memo = "memo"; //Act Transaction transaction = new Transaction(id, timestamp, sourceAccountId, destAccountId, transferAmount, memo, repositories); var propertyValues = transaction.GetPropertyValues().ToList(); //Assert Assert.Equal(6, propertyValues.Count); Assert.Equal(id, propertyValues.First(x => x.Property.Equals(Transaction.PROP_ID)).Value); Assert.Equal(timestamp, propertyValues.First(x => x.Property.Equals(Transaction.PROP_TIMESTAMP)).Value); Assert.Equal(account1, propertyValues.First(x => x.Property.Equals(Transaction.PROP_SOURCE)).Value); Assert.Equal(account2, propertyValues.First(x => x.Property.Equals(Transaction.PROP_DEST)).Value); Assert.Equal(memo, propertyValues.First(x => x.Property.Equals(Transaction.PROP_MEMO)).Value); Assert.Equal(transferAmount, propertyValues.First(x => x.Property.Equals(Transaction.PROP_AMOUNT)).Value); } }
public void TestGetLatestStateByAccountId_MultipleAccounts() { using (var testDbInfo = SetupUtil.CreateTestDb()) { //Arrange Mock <ILog> log = new Mock <ILog>(); AccountRepository accountRepo = new AccountRepository(testDbInfo.ConnectionString, log.Object); AccountStateRepository repo = new AccountStateRepository(testDbInfo.ConnectionString, log.Object); AccountDto account = new AccountDto() { AccountKind = Enums.AccountKind.Category, Description = String.Empty, Name = "account", Priority = 5, CategoryId = null }; AccountDto account2 = new AccountDto() { AccountKind = Enums.AccountKind.Category, Description = String.Empty, Name = "account2", Priority = 5, CategoryId = null }; bool isInsertSuccessful = accountRepo.Upsert(account); isInsertSuccessful &= accountRepo.Upsert(account2); DateTime state1Timestamp = DateTime.Now; AccountStateDto accountState = new AccountStateDto() { AccountId = account.Id.Value, Funds = (new Money(100)).InternalValue, IsClosed = false, Timestamp = state1Timestamp }; isInsertSuccessful &= repo.Upsert(accountState); DateTime state2Timestamp = state1Timestamp.AddDays(-1); AccountStateDto accountState2 = new AccountStateDto() { AccountId = account.Id.Value, Funds = (new Money(500)).InternalValue, IsClosed = false, Timestamp = state2Timestamp }; isInsertSuccessful &= repo.Upsert(accountState2); DateTime state3Timestamp = state1Timestamp.AddDays(-2); AccountStateDto accountState3 = new AccountStateDto() { AccountId = account.Id.Value, Funds = (new Money(800)).InternalValue, IsClosed = false, Timestamp = state3Timestamp }; isInsertSuccessful &= repo.Upsert(accountState3); //This should be the most recent state, but doesn't belong to the original account DateTime state4Timestamp = state1Timestamp.AddDays(5); AccountStateDto accountState4 = new AccountStateDto() { AccountId = account2.Id.Value, Funds = (new Money(800)).InternalValue, IsClosed = false, Timestamp = state3Timestamp }; isInsertSuccessful &= repo.Upsert(accountState4); //Act AccountStateDto latest = repo.GetLatestByAccountId(account.Id.Value); //Assert Assert.True(isInsertSuccessful); Assert.Equal(state1Timestamp, latest.Timestamp); Assert.Equal(100, new Money(latest.Funds, true)); } }
public async Task Instance_Post_WithNæringOgSkattemelding_ValidateOk() { string token = PrincipalUtil.GetToken(1337); HttpClient client = SetupUtil.GetTestClient(_factory, "tdd", "sirius"); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); HttpRequestMessage httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, "/tdd/sirius/instances?instanceOwnerPartyId=1337"); HttpResponseMessage response = await client.SendAsync(httpRequestMessage); string responseContent = await response.Content.ReadAsStringAsync(); Instance instance = JsonConvert.DeserializeObject <Instance>(responseContent); Assert.Equal(HttpStatusCode.Created, response.StatusCode); Assert.NotNull(instance); Assert.Equal("1337", instance.InstanceOwner.PartyId); // Get Data from Instance HttpRequestMessage httpRequestMessageGetData = new HttpRequestMessage(HttpMethod.Get, "/tdd/sirius/instances/" + instance.Id + "/data/" + instance.Data[0].Id); HttpResponseMessage responseData = await client.SendAsync(httpRequestMessageGetData); string responseContentData = await responseData.Content.ReadAsStringAsync(); Skjema siriusMainForm = (Skjema)JsonConvert.DeserializeObject(responseContentData, typeof(Skjema)); // Modify the prefilled form. This would need to be replaced with the real sirius form siriusMainForm.Permisjonsopplysningergrp8822 = new Permisjonsopplysningergrp8822(); siriusMainForm.Permisjonsopplysningergrp8822.AnsattEierandel20EllerMerdatadef33294 = new AnsattEierandel20EllerMerdatadef33294() { value = "50" }; XmlSerializer serializer = new XmlSerializer(typeof(Skjema)); using MemoryStream stream = new MemoryStream(); serializer.Serialize(stream, siriusMainForm); stream.Position = 0; StreamContent streamContent = new StreamContent(stream); streamContent.Headers.ContentType = MediaTypeHeaderValue.Parse("application/xml"); HttpResponseMessage putresponse = await client.PutAsync("/tdd/sirius/instances/" + instance.Id + "/data/" + instance.Data[0].Id, streamContent); // Add Næringsoppgave.xml string næringsppgave = File.ReadAllText("Data/Files/data-element.xml"); byte[] byteArray = Encoding.UTF8.GetBytes(næringsppgave); MemoryStream næringsoppgavestream = new MemoryStream(byteArray); StreamContent streamContentNæring = new StreamContent(næringsoppgavestream); streamContentNæring.Headers.ContentType = MediaTypeHeaderValue.Parse("text/xml"); streamContentNæring.Headers.ContentDisposition = ContentDispositionHeaderValue.Parse("attachment; filename=data-element.xml"); HttpResponseMessage postresponseNæring = await client.PostAsync("/tdd/sirius/instances/" + instance.Id + "/data/?datatype=næringsoppgave", streamContentNæring); DataElement dataElementNæring = (DataElement)JsonConvert.DeserializeObject(await postresponseNæring.Content.ReadAsStringAsync(), typeof(DataElement)); // Add skattemelding.xml string skattemelding = File.ReadAllText("Data/Files/data-element.xml"); byte[] byteArraySkattemelding = Encoding.UTF8.GetBytes(næringsppgave); MemoryStream skattemeldingstream = new MemoryStream(byteArraySkattemelding); StreamContent streamContentSkattemelding = new StreamContent(skattemeldingstream); streamContent.Headers.ContentType = MediaTypeHeaderValue.Parse("text/xml"); HttpResponseMessage postresponseskattemelding = await client.PostAsync("/tdd/sirius/instances/" + instance.Id + "/data/?datatype=skattemelding", streamContentNæring); DataElement dataElementSkattemelding = (DataElement)JsonConvert.DeserializeObject(await postresponseskattemelding.Content.ReadAsStringAsync(), typeof(DataElement)); // Validate instance string url = "/tdd/sirius/instances/" + instance.Id + "/validate"; HttpResponseMessage responseValidation = await client.GetAsync(url); string responseContentValidation = await responseValidation.Content.ReadAsStringAsync(); List <ValidationIssue> messages = (List <ValidationIssue>)JsonConvert.DeserializeObject(responseContentValidation, typeof(List <ValidationIssue>)); Assert.Empty(messages); TestDataUtil.DeleteInstanceAndData("tdd", "sirius", 1337, new Guid(instance.Id.Split('/')[1])); }
public void TestGetChildAccountIds() { using (var testDbInfo = SetupUtil.CreateTestDb()) { //Arrange Mock <ILog> log = new Mock <ILog>(); AccountRepository repo = new AccountRepository(testDbInfo.ConnectionString, log.Object); AccountDto parent = new AccountDto() { AccountKind = Enums.AccountKind.Category, Description = String.Empty, Name = "parent", Priority = 5, CategoryId = null }; bool isParentInsertSuccessful = repo.Upsert(parent); AccountDto child1 = new AccountDto() { AccountKind = Enums.AccountKind.Category, Description = String.Empty, Name = "child1", Priority = 5, CategoryId = parent.Id }; bool isChild1InsertSuccessful = repo.Upsert(child1); AccountDto unrelated = new AccountDto() { AccountKind = Enums.AccountKind.Category, Description = String.Empty, Name = "unrelated", Priority = 5, CategoryId = null }; bool isUnrelatedInsertSuccessful = repo.Upsert(unrelated); AccountDto child2 = new AccountDto() { AccountKind = Enums.AccountKind.Category, Description = String.Empty, Name = "child2", Priority = 5, CategoryId = parent.Id }; bool isChild2InsertSuccessful = repo.Upsert(child2); //Act var childIds = repo.GetChildAccountIds(parent.Id.Value); //Assert Assert.True(isParentInsertSuccessful); Assert.True(isChild1InsertSuccessful); Assert.True(isChild2InsertSuccessful); Assert.True(childIds.Contains(child1.Id.Value)); Assert.True(childIds.Contains(child2.Id.Value)); Assert.False(childIds.Contains(unrelated.Id.Value)); } }