Skip to content

Commit

Permalink
Merge pull request #529 from microsoft/andrueastman/SerializationTests
Browse files Browse the repository at this point in the history
Adds test project for Serialization project
  • Loading branch information
andrueastman authored Aug 25, 2021
2 parents 8307c9f + fd02ffd commit 05ffc45
Show file tree
Hide file tree
Showing 12 changed files with 395 additions and 48 deletions.
11 changes: 9 additions & 2 deletions .github/workflows/serialization-dotnet-json.yml
Original file line number Diff line number Diff line change
Expand Up @@ -29,15 +29,22 @@ jobs:
run: dotnet build ${{ env.solutionName }} --no-restore -c Release
working-directory: ${{ env.relativePath }}
- name: Test
run: dotnet test ${{ env.solutionName }} --no-build --verbosity normal -c Release
run: dotnet test ${{ env.solutionName }} --no-build --verbosity normal -c Release /p:CollectCoverage=true /p:CoverletOutput=TestResults/ /p:CoverletOutputFormat=opencover
working-directory: ${{ env.relativePath }}
- name: Publish
run: dotnet publish ${{ env.solutionName }} --no-restore --no-build --verbosity normal -c Release
working-directory: ${{ env.relativePath }}
- name: Pack
run: dotnet pack ${{ env.solutionName }} --no-restore --no-build --verbosity normal -c Release
working-directory: ${{ env.relativePath }}
- uses: actions/upload-artifact@v2
- name: Upload Coverage Results
uses: actions/upload-artifact@v2
with:
name: codeCoverage
path: |
${{ env.relativePath }}/Microsoft.Kiota.Serialization.Json.Tests/TestResults
- name: Upload Nuget Package
uses: actions/upload-artifact@v2
with:
name: drop
path: |
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
using System;
using System.IO;
using System.Text;
using Xunit;

namespace Microsoft.Kiota.Serialization.Json.Tests
{
public class JsonParseNodeFactoryTests
{
private readonly JsonParseNodeFactory _jsonParseNodeFactory;
private const string TestJsonString = "{\"key\":\"value\"}";

public JsonParseNodeFactoryTests()
{
_jsonParseNodeFactory = new JsonParseNodeFactory();
}

[Fact]
public void GetsWriterForJsonContentType()
{
using var jsonStream = new MemoryStream(Encoding.UTF8.GetBytes(TestJsonString));
var jsonWriter = _jsonParseNodeFactory.GetRootParseNode(_jsonParseNodeFactory.ValidContentType,jsonStream);

// Assert
Assert.NotNull(jsonWriter);
Assert.IsAssignableFrom<JsonParseNode>(jsonWriter);
}

[Fact]
public void ThrowsArgumentOutOfRangeExceptionForInvalidContentType()
{
var streamContentType = "application/octet-stream";
using var jsonStream = new MemoryStream(Encoding.UTF8.GetBytes(TestJsonString));
var exception = Assert.Throws<ArgumentOutOfRangeException>(() => _jsonParseNodeFactory.GetRootParseNode(streamContentType,jsonStream));

// Assert
Assert.NotNull(exception);
Assert.Equal($"expected a {_jsonParseNodeFactory.ValidContentType} content type", exception.ParamName);
}

[Theory]
[InlineData(null)]
[InlineData("")]
public void ThrowsArgumentNullExceptionForNoContentType(string contentType)
{
using var jsonStream = new MemoryStream(Encoding.UTF8.GetBytes(TestJsonString));
var exception = Assert.Throws<ArgumentNullException>(() => _jsonParseNodeFactory.GetRootParseNode(contentType,jsonStream));

// Assert
Assert.NotNull(exception);
Assert.Equal("contentType", exception.ParamName);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
using System.Linq;
using System.Text.Json;
using Microsoft.Kiota.Serialization.Json.Tests.Mocks;
using Xunit;

namespace Microsoft.Kiota.Serialization.Json.Tests
{
public class JsonParseNodeTests
{
private const string TestUserJson = "{\r\n" +
" \"@odata.context\": \"https://graph.microsoft.com/v1.0/$metadata#users/$entity\",\r\n" +
" \"@odata.id\": \"https://graph.microsoft.com/v2/dcd219dd-bc68-4b9b-bf0b-4a33a796be35/directoryObjects/48d31887-5fad-4d73-a9f5-3c356e68a038/Microsoft.DirectoryServices.User\",\r\n" +
" \"businessPhones\": [\r\n" +
" \"+1 412 555 0109\"\r\n" +
" ],\r\n" +
" \"displayName\": \"Megan Bowen\",\r\n" +
" \"givenName\": \"Megan\",\r\n" +
" \"accountEnabled\": true,\r\n" +
" \"createdDateTime\": \"2017-07-29T03:07:25Z\",\r\n" +
" \"jobTitle\": \"Auditor\",\r\n" +
" \"mail\": \"[email protected]\",\r\n" +
" \"mobilePhone\": null,\r\n" +
" \"officeLocation\": \"12/1110\",\r\n" +
" \"preferredLanguage\": \"en-US\",\r\n" +
" \"surname\": \"Bowen\",\r\n" +
" \"userPrincipalName\": \"[email protected]\",\r\n" +
" \"id\": \"48d31887-5fad-4d73-a9f5-3c356e68a038\"\r\n" +
"}";

private static readonly string TestUserCollectionString = $"[{TestUserJson}]";

[Fact]
public void GetsEntityValueFromJson()
{
// Arrange
using var jsonDocument = JsonDocument.Parse(TestUserJson);
var jsonParseNode = new JsonParseNode(jsonDocument.RootElement);
// Act
var testEntity = jsonParseNode.GetObjectValue<TestEntity>();
// Assert
Assert.NotNull(testEntity);
Assert.NotEmpty(testEntity.AdditionalData);
Assert.True(testEntity.AdditionalData.ContainsKey("jobTitle"));
Assert.Equal("Auditor", testEntity.AdditionalData["jobTitle"]);
Assert.Equal("48d31887-5fad-4d73-a9f5-3c356e68a038", testEntity.Id);
}

[Fact]
public void GetCollectionOfObjectValuesFromJson()
{
// Arrange
using var jsonDocument = JsonDocument.Parse(TestUserCollectionString);
var jsonParseNode = new JsonParseNode(jsonDocument.RootElement);
// Act
var testEntityCollection = jsonParseNode.GetCollectionOfObjectValues<TestEntity>().ToArray();
// Assert
Assert.NotEmpty(testEntityCollection);
Assert.Equal("48d31887-5fad-4d73-a9f5-3c356e68a038", testEntityCollection[0].Id);
}

[Fact]
public void GetsChildNodeAndGetCollectionOfPrimitiveValuesFromJsonParseNode()
{
// Arrange
using var jsonDocument = JsonDocument.Parse(TestUserJson);
var rootParseNode = new JsonParseNode(jsonDocument.RootElement);
// Act to get business phones list
var phonesListChildNode = rootParseNode.GetChildNode("businessPhones");
var phonesList = phonesListChildNode.GetCollectionOfPrimitiveValues<string>().ToArray();
// Assert
Assert.NotEmpty(phonesList);
Assert.Equal("+1 412 555 0109", phonesList[0]);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
using System;
using Xunit;

namespace Microsoft.Kiota.Serialization.Json.Tests
{
public class JsonSerializationWriterFactoryTests
{
private readonly JsonSerializationWriterFactory _jsonSerializationFactory;

public JsonSerializationWriterFactoryTests()
{
_jsonSerializationFactory = new JsonSerializationWriterFactory();
}

[Fact]
public void GetsWriterForJsonContentType()
{
var jsonWriter = _jsonSerializationFactory.GetSerializationWriter(_jsonSerializationFactory.ValidContentType);

// Assert
Assert.NotNull(jsonWriter);
Assert.IsAssignableFrom<JsonSerializationWriter>(jsonWriter);
}

[Fact]
public void ThrowsArgumentOutOfRangeExceptionForInvalidContentType()
{
var streamContentType = "application/octet-stream";
var exception = Assert.Throws<ArgumentOutOfRangeException>(() => _jsonSerializationFactory.GetSerializationWriter(streamContentType));

// Assert
Assert.NotNull(exception);
Assert.Equal($"expected a {_jsonSerializationFactory.ValidContentType} content type", exception.ParamName);
}

[Theory]
[InlineData(null)]
[InlineData("")]
public void ThrowsArgumentNullExceptionForNoContentType(string contentType)
{
var exception = Assert.Throws<ArgumentNullException>(() => _jsonSerializationFactory.GetSerializationWriter(contentType));

// Assert
Assert.NotNull(exception);
Assert.Equal("contentType", exception.ParamName);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using Microsoft.Kiota.Serialization.Json.Tests.Mocks;
using Xunit;

namespace Microsoft.Kiota.Serialization.Json.Tests
{
public class JsonSerializationWriterTests
{
[Fact]
public void WritesSampleObjectValue()
{
// Arrange
var testEntity = new TestEntity()
{
Id = "48d31887-5fad-4d73-a9f5-3c356e68a038",
AdditionalData = new Dictionary<string, object>
{
{"mobilePhone",null}, // write null value
{"accountEnabled",false}, // write bool value
{"jobTitle","Author"}, // write string value
{"createdDateTime", DateTimeOffset.MinValue}, // write date value
{"businessPhones", new List<string>() {"+1 412 555 0109"}}, // write collection of primitives value
{"manager", new TestEntity{Id = "48d31887-5fad-4d73-a9f5-3c356e68a038"}}, // write nested object value
}
};
using var jsonSerializerWriter = new JsonSerializationWriter();
// Act
jsonSerializerWriter.WriteObjectValue(string.Empty,testEntity);
// Get the json string from the stream.
var serializedStream = jsonSerializerWriter.GetSerializedContent();
using var reader = new StreamReader(serializedStream, Encoding.UTF8);
var serializedJsonString = reader.ReadToEnd();

// Assert
var expectedString = "{" +
"\"id\":\"48d31887-5fad-4d73-a9f5-3c356e68a038\"," +
"\"mobilePhone\":null," +
"\"accountEnabled\":false," +
"\"jobTitle\":\"Author\"," +
"\"createdDateTime\":\"0001-01-01T00:00:00+00:00\"," +
"\"businessPhones\":[\"\\u002B1 412 555 0109\"]," +
"\"manager\":{\"id\":\"48d31887-5fad-4d73-a9f5-3c356e68a038\"}"+
"}";
Assert.Equal(expectedString, serializedJsonString);
}

[Fact]
public void WritesSampleCollectionOfObjectValues()
{
// Arrange
var testEntity = new TestEntity()
{
Id = "48d31887-5fad-4d73-a9f5-3c356e68a038",
AdditionalData = new Dictionary<string, object>
{
{"mobilePhone",null}, // write null value
{"accountEnabled",false}, // write bool value
{"jobTitle","Author"}, // write string value
{"createdDateTime", DateTimeOffset.MinValue}, // write date value
{"businessPhones", new List<string>() {"+1 412 555 0109"}}, // write collection of primitives value
{"manager", new TestEntity{Id = "48d31887-5fad-4d73-a9f5-3c356e68a038"}}, // write nested object value
}
};
var entityList = new List<TestEntity>() { testEntity};
using var jsonSerializerWriter = new JsonSerializationWriter();
// Act
jsonSerializerWriter.WriteCollectionOfObjectValues(string.Empty, entityList);
// Get the json string from the stream.
var serializedStream = jsonSerializerWriter.GetSerializedContent();
using var reader = new StreamReader(serializedStream, Encoding.UTF8);
var serializedJsonString = reader.ReadToEnd();

// Assert
var expectedString = "[{" +
"\"id\":\"48d31887-5fad-4d73-a9f5-3c356e68a038\"," +
"\"mobilePhone\":null," +
"\"accountEnabled\":false," +
"\"jobTitle\":\"Author\"," +
"\"createdDateTime\":\"0001-01-01T00:00:00+00:00\"," +
"\"businessPhones\":[\"\\u002B1 412 555 0109\"]," +
"\"manager\":{\"id\":\"48d31887-5fad-4d73-a9f5-3c356e68a038\"}" +
"}]";
Assert.Equal(expectedString, serializedJsonString);
}

}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net5.0</TargetFramework>

<IsPackable>false</IsPackable>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="coverlet.msbuild" Version="3.1.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.11.0" />
<PackageReference Include="Moq" Version="4.16.1" />
<PackageReference Include="xunit" Version="2.4.1" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.3">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="coverlet.collector" Version="3.1.0">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\src\Microsoft.Kiota.Serialization.Json.csproj" />
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
using System;
using System.Collections.Generic;
using Microsoft.Kiota.Abstractions.Serialization;

namespace Microsoft.Kiota.Serialization.Json.Tests.Mocks
{
public class TestEntity : IParsable
{
/// <summary>Stores additional data not described in the OpenAPI description found when deserializing. Can be used for serialization as well.</summary>
public IDictionary<string, object> AdditionalData { get; set; }
/// <summary>Read-only.</summary>
public string Id { get; set; }
/// <summary>
/// Instantiates a new entity and sets the default values.
/// </summary>
public TestEntity()
{
AdditionalData = new Dictionary<string, object>();
}
/// <summary>
/// The deserialization information for the current model
/// </summary>
public IDictionary<string, Action<T, IParseNode>> GetFieldDeserializers<T>()
{
return new Dictionary<string, Action<T, IParseNode>> {
{"id", (o,n) => { (o as TestEntity).Id = n.GetStringValue(); } },
};
}
/// <summary>
/// Serializes information the current object
/// <param name="writer">Serialization writer to use to serialize this model</param>
/// </summary>
public void Serialize(ISerializationWriter writer)
{
_ = writer ?? throw new ArgumentNullException(nameof(writer));
writer.WriteStringValue("id", Id);
writer.WriteAdditionalData(AdditionalData);
}
}
}
14 changes: 14 additions & 0 deletions serialization/dotnet/json/Microsoft.Kiota.Serialization.Json.sln
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution
.editorconfig = .editorconfig
EndProjectSection
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Microsoft.Kiota.Serialization.Json.Tests", "Microsoft.Kiota.Serialization.Json.Tests\Microsoft.Kiota.Serialization.Json.Tests.csproj", "{AC81733F-EC61-4241-ADCF-E16BA1EDD7AF}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand All @@ -32,6 +34,18 @@ Global
{8CC6634E-A611-4FB9-9C31-1BE038D75E1E}.Release|x64.Build.0 = Release|Any CPU
{8CC6634E-A611-4FB9-9C31-1BE038D75E1E}.Release|x86.ActiveCfg = Release|Any CPU
{8CC6634E-A611-4FB9-9C31-1BE038D75E1E}.Release|x86.Build.0 = Release|Any CPU
{AC81733F-EC61-4241-ADCF-E16BA1EDD7AF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{AC81733F-EC61-4241-ADCF-E16BA1EDD7AF}.Debug|Any CPU.Build.0 = Debug|Any CPU
{AC81733F-EC61-4241-ADCF-E16BA1EDD7AF}.Debug|x64.ActiveCfg = Debug|Any CPU
{AC81733F-EC61-4241-ADCF-E16BA1EDD7AF}.Debug|x64.Build.0 = Debug|Any CPU
{AC81733F-EC61-4241-ADCF-E16BA1EDD7AF}.Debug|x86.ActiveCfg = Debug|Any CPU
{AC81733F-EC61-4241-ADCF-E16BA1EDD7AF}.Debug|x86.Build.0 = Debug|Any CPU
{AC81733F-EC61-4241-ADCF-E16BA1EDD7AF}.Release|Any CPU.ActiveCfg = Release|Any CPU
{AC81733F-EC61-4241-ADCF-E16BA1EDD7AF}.Release|Any CPU.Build.0 = Release|Any CPU
{AC81733F-EC61-4241-ADCF-E16BA1EDD7AF}.Release|x64.ActiveCfg = Release|Any CPU
{AC81733F-EC61-4241-ADCF-E16BA1EDD7AF}.Release|x64.Build.0 = Release|Any CPU
{AC81733F-EC61-4241-ADCF-E16BA1EDD7AF}.Release|x86.ActiveCfg = Release|Any CPU
{AC81733F-EC61-4241-ADCF-E16BA1EDD7AF}.Release|x86.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand Down
Loading

0 comments on commit 05ffc45

Please sign in to comment.