Esempio n. 1
0
        public async Task Can_Paginate_TodoItems_From_End()
        {
            // Arrange
            const int expectedEntitiesPerPage = 2;
            var       totalCount = expectedEntitiesPerPage * 2;
            var       person     = new Person();
            var       todoItems  = _todoItemFaker.Generate(totalCount).ToList();

            foreach (var todoItem in todoItems)
            {
                todoItem.Owner = person;
            }

            Context.TodoItems.RemoveRange(Context.TodoItems);
            Context.TodoItems.AddRange(todoItems);
            Context.SaveChanges();

            var route = $"/api/v1/todo-items?page[size]={expectedEntitiesPerPage}&page[number]=-1";

            // Act
            var response = await Client.GetAsync(route);

            // Assert
            Assert.Equal(HttpStatusCode.OK, response.StatusCode);

            var body = await response.Content.ReadAsStringAsync();

            var deserializedBody = GetService <IJsonApiDeSerializer>().DeserializeList <TodoItem>(body);

            var expectedTodoItems = new[] { todoItems[totalCount - 2], todoItems[totalCount - 1] };

            Assert.Equal(expectedTodoItems, deserializedBody, new IdComparer <TodoItem>());
        }
Esempio n. 2
0
        public async Task CreateWithRelationship_HasOneFromIndependentSide_IsCreated()
        {
            // Arrange
            var serializer = GetSerializer <PersonRole>(pr => new { }, pr => new { pr.Person });
            var person     = new Person();

            _dbContext.People.Add(person);
            _dbContext.SaveChanges();
            var personRole = new PersonRole {
                Person = person
            };

            // Act
            var(body, response) = await Post("/api/v1/personRoles", serializer.Serialize(personRole));

            // Assert
            AssertEqualStatusCode(HttpStatusCode.Created, response);
            var responseItem     = _deserializer.DeserializeSingle <PersonRole>(body).Data;
            var personRoleResult = _dbContext.PersonRoles.AsNoTracking()
                                   .Include(c => c.Person)
                                   .SingleOrDefault(c => c.Id == responseItem.Id);

            Assert.NotEqual(0, responseItem.Id);
            Assert.Equal(person.Id, personRoleResult.Person.Id);
        }
        public async Task Pagination_WithPageSizeAndPageNumber_ReturnsCorrectSubsetOfResources(int pageNum)
        {
            // Arrange
            const int expectedEntitiesPerPage = 2;
            var       totalCount = expectedEntitiesPerPage * 2;
            var       person     = new Person();
            var       todoItems  = _todoItemFaker.Generate(totalCount);

            foreach (var todoItem in todoItems)
            {
                todoItem.Owner = person;
            }
            Context.TodoItems.RemoveRange(Context.TodoItems);
            Context.TodoItems.AddRange(todoItems);
            Context.SaveChanges();

            // Act
            var route    = $"/api/v1/todoItems?page[size]={expectedEntitiesPerPage}&page[number]={pageNum}";
            var response = await Client.GetAsync(route);

            // Assert
            Assert.Equal(HttpStatusCode.OK, response.StatusCode);

            var body = await response.Content.ReadAsStringAsync();

            var deserializedBody = _fixture.GetDeserializer().DeserializeList <TodoItem>(body).Data;

            if (pageNum < 0)
            {
                todoItems.Reverse();
            }
            var expectedTodoItems = todoItems.Take(expectedEntitiesPerPage).ToList();

            Assert.Equal(expectedTodoItems, deserializedBody, new IdComparer <TodoItem>());
        }
Esempio n. 4
0
        public async Task Can_Get_TodoItems_Paginate_Check()
        {
            // Arrange
            await _context.ClearTableAsync <TodoItem>();

            await _context.SaveChangesAsync();

            var expectedResourcesPerPage = _fixture.GetRequiredService <IJsonApiOptions>().DefaultPageSize.Value;
            var person    = new Person();
            var todoItems = _todoItemFaker.Generate(expectedResourcesPerPage + 1);

            foreach (var todoItem in todoItems)
            {
                todoItem.Owner = person;
                _context.TodoItems.Add(todoItem);
                await _context.SaveChangesAsync();
            }

            var httpMethod = new HttpMethod("GET");
            var route      = "/api/v1/todoItems";
            var request    = new HttpRequestMessage(httpMethod, route);

            // Act
            var response = await _fixture.Client.SendAsync(request);

            var body = await response.Content.ReadAsStringAsync();

            var deserializedBody = _fixture.GetDeserializer().DeserializeMany <TodoItem>(body).Data;

            // Assert
            Assert.Equal(HttpStatusCode.OK, response.StatusCode);
            Assert.NotEmpty(deserializedBody);
            Assert.True(deserializedBody.Count <= expectedResourcesPerPage, $"There are more items on the page than the default page size. {deserializedBody.Count} > {expectedResourcesPerPage}");
        }
Esempio n. 5
0
        public async Task Can_Filter_TodoItems()
        {
            // Arrange
            var person   = new Person();
            var todoItem = _todoItemFaker.Generate();

            todoItem.Ordinal = 999999;
            todoItem.Owner   = person;
            _context.TodoItems.Add(todoItem);
            _context.SaveChanges();

            var httpMethod = new HttpMethod("GET");
            var route      = $"/api/v1/todo-items?filter[ordinal]={todoItem.Ordinal}";

            var description = new RequestProperties("Filter TodoItems By Attribute", new Dictionary <string, string> {
                { "?filter[...]=", "Filter on attribute" }
            });

            // Act
            var response = await _fixture.MakeRequest <TodoItem>(description, httpMethod, route);

            var body = await response.Content.ReadAsStringAsync();

            var deserializedBody = _fixture.GetService <IJsonApiDeSerializer>().DeserializeList <TodoItem>(body);

            // Assert
            Assert.Equal(HttpStatusCode.OK, response.StatusCode);
            Assert.NotEmpty(deserializedBody);

            foreach (var todoItemResult in deserializedBody)
            {
                Assert.Equal(todoItem.Ordinal, todoItemResult.Ordinal);
            }
        }
Esempio n. 6
0
        public async Task CreateWithRelationship_HasOneAndIncludeAndSparseFieldset_IsCreatedAndIncludes()
        {
            // Arrange
            var serializer = GetSerializer <TodoItem>(attributes: ti => new { ti.Ordinal }, relationships: ti => new { ti.Owner });
            var todoItem   = new TodoItem
            {
                Ordinal     = 123,
                Description = "some"
            };
            var owner = new Person {
                FirstName = "Alice", LastName = "Cooper"
            };

            _dbContext.People.Add(owner);
            _dbContext.SaveChanges();
            todoItem.Owner = owner;

            // Act
            var(body, response) = await Post("/api/v1/todoItems?include=owner&fields=ordinal&fields[owner]=firstName", serializer.Serialize(todoItem));

            // Assert
            AssertEqualStatusCode(HttpStatusCode.Created, response);
            var responseItem = _deserializer.DeserializeSingle <TodoItemClient>(body).Data;

            Assert.NotNull(responseItem);
            Assert.Equal(todoItem.Ordinal, responseItem.Ordinal);
            Assert.Null(responseItem.Description);

            Assert.NotNull(responseItem.Owner);
            Assert.Equal(owner.FirstName, responseItem.Owner.FirstName);
            Assert.Null(responseItem.Owner.LastName);
        }
        public async Task Can_Get_TodoItems()
        {
            // Arrange
            const int expectedEntitiesPerPage = 5;
            var       person   = new Person();
            var       todoItem = _todoItemFaker.Generate();

            todoItem.Owner = person;
            _context.TodoItems.Add(todoItem);
            _context.SaveChanges();

            var httpMethod = new HttpMethod("GET");
            var route      = "/api/v1/todo-items";
            var request    = new HttpRequestMessage(httpMethod, route);

            // Act
            var response = await _fixture.Client.SendAsync(request);

            var body = await response.Content.ReadAsStringAsync();

            var deserializedBody = _fixture.GetService <IJsonApiDeSerializer>().DeserializeList <TodoItem>(body);

            // Assert
            Assert.Equal(HttpStatusCode.OK, response.StatusCode);
            Assert.NotEmpty(deserializedBody);
            Assert.True(deserializedBody.Count <= expectedEntitiesPerPage);
        }
Esempio n. 8
0
        public async Task Can_Paginate_TodoItems()
        {
            // Arrange
            const int expectedEntitiesPerPage = 2;
            var       person   = new Person();
            var       todoItem = _todoItemFaker.Generate();

            todoItem.Owner = person;
            _context.TodoItems.Add(todoItem);
            _context.SaveChanges();

            var httpMethod = new HttpMethod("GET");
            var route      = $"/api/v1/todo-items?page[size]={expectedEntitiesPerPage}";

            var description = new RequestProperties("Paginate TodoItems", new Dictionary <string, string> {
                { "?page[size]=", "Number of entities per page" }
            });

            // Act
            var response = await _fixture.MakeRequest <TodoItem>(description, httpMethod, route);

            var body = await response.Content.ReadAsStringAsync();

            var deserializedBody = _fixture.GetService <IJsonApiDeSerializer>().DeserializeList <TodoItem>(body);

            // Assert
            Assert.Equal(HttpStatusCode.OK, response.StatusCode);
            Assert.NotEmpty(deserializedBody);
            Assert.True(deserializedBody.Count <= expectedEntitiesPerPage);
        }
Esempio n. 9
0
        public async Task CreateWithRelationship_HasManyAndIncludeAndSparseFieldset_IsCreatedAndIncludes()
        {
            // Arrange
            var serializer = GetSerializer <TodoItemCollection>(e => new { e.Name }, e => new { e.TodoItems, e.Owner });
            var owner      = new Person();
            var todoItem   = new TodoItem {
                Owner = owner, Ordinal = 123, Description = "Description"
            };

            _dbContext.People.Add(owner);
            _dbContext.TodoItems.Add(todoItem);
            _dbContext.SaveChanges();
            var todoCollection = new TodoItemCollection {
                Owner = owner, Name = "Jack", TodoItems = new HashSet <TodoItem> {
                    todoItem
                }
            };

            // Act
            var(body, response) = await Post("/api/v1/todoCollections?include=todoItems&fields=name&fields[todoItems]=ordinal", serializer.Serialize(todoCollection));

            // Assert
            AssertEqualStatusCode(HttpStatusCode.Created, response);
            var responseItem = _deserializer.DeserializeSingle <TodoItemCollectionClient>(body).Data;

            Assert.NotNull(responseItem);
            Assert.Equal(todoCollection.Name, responseItem.Name);

            Assert.NotEmpty(responseItem.TodoItems);
            Assert.Equal(todoItem.Ordinal, responseItem.TodoItems.Single().Ordinal);
            Assert.Null(responseItem.TodoItems.Single().Description);
        }
        public async Task CreateWithRelationship_HasManyAndInclude_IsCreatedAndIncludes()
        {
            // Arrange
            var serializer = GetSerializer <TodoItemCollection>(e => new { }, e => new { e.TodoItems, e.Owner });
            var owner      = new Person();
            var todoItem   = new TodoItem {
                Owner = owner, Description = "Description"
            };

            _dbContext.People.Add(owner);
            _dbContext.TodoItems.Add(todoItem);
            _dbContext.SaveChanges();
            var todoCollection = new TodoItemCollection {
                Owner = owner, TodoItems = new List <TodoItem> {
                    todoItem
                }
            };

            // Act
            var(body, response) = await Post("/api/v1/todoCollections?include=todoItems", serializer.Serialize(todoCollection));

            // Assert
            AssertEqualStatusCode(HttpStatusCode.Created, response);
            var responseItem = _deserializer.DeserializeSingle <TodoItemCollectionClient>(body).Data;

            Assert.NotNull(responseItem);
            Assert.NotEmpty(responseItem.TodoItems);
            Assert.Equal(todoItem.Description, responseItem.TodoItems.Single().Description);
        }
Esempio n. 11
0
        public async Task Can_Filter_By_Relationship_Id()
        {
            // Arrange
            var person   = new Person();
            var todoItem = _todoItemFaker.Generate();

            todoItem.Owner = person;
            _context.TodoItems.Add(todoItem);
            _context.SaveChanges();

            var httpMethod = new HttpMethod("GET");
            var route      = $"/api/v1/todo-items?filter[owner.id]={person.Id}";
            var request    = new HttpRequestMessage(httpMethod, route);

            // Act
            var response = await _fixture.Client.SendAsync(request);

            var body = await response.Content.ReadAsStringAsync();

            var deserializedBody = _fixture.GetService <IJsonApiDeSerializer>().DeserializeList <TodoItem>(body);

            // Assert
            Assert.Equal(HttpStatusCode.OK, response.StatusCode);
            Assert.NotEmpty(deserializedBody);
            Assert.Contains(deserializedBody, (i) => i.Owner.Id == person.Id);
        }
        public async Task Can_Delete_TodoItem()
        {
            // Arrange
            var person = new Person();

            _context.People.Add(person);
            _context.SaveChanges();

            var todoItem = _todoItemFaker.Generate();

            todoItem.Owner = person;
            _context.TodoItems.Add(todoItem);
            _context.SaveChanges();

            var httpMethod = new HttpMethod("DELETE");
            var route      = $"/api/v1/todo-items/{todoItem.Id}";

            var request = new HttpRequestMessage(httpMethod, route);

            request.Content = new StringContent(string.Empty);
            request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.api+json");

            // Act
            var response = await _fixture.Client.SendAsync(request);

            // Assert
            Assert.Equal(HttpStatusCode.NoContent, response.StatusCode);
            Assert.Null(_context.TodoItems.FirstOrDefault(t => t.Id == todoItem.Id));
        }
Esempio n. 13
0
        public async Task Can_Paginate_TodoItems()
        {
            // Arrange
            const int expectedEntitiesPerPage = 2;
            var       totalCount = expectedEntitiesPerPage * 2;
            var       person     = new Person();
            var       todoItems  = _todoItemFaker.Generate(totalCount);

            foreach (var todoItem in todoItems)
            {
                todoItem.Owner = person;
            }

            Context.TodoItems.AddRange(todoItems);
            Context.SaveChanges();

            var route = $"/api/v1/todo-items?page[size]={expectedEntitiesPerPage}";

            // Act
            var response = await Client.GetAsync(route);

            // Assert
            Assert.Equal(HttpStatusCode.OK, response.StatusCode);

            var body = await response.Content.ReadAsStringAsync();

            var deserializedBody = GetService <IJsonApiDeSerializer>().DeserializeList <TodoItem>(body);

            Assert.NotEmpty(deserializedBody);
            Assert.Equal(expectedEntitiesPerPage, deserializedBody.Count);
        }
        public async Task Can_Get_TodoItem_ById()
        {
            // Arrange
            var person   = new Person();
            var todoItem = _todoItemFaker.Generate();

            todoItem.Owner = person;
            _context.TodoItems.Add(todoItem);
            _context.SaveChanges();

            var httpMethod = new HttpMethod("GET");
            var route      = $"/api/v1/todo-items/{todoItem.Id}";

            var description = new RequestProperties("Get TodoItem By Id", new Dictionary <string, string> {
                { "/todo-items/{id}", "TodoItem Id" }
            });

            // Act
            var response = await _fixture.MakeRequest <TodoItem>(description, httpMethod, route);

            var body = await response.Content.ReadAsStringAsync();

            var deserializedBody = (TodoItem)JsonApiDeSerializer.Deserialize(body, _jsonApiContext);

            // Assert
            Assert.Equal(HttpStatusCode.OK, response.StatusCode);
            Assert.Equal(todoItem.Id, deserializedBody.Id);
            Assert.Equal(todoItem.Description, deserializedBody.Description);
            Assert.Equal(todoItem.Ordinal, deserializedBody.Ordinal);
        }
        public async Task CreateWithRelationship_HasOneAndInclude_IsCreatedAndIncluded()
        {
            // Arrange
            var serializer = GetSerializer <TodoItem>(attributes: ti => new { }, relationships: ti => new { ti.Owner });
            var todoItem   = new TodoItem();
            var owner      = new Person {
                FirstName = "Alice"
            };

            _dbContext.People.Add(owner);
            await _dbContext.SaveChangesAsync();

            todoItem.Owner = owner;

            // Act
            var(body, response) = await Post("/api/v1/todoItems?include=owner", serializer.Serialize(todoItem));

            // Assert
            AssertEqualStatusCode(HttpStatusCode.Created, response);
            var responseItem = _deserializer.DeserializeSingle <TodoItemClient>(body).Data;

            Assert.NotNull(responseItem);
            Assert.NotNull(responseItem.Owner);
            Assert.Equal(owner.FirstName, responseItem.Owner.FirstName);
        }
        public async Task Can_Filter_TodoItems()
        {
            // Arrange
            var person   = new Person();
            var todoItem = _todoItemFaker.Generate();

            todoItem.Ordinal = 999999;
            todoItem.Owner   = person;
            _context.TodoItems.Add(todoItem);
            _context.SaveChanges();

            var httpMethod = new HttpMethod("GET");
            var route      = $"/api/v1/todo-items?filter[ordinal]={todoItem.Ordinal}";
            var request    = new HttpRequestMessage(httpMethod, route);

            // Act
            var response = await _fixture.Client.SendAsync(request);

            var body = await response.Content.ReadAsStringAsync();

            var deserializedBody = _fixture.GetService <IJsonApiDeSerializer>().DeserializeList <TodoItem>(body);

            // Assert
            Assert.Equal(HttpStatusCode.OK, response.StatusCode);
            Assert.NotEmpty(deserializedBody);

            foreach (var todoItemResult in deserializedBody)
            {
                Assert.Equal(todoItem.Ordinal, todoItemResult.Ordinal);
            }
        }
Esempio n. 17
0
        public async Task Can_Get_TodoItem_WithOwner()
        {
            // Arrange
            var person   = new Person();
            var todoItem = _todoItemFaker.Generate();

            todoItem.Owner = person;
            _context.TodoItems.Add(todoItem);
            _context.SaveChanges();

            var httpMethod = new HttpMethod("GET");
            var route      = $"/api/v1/todo-items/{todoItem.Id}?include=owner";

            var description = new RequestProperties("Get TodoItem By Id", new Dictionary <string, string> {
                { "/todo-items/{id}", "TodoItem Id" },
                { "?include={relationship}", "Included Relationship" }
            });

            // Act
            var response = await _fixture.MakeRequest <TodoItem>(description, httpMethod, route);

            var body = await response.Content.ReadAsStringAsync();

            var deserializedBody = (TodoItem)_fixture.GetService <IJsonApiDeSerializer>().Deserialize(body);

            // Assert
            Assert.Equal(HttpStatusCode.OK, response.StatusCode);
            Assert.Equal(person.Id, deserializedBody.OwnerId);
            Assert.Equal(todoItem.Id, deserializedBody.Id);
            Assert.Equal(todoItem.Description, deserializedBody.Description);
            Assert.Equal(todoItem.Ordinal, deserializedBody.Ordinal);
            Assert.Equal(todoItem.CreatedDate.ToString("G"), deserializedBody.CreatedDate.ToString("G"));
            Assert.Equal(null, deserializedBody.AchievedDate);
        }
        public async Task Can_Get_TodoItem_WithOwner()
        {
            // Arrange
            var person   = new Person();
            var todoItem = _todoItemFaker.Generate();

            todoItem.Owner = person;
            _context.TodoItems.Add(todoItem);
            _context.SaveChanges();

            var httpMethod = new HttpMethod("GET");
            var route      = $"/api/v1/todo-items/{todoItem.Id}?include=owner";
            var request    = new HttpRequestMessage(httpMethod, route);

            // Act
            var response = await _fixture.Client.SendAsync(request);

            var body = await response.Content.ReadAsStringAsync();

            // Assert
            Assert.Equal(HttpStatusCode.OK, response.StatusCode);
            var deserializedBody = (TodoItem)_fixture.GetService <IJsonApiDeSerializer>().Deserialize(body);

            Assert.Equal(person.Id, deserializedBody.OwnerId);
            Assert.Equal(todoItem.Id, deserializedBody.Id);
            Assert.Equal(todoItem.Description, deserializedBody.Description);
            Assert.Equal(todoItem.Ordinal, deserializedBody.Ordinal);
            Assert.Equal(todoItem.CreatedDate.ToString("G"), deserializedBody.CreatedDate.ToString("G"));
            Assert.Null(deserializedBody.AchievedDate);
        }
Esempio n. 19
0
        public async Task Can_Post_TodoItem()
        {
            // Arrange
            var person = new Person();

            _context.People.Add(person);
            _context.SaveChanges();

            var todoItem  = _todoItemFaker.Generate();
            var nowOffset = new DateTimeOffset();
            var content   = new
            {
                data = new
                {
                    type       = "todo-items",
                    attributes = new Dictionary <string, object>()
                    {
                        { "description", todoItem.Description },
                        { "ordinal", todoItem.Ordinal },
                        { "created-date", todoItem.CreatedDate },
                        { "offset-date", nowOffset }
                    },
                    relationships = new
                    {
                        owner = new
                        {
                            data = new
                            {
                                type = "people",
                                id   = person.Id.ToString()
                            }
                        }
                    }
                }
            };

            var httpMethod = new HttpMethod("POST");
            var route      = $"/api/v1/todo-items";

            var request = new HttpRequestMessage(httpMethod, route);

            request.Content = new StringContent(JsonConvert.SerializeObject(content));
            request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.api+json");

            // Act
            var response = await _fixture.Client.SendAsync(request);

            // Assert
            Assert.Equal(HttpStatusCode.Created, response.StatusCode);
            var body = await response.Content.ReadAsStringAsync();

            var deserializedBody = (TodoItem)_fixture.GetService <IJsonApiDeSerializer>().Deserialize(body);

            Assert.Equal(HttpStatusCode.Created, response.StatusCode);
            Assert.Equal(todoItem.Description, deserializedBody.Description);
            Assert.Equal(todoItem.CreatedDate.ToString("G"), deserializedBody.CreatedDate.ToString("G"));
            Assert.Equal(nowOffset.ToString("yyyy-MM-ddTHH:mm:ssK"), deserializedBody.OffsetDate?.ToString("yyyy-MM-ddTHH:mm:ssK"));
            Assert.Null(deserializedBody.AchievedDate);
        }
Esempio n. 20
0
        public async Task Can_Patch_TodoItemWithNullable()
        {
            // Arrange
            var person = new Person();

            _context.People.Add(person);
            await _context.SaveChangesAsync();

            var todoItem = _todoItemFaker.Generate();

            todoItem.AchievedDate = new DateTime(2002, 2, 2);
            todoItem.Owner        = person;
            _context.TodoItems.Add(todoItem);
            await _context.SaveChangesAsync();

            var newTodoItem = _todoItemFaker.Generate();

            newTodoItem.AchievedDate = new DateTime(2002, 2, 4);

            var content = new
            {
                data = new
                {
                    id         = todoItem.Id,
                    type       = "todoItems",
                    attributes = new Dictionary <string, object>
                    {
                        { "description", newTodoItem.Description },
                        { "ordinal", newTodoItem.Ordinal },
                        { "createdDate", newTodoItem.CreatedDate },
                        { "achievedDate", newTodoItem.AchievedDate }
                    }
                }
            };

            var httpMethod = new HttpMethod("PATCH");
            var route      = $"/api/v1/todoItems/{todoItem.Id}";

            var request = new HttpRequestMessage(httpMethod, route)
            {
                Content = new StringContent(JsonConvert.SerializeObject(content))
            };

            request.Content.Headers.ContentType = new MediaTypeHeaderValue(HeaderConstants.MediaType);

            // Act
            var response = await _fixture.Client.SendAsync(request);

            var body = await response.Content.ReadAsStringAsync();

            var deserializedBody = _fixture.GetDeserializer().DeserializeSingle <TodoItem>(body).Data;

            // Assert
            Assert.Equal(HttpStatusCode.OK, response.StatusCode);
            Assert.Equal(newTodoItem.Description, deserializedBody.Description);
            Assert.Equal(newTodoItem.Ordinal, deserializedBody.Ordinal);
            Assert.Equal(newTodoItem.CreatedDate.ToString("G"), deserializedBody.CreatedDate.ToString("G"));
            Assert.Equal(newTodoItem.AchievedDate.GetValueOrDefault().ToString("G"), deserializedBody.AchievedDate.GetValueOrDefault().ToString("G"));
        }
Esempio n. 21
0
        public async Task Can_Patch_TodoItemWithNullable()
        {
            // Arrange
            var person = new Person();

            _context.People.Add(person);
            _context.SaveChanges();

            var todoItem = _todoItemFaker.Generate();

            todoItem.AchievedDate = System.DateTime.Now;
            todoItem.Owner        = person;
            _context.TodoItems.Add(todoItem);
            _context.SaveChanges();

            var newTodoItem = _todoItemFaker.Generate();

            newTodoItem.AchievedDate = System.DateTime.Now.AddDays(2);

            var content = new
            {
                data = new
                {
                    type       = "todo-items",
                    attributes = new Dictionary <string, object>()
                    {
                        { "description", newTodoItem.Description },
                        { "ordinal", newTodoItem.Ordinal },
                        { "created-date", newTodoItem.CreatedDate },
                        { "achieved-date", newTodoItem.AchievedDate }
                    }
                }
            };

            var httpMethod = new HttpMethod("PATCH");
            var route      = $"/api/v1/todo-items/{todoItem.Id}";

            var request = new HttpRequestMessage(httpMethod, route);

            request.Content = new StringContent(JsonConvert.SerializeObject(content));
            request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.api+json");

            var description = new RequestProperties("Patch TodoItem");

            // Act
            var response = await _fixture.MakeRequest <TodoItem>(description, request);

            var body = await response.Content.ReadAsStringAsync();

            var deserializedBody = (TodoItem)_fixture.GetService <IJsonApiDeSerializer>().Deserialize(body);

            // Assert
            Assert.Equal(HttpStatusCode.OK, response.StatusCode);
            Assert.Equal(newTodoItem.Description, deserializedBody.Description);
            Assert.Equal(newTodoItem.Ordinal, deserializedBody.Ordinal);
            Assert.Equal(newTodoItem.CreatedDate.ToString("G"), deserializedBody.CreatedDate.ToString("G"));
            Assert.Equal(newTodoItem.AchievedDate.GetValueOrDefault().ToString("G"), deserializedBody.AchievedDate.GetValueOrDefault().ToString("G"));
        }
        public async Task Can_Create_And_Set_HasOne_Relationships()
        {
            // arrange
            var builder = new WebHostBuilder()
                          .UseStartup <Startup>();
            var httpMethod = new HttpMethod("POST");
            var server     = new TestServer(builder);
            var client     = server.CreateClient();

            var context = _fixture.GetService <AppDbContext>();

            var todoItem = new TodoItem();
            var owner    = new JsonApiDotNetCoreExample.Models.Person();

            context.People.Add(owner);
            await context.SaveChangesAsync();

            var route   = "/api/v1/todo-items";
            var request = new HttpRequestMessage(httpMethod, route);
            var content = new
            {
                data = new
                {
                    type          = "todo-items",
                    relationships = new Dictionary <string, dynamic>
                    {
                        { "owner", new {
                              data = new
                              {
                                  type = "people",
                                  id   = owner.Id.ToString()
                              }
                          } }
                    }
                }
            };

            request.Content = new StringContent(JsonConvert.SerializeObject(content));
            request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.api+json");

            // act
            var response = await client.SendAsync(request);

            var body = await response.Content.ReadAsStringAsync();

            // assert
            Assert.Equal(HttpStatusCode.Created, response.StatusCode);
            var deserializedBody = (TodoItem)_fixture.GetService <IJsonApiDeSerializer>().Deserialize(body);
            var newId            = deserializedBody.Id;

            context = _fixture.GetService <AppDbContext>();
            var todoItemResult = context.TodoItems
                                 .Include(c => c.Owner)
                                 .SingleOrDefault(c => c.Id == newId);

            Assert.Equal(owner.Id, todoItemResult.OwnerId);
        }
Esempio n. 23
0
        protected IList <TodoItem> CreateTodoWithToOnePerson()
        {
            TodoItem        todoItem = TodoFaker.Generate();
            Person          person   = PersonFaker.Generate();
            List <TodoItem> todoList = todoItem.AsList();

            person.OneToOneTodoItem = todoItem;
            todoItem.OneToOnePerson = person;
            return(todoList);
        }
        public async Task Can_Post_TodoItem()
        {
            // Arrange
            var person = new Person();

            _context.People.Add(person);
            _context.SaveChanges();

            var todoItem = _todoItemFaker.Generate();
            var content  = new
            {
                data = new
                {
                    type       = "todo-items",
                    attributes = new
                    {
                        description = todoItem.Description,
                        ordinal     = todoItem.Ordinal
                    },
                    relationships = new
                    {
                        owner = new
                        {
                            data = new
                            {
                                type = "people",
                                id   = person.Id.ToString()
                            }
                        }
                    }
                }
            };

            var httpMethod = new HttpMethod("POST");
            var route      = $"/api/v1/todo-items";

            var request = new HttpRequestMessage(httpMethod, route);

            request.Content = new StringContent(JsonConvert.SerializeObject(content));
            request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.api+json");

            var description = new RequestProperties("Post TodoItem");

            // Act
            var response = await _fixture.MakeRequest <TodoItem>(description, request);

            var body = await response.Content.ReadAsStringAsync();

            var deserializedBody = (TodoItem)JsonApiDeSerializer.Deserialize(body, _jsonApiContext);

            // Assert
            Assert.Equal(HttpStatusCode.Created, response.StatusCode);
            Assert.Equal(todoItem.Description, deserializedBody.Description);
        }
        public async Task Can_Create_Guid_Identifiable_Entity_With_Client_Defined_Id_If_Configured()
        {
            // arrange
            var builder = new WebHostBuilder()
                          .UseStartup <ClientGeneratedIdsStartup>();
            var httpMethod = new HttpMethod("POST");
            var server     = new TestServer(builder);
            var client     = server.CreateClient();

            var context = _fixture.GetService <AppDbContext>();

            var owner = new JsonApiDotNetCoreExample.Models.Person();

            context.People.Add(owner);
            await context.SaveChangesAsync();

            var route           = "/api/v1/todo-collections";
            var request         = new HttpRequestMessage(httpMethod, route);
            var clientDefinedId = Guid.NewGuid();
            var content         = new
            {
                data = new
                {
                    type          = "todo-collections",
                    id            = $"{clientDefinedId}",
                    relationships = new
                    {
                        owner = new
                        {
                            data = new
                            {
                                type = "people",
                                id   = owner.Id.ToString()
                            }
                        }
                    }
                }
            };

            request.Content = new StringContent(JsonConvert.SerializeObject(content));
            request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.api+json");

            // act
            var response = await client.SendAsync(request);

            var body = await response.Content.ReadAsStringAsync();

            var deserializedBody = (TodoItemCollection)_fixture.GetService <IJsonApiDeSerializer>().Deserialize(body);

            // assert
            Assert.Equal(HttpStatusCode.Created, response.StatusCode);
            Assert.Equal(clientDefinedId, deserializedBody.Id);
        }
        public async Task Can_Create_And_Set_HasOne_Relationships_From_Independent_Side()
        {
            // arrange
            var builder = new WebHostBuilder()
                          .UseStartup <ClientGeneratedIdsStartup>();
            var httpMethod = new HttpMethod("POST");
            var server     = new TestServer(builder);
            var client     = server.CreateClient();

            var context = _fixture.GetService <AppDbContext>();

            var person = new JsonApiDotNetCoreExample.Models.Person();

            context.People.Add(person);
            await context.SaveChangesAsync();

            var route           = "/api/v1/person-roles";
            var request         = new HttpRequestMessage(httpMethod, route);
            var clientDefinedId = Guid.NewGuid();
            var content         = new
            {
                data = new
                {
                    type          = "person-roles",
                    relationships = new
                    {
                        person = new
                        {
                            data = new
                            {
                                type = "people",
                                id   = person.Id.ToString()
                            }
                        }
                    }
                }
            };

            request.Content = new StringContent(JsonConvert.SerializeObject(content));
            request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.api+json");

            // act
            var response = await client.SendAsync(request);

            var body = await response.Content.ReadAsStringAsync();

            // assert
            Assert.Equal(HttpStatusCode.Created, response.StatusCode);
            var deserializedBody = (PersonRole)_fixture.GetService <IJsonApiDeSerializer>().Deserialize(body);

            Assert.Equal(person.Id, deserializedBody.Person.Id);
        }
Esempio n. 27
0
        protected IEnumerable <TodoItem> CreateTodoWithOwner()
        {
            TodoItem todoItem = TodoFaker.Generate();
            Person   person   = PersonFaker.Generate();

            var todoSet = new HashSet <TodoItem>
            {
                todoItem
            };

            person.AssignedTodoItems = todoSet;
            todoItem.Owner           = person;
            return(todoSet);
        }
        public async Task Can_Include_Doubly_HasMany_Relationships()
        {
            // Arrange
            var person = new Person {
                todoCollections = new HashSet <TodoItemCollection> {
                    new TodoItemCollection {
                        TodoItems = new HashSet <TodoItem> {
                            new TodoItem(),
                            new TodoItem()
                        }
                    },
                    new TodoItemCollection {
                        TodoItems = new HashSet <TodoItem> {
                            new TodoItem(),
                            new TodoItem(),
                            new TodoItem()
                        }
                    }
                }
            };

            var context = _fixture.GetService <AppDbContext>();

            ResetContext(context);

            context.People.Add(person);

            await context.SaveChangesAsync();

            string route = "/api/v1/people/" + person.Id + "?include=todoCollections.todoItems";

            // Act
            var response = await _fixture.Client.GetAsync(route);

            // Assert
            Assert.Equal(HttpStatusCode.OK, response.StatusCode);

            var body = await response.Content.ReadAsStringAsync();

            var documents = JsonConvert.DeserializeObject <Document>(body);
            var included  = documents.Included;

            Assert.Equal(7, included.Count);

            Assert.Equal(5, included.CountOfType("todoItems"));
            Assert.Equal(2, included.CountOfType("todoCollections"));
        }
        public async Task Can_Create_Guid_Identifiable_Entity()
        {
            // arrange
            var builder = new WebHostBuilder()
                          .UseStartup <Startup>();
            var httpMethod = new HttpMethod("POST");
            var server     = new TestServer(builder);
            var client     = server.CreateClient();

            var context = _fixture.GetService <AppDbContext>();

            var owner = new JsonApiDotNetCoreExample.Models.Person();

            context.People.Add(owner);
            await context.SaveChangesAsync();

            var route   = "/api/v1/todo-collections";
            var request = new HttpRequestMessage(httpMethod, route);
            var content = new
            {
                data = new
                {
                    type          = "todo-collections",
                    relationships = new
                    {
                        owner = new
                        {
                            data = new
                            {
                                type = "people",
                                id   = owner.Id.ToString()
                            }
                        }
                    }
                }
            };

            request.Content = new StringContent(JsonConvert.SerializeObject(content));
            request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.api+json");

            // act
            var response = await client.SendAsync(request);

            // assert
            Assert.Equal(HttpStatusCode.Created, response.StatusCode);
        }
Esempio n. 30
0
        public async Task CreateResource_GuidResource_IsCreated()
        {
            // Arrange
            var serializer = GetSerializer <TodoItemCollection>(e => new { }, e => new { e.Owner });
            var owner      = new Person();

            _dbContext.People.Add(owner);
            _dbContext.SaveChanges();
            var todoItemCollection = new TodoItemCollection {
                Owner = owner
            };

            // Act
            var(_, response) = await Post("/api/v1/todoCollections", serializer.Serialize(todoItemCollection));

            // Assert
            AssertEqualStatusCode(HttpStatusCode.Created, response);
        }