public void WHEN_Patch2_is_applied_with_multiples_changes_THEN_sum_change_to_correct_value() { var basket = JsonConvert.DeserializeObject<StockMarketOrders>(TestData.ORIGINAL_DATA); var patch = JsonConvert.DeserializeObject<List<Operation<StockMarketOrders>>>(TestData.PATCH_2); JsonPatchDocument<StockMarketOrders> doc = new JsonPatchDocument<StockMarketOrders>(patch); doc.ApplyTo(basket); var sum = basket.Select(x => x.Price).Sum(); //expected = original sum + sum(- item source price + item new price) var expectedSum = 718 + (-78 + 0) + (-77 + 13) + (-22 + 27); Check.That(sum).IsEqualTo(expectedSum);//=581 }
public void WHEN_Patch1_is_applied_THEN_sum_change_to_correct_value() { var basket = JsonConvert.DeserializeObject<StockMarketOrders>(TestData.ORIGINAL_DATA); var patch = JsonConvert.DeserializeObject<List<Operation<StockMarketOrders>>>(TestData.PATCH_1); JsonPatchDocument<StockMarketOrders> doc = new JsonPatchDocument<StockMarketOrders>(patch); doc.ApplyTo(basket); var sum = basket.Select(x => x.Price).Sum(); var expectedSum = 718 - 60 + 95; //on patch one only one value changed from 60 to 95 Check.That(sum).IsEqualTo(expectedSum); }
public void WHEN_Two_patches_are_applied_THEN_sum_change_to_correct_value() { var basket = JsonConvert.DeserializeObject<StockMarketOrders>(TestData.ORIGINAL_DATA); var patch1 = JsonConvert.DeserializeObject<List<Operation<StockMarketOrders>>>(TestData.PATCH_1); var patch2 = JsonConvert.DeserializeObject<List<Operation<StockMarketOrders>>>(TestData.PATCH_2); JsonPatchDocument<StockMarketOrders> documentPatcher1 = new JsonPatchDocument<StockMarketOrders>(patch1); JsonPatchDocument<StockMarketOrders> documentPatcher2 = new JsonPatchDocument<StockMarketOrders>(patch2); documentPatcher1.ApplyTo(basket); documentPatcher2.ApplyTo(basket); var sum = basket.Select(x => x.Price).Sum(); Check.That(sum).IsEqualTo(616); }
public void AddToList() { var doc = new SimpleDTO() { IntegerList = new List<int>() { 1, 2, 3 } }; // create patch JsonPatchDocument<SimpleDTO> patchDoc = new JsonPatchDocument<SimpleDTO>(); patchDoc.Add<int>(o => o.IntegerList, 4, 0); patchDoc.ApplyTo(doc); Assert.Equal(new List<int>() { 4, 1, 2, 3 }, doc.IntegerList); }
public void ReplacePropertyInNestedObject() { var doc = new SimpleDTOWithNestedDTO() { IntegerValue = 1 }; // create patch JsonPatchDocument<SimpleDTOWithNestedDTO> patchDoc = new JsonPatchDocument<SimpleDTOWithNestedDTO>(); patchDoc.Replace<string>(o => o.NestedDTO.StringProperty, "B"); patchDoc.ApplyTo(doc); Assert.Equal("B", doc.NestedDTO.StringProperty); }
public async Task <int> Patch(int id, JsonPatchDocument <UserProfile>?userProfilePatch) { using IDbConnection connection = GetConnection(); using var transaction = connection.BeginTransaction(); var userProfileDto = await connection.GetAsync <UserProfileDto>(id, transaction); if (userProfileDto == null) { return(HttpBadRequest); } var userProfile = _profileMapper.Map <UserProfile>(userProfileDto); userProfilePatch?.ApplyTo(userProfile); await connection.UpdateAsync(userProfileDto, transaction); return(HttpOk); }
public void AddResultsShouldReplace() { // Arrange var doc = new SimpleDTO() { StringProperty = "A" }; // create patch var patchDoc = new JsonPatchDocument<SimpleDTO>(); patchDoc.Add<string>(o => o.StringProperty, "B"); // Act patchDoc.ApplyTo(doc); // Assert Assert.Equal("B", doc.StringProperty); }
public void AddResultsShouldReplace() { var doc = new SimpleDTO() { StringProperty = "A" }; // create patch JsonPatchDocument<SimpleDTO> patchDoc = new JsonPatchDocument<SimpleDTO>(); patchDoc.Add<string>(o => o.StringProperty, "B"); patchDoc.ApplyTo(doc); var s = new Operations.Operation(); Assert.Equal("B", doc.StringProperty); }
public HttpStatusCode PingUpdate(int id, [FromBody] JsonPatchDocument <ChannelInfo?> data) { var chann = MasterClientListSingleton.Instance.Channels.FirstOrDefault(s => s.Id == id); if (chann == null) { return(HttpStatusCode.NotFound); } if ((chann.LastPing.AddSeconds(10) < SystemTime.Now()) && !Debugger.IsAttached) { MasterClientListSingleton.Instance.Channels.RemoveAll(s => s.Id == _id); _logger.Warning(LogLanguage.Instance.GetMessageFromKey(LogLanguageKey.CONNECTION_LOST), _id.ToString(CultureInfo.CurrentCulture)); return(HttpStatusCode.RequestTimeout); } data?.ApplyTo(chann); return(HttpStatusCode.OK); }
public void ReplaceNestedObject() { // Arrange var doc = new SimpleDTOWithNestedDTO() { IntegerValue = 1 }; var newNested = new NestedDTO() { StringProperty = "B" }; // create patch var patchDoc = new JsonPatchDocument<SimpleDTOWithNestedDTO>(); patchDoc.Replace<NestedDTO>(o => o.NestedDTO, newNested); // Act patchDoc.ApplyTo(doc); // Assert Assert.Equal("B", doc.NestedDTO.StringProperty); }
public async Task <OrderEditDto> PatchOrderAsync(string id, JsonPatchDocument <OrderEditDto> model) { await _activityLog.Post(id, ActivityType.Update); var order = await _context.Orders.SingleOrDefaultAsync(w => w.Id == id); var tmp = Mapper.Map <OrderEditDto>(order); model?.ApplyTo(tmp); Mapper.Map(order, tmp); ChangeStatus(order); _context.Orders.Update(order); await _context.SaveChangesAsync(); return(Mapper.Map <OrderEditDto>(order)); }
public async Task <IActionResult> UpdateDelivery(string id, [FromBody] JsonPatchDocument <Models.Delivery> patch) { IActionResult result = null; Models.Delivery delivery = null; try { if (string.IsNullOrEmpty(id)) { return(BadRequest($"The id {id} is not valid (null or empty)")); } if (patch == null) { return(BadRequest($"The patch argument is not valid")); } delivery = await _repository.GetDeliveryByIdAsync(id); if (delivery != null) { patch?.ApplyTo(delivery); delivery = await _repository.UpdateDeliveryAsync(id, delivery); result = Ok(delivery); } else { result = NotFound($"The delivery with id {id} was not found"); } return(result); } catch (Exception ex) { throw new DeliveryDomainException("An error caused an exception", ex); } }
public ActionResult PatchComment(int id, JsonPatchDocument <CommentUpdateDto> patch) { var oldCom = _repository.Find(id); if (oldCom == null) { return(NotFound()); } var comToPatch = _mapper.Map <CommentUpdateDto>(oldCom); patch.ApplyTo(comToPatch, ModelState); if (!TryValidateModel(comToPatch)) { return(ValidationProblem(ModelState)); } _mapper.Map(comToPatch, oldCom); _repository.Save(); return(NoContent()); }
public void CreatePatch() { var mapper = new ApiEventModelMapper(); var model = new ApiEventRequestModel(); model.SetProperties(1, "A", "A", "A", "A", DateTimeOffset.Parse("1/1/1987 12:00:00 AM"), "A", "A", "A", "A", "A"); JsonPatchDocument <ApiEventRequestModel> patch = mapper.CreatePatch(model); var response = new ApiEventRequestModel(); patch.ApplyTo(response); response.AutoId.Should().Be(1); response.Category.Should().Be("A"); response.EnvironmentId.Should().Be("A"); response.JSON.Should().Be("A"); response.Message.Should().Be("A"); response.Occurred.Should().Be(DateTimeOffset.Parse("1/1/1987 12:00:00 AM")); response.ProjectId.Should().Be("A"); response.RelatedDocumentIds.Should().Be("A"); response.TenantId.Should().Be("A"); response.UserId.Should().Be("A"); response.Username.Should().Be("A"); }
public void CopyPropertyValue_ToDynamicTestObject_WithCustomNamingStrategy() { // Arrange var jsonSerializerOptions = new JsonSerializerOptions { DictionaryKeyPolicy = new TestDictionaryNamingStrategy() }; dynamic targetObject = new DynamicTestObject(); targetObject.customStringProperty = "A"; targetObject.customAnotherStringProperty = "B"; var patchDocument = new JsonPatchDocument(); patchDocument.Copy("StringProperty", "AnotherStringProperty"); // Act patchDocument.ApplyTo(targetObject, jsonSerializerOptions); // Assert Assert.Equal("A", targetObject.customAnotherStringProperty); }
public void Move_ToNonExistingProperty() { // Arrange dynamic targetObject = new ExpandoObject(); targetObject.StringProperty = "A"; var patchDocument = new JsonPatchDocument(); patchDocument.Move("StringProperty", "AnotherStringProperty"); // Act patchDocument.ApplyTo(targetObject); Assert.Equal("A", targetObject.AnotherStringProperty); var cont = targetObject as IDictionary <string, object>; cont.TryGetValue("StringProperty", out var valueFromDictionary); // Assert Assert.Null(valueFromDictionary); }
public ActionResult PartialUserUpdate(int id, JsonPatchDocument <UserUpdateDto> patchDoc) { var userModelFromRepo = _repository.GetUserById(id); if (userModelFromRepo == null) { return(NotFound()); } var userToPatch = _mapper.Map <UserUpdateDto>(userModelFromRepo); patchDoc.ApplyTo(userToPatch, ModelState); if (!TryValidateModel(userToPatch)) { return(ValidationProblem(ModelState)); } _mapper.Map(userToPatch, userModelFromRepo); _repository.UpdateUser(userModelFromRepo); _repository.SaveChanges(); return(NoContent()); }
/// <summary> /// Applies JSON patch operations on object and logs errors in <see cref="ModelStateDictionary"/>. /// </summary> /// <param name="patchDoc">The <see cref="JsonPatchDocument{T}"/>.</param> /// <param name="objectToApplyTo">The entity on which <see cref="JsonPatchDocument{T}"/> is applied.</param> /// <param name="objectAdapter">Object Adapter to use</param> /// <param name="modelState">The <see cref="ModelStateDictionary"/> to add errors.</param> public static void ApplyTo <T>( this JsonPatchDocument <T> patchDoc, T objectToApplyTo, IObjectAdapter objectAdapter, ModelStateDictionary modelState) where T : class { if (patchDoc == null) { throw new ArgumentNullException(nameof(patchDoc)); } if (objectToApplyTo == null) { throw new ArgumentNullException(nameof(objectToApplyTo)); } if (modelState == null) { throw new ArgumentNullException(nameof(modelState)); } patchDoc.ApplyTo(objectToApplyTo, objectAdapter, modelState, string.Empty); }
public ActionResult PartialCommandUpdate(int id, JsonPatchDocument <CommandUpdateDto> patchDoc) { var commandModelFromRepo = _repository.GetCommandById(id); if (commandModelFromRepo == null) { return(NotFound()); } var commandToPatch = _mapper.Map <CommandUpdateDto>(commandModelFromRepo); patchDoc.ApplyTo(commandToPatch, ModelState); if (!TryValidateModel(commandToPatch)) { return(ValidationProblem(ModelState)); } _mapper.Map(commandToPatch, commandModelFromRepo); _repository.UpdateCommand(commandModelFromRepo); _repository.SaveChanges(); return(NoContent()); }
// PATCH /api/[controller]/{id} public virtual async Task <ActionResult <TViewModel> > Patch(TKey parentId, TKey id, [FromBody] JsonPatchDocument <TViewModel> patch) { var entity = await Database.Set <TData>().FindAsync(id); if (entity == null) { return(NotFound(id)); } if (!await Permissions.AllowWrite(await CurrentUser, entity) || entity.Deleted) { return(Forbid()); } var dto = await CreateViewModelAsync(entity); patch.ApplyTo(dto); await UpdateDataModelAsync(entity, dto); await Database.SaveChangesAsync(); return(Ok(await CreateViewModelAsync(entity))); }
public async Task <IActionResult> PartialUpdate(int id, [FromBody] JsonPatchDocument <Message> jsonPatch, [FromHeader(Name = "Accept")] string mediaType) { //JSONPatch if (jsonPatch == null) { return(BadRequest()); } var message = await _repo.FindMessageAsync(id); jsonPatch.ApplyTo(message); message.Updated = DateTime.UtcNow; await _repo.UpdateAsync(message); if (mediaType == CustomMediaType.Hateoas) { var dtomessage = _mapper.Map <Message, DTOMessage>(message); dtomessage.Links.Add(new DTOLink("update", Url.Link("PartialUpdate", new { id = message.Id }), "PATCH")); } return(NoContent()); }
public void ApplyTo_InvalidPatchOperations_AddsModelStateError( string op, string path, string from, string value, string error) { // Arrange var patch = new JsonPatchDocument <Customer>(); patch.Operations.Add(new Operation <Customer>(op, path, from, value)); var model = new Customer(); var modelState = new ModelStateDictionary(); // Act patch.ApplyTo(model, modelState); // Assert Assert.Equal(1, modelState.ErrorCount); Assert.Equal(nameof(Customer), modelState.First().Key); Assert.Single(modelState.First().Value.Errors); Assert.Equal(error, modelState.First().Value.Errors.First().ErrorMessage); }
public async Task <ActionResult> UpdatePartial([FromRoute] int id, [FromBody] JsonPatchDocument <UpdateClientDTO> patchClientDTO) { Client client = await _clientRepository.FindByIdAsync(id); if (client.IsNull()) { return(NotFound()); } UpdateClientDTO clientDTO = _mapper.Map <UpdateClientDTO>(client); patchClientDTO.ApplyTo(clientDTO); if (!TryValidateModel(clientDTO)) { return(ValidationProblem(ModelState)); } _mapper.Map(clientDTO, client); await _clientRepository.UpdateAsync(client); return(NoContent()); }
public virtual async Task <ActionResult> Update(TKey id, JsonPatchDocument <TEntityForUpdatingDto> patchDocument) { var entity = await Repository.ReadAsync(id); if (entity == null) { return(NotFound()); } var entityForUpdatingDto = Mapper.Map <TEntityForUpdatingDto>(entity); patchDocument.ApplyTo(entityForUpdatingDto, (Microsoft.AspNetCore.JsonPatch.Adapters.IObjectAdapter)ModelState); if (!TryValidateModel(entityForUpdatingDto)) { return(ValidationProblem(ModelState)); //TODO Баг: дает 400 ошибку вместо 422 } Mapper.Map(entityForUpdatingDto, entity); Repository.Update(entity); await Repository.SaveAsync(); return(NoContent()); }
public ActionResult PartialUpdateMovie(int id, JsonPatchDocument <MovieUpdateDTO> patchDoc) { var movieFromDb = _repository.GetMovieById(id); if (movieFromDb == null) { return(NotFound()); } var movieUpdateDTO = _mapper.Map <MovieUpdateDTO>(movieFromDb); patchDoc.ApplyTo(movieUpdateDTO, ModelState); if (!TryValidateModel(movieUpdateDTO)) { return(ValidationProblem(ModelState)); } _mapper.Map(movieUpdateDTO, movieFromDb); _repository.UpdateMovie(movieFromDb); _repository.SaveChanges(); return(NoContent()); }
public async Task <ActionResult> Patch(Guid id, [FromBody] JsonPatchDocument <Pessoa> patchPessoa) { if (patchPessoa == null) { return(BadRequest()); } var pessoaDB = await _context.Pessoas.FirstOrDefaultAsync(p => p.ID == id); if (pessoaDB == null) { return(NotFound()); } patchPessoa.ApplyTo(pessoaDB, ModelState); var isValid = TryValidateModel(pessoaDB); if (!isValid) { return(BadRequest(ModelState)); } await _context.SaveChangesAsync(); return(NoContent()); }
public IActionResult UpdateProduct(long id, [FromBody] JsonPatchDocument <ProductData> patch) { Product product = context.Products.Include(p => p.Supplier) .First(p => p.ProductId == id); ProductData pdata = new ProductData { Product = product }; patch.ApplyTo(pdata, ModelState); if (ModelState.IsValid && TryValidateModel(pdata)) { if (product.Supplier != null && product.Supplier.Id != 0) { context.Attach(product.Supplier); } context.SaveChanges(); return(Ok()); } else { return(BadRequest(ModelState)); } }
public IActionResult UpdateParty(int id, [FromBody] JsonPatchDocument <DomainParty> patchDoc) { var domainParty = _partyService.GetParty(id); Authorize.TokenAgainstResource(HttpContext.User, domainParty.CustomerId); Validate <DomainParty> .EmptyPatchRequest(patchDoc); Validate <DomainParty> .PatchRestrictedFields(patchDoc, _allowedPatchFields); patchDoc.ApplyTo(domainParty, ModelState); if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var isNotifyRequest = ValidateNotifyRequest(domainParty, patchDoc); _partyService.UpdateParty(domainParty, isNotifyRequest); return(Ok()); }
public ActionResult UpdateSprint(int id, JsonPatchDocument <SprintUpdateDto> jsonPatchDocument) { var sprint = _repository.GetSprintById(id); if (sprint == null) { return(NotFound()); } var sprintToPatch = _mapper.Map <SprintUpdateDto>(sprint); jsonPatchDocument.ApplyTo(sprintToPatch, ModelState); if (!TryValidateModel(sprintToPatch)) { return(ValidationProblem(ModelState)); } _mapper.Map(sprintToPatch, sprint); _repository.SaveChanges(); return(NoContent()); }
public async Task <IActionResult> PatchFinancierInfo(Guid financierId, [FromBody] JsonPatchDocument <EditFinancierInfo> patchDoc) { try { if (patchDoc is null) { _logger.LogError("patchDoc object sent from client is null."); return(BadRequest("patchDoc object is null.")); } var writeModel = HttpContext.Items["EditFinancierInfo"] as EditFinancierInfo; patchDoc.ApplyTo(writeModel); await _commandHandler.Handle(writeModel); return(Ok()); } catch (Exception ex) { _logger.LogError(ex.Message); return(BadRequest(ex.Message)); } }
public async Task <ActionResult> PartiallyUpdateUser(Guid userId, JsonPatchDocument <BasicUserData> patchDocument) { User userFromRepo = await _userRepository.GetUserAsync(userId); if (userFromRepo == null) { return(NotFound()); } BasicUserData userToPatch = _mapper.Map <BasicUserData>(userFromRepo); patchDocument.ApplyTo(userToPatch, ModelState); if (!TryValidateModel(userToPatch)) { return(ValidationProblem(ModelState)); } _mapper.Map(userToPatch, userFromRepo); await _userRepository.UpdateUserAsync(userFromRepo); return(NoContent()); }
public IActionResult PatchCustomer(int id, [FromBody] JsonPatchDocument <CustomerUpdateDTO> patchDoc) { var customer = _customerManager.GetById(id); if (customer == null) { return(NotFound()); } var customerDto = _mapper.Map <CustomerUpdateDTO>(customer); patchDoc.ApplyTo(customerDto); _mapper.Map(customerDto, customer); var isUpdated = _customerManager.Update(customer); if (isUpdated) { return(Ok()); } else { return(BadRequest("Update Failed!")); } }
public void AddProperty_ToDynamicTestObject_WithCustomNamingStrategy() { // Arrange var jsonSerializerOptions = new JsonSerializerOptions { DictionaryKeyPolicy = new TestDictionaryNamingStrategy() }; dynamic targetObject = new DynamicTestObject(); targetObject.Test = 1; var patchDocument = new JsonPatchDocument(); patchDocument.Add("NewInt", 1); // Act patchDocument.ApplyTo(targetObject, jsonSerializerOptions); // Assert Assert.Equal(1, targetObject.customNewInt); Assert.Equal(1, targetObject.Test); }
public void MoveIntegerValue_ToAnotherIntegerProperty() { // Arrange var targetObject = new SimpleObjectWithNestedObject() { SimpleObject = new SimpleObject() { IntegerValue = 2, AnotherIntegerValue = 3 } }; var patchDocument = new JsonPatchDocument <SimpleObjectWithNestedObject>(); patchDocument.Move(o => o.SimpleObject.IntegerValue, o => o.SimpleObject.AnotherIntegerValue); // Act patchDocument.ApplyTo(targetObject); // Assert Assert.Equal(2, targetObject.SimpleObject.AnotherIntegerValue); Assert.Equal(0, targetObject.SimpleObject.IntegerValue); }
public void CreatePatch() { var mapper = new ApiFileModelMapper(); var model = new ApiFileRequestModel(); model.SetProperties(1, DateTime.Parse("1/1/1987 12:00:00 AM"), "A", DateTime.Parse("1/1/1987 12:00:00 AM"), "A", Guid.Parse("8420cdcf-d595-ef65-66e7-dff9f98764da"), 1, 1, "A", "A", "A"); JsonPatchDocument <ApiFileRequestModel> patch = mapper.CreatePatch(model); var response = new ApiFileRequestModel(); patch.ApplyTo(response); response.BucketId.Should().Be(1); response.DateCreated.Should().Be(DateTime.Parse("1/1/1987 12:00:00 AM")); response.Description.Should().Be("A"); response.Expiration.Should().Be(DateTime.Parse("1/1/1987 12:00:00 AM")); response.Extension.Should().Be("A"); response.ExternalId.Should().Be(Guid.Parse("8420cdcf-d595-ef65-66e7-dff9f98764da")); response.FileSizeInByte.Should().Be(1); response.FileTypeId.Should().Be(1); response.Location.Should().Be("A"); response.PrivateKey.Should().Be("A"); response.PublicKey.Should().Be("A"); }
public ActionResult <MenuItemReadDto> PartialUpdateMenuItem(int id, [FromBody] JsonPatchDocument <MenuItemUpdateDto> patchDocument) { var menuItemModelFromRepo = _menuItemRepo.GetElementById(id); if (menuItemModelFromRepo == null) { return(NotFound()); } var menuItemPatch = _mapper.Map <MenuItemUpdateDto>(menuItemModelFromRepo); patchDocument.ApplyTo(menuItemPatch, ModelState); if (!TryValidateModel(menuItemPatch)) { return(ValidationProblem(ModelState)); } _mapper.Map(menuItemPatch, menuItemModelFromRepo); _menuItemRepo.UpdateMenuItem(menuItemModelFromRepo); _menuItemRepo.SaveChanges(); return(NoContent()); }
public ActionResult PartialContactUpdate(int id, JsonPatchDocument <ContactUpdateDto> patchDocument) { var existingContactFromDb = _repository.GetContactById(id); if (existingContactFromDb == null) { return(NotFound()); } var contactToPatch = _mapper.Map <ContactUpdateDto>(existingContactFromDb); patchDocument.ApplyTo(contactToPatch, ModelState); if (!TryValidateModel(contactToPatch)) { return(ValidationProblem(ModelState)); } _mapper.Map(contactToPatch, existingContactFromDb); _repository.UpdateContact(existingContactFromDb); _repository.SaveChanges(); return(NoContent()); }
public async Task <IActionResult> PartiallyUpdate(int id, [FromBody] JsonPatchDocument <SubItemDetailModel> model) { if (id == 0) { return(BadRequest()); } var record = await repo.GetOneAsync <SubItemDetail, SubItemDetailModel>(id); if (record == null) { return(NotFound()); } model.ApplyTo(record, ModelState); if (!ModelState.IsValid) { return(BadRequest(ModelState)); } await repo.UpdateAsync <SubItemDetail, SubItemDetailModel>(record); return(NoContent()); }
public void MoveFomListToNonListBetweenHierarchy() { var doc = new SimpleDTOWithNestedDTO() { SimpleDTO = new SimpleDTO() { IntegerList = new List<int>() { 1, 2, 3 } } }; // create patch JsonPatchDocument<SimpleDTOWithNestedDTO> patchDoc = new JsonPatchDocument<SimpleDTOWithNestedDTO>(); patchDoc.Move<int>(o => o.SimpleDTO.IntegerList, 0, o => o.IntegerValue); patchDoc.ApplyTo(doc); Assert.Equal(new List<int>() { 2, 3 }, doc.SimpleDTO.IntegerList); Assert.Equal(1, doc.IntegerValue); }
public void CopyFromNonListToList() { var doc = new SimpleDTOWithNestedDTO() { SimpleDTO = new SimpleDTO() { IntegerValue = 5, IntegerList = new List<int>() { 1, 2, 3 } } }; // create patch JsonPatchDocument<SimpleDTOWithNestedDTO> patchDoc = new JsonPatchDocument<SimpleDTOWithNestedDTO>(); patchDoc.Copy<int>(o => o.SimpleDTO.IntegerValue, o => o.SimpleDTO.IntegerList, 0); patchDoc.ApplyTo(doc); Assert.Equal(new List<int>() { 5, 1, 2, 3 }, doc.SimpleDTO.IntegerList); }
public void MoveInList() { var doc = new SimpleDTOWithNestedDTO() { SimpleDTO = new SimpleDTO() { IntegerList = new List<int>() { 1, 2, 3 } } }; // create patch JsonPatchDocument<SimpleDTOWithNestedDTO> patchDoc = new JsonPatchDocument<SimpleDTOWithNestedDTO>(); patchDoc.Move<int>(o => o.SimpleDTO.IntegerList, 0, o => o.SimpleDTO.IntegerList, 1); patchDoc.ApplyTo(doc); Assert.Equal(new List<int>() { 2, 1, 3 }, doc.SimpleDTO.IntegerList); }
public void Replace() { var doc = new SimpleDTOWithNestedDTO() { SimpleDTO = new SimpleDTO() { StringProperty = "A", DecimalValue = 10 } }; // create patch JsonPatchDocument<SimpleDTOWithNestedDTO> patchDoc = new JsonPatchDocument<SimpleDTOWithNestedDTO>(); patchDoc.Replace<string>(o => o.SimpleDTO.StringProperty, "B"); patchDoc.Replace(o => o.SimpleDTO.DecimalValue, 12); patchDoc.ApplyTo(doc); Assert.Equal("B", doc.SimpleDTO.StringProperty); Assert.Equal(12, doc.SimpleDTO.DecimalValue); }
public void RemoveFromListInvalidPositionTooLarge_LogsError() { // Arrange var doc = new SimpleDTO() { IntegerList = new List<int>() { 1, 2, 3 } }; // create patch var patchDoc = new JsonPatchDocument<SimpleDTO>(); patchDoc.Remove<int>(o => o.IntegerList, 3); var logger = new TestErrorLogger<SimpleDTO>(); // Act patchDoc.ApplyTo(doc, logger.LogErrorMessage); // Assert Assert.Equal( "For operation 'remove' on array property at path '/integerlist/3', the index is " + "larger than the array size.", logger.ErrorMessage); }
public void Remove() { // Arrange var doc = new SimpleDTO() { StringProperty = "A" }; // create patch var patchDoc = new JsonPatchDocument<SimpleDTO>(); patchDoc.Remove<string>(o => o.StringProperty); // Act patchDoc.ApplyTo(doc); // Assert Assert.Equal(null, doc.StringProperty); }
public void AddToListAppend() { var doc = new SimpleDTOWithNestedDTO() { SimpleDTO = new SimpleDTO() { IntegerList = new List<int>() { 1, 2, 3 } } }; // create patch JsonPatchDocument<SimpleDTOWithNestedDTO> patchDoc = new JsonPatchDocument<SimpleDTOWithNestedDTO>(); patchDoc.Add<int>(o => o.SimpleDTO.IntegerList, 4); patchDoc.ApplyTo(doc); Assert.Equal(new List<int>() { 1, 2, 3, 4 }, doc.SimpleDTO.IntegerList); }
public void ReplaceInList() { // Arrange var doc = new SimpleDTO() { IntegerList = new List<int>() { 1, 2, 3 } }; // create patch var patchDoc = new JsonPatchDocument<SimpleDTO>(); patchDoc.Replace<int>(o => o.IntegerList, 5, 0); // Act patchDoc.ApplyTo(doc); // Assert Assert.Equal(new List<int>() { 5, 2, 3 }, doc.IntegerList); }
public void ReplaceFullListFromEnumerable() { // Arrange var doc = new SimpleDTO() { IntegerList = new List<int>() { 1, 2, 3 } }; // create patch var patchDoc = new JsonPatchDocument<SimpleDTO>(); patchDoc.Replace<IEnumerable<int>>(o => o.IntegerList, new List<int>() { 4, 5, 6 }); // Act patchDoc.ApplyTo(doc); // Assert Assert.Equal(new List<int>() { 4, 5, 6 }, doc.IntegerList); }
public void Replace() { // Arrange var doc = new SimpleDTO() { StringProperty = "A", DecimalValue = 10 }; // create patch var patchDoc = new JsonPatchDocument<SimpleDTO>(); patchDoc.Replace<string>(o => o.StringProperty, "B"); patchDoc.Replace(o => o.DecimalValue, 12); // Act patchDoc.ApplyTo(doc); // Assert Assert.Equal("B", doc.StringProperty); Assert.Equal(12, doc.DecimalValue); }
public void RemoveFromListInvalidPositionTooSmall_LogsError() { // Arrange var doc = new SimpleDTO() { IntegerList = new List<int>() { 1, 2, 3 } }; // create patch var patchDoc = new JsonPatchDocument<SimpleDTO>(); patchDoc.Remove<int>(o => o.IntegerList, -1); var logger = new TestErrorLogger<SimpleDTO>(); // Act patchDoc.ApplyTo(doc, logger.LogErrorMessage); // Assert Assert.Equal("Property does not exist at path '/integerlist/-1'.", logger.ErrorMessage); }
public void RemoveFromListInvalidPositionTooSmall() { // Arrange var doc = new SimpleDTO() { IntegerList = new List<int>() { 1, 2, 3 } }; // create patch var patchDoc = new JsonPatchDocument<SimpleDTO>(); patchDoc.Remove<int>(o => o.IntegerList, -1); // Act & Assert var exception = Assert.Throws<JsonPatchException<SimpleDTO>>(() => { patchDoc.ApplyTo(doc); }); Assert.Equal("Property does not exist at path '/integerlist/-1'.", exception.Message); }
public void MoveToEndOfList() { var doc = new SimpleDTOWithNestedDTO() { SimpleDTO = new SimpleDTO() { IntegerValue = 5, IntegerList = new List<int>() { 1, 2, 3 } } }; // create patch JsonPatchDocument<SimpleDTOWithNestedDTO> patchDoc = new JsonPatchDocument<SimpleDTOWithNestedDTO>(); patchDoc.Move<int>(o => o.SimpleDTO.IntegerValue, o => o.SimpleDTO.IntegerList); patchDoc.ApplyTo(doc); Assert.Equal(0, doc.IntegerValue); Assert.Equal(new List<int>() { 1, 2, 3, 5 }, doc.SimpleDTO.IntegerList); }
public void ReplaceAtEndOfList() { var doc = new SimpleDTOWithNestedDTO() { SimpleDTO = new SimpleDTO() { IntegerList = new List<int>() { 1, 2, 3 } } }; // create patch JsonPatchDocument<SimpleDTOWithNestedDTO> patchDoc = new JsonPatchDocument<SimpleDTOWithNestedDTO>(); patchDoc.Replace<int>(o => o.SimpleDTO.IntegerList, 5); patchDoc.ApplyTo(doc); Assert.Equal(new List<int>() { 1, 2, 5 }, doc.SimpleDTO.IntegerList); }
public void AddToListInvalidPositionTooSmall() { var doc = new SimpleDTOWithNestedDTO() { SimpleDTO = new SimpleDTO() { IntegerList = new List<int>() { 1, 2, 3 } } }; // create patch JsonPatchDocument<SimpleDTOWithNestedDTO> patchDoc = new JsonPatchDocument<SimpleDTOWithNestedDTO>(); patchDoc.Add<int>(o => o.SimpleDTO.IntegerList, 4, -1); Assert.Throws<JsonPatchException>(() => { patchDoc.ApplyTo(doc); }); }
public void Copy() { var doc = new SimpleDTOWithNestedDTO() { SimpleDTO = new SimpleDTO() { StringProperty = "A", AnotherStringProperty = "B" } }; // create patch JsonPatchDocument<SimpleDTOWithNestedDTO> patchDoc = new JsonPatchDocument<SimpleDTOWithNestedDTO>(); patchDoc.Copy<string>(o => o.SimpleDTO.StringProperty, o => o.SimpleDTO.AnotherStringProperty); patchDoc.ApplyTo(doc); Assert.Equal("A", doc.SimpleDTO.AnotherStringProperty); }
public void Remove() { var doc = new SimpleDTOWithNestedDTO() { SimpleDTO = new SimpleDTO() { StringProperty = "A" } }; // create patch JsonPatchDocument<SimpleDTOWithNestedDTO> patchDoc = new JsonPatchDocument<SimpleDTOWithNestedDTO>(); patchDoc.Remove<string>(o => o.SimpleDTO.StringProperty); patchDoc.ApplyTo(doc); Assert.Equal(null, doc.SimpleDTO.StringProperty); }
public void AddResultsInReplace() { var doc = new SimpleDTOWithNestedDTO() { SimpleDTO = new SimpleDTO() { StringProperty = "A" } }; // create patch JsonPatchDocument<SimpleDTOWithNestedDTO> patchDoc = new JsonPatchDocument<SimpleDTOWithNestedDTO>(); patchDoc.Add<string>(o => o.SimpleDTO.StringProperty, "B"); patchDoc.ApplyTo(doc); Assert.Equal("B", doc.SimpleDTO.StringProperty); }
public void ReplaceFullListWithCollection() { var doc = new SimpleDTOWithNestedDTO() { SimpleDTO = new SimpleDTO() { IntegerList = new List<int>() { 1, 2, 3 } } }; // create patch JsonPatchDocument<SimpleDTOWithNestedDTO> patchDoc = new JsonPatchDocument<SimpleDTOWithNestedDTO>(); patchDoc.Replace<IEnumerable<int>>(o => o.SimpleDTO.IntegerList, new Collection<int>() { 4, 5, 6 }); patchDoc.ApplyTo(doc); Assert.Equal(new List<int>() { 4, 5, 6 }, doc.SimpleDTO.IntegerList); }
public void RemoveFromListInvalidPositionTooLarge() { // Arrange var doc = new SimpleDTO() { IntegerList = new List<int>() { 1, 2, 3 } }; // create patch var patchDoc = new JsonPatchDocument<SimpleDTO>(); patchDoc.Remove<int>(o => o.IntegerList, 3); // Act & Assert var exception = Assert.Throws<JsonPatchException<SimpleDTO>>(() => { patchDoc.ApplyTo(doc); }); Assert.Equal( "For operation 'remove' on array property at path '/integerlist/3', the index is " + "larger than the array size.", exception.Message); }
public void ReplaceInListInvalidInvalidPositionTooLarge() { var doc = new SimpleDTOWithNestedDTO() { SimpleDTO = new SimpleDTO() { IntegerList = new List<int>() { 1, 2, 3 } } }; // create patch JsonPatchDocument<SimpleDTOWithNestedDTO> patchDoc = new JsonPatchDocument<SimpleDTOWithNestedDTO>(); patchDoc.Replace<int>(o => o.SimpleDTO.IntegerList, 5, 3); Assert.Throws<JsonPatchException>(() => { patchDoc.ApplyTo(doc); }); }
public void AddToListAppend() { // Arrange var doc = new SimpleDTO() { IntegerList = new List<int>() { 1, 2, 3 } }; // create patch var patchDoc = new JsonPatchDocument<SimpleDTO>(); patchDoc.Add<int>(o => o.IntegerList, 4); // Act patchDoc.ApplyTo(doc); // Assert Assert.Equal(new List<int>() { 1, 2, 3, 4 }, doc.IntegerList); }