Esempio n. 1
0
        public void SerializeErrorIntegrationTest()
        {
            // Arrange
            JsonApiFormatter formatter = new JSONAPI.Json.JsonApiFormatter(new JSONAPI.Core.PluralizationService());
            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 PropertyWasPresentTest()
        {
            // Arrange

            JsonApiFormatter formatter = new JSONAPI.Json.JsonApiFormatter(new JSONAPI.Core.PluralizationService());
            MemoryStream     stream    = new MemoryStream();

            stream = new MemoryStream(System.Text.Encoding.ASCII.GetBytes(@"{""posts"":{""id"":42,""links"":{""author"":""18""}}}"));

            Post p;

            p = (Post)formatter.ReadFromStreamAsync(typeof(Post), stream, (System.Net.Http.HttpContent)null, (System.Net.Http.Formatting.IFormatterLogger)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.");
        }
        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.");
            }
        }
Esempio n. 4
0
        public async Task UnderpostingTest()
        {
            // Arrange
            JsonApiFormatter formatter = new JSONAPI.Json.JsonApiFormatter(new JSONAPI.Core.PluralizationService());
            MemoryStream     stream    = new MemoryStream();

            EntityFrameworkMaterializer materializer = new EntityFrameworkMaterializer(context);

            string underpost = @"{""posts"":{""id"":""" + p.Id.ToString() + @""",""title"":""Not at all linkbait!""}}";

            stream = new MemoryStream(System.Text.Encoding.ASCII.GetBytes(underpost));

            int previousCommentsCount = p.Comments.Count;

            // Act
            Post pUpdated;

            pUpdated = (Post)await formatter.ReadFromStreamAsync(typeof(Post), stream, (System.Net.Http.HttpContent) null, (System.Net.Http.Formatting.IFormatterLogger) null);

            pUpdated = await materializer.MaterializeUpdateAsync <Post>(pUpdated);

            // Assert
            Assert.AreEqual(previousCommentsCount, pUpdated.Comments.Count, "Comments were wiped out!");
            Assert.AreEqual("Not at all linkbait!", pUpdated.Title, "Title was not updated.");
        }
Esempio n. 5
0
        public async Task DeserializePostIntegrationTest()
        {
            // Arrange
            JsonApiFormatter formatter = new JSONAPI.Json.JsonApiFormatter(new JSONAPI.Core.PluralizationService());
            MemoryStream     stream    = new MemoryStream();

            EntityFrameworkMaterializer materializer = new EntityFrameworkMaterializer(context);

            // Serialize a post and change the JSON... Not "unit" at all, I know, but a good integration test I think...
            formatter.WriteToStreamAsync(typeof(Post), p, stream, (System.Net.Http.HttpContent)null, (System.Net.TransportContext)null);
            string serializedPost = System.Text.Encoding.ASCII.GetString(stream.ToArray());

            // Change the post title (a scalar value)
            serializedPost = serializedPost.Replace("Linkbait!", "Not at all linkbait!");
            // Remove a comment (Note that order is undefined/not deterministic!)
            serializedPost = Regex.Replace(serializedPost, String.Format(@"(""comments""\s*:\s*\[[^]]*)(,""{0}""|""{0}"",)", c3.Id), @"$1");

            // Reread the serialized JSON...
            stream.Dispose();
            stream = new MemoryStream(System.Text.Encoding.ASCII.GetBytes(serializedPost));

            // Act
            Post pUpdated;

            pUpdated = (Post)await formatter.ReadFromStreamAsync(typeof(Post), stream, (System.Net.Http.HttpContent) null, (System.Net.Http.Formatting.IFormatterLogger) null);

            pUpdated = await materializer.MaterializeUpdateAsync <Post>(pUpdated);

            // Assert
            Assert.AreEqual(a, pUpdated.Author);
            Assert.AreEqual("Not at all linkbait!", pUpdated.Title);
            Assert.AreEqual(2, pUpdated.Comments.Count());
            Assert.IsFalse(pUpdated.Comments.Contains(c3));
            //Debug.WriteLine(sw.ToString());
        }
        /// <summary>
        /// Creates a new configuration
        /// </summary>
        public JsonApiHttpConfiguration(JsonApiFormatter formatter,
            FallbackDocumentBuilderAttribute fallbackDocumentBuilderAttribute,
            JsonApiExceptionFilterAttribute jsonApiExceptionFilterAttribute)
        {
            if (formatter == null) throw new ArgumentNullException("formatter");
            if (fallbackDocumentBuilderAttribute == null) throw new ArgumentNullException("fallbackDocumentBuilderAttribute");
            if (jsonApiExceptionFilterAttribute == null) throw new ArgumentNullException("jsonApiExceptionFilterAttribute");

            _formatter = formatter;
            _fallbackDocumentBuilderAttribute = fallbackDocumentBuilderAttribute;
            _jsonApiExceptionFilterAttribute = jsonApiExceptionFilterAttribute;
        }
        /// <summary>
        /// Applies the running configuration to an HttpConfiguration instance
        /// </summary>
        /// <param name="httpConfig">The HttpConfiguration to apply this JsonApiConfiguration to</param>
        public void Apply(HttpConfiguration httpConfig)
        {
            var formatter = new JsonApiFormatter(_modelManager);

            httpConfig.Formatters.Clear();
            httpConfig.Formatters.Add(formatter);

            var queryablePayloadBuilder = _payloadBuilderFactory();
            httpConfig.Filters.Add(new JsonApiQueryableAttribute(queryablePayloadBuilder));

            httpConfig.Services.Replace(typeof (IHttpControllerSelector),
                new PascalizedControllerSelector(httpConfig));
        }
Esempio n. 8
0
        public void SerializeTest()
        {
            // Arrange
            JsonApiFormatter formatter = new JSONAPI.Json.JsonApiFormatter(new JSONAPI.Core.PluralizationService());
            MemoryStream     stream    = new MemoryStream();

            // Act
            formatter.WriteToStreamAsync(typeof(Post), p.Comments.First(), stream, (System.Net.Http.HttpContent)null, (System.Net.TransportContext)null);

            // Assert
            string output = System.Text.Encoding.ASCII.GetString(stream.ToArray());

            Trace.WriteLine(output);
        }
Esempio n. 9
0
        public void DeserializeNonStandardIdTest()
        {
            var formatter = new JSONAPI.Json.JsonApiFormatter(new PluralizationService());
            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"));
        }
Esempio n. 10
0
        public void DeserializeExtraRelationshipTest()
        {
            JsonApiFormatter formatter = new JSONAPI.Json.JsonApiFormatter(new JSONAPI.Core.PluralizationService());
            MemoryStream     stream    = new MemoryStream();

            stream = new MemoryStream(System.Text.Encoding.ASCII.GetBytes(@"{""authors"":{""id"":13,""name"":""Jason Hater"",""links"":{""posts"":[],""bogus"":[""PANIC!""]}}}"));

            // 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!
        }
Esempio n. 11
0
        public void Should_serialize_error()
        {
            // Arrange
            var formatter = new JSONAPI.Json.JsonApiFormatter(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);
        }
Esempio n. 12
0
        public void DeserializeNonStandardIdWithoutId()
        {
            var    formatter = new JSONAPI.Json.JsonApiFormatter(new PluralizationService());
            string json      = File.ReadAllText("NonStandardIdTest.json");

            json = Regex.Replace(json, @"""id"":\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("\"id\"", "The \"id\" 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"));
        }
Esempio n. 13
0
        public void SerializeNonStandardIdTest()
        {
            var formatter = new JSONAPI.Json.JsonApiFormatter(new PluralizationService());
            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);
        }
Esempio n. 14
0
        public void DeserializeCollectionIntegrationTest()
        {
            // Arrange
            JsonApiFormatter formatter = new JSONAPI.Json.JsonApiFormatter(new JSONAPI.Core.PluralizationService());
            MemoryStream     stream    = new MemoryStream();

            formatter.WriteToStreamAsync(typeof(Post), new List <Post> {
                p, p2
            }, stream, (System.Net.Http.HttpContent)null, (System.Net.TransportContext)null);
            stream.Seek(0, SeekOrigin.Begin);

            // Act
            IList <Post> posts;

            posts = (IList <Post>)formatter.ReadFromStreamAsync(typeof(Post), stream, (System.Net.Http.HttpContent)null, (System.Net.Http.Formatting.IFormatterLogger)null).Result;

            // Assert
            Assert.AreEqual(2, posts.Count);
            Assert.AreEqual(p.Id, posts[0].Id); // Order matters, right?
        }
Esempio n. 15
0
        public void CanWritePrimitiveTest()
        {
            // Arrange
            JsonApiFormatter formatter = new JSONAPI.Json.JsonApiFormatter(new PluralizationService());

            // Act
            // Assert
            Assert.IsTrue(formatter.CanWriteTypeAsPrimitive(typeof(Int32)), "CanWriteTypeAsPrimitive returned wrong answer for Integer!");
            Assert.IsTrue(formatter.CanWriteTypeAsPrimitive(typeof(Double)), "CanWriteTypeAsPrimitive returned wrong answer for Double!");
            Assert.IsTrue(formatter.CanWriteTypeAsPrimitive(typeof(DateTime)), "CanWriteTypeAsPrimitive returned wrong answer for DateTime!");
            Assert.IsTrue(formatter.CanWriteTypeAsPrimitive(typeof(DateTimeOffset)), "CanWriteTypeAsPrimitive returned wrong answer for DateTimeOffset!");
            Assert.IsTrue(formatter.CanWriteTypeAsPrimitive(typeof(Guid)), "CanWriteTypeAsPrimitive returned wrong answer for Guid!");
            Assert.IsTrue(formatter.CanWriteTypeAsPrimitive(typeof(String)), "CanWriteTypeAsPrimitive returned wrong answer for String!");
            Assert.IsTrue(formatter.CanWriteTypeAsPrimitive(typeof(DateTime?)), "CanWriteTypeAsPrimitive returned wrong answer for nullable DateTime!");
            Assert.IsTrue(formatter.CanWriteTypeAsPrimitive(typeof(DateTimeOffset?)), "CanWriteTypeAsPrimitive returned wrong answer for nullable DateTimeOffset!");
            Assert.IsTrue(formatter.CanWriteTypeAsPrimitive(typeof(Guid?)), "CanWriteTypeAsPrimitive returned wrong answer for nullable Guid!");
            Assert.IsTrue(formatter.CanWriteTypeAsPrimitive(typeof(TestEnum)), "CanWriteTypeAsPrimitive returned wrong answer for enum!");
            Assert.IsTrue(formatter.CanWriteTypeAsPrimitive(typeof(TestEnum?)), "CanWriteTypeAsPrimitive returned wrong answer for nullable enum!");
            Assert.IsFalse(formatter.CanWriteTypeAsPrimitive(typeof(Object)), "CanWriteTypeAsPrimitive returned wrong answer for Object!");
        }
Esempio n. 16
0
        public void SerializeErrorIntegrationTest()
        {
            // Arrange
            JsonApiFormatter formatter = new JSONAPI.Json.JsonApiFormatter(new JSONAPI.Core.PluralizationService());
            MemoryStream     stream    = new MemoryStream();

            // Act
            var payload = new HttpError(new Exception("This is the exception message!"), true)
            {
                StackTrace = "Stack trace would go here"
            };

            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());

            output = Regex.Replace(output,
                                   @"[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}",
                                   "TEST-ERROR-ID"); // We don't know what the GUID will be, so replace it
            output.Should().Be(minifiedExpectedJson);
        }
Esempio n. 17
0
        public void SerializeArrayIntegrationTest()
        {
            // Arrange
            //PayloadConverter pc = new PayloadConverter();
            //ModelConverter mc = new ModelConverter();
            //ContractResolver.PluralizationService = new PluralizationService();

            JsonApiFormatter formatter = new JSONAPI.Json.JsonApiFormatter(new JSONAPI.Core.PluralizationService());
            MemoryStream     stream    = new MemoryStream();

            // Act
            //Payload payload = new Payload(a.Posts);
            //js.Serialize(jw, payload);
            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());
            //Assert.AreEqual("[2,3,4]", sw.ToString());
        }
        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 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 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);
            }
        }
 /// <summary>
 /// 
 /// </summary>
 /// <param name="errorDocumentBuilder"></param>
 /// <param name="jsonApiFormatter"></param>
 public JsonApiExceptionFilterAttribute(IErrorDocumentBuilder errorDocumentBuilder, JsonApiFormatter jsonApiFormatter)
 {
     _errorDocumentBuilder = errorDocumentBuilder;
     _jsonApiFormatter = jsonApiFormatter;
 }
        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 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 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 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 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 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 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 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 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);
        }