Skip to content

Commit b13f55e

Browse files
committed
chore: response resource object builder unit test, restored repo and resourcedef unit tests
1 parent 883bfee commit b13f55e

File tree

8 files changed

+354
-402
lines changed

8 files changed

+354
-402
lines changed

src/Examples/JsonApiDotNetCoreExample/Resources/UserResource.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ public class UserResource : ResourceDefinition<User>
1111
{
1212
public UserResource(IResourceGraph graph, IFieldsExplorer fieldExplorer) : base(fieldExplorer, graph)
1313
{
14-
HideAttributes(u => u.Password);
14+
HideFields(u => u.Password);
1515
}
1616

1717
public override QueryFilters GetQueryFilters()

src/JsonApiDotNetCore/Models/ResourceDefinition.cs

Lines changed: 6 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -48,28 +48,17 @@ public ResourceDefinition(IResourceGraph graph)
4848
public List<AttrAttribute> GetAllowedAttributes() => _allowedAttributes;
4949

5050
/// <summary>
51-
/// Hides specified attributes from the serialized output. Can be called directly in a resource definition implementation or
51+
/// Hides specified attributes and relationships from the serialized output. Can be called directly in a resource definition implementation or
5252
/// in any resource hook to combine it with eg authorization.
5353
/// </summary>
54-
/// <param name="selector">Should be of the form: (TResource e) => new { e.Attribute1, e.Arttribute2 }</param>
55-
public void HideAttributes(Expression<Func<TResource, dynamic>> selector)
54+
/// <param name="selector">Should be of the form: (TResource e) => new { e.Attribute1, e.Arttribute2, e.Relationship1, e.Relationship2 }</param>
55+
public void HideFields(Expression<Func<TResource, dynamic>> selector)
5656
{
57-
var attributesToHide = _fieldExplorer.GetAttributes(selector);
58-
_allowedAttributes = _allowedAttributes.Except(attributesToHide).ToList();
57+
var fieldsToHide = _fieldExplorer.GetFields(selector);
58+
_allowedAttributes = _allowedAttributes.Except(fieldsToHide.Where(f => f is AttrAttribute)).Cast<AttrAttribute>().ToList();
59+
_allowedRelationships = _allowedRelationships.Except(fieldsToHide.Where(f => f is RelationshipAttribute)).Cast<RelationshipAttribute>().ToList();
5960
}
6061

61-
/// <summary>
62-
/// Hides specified relationships from the serialized output. Can be called directly in a resource definition implementation or
63-
/// in any resource hook to combine it with eg authorization.
64-
/// </summary>
65-
/// <param name="selector">Should be of the form: (TResource e) => new { e.Relationship1, e.Relationship2 }</param>
66-
public void HideRelationships(Expression<Func<TResource, dynamic>> selector)
67-
{
68-
var relationshipsToHide = _fieldExplorer.GetRelationships(selector);
69-
_allowedRelationships = _allowedRelationships.Except(relationshipsToHide).ToList();
70-
}
71-
72-
7362
/// <summary>
7463
/// Define a set of custom query expressions that can be applied
7564
/// instead of the default query behavior. A common use-case for this
Lines changed: 167 additions & 179 deletions
Original file line numberDiff line numberDiff line change
@@ -1,179 +1,167 @@
1-
//using System;
2-
//using System.Collections.Generic;
3-
//using JsonApiDotNetCore.Controllers;
4-
//using Xunit;
5-
//using Moq;
6-
//using Microsoft.EntityFrameworkCore;
7-
//using JsonApiDotNetCoreExample.Models;
8-
//using JsonApiDotNetCore.Extensions;
9-
//using JsonApiDotNetCore.Data;
10-
//using JsonApiDotNetCore.Models;
11-
//using Microsoft.Extensions.Logging;
12-
//using JsonApiDotNetCore.Services;
13-
//using System.Threading.Tasks;
14-
//using System.Linq;
15-
16-
//namespace UnitTests.Data
17-
//{
18-
// public class DefaultEntityRepository_Tests : JsonApiControllerMixin
19-
// {
20-
// private readonly Mock<IJsonApiContext> _jsonApiContextMock;
21-
// private readonly Mock<ILoggerFactory> _loggFactoryMock;
22-
// private readonly Mock<DbSet<TodoItem>> _dbSetMock;
23-
// private readonly Mock<DbContext> _contextMock;
24-
// private readonly Mock<IDbContextResolver> _contextResolverMock;
25-
// private readonly TodoItem _todoItem;
26-
// private Dictionary<AttrAttribute, object> _attrsToUpdate = new Dictionary<AttrAttribute, object>();
27-
// private Dictionary<RelationshipAttribute, object> _relationshipsToUpdate = new Dictionary<RelationshipAttribute, object>();
28-
29-
// public DefaultEntityRepository_Tests()
30-
// {
31-
// _todoItem = new TodoItem
32-
// {
33-
// Id = 1,
34-
// Description = Guid.NewGuid().ToString(),
35-
// Ordinal = 10
36-
// };
37-
// _jsonApiContextMock = new Mock<IJsonApiContext>();
38-
// _loggFactoryMock = new Mock<ILoggerFactory>();
39-
// _dbSetMock = DbSetMock.Create<TodoItem>(new[] { _todoItem });
40-
// _contextMock = new Mock<DbContext>();
41-
// _contextResolverMock = new Mock<IDbContextResolver>();
42-
// }
43-
44-
// [Fact]
45-
// public async Task UpdateAsync_Updates_Attributes_In_AttributesToUpdate()
46-
// {
47-
// // arrange
48-
// var todoItemUpdates = new TodoItem
49-
// {
50-
// Id = _todoItem.Id,
51-
// Description = Guid.NewGuid().ToString()
52-
// };
53-
54-
// var descAttr = new AttrAttribute("description", "Description");
55-
// descAttr.PropertyInfo = typeof(TodoItem).GetProperty(nameof(TodoItem.Description));
56-
57-
// _attrsToUpdate = new Dictionary<AttrAttribute, object>
58-
// {
59-
// {
60-
// descAttr,
61-
// null //todoItemUpdates.Description
62-
// }
63-
// };
64-
65-
// var repository = GetRepository();
66-
67-
// // act
68-
// var updatedItem = await repository.UpdateAsync(todoItemUpdates);
69-
70-
// // assert
71-
// Assert.NotNull(updatedItem);
72-
// Assert.Equal(_todoItem.Ordinal, updatedItem.Ordinal);
73-
// Assert.Equal(todoItemUpdates.Description, updatedItem.Description);
74-
// }
75-
76-
// private DefaultEntityRepository<TodoItem> GetRepository()
77-
// {
78-
79-
// _contextMock
80-
// .Setup(m => m.Set<TodoItem>())
81-
// .Returns(_dbSetMock.Object);
82-
83-
// _contextResolverMock
84-
// .Setup(m => m.GetContext())
85-
// .Returns(_contextMock.Object);
86-
87-
// _jsonApiContextMock
88-
// .Setup(m => m.RequestManager.GetUpdatedAttributes())
89-
// .Returns(_attrsToUpdate);
90-
91-
// _jsonApiContextMock
92-
// .Setup(m => m.RequestManager.GetUpdatedRelationships())
93-
// .Returns(_relationshipsToUpdate);
94-
95-
96-
// return new DefaultEntityRepository<TodoItem>(
97-
// _loggFactoryMock.Object,
98-
// _jsonApiContextMock.Object,
99-
// _contextResolverMock.Object);
100-
// }
101-
102-
// [Theory]
103-
// [InlineData(0)]
104-
// [InlineData(-1)]
105-
// [InlineData(-10)]
106-
// public async Task Page_When_PageSize_Is_NonPositive_Does_Nothing(int pageSize)
107-
// {
108-
// var todoItems = DbSetMock.Create(TodoItems(2, 3, 1)).Object;
109-
// var repository = GetRepository();
110-
111-
// var result = await repository.PageAsync(todoItems, pageSize, 3);
112-
113-
// Assert.Equal(TodoItems(2, 3, 1), result, new IdComparer<TodoItem>());
114-
// }
115-
116-
// [Fact]
117-
// public async Task Page_When_PageNumber_Is_Zero_Pretends_PageNumber_Is_One()
118-
// {
119-
// var todoItems = DbSetMock.Create(TodoItems(2, 3, 1)).Object;
120-
// var repository = GetRepository();
121-
122-
// var result = await repository.PageAsync(todoItems, 1, 0);
123-
124-
// Assert.Equal(TodoItems(2), result, new IdComparer<TodoItem>());
125-
// }
126-
127-
// [Fact]
128-
// public async Task Page_When_PageNumber_Of_PageSize_Does_Not_Exist_Return_Empty_Queryable()
129-
// {
130-
// var todoItems = DbSetMock.Create(TodoItems(2, 3, 1)).Object;
131-
// var repository = GetRepository();
132-
133-
// var result = await repository.PageAsync(todoItems, 2, 3);
134-
135-
// Assert.Empty(result);
136-
// }
137-
138-
// [Theory]
139-
// [InlineData(3, 2, new[] { 4, 5, 6 })]
140-
// [InlineData(8, 2, new[] { 9 })]
141-
// [InlineData(20, 1, new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 })]
142-
// public async Task Page_When_PageNumber_Is_Positive_Returns_PageNumberTh_Page_Of_Size_PageSize(int pageSize, int pageNumber, int[] expectedResult)
143-
// {
144-
// var todoItems = DbSetMock.Create(TodoItems(1, 2, 3, 4, 5, 6, 7, 8, 9)).Object;
145-
// var repository = GetRepository();
146-
147-
// var result = await repository.PageAsync(todoItems, pageSize, pageNumber);
148-
149-
// Assert.Equal(TodoItems(expectedResult), result, new IdComparer<TodoItem>());
150-
// }
151-
152-
// [Theory]
153-
// [InlineData(6, -1, new[] { 4, 5, 6, 7, 8, 9 })]
154-
// [InlineData(6, -2, new[] { 1, 2, 3 })]
155-
// [InlineData(20, -1, new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 })]
156-
// public async Task Page_When_PageNumber_Is_Negative_Returns_PageNumberTh_Page_From_End(int pageSize, int pageNumber, int[] expectedIds)
157-
// {
158-
// var todoItems = DbSetMock.Create(TodoItems(1, 2, 3, 4, 5, 6, 7, 8, 9)).Object;
159-
// var repository = GetRepository();
160-
161-
// var result = await repository.PageAsync(todoItems, pageSize, pageNumber);
162-
163-
// Assert.Equal(TodoItems(expectedIds), result, new IdComparer<TodoItem>());
164-
// }
165-
166-
// private static TodoItem[] TodoItems(params int[] ids)
167-
// {
168-
// return ids.Select(id => new TodoItem { Id = id }).ToArray();
169-
// }
170-
171-
// private class IdComparer<T> : IEqualityComparer<T>
172-
// where T : IIdentifiable
173-
// {
174-
// public bool Equals(T x, T y) => x?.StringId == y?.StringId;
175-
176-
// public int GetHashCode(T obj) => obj?.StringId?.GetHashCode() ?? 0;
177-
// }
178-
// }
179-
//}
1+
using System;
2+
using System.Collections.Generic;
3+
using JsonApiDotNetCore.Controllers;
4+
using Xunit;
5+
using Moq;
6+
using Microsoft.EntityFrameworkCore;
7+
using JsonApiDotNetCoreExample.Models;
8+
using JsonApiDotNetCore.Extensions;
9+
using JsonApiDotNetCore.Data;
10+
using JsonApiDotNetCore.Models;
11+
using System.Threading.Tasks;
12+
using System.Linq;
13+
using JsonApiDotNetCore.Serialization;
14+
using JsonApiDotNetCore.Builders;
15+
using JsonApiDotNetCore.Managers.Contracts;
16+
17+
namespace UnitTests.Data
18+
{
19+
public class DefaultEntityRepository_Tests : JsonApiControllerMixin
20+
{
21+
private readonly Mock<ICurrentRequest> _currentRequestMock;
22+
private readonly Mock<DbSet<TodoItem>> _dbSetMock;
23+
private readonly Mock<DbContext> _contextMock;
24+
private readonly Mock<ITargetedFields> _targetedFieldsMock;
25+
private readonly Mock<IDbContextResolver> _contextResolverMock;
26+
private readonly TodoItem _todoItem;
27+
28+
public DefaultEntityRepository_Tests()
29+
{
30+
_todoItem = new TodoItem
31+
{
32+
Id = 1,
33+
Description = Guid.NewGuid().ToString(),
34+
Ordinal = 10
35+
};
36+
_currentRequestMock = new Mock<ICurrentRequest>();
37+
_dbSetMock = DbSetMock.Create(new[] { _todoItem });
38+
_contextMock = new Mock<DbContext>();
39+
_contextResolverMock = new Mock<IDbContextResolver>();
40+
_targetedFieldsMock = new Mock<ITargetedFields>();
41+
}
42+
43+
[Fact]
44+
public async Task UpdateAsync_Updates_Attributes_In_AttributesToUpdate()
45+
{
46+
// arrange
47+
var todoItemUpdates = new TodoItem
48+
{
49+
Id = _todoItem.Id,
50+
Description = Guid.NewGuid().ToString()
51+
};
52+
53+
var descAttr = new AttrAttribute("description", "Description");
54+
descAttr.PropertyInfo = typeof(TodoItem).GetProperty(nameof(TodoItem.Description));
55+
_targetedFieldsMock.Setup(m => m.Attributes).Returns(new List<AttrAttribute> { descAttr });
56+
_targetedFieldsMock.Setup(m => m.Relationships).Returns(new List<RelationshipAttribute>());
57+
58+
var repository = GetRepository();
59+
60+
// act
61+
var updatedItem = await repository.UpdateAsync(todoItemUpdates);
62+
63+
// assert
64+
Assert.NotNull(updatedItem);
65+
Assert.Equal(_todoItem.Ordinal, updatedItem.Ordinal);
66+
Assert.Equal(todoItemUpdates.Description, updatedItem.Description);
67+
}
68+
69+
private DefaultEntityRepository<TodoItem> GetRepository()
70+
{
71+
72+
_contextMock
73+
.Setup(m => m.Set<TodoItem>())
74+
.Returns(_dbSetMock.Object);
75+
76+
_contextResolverMock
77+
.Setup(m => m.GetContext())
78+
.Returns(_contextMock.Object);
79+
80+
var graph = new ResourceGraphBuilder().AddResource<TodoItem>().Build();
81+
82+
83+
return new DefaultEntityRepository<TodoItem>(
84+
_currentRequestMock.Object,
85+
_targetedFieldsMock.Object,
86+
_contextResolverMock.Object,
87+
graph, null, null);
88+
}
89+
90+
[Theory]
91+
[InlineData(0)]
92+
[InlineData(-1)]
93+
[InlineData(-10)]
94+
public async Task Page_When_PageSize_Is_NonPositive_Does_Nothing(int pageSize)
95+
{
96+
var todoItems = DbSetMock.Create(TodoItems(2, 3, 1)).Object;
97+
var repository = GetRepository();
98+
99+
var result = await repository.PageAsync(todoItems, pageSize, 3);
100+
101+
Assert.Equal(TodoItems(2, 3, 1), result, new IdComparer<TodoItem>());
102+
}
103+
104+
[Fact]
105+
public async Task Page_When_PageNumber_Is_Zero_Pretends_PageNumber_Is_One()
106+
{
107+
var todoItems = DbSetMock.Create(TodoItems(2, 3, 1)).Object;
108+
var repository = GetRepository();
109+
110+
var result = await repository.PageAsync(todoItems, 1, 0);
111+
112+
Assert.Equal(TodoItems(2), result, new IdComparer<TodoItem>());
113+
}
114+
115+
[Fact]
116+
public async Task Page_When_PageNumber_Of_PageSize_Does_Not_Exist_Return_Empty_Queryable()
117+
{
118+
var todoItems = DbSetMock.Create(TodoItems(2, 3, 1)).Object;
119+
var repository = GetRepository();
120+
121+
var result = await repository.PageAsync(todoItems, 2, 3);
122+
123+
Assert.Empty(result);
124+
}
125+
126+
[Theory]
127+
[InlineData(3, 2, new[] { 4, 5, 6 })]
128+
[InlineData(8, 2, new[] { 9 })]
129+
[InlineData(20, 1, new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 })]
130+
public async Task Page_When_PageNumber_Is_Positive_Returns_PageNumberTh_Page_Of_Size_PageSize(int pageSize, int pageNumber, int[] expectedResult)
131+
{
132+
var todoItems = DbSetMock.Create(TodoItems(1, 2, 3, 4, 5, 6, 7, 8, 9)).Object;
133+
var repository = GetRepository();
134+
135+
var result = await repository.PageAsync(todoItems, pageSize, pageNumber);
136+
137+
Assert.Equal(TodoItems(expectedResult), result, new IdComparer<TodoItem>());
138+
}
139+
140+
[Theory]
141+
[InlineData(6, -1, new[] { 4, 5, 6, 7, 8, 9 })]
142+
[InlineData(6, -2, new[] { 1, 2, 3 })]
143+
[InlineData(20, -1, new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 })]
144+
public async Task Page_When_PageNumber_Is_Negative_Returns_PageNumberTh_Page_From_End(int pageSize, int pageNumber, int[] expectedIds)
145+
{
146+
var todoItems = DbSetMock.Create(TodoItems(1, 2, 3, 4, 5, 6, 7, 8, 9)).Object;
147+
var repository = GetRepository();
148+
149+
var result = await repository.PageAsync(todoItems, pageSize, pageNumber);
150+
151+
Assert.Equal(TodoItems(expectedIds), result, new IdComparer<TodoItem>());
152+
}
153+
154+
private static TodoItem[] TodoItems(params int[] ids)
155+
{
156+
return ids.Select(id => new TodoItem { Id = id }).ToArray();
157+
}
158+
159+
private class IdComparer<T> : IEqualityComparer<T>
160+
where T : IIdentifiable
161+
{
162+
public bool Equals(T x, T y) => x?.StringId == y?.StringId;
163+
164+
public int GetHashCode(T obj) => obj?.StringId?.GetHashCode() ?? 0;
165+
}
166+
}
167+
}

0 commit comments

Comments
 (0)