forked from JSONAPIdotNET/JSONAPI.NET
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJsonApiFormatterTestsBase.cs
More file actions
61 lines (57 loc) · 2.45 KB
/
Copy pathJsonApiFormatterTestsBase.cs
File metadata and controls
61 lines (57 loc) · 2.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
using System.IO;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using FluentAssertions;
using JSONAPI.Json;
using Newtonsoft.Json;
namespace JSONAPI.Tests.Json
{
public abstract class JsonApiFormatterTestsBase
{
protected async Task AssertSerializeOutput<TFormatter, TComponent>(TFormatter formatter, TComponent component, string expectedJsonFile)
where TFormatter : IJsonApiFormatter<TComponent>
{
var output = await GetSerializedString(formatter, component);
// Assert
var expectedJson = TestHelpers.ReadEmbeddedFile(expectedJsonFile);
var minifiedExpectedJson = JsonHelpers.MinifyJson(expectedJson);
output.Should().Be(minifiedExpectedJson);
}
protected async Task<string> GetSerializedString<TFormatter, TComponent>(TFormatter formatter, TComponent component)
where TFormatter : IJsonApiFormatter<TComponent>
{
using (var stream = new MemoryStream())
{
using (var textWriter = new StreamWriter(stream))
{
using (var writer = new JsonTextWriter(textWriter))
{
await formatter.Serialize(component, writer);
writer.Flush();
return Encoding.ASCII.GetString(stream.ToArray());
}
}
}
}
protected async Task<TComponent> GetDeserializedOutput<TFormatter, TComponent>(TFormatter formatter, string requestFileName)
where TFormatter : IJsonApiFormatter<TComponent>
{
var resourcePath = "JSONAPI.Tests." + requestFileName.Replace("\\", ".").Replace("/", ".");
using (var resourceStream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourcePath))
{
// ReSharper disable once AssignNullToNotNullAttribute
using (var textReader = new StreamReader(resourceStream))
{
using (var reader = new JsonTextReader(textReader))
{
reader.Read();
var deserialized = await formatter.Deserialize(reader, "");
reader.Read().Should().BeFalse(); // There should be nothing left to read.
return deserialized;
}
}
}
}
}
}