public void PropertyWasPresentTest() { using (var inputStream = File.OpenRead("MetadataManagerPropertyWasPresentRequest.json")) { // Arrange var modelManager = new ModelManager(new PluralizationService()); modelManager.RegisterResourceType(typeof(Post)); modelManager.RegisterResourceType(typeof(Author)); JsonApiFormatter formatter = new JsonApiFormatter(modelManager); var p = (Post) formatter.ReadFromStreamAsync(typeof(Post), inputStream, null, null).Result; // Act bool idWasSet = MetadataManager.Instance.PropertyWasPresent(p, p.GetType().GetProperty("Id")); bool titleWasSet = MetadataManager.Instance.PropertyWasPresent(p, p.GetType().GetProperty("Title")); bool authorWasSet = MetadataManager.Instance.PropertyWasPresent(p, p.GetType().GetProperty("Author")); bool commentsWasSet = MetadataManager.Instance.PropertyWasPresent(p, p.GetType().GetProperty("Comments")); // Assert Assert.IsTrue(idWasSet, "Id was not reported as set, but was."); Assert.IsFalse(titleWasSet, "Title was reported as set, but was not."); Assert.IsTrue(authorWasSet, "Author was not reported as set, but was."); Assert.IsFalse(commentsWasSet, "Comments was reported as set, but was not."); } }
private DefaultSortingTransformer GetTransformer() { var pluralizationService = new PluralizationService(new Dictionary<string, string> { {"Dummy", "Dummies"} }); var modelManager = new ModelManager(pluralizationService); modelManager.RegisterResourceType(typeof(Dummy)); return new DefaultSortingTransformer(modelManager); }
public void FindsIdNamedId() { // Arrange var mm = new ModelManager(new PluralizationService()); mm.RegisterResourceType(typeof(Author)); // Act PropertyInfo idprop = mm.GetIdProperty(typeof(Author)); // Assert Assert.AreSame(typeof(Author).GetProperty("Id"), idprop); }
public void Cant_register_model_with_missing_id() { // Arrange var mm = new ModelManager(new PluralizationService()); // Act Action action = () => mm.RegisterResourceType(typeof(InvalidModel)); // Assert action.ShouldThrow<InvalidOperationException>() .Which.Message.Should() .Be("Unable to determine Id property for type `invalid-models`."); }
private static HttpConfiguration GetWebApiConfiguration() { var pluralizationService = new PluralizationService(); pluralizationService.AddMapping("todo", "todos"); var modelManager = new ModelManager(pluralizationService); modelManager.RegisterResourceType(typeof (Todo)); var httpConfig = new HttpConfiguration(); // Configure JSON API new JsonApiConfiguration(modelManager) .UsingDefaultQueryablePayloadBuilder(c => c.EnumerateQueriesAsynchronously()) .Apply(httpConfig); // Web API routes httpConfig.Routes.MapHttpRoute("DefaultApi", "{controller}/{id}", new { id = RouteParameter.Optional }); return httpConfig; }
public void Does_not_serialize_malformed_raw_json_string() { // Arrange var modelManager = new ModelManager(new PluralizationService()); modelManager.RegisterResourceType(typeof(Comment)); var formatter = new JsonApiFormatter(modelManager); MemoryStream stream = new MemoryStream(); // Act var payload = new[] { new Comment { Id = 5, CustomData = "{ x }" } }; formatter.WriteToStreamAsync(typeof(Comment), payload, stream, null, null); // Assert var minifiedExpectedJson = JsonHelpers.MinifyJson(File.ReadAllText("MalformedRawJsonString.json")); string output = System.Text.Encoding.ASCII.GetString(stream.ToArray()); Trace.WriteLine(output); output.Should().Be(minifiedExpectedJson); }
public void Should_serialize_error() { // Arrange var modelManager = new ModelManager(new PluralizationService()); var formatter = new JsonApiFormatter(modelManager, new MockErrorSerializer()); var stream = new MemoryStream(); // Act var payload = new HttpError(new Exception(), true); formatter.WriteToStreamAsync(typeof(HttpError), payload, stream, (System.Net.Http.HttpContent)null, (System.Net.TransportContext)null); // Assert var expectedJson = File.ReadAllText("FormatterErrorSerializationTest.json"); var minifiedExpectedJson = JsonHelpers.MinifyJson(expectedJson); var output = System.Text.Encoding.ASCII.GetString(stream.ToArray()); output.Should().Be(minifiedExpectedJson); }
public void Cant_register_type_with_two_properties_with_the_same_name() { var pluralizationService = new PluralizationService(); var mm = new ModelManager(pluralizationService); Type saladType = typeof(Salad); // Act Action action = () => mm.RegisterResourceType(saladType); // Assert action.ShouldThrow<InvalidOperationException>().Which.Message.Should().Be("The type `salads` already contains a property keyed at `salad-type`."); }
public void Serializes_null_list_as_empty_array() { // Arrange var modelManager = new ModelManager(new PluralizationService()); modelManager.RegisterResourceType(typeof(Comment)); var formatter = new JsonApiFormatter(modelManager); MemoryStream stream = new MemoryStream(); // Act formatter.WriteToStreamAsync(typeof(List<Comment>), null, stream, null, null); // Assert var minifiedExpectedJson = JsonHelpers.MinifyJson(File.ReadAllText("EmptyArrayResult.json")); string output = System.Text.Encoding.ASCII.GetString(stream.ToArray()); Trace.WriteLine(output); output.Should().Be(minifiedExpectedJson); }
public void DeserializeExtraRelationshipTest() { // Arrange var modelManager = new ModelManager(new PluralizationService()); modelManager.RegisterResourceType(typeof(Author)); var formatter = new JsonApiFormatter(modelManager); MemoryStream stream = new MemoryStream(); stream = new MemoryStream(System.Text.Encoding.ASCII.GetBytes(@"{""data"":{""id"":13,""type"":""authors"",""attributes"":{""name"":""Jason Hater""},""relationships"":{""posts"":{""data"":[]},""bogus"":{""data"":[]}}}}")); // Act Author a; a = (Author)formatter.ReadFromStreamAsync(typeof(Author), stream, (System.Net.Http.HttpContent)null, (System.Net.Http.Formatting.IFormatterLogger)null).Result; // Assert Assert.AreEqual("Jason Hater", a.Name); // Completed without exceptions and didn't timeout! }
public void DeserializeNonStandardIdTest() { var modelManager = new ModelManager(new PluralizationService()); modelManager.RegisterResourceType(typeof(NonStandardIdThing)); var formatter = new JsonApiFormatter(modelManager); var stream = new FileStream("NonStandardIdTest.json",FileMode.Open); // Act IList<NonStandardIdThing> things; things = (IList<NonStandardIdThing>)formatter.ReadFromStreamAsync(typeof(NonStandardIdThing), stream, (System.Net.Http.HttpContent)null, (System.Net.Http.Formatting.IFormatterLogger)null).Result; stream.Close(); // Assert things.Count.Should().Be(1); things.First().Uuid.Should().Be(new Guid("0657fd6d-a4ab-43c4-84e5-0933c84b4f4f")); }
public void FindsIdFromAttribute() { // Arrange var mm = new ModelManager(new PluralizationService()); mm.RegisterResourceType(typeof(CustomIdModel)); // Act PropertyInfo idprop = mm.GetIdProperty(typeof(CustomIdModel)); // Assert Assert.AreSame(typeof(CustomIdModel).GetProperty("Uuid"), idprop); }
public async Task Deserializes_attributes_properly() { using (var inputStream = File.OpenRead("DeserializeAttributeRequest.json")) { // Arrange var modelManager = new ModelManager(new PluralizationService()); modelManager.RegisterResourceType(typeof(Sample)); var formatter = new JsonApiFormatter(modelManager); // Act var deserialized = (IList<Sample>)await formatter.ReadFromStreamAsync(typeof(Sample), inputStream, null, null); // Assert deserialized.Count.Should().Be(2); deserialized[0].ShouldBeEquivalentTo(s1); deserialized[1].ShouldBeEquivalentTo(s2); } }
public void GetPropertyForJsonKey_returns_correct_value_for_custom_id() { // Arrange var pluralizationService = new PluralizationService(); var mm = new ModelManager(pluralizationService); Type bandType = typeof(Band); mm.RegisterResourceType(bandType); // Act var idProp = mm.GetPropertyForJsonKey(bandType, "id"); // Assert idProp.Property.Should().BeSameAs(bandType.GetProperty("BandName")); idProp.Should().BeOfType<FieldModelProperty>(); }
public void GetPropertyForJsonKeyTest() { // Arrange var pluralizationService = new PluralizationService(); var mm = new ModelManager(pluralizationService); Type authorType = typeof(Author); mm.RegisterResourceType(authorType); // Act var idProp = mm.GetPropertyForJsonKey(authorType, "id"); var nameProp = mm.GetPropertyForJsonKey(authorType, "name"); var postsProp = mm.GetPropertyForJsonKey(authorType, "posts"); // Assert idProp.Property.Should().BeSameAs(authorType.GetProperty("Id")); idProp.Should().BeOfType<FieldModelProperty>(); nameProp.Property.Should().BeSameAs(authorType.GetProperty("Name")); nameProp.Should().BeOfType<FieldModelProperty>(); postsProp.Property.Should().BeSameAs(authorType.GetProperty("Posts")); postsProp.Should().BeOfType<RelationshipModelProperty>(); }
public void GetElementTypeInvalidArgumentTest() { // Arrange var mm = new ModelManager(new PluralizationService()); // Act Type x = mm.GetElementType(typeof(Author)); // Assert Assert.IsNull(x, "Return value of GetElementType should be null for a non-Many type argument!"); }
public void GetElementTypeTest() { // Arrange var mm = new ModelManager(new PluralizationService()); // Act Type postTypeFromArray = mm.GetElementType(typeof(Post[])); Type postTypeFromEnumerable = mm.GetElementType(typeof(IEnumerable<Post>)); // Assert Assert.AreSame(typeof(Post), postTypeFromArray); Assert.AreSame(typeof(Post), postTypeFromEnumerable); }
public void IsSerializedAsManyTest() { // Arrange var mm = new ModelManager(new PluralizationService()); // Act bool isArray = mm.IsSerializedAsMany(typeof(Post[])); bool isGenericEnumerable = mm.IsSerializedAsMany(typeof(IEnumerable<Post>)); bool isString = mm.IsSerializedAsMany(typeof(string)); bool isAuthor = mm.IsSerializedAsMany(typeof(Author)); bool isNonGenericEnumerable = mm.IsSerializedAsMany(typeof(IEnumerable)); // Assert Assert.IsTrue(isArray); Assert.IsTrue(isGenericEnumerable); Assert.IsFalse(isString); Assert.IsFalse(isAuthor); Assert.IsFalse(isNonGenericEnumerable); }
public void SerializeErrorIntegrationTest() { // Arrange var modelManager = new ModelManager(new PluralizationService()); var formatter = new JsonApiFormatter(modelManager); MemoryStream stream = new MemoryStream(); var mockInnerException = new Mock<Exception>(MockBehavior.Strict); mockInnerException.Setup(m => m.Message).Returns("Inner exception message"); mockInnerException.Setup(m => m.StackTrace).Returns("Inner stack trace"); var outerException = new Exception("Outer exception message", mockInnerException.Object); var payload = new HttpError(outerException, true) { StackTrace = "Outer stack trace" }; // Act formatter.WriteToStreamAsync(typeof(HttpError), payload, stream, (System.Net.Http.HttpContent)null, (System.Net.TransportContext)null); // Assert var expectedJson = File.ReadAllText("ErrorSerializerTest.json"); var minifiedExpectedJson = JsonHelpers.MinifyJson(expectedJson); var output = System.Text.Encoding.ASCII.GetString(stream.ToArray()); // We don't know what the GUIDs will be, so replace them var regex = new Regex(@"[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}"); output = regex.Replace(output, "OUTER-ID", 1); output = regex.Replace(output, "INNER-ID", 1); output.Should().Be(minifiedExpectedJson); }
public void GetResourceTypeName_returns_correct_value_for_registered_types() { // Arrange var pluralizationService = new PluralizationService(); var mm = new ModelManager(pluralizationService); mm.RegisterResourceType(typeof(Post)); mm.RegisterResourceType(typeof(Author)); mm.RegisterResourceType(typeof(Comment)); mm.RegisterResourceType(typeof(UserGroup)); // Act var postKey = mm.GetResourceTypeNameForType(typeof(Post)); var authorKey = mm.GetResourceTypeNameForType(typeof(Author)); var commentKey = mm.GetResourceTypeNameForType(typeof(Comment)); var manyCommentKey = mm.GetResourceTypeNameForType(typeof(Comment[])); var userGroupsKey = mm.GetResourceTypeNameForType(typeof(UserGroup)); // Assert Assert.AreEqual("posts", postKey); Assert.AreEqual("authors", authorKey); Assert.AreEqual("comments", commentKey); Assert.AreEqual("comments", manyCommentKey); Assert.AreEqual("user-groups", userGroupsKey); }
public void Deserializes_collections_properly() { using (var inputStream = File.OpenRead("DeserializeCollectionRequest.json")) { // Arrange var modelManager = new ModelManager(new PluralizationService()); modelManager.RegisterResourceType(typeof(Post)); modelManager.RegisterResourceType(typeof(Author)); modelManager.RegisterResourceType(typeof(Comment)); var formatter = new JsonApiFormatter(modelManager); // Act var posts = (IList<Post>)formatter.ReadFromStreamAsync(typeof(Post), inputStream, null, null).Result; // Assert posts.Count.Should().Be(2); posts[0].Id.Should().Be(p.Id); posts[0].Title.Should().Be(p.Title); posts[0].Author.Id.Should().Be(a.Id); posts[0].Comments.Count.Should().Be(2); posts[0].Comments[0].Id.Should().Be(400); posts[0].Comments[1].Id.Should().Be(401); posts[1].Id.Should().Be(p2.Id); posts[1].Title.Should().Be(p2.Title); posts[1].Author.Id.Should().Be(a.Id); } }
public void GetJsonKeyForPropertyTest() { // Arrange var pluralizationService = new PluralizationService(); var mm = new ModelManager(pluralizationService); // Act var idKey = mm.CalculateJsonKeyForProperty(typeof(Author).GetProperty("Id")); var nameKey = mm.CalculateJsonKeyForProperty(typeof(Author).GetProperty("Name")); var postsKey = mm.CalculateJsonKeyForProperty(typeof(Author).GetProperty("Posts")); // Assert Assert.AreEqual("id", idKey); Assert.AreEqual("name", nameKey); Assert.AreEqual("posts", postsKey); }
public async Task DeserializeRawJsonTest() { using (var inputStream = File.OpenRead("DeserializeRawJsonTest.json")) { // Arrange var modelManager = new ModelManager(new PluralizationService()); modelManager.RegisterResourceType(typeof(Comment)); var formatter = new JsonApiFormatter(modelManager); // Act var comments = ((IEnumerable<Comment>)await formatter.ReadFromStreamAsync(typeof (Comment), inputStream, null, null)).ToArray(); // Assert Assert.AreEqual(2, comments.Count()); Assert.AreEqual(null, comments[0].CustomData); Assert.AreEqual("{\"foo\":\"bar\"}", comments[1].CustomData); } }
public void TypeIsRegistered_returns_false_for_collection_of_unregistered_types() { // Arrange var pluralizationService = new PluralizationService(); var mm = new ModelManager(pluralizationService); // Act var isRegistered = mm.TypeIsRegistered(typeof(ICollection<Comment>)); // Assert isRegistered.Should().BeFalse(); }
public void SerializeNonStandardIdTest() { // Arrange var modelManager = new ModelManager(new PluralizationService()); modelManager.RegisterResourceType(typeof(NonStandardIdThing)); var formatter = new JsonApiFormatter(modelManager); var stream = new MemoryStream(); var payload = new List<NonStandardIdThing> { new NonStandardIdThing { Uuid = new Guid("0657fd6d-a4ab-43c4-84e5-0933c84b4f4f"), Data = "Swap" } }; // Act formatter.WriteToStreamAsync(typeof(List<NonStandardIdThing>), payload, stream, (System.Net.Http.HttpContent)null, (System.Net.TransportContext)null); // Assert var expectedJson = File.ReadAllText("NonStandardIdTest.json"); var minifiedExpectedJson = JsonHelpers.MinifyJson(expectedJson); var output = System.Text.Encoding.ASCII.GetString(stream.ToArray()); output.Should().Be(minifiedExpectedJson); }
public void Serializes_byte_ids_properly() { // Arrang var modelManager = new ModelManager(new PluralizationService()); modelManager.RegisterResourceType(typeof(Tag)); var formatter = new JsonApiFormatter(modelManager); MemoryStream stream = new MemoryStream(); // Act formatter.WriteToStreamAsync(typeof(Tag), new[] { t1, t2, t3 }, stream, null, null); // Assert string output = System.Text.Encoding.ASCII.GetString(stream.ToArray()); Trace.WriteLine(output); var expected = JsonHelpers.MinifyJson(File.ReadAllText("ByteIdSerializationTest.json")); Assert.AreEqual(expected, output.Trim()); }
public void DeserializeNonStandardId() { var modelManager = new ModelManager(new PluralizationService()); modelManager.RegisterResourceType(typeof(NonStandardIdThing)); var formatter = new JsonApiFormatter(modelManager); string json = File.ReadAllText("NonStandardIdTest.json"); json = Regex.Replace(json, @"""uuid"":\s*""0657fd6d-a4ab-43c4-84e5-0933c84b4f4f""\s*,",""); // remove the uuid attribute var stream = new MemoryStream(System.Text.Encoding.ASCII.GetBytes(json)); // Act IList<NonStandardIdThing> things; things = (IList<NonStandardIdThing>)formatter.ReadFromStreamAsync(typeof(NonStandardIdThing), stream, (System.Net.Http.HttpContent)null, (System.Net.Http.Formatting.IFormatterLogger)null).Result; // Assert json.Should().NotContain("uuid", "The \"uuid\" attribute was supposed to be removed, test methodology problem!"); things.Count.Should().Be(1); things.First().Uuid.Should().Be(new Guid("0657fd6d-a4ab-43c4-84e5-0933c84b4f4f")); }
public void GetPropertyForJsonKey_returns_correct_value_for_JsonProperty_attribute() { // Arrange var pluralizationService = new PluralizationService(); var mm = new ModelManager(pluralizationService); Type bandType = typeof(Band); mm.RegisterResourceType(bandType); // Act var prop = mm.GetPropertyForJsonKey(bandType, "THE-GENRE"); // Assert prop.Property.Should().BeSameAs(bandType.GetProperty("Genre")); prop.Should().BeOfType<FieldModelProperty>(); }
public void SerializeArrayIntegrationTest() { // Arrange var modelManager = new ModelManager(new PluralizationService()); modelManager.RegisterResourceType(typeof(Author)); modelManager.RegisterResourceType(typeof(Comment)); modelManager.RegisterResourceType(typeof(Post)); var formatter = new JsonApiFormatter(modelManager); MemoryStream stream = new MemoryStream(); // Act formatter.WriteToStreamAsync(typeof(Post), new[] { p, p2, p3, p4 }, stream, (System.Net.Http.HttpContent)null, (System.Net.TransportContext)null); // Assert string output = System.Text.Encoding.ASCII.GetString(stream.ToArray()); Trace.WriteLine(output); var expected = JsonHelpers.MinifyJson(File.ReadAllText("SerializerIntegrationTest.json")); Assert.AreEqual(expected, output.Trim()); }
public void TypeIsRegistered_returns_false_if_no_type_in_hierarchy_is_registered() { // Arrange var pluralizationService = new PluralizationService(); var mm = new ModelManager(pluralizationService); // Act var isRegistered = mm.TypeIsRegistered(typeof(Comment)); // Assert isRegistered.Should().BeFalse(); }