public async Task ReadAsync_ReturnsFailure_IfItCanNotUnderstandTheContentTypeEncoding()
        {
            // Arrange
            var formatter = new TestFormatter();

            formatter.SupportedEncodings.Add(Encoding.ASCII);

            var context = new InputFormatterContext(
                new DefaultHttpContext(),
                "something",
                new ModelStateDictionary(),
                new EmptyModelMetadataProvider().GetMetadataForType(typeof(object)),
                (stream, encoding) => new StreamReader(stream, encoding));

            context.HttpContext.Request.ContentType   = "application/json;charset=utf-8";
            context.HttpContext.Request.ContentLength = 1;

            // Act
            var result = await formatter.ReadAsync(context);

            // Assert
            Assert.True(result.HasError);
            Assert.True(context.ModelState.ContainsKey("something"));
            Assert.Single(context.ModelState["something"].Errors);

            var error = context.ModelState["something"].Errors[0];

            Assert.IsType <UnsupportedContentTypeException>(error.Exception);
        }
Beispiel #2
0
 public void GetNext_UnexpectedObject_ThrowsException()
 {
     var f = new TestFormatter();
     f.m_objectQueue.Enqueue(new object());
     long id;
     Assert.Throws<SerializationException>(() => f.GetNext(out id));
 }
        public void GetNext_UnexpectedObject_ThrowsException()
        {
            var f = new TestFormatter();

            f.m_objectQueue.Enqueue(new object());
            long id;

            Assert.Throws <SerializationException>(() => f.GetNext(out id));
        }
Beispiel #4
0
        public void Should_format_message_without_output_template()
        {
            var formatter = new TestFormatter();

            var template  = new MessageTemplateParser().Parse(MESSAGE);
            var infoEvent = new LogEvent(DateTimeOffset.Now, LogEventLevel.Information, null, template, Enumerable.Empty <LogEventProperty>());

            var formatted = formatter.FormatMessage(infoEvent);

            formatted.ShouldBe(MESSAGE);
        }
Beispiel #5
0
        public void DefaultCtor_ObjectsInitialized()
        {
            var f = new TestFormatter();

            Assert.NotNull(f.m_idGenerator);
            Assert.NotNull(f.m_objectQueue);
            Assert.Equal(0, f.m_objectQueue.Count);

            bool firstTime;
            Assert.Throws<ArgumentNullException>("obj", () => f.m_idGenerator.GetId(null, out firstTime));
            Assert.Throws<ArgumentNullException>("obj", () => f.m_idGenerator.HasId(null, out firstTime));
        }
        public void DefaultCtor_ObjectsInitialized()
        {
            var f = new TestFormatter();

            Assert.NotNull(f.m_idGenerator);
            Assert.NotNull(f.m_objectQueue);
            Assert.Equal(0, f.m_objectQueue.Count);

            bool firstTime;

            Assert.Throws <ArgumentNullException>("obj", () => f.m_idGenerator.GetId(null, out firstTime));
            Assert.Throws <ArgumentNullException>("obj", () => f.m_idGenerator.HasId(null, out firstTime));
        }
        public void GetSupportedContentTypes_NonNullContentType_FiltersContentTypes()
        {
            // Arrange
            var formatter = new TestFormatter();

            formatter.SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse("application/xml"));
            formatter.SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse("text/xml"));

            // Act
            var results = formatter.GetSupportedContentTypes("text/*", typeof(string));

            // Assert
            Assert.Collection(results, c => Assert.Equal("text/xml", c));
        }
        public void GetSupportedContentTypes_SupportedObjectType_ReturnsContentTypes()
        {
            // Arrange
            var formatter = new TestFormatter();

            formatter.SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse("text/xml"));
            formatter.SupportedTypes.Add(typeof(string));

            // Act
            var results = formatter.GetSupportedContentTypes(contentType: null, objectType: typeof(string));

            // Assert
            Assert.Collection(results, c => Assert.Equal("text/xml", c));
        }
        public void GetSupportedContentTypes_UnsupportedObjectType_ReturnsNull()
        {
            // Arrange
            var formatter = new TestFormatter();

            formatter.SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse("text/xml"));
            formatter.SupportedTypes.Add(typeof(string));

            // Act
            var results = formatter.GetSupportedContentTypes(contentType: null, objectType: typeof(int));

            // Assert
            Assert.Null(results);
        }
        public void SelectCharacterEncoding_ThrowsInvalidOperationException_IfItDoesNotHaveAValidEncoding()
        {
            // Arrange
            var formatter = new TestFormatter();

            var context = new InputFormatterContext(
                new DefaultHttpContext(),
                "something",
                new ModelStateDictionary(),
                new EmptyModelMetadataProvider().GetMetadataForType(typeof(object)),
                (stream, encoding) => new StreamReader(stream, encoding));

            context.HttpContext.Request.ContentLength = 1;

            // Act & Assert
            Assert.Throws <InvalidOperationException>(() => formatter.TestSelectCharacterEncoding(context));
        }
        public void GetSupportedContentTypes_NullContentType_ReturnsAllContentTypes()
        {
            // Arrange
            var formatter = new TestFormatter();

            formatter.SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse("application/xml"));
            formatter.SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse("text/xml"));

            // Act
            var results = formatter.GetSupportedContentTypes(contentType: null, objectType: typeof(string));

            // Assert
            Assert.Collection(
                results.OrderBy(c => c.ToString()),
                c => Assert.Equal("application/xml", c),
                c => Assert.Equal("text/xml", c));
        }
        public void WriteMember_InvokesProperMethod()
        {
            string calledMethod = null;
            object result       = null;
            var    f            = new TestFormatter {
                WriteCallback = (name, val) => { calledMethod = name; result = val; }
            };

            Action <string, object> verify = (expectedMember, expectedValue) =>
            {
                f.WriteMember("Member", expectedValue);
                Assert.Equal(expectedMember, calledMethod);
                Assert.Equal(expectedValue, result);
            };

            verify("WriteBoolean", true);
            verify("WriteByte", (byte)42);
            verify("WriteChar", 'c');
            verify("WriteDateTime", DateTime.Now);
            verify("WriteDecimal", 42m);
            verify("WriteDouble", 1.2);
            verify("WriteInt16", (short)42);
            verify("WriteInt32", 42);
            verify("WriteInt64", (long)42);
            verify("WriteSByte", (sbyte)42);
            verify("WriteSingle", 1.2f);
            verify("WriteUInt16", (ushort)42);
            verify("WriteUInt32", (uint)42);
            verify("WriteUInt64", (ulong)42);
            verify("WriteValueType", new KeyValuePair <int, int>(1, 2));
            // verify("WriteTimeSpan", TimeSpan.FromSeconds(42)); // Fails on both desktop and core, getting routed as a normal ValueType:
            verify("WriteValueType", TimeSpan.FromSeconds(42));
            verify("WriteObjectRef", new ObjectWithIntStringUShortUIntULongAndCustomObjectFields());
            verify("WriteObjectRef", null);

            f.WriteMember("Member", new[] { 1, 2, 3, 4, 5 });
            Assert.Equal("WriteArray", calledMethod);
            Assert.Equal <int>(new[] { 1, 2, 3, 4, 5 }, (int[])result);
        }
        public void SelectCharacterEncoding_ReturnsNull_IfItCanNotUnderstandContentTypeEncoding(string charset)
        {
            // Arrange
            var formatter = new TestFormatter();

            formatter.SupportedEncodings.Add(Encoding.UTF32);

            var context = new InputFormatterContext(
                new DefaultHttpContext(),
                "something",
                new ModelStateDictionary(),
                new EmptyModelMetadataProvider().GetMetadataForType(typeof(object)),
                (stream, encoding) => new StreamReader(stream, encoding));

            context.HttpContext.Request.ContentType = "application/json;charset=" + charset;

            // Act
            var result = formatter.TestSelectCharacterEncoding(context);

            // Assert
            Assert.Null(result);
        }
        public async Task ReadAsync_WithEmptyRequest_ReturnsNoValueResultWhenExpected(bool allowEmptyInputValue, bool expectedIsModelSet)
        {
            // Arrange
            var formatter = new TestFormatter();
            var context   = new InputFormatterContext(
                new DefaultHttpContext(),
                string.Empty,
                new ModelStateDictionary(),
                new EmptyModelMetadataProvider().GetMetadataForType(typeof(object)),
                (s, e) => new StreamReader(s, e),
                allowEmptyInputValue);

            context.HttpContext.Request.ContentLength = 0;

            // Act
            var result = await formatter.ReadAsync(context);

            // Assert
            Assert.False(result.HasError);
            Assert.Null(result.Model);
            Assert.Equal(expectedIsModelSet, result.IsModelSet);
        }
        public void ScheduleAndGetObjects_ExpectedIDsAndOrder()
        {
            var f = new TestFormatter();

            // null values don't count
            long actualId;

            Assert.Equal(0, f.Schedule(null));
            Assert.Equal(0, f.Schedule(null));
            Assert.Null(f.GetNext(out actualId));
            Assert.Equal(0, actualId);

            var objects = new object[] { new object(), new object(), new object() };

            // Add each object for the first time
            long nextExpectedId = 1;

            foreach (var obj in objects)
            {
                Assert.Equal(nextExpectedId++, f.Schedule(obj));
            }

            // Adding them again should produce the same IDs
            nextExpectedId = 1;
            foreach (var obj in objects)
            {
                Assert.Equal(nextExpectedId++, f.Schedule(obj));
            }

            // Now retrieve them all
            nextExpectedId = 1;
            foreach (var obj in objects)
            {
                var actualObj = f.GetNext(out actualId);
                Assert.Same(obj, actualObj);
                Assert.Equal(nextExpectedId++, actualId);
            }
        }
        public void SelectCharacterEncoding_ReturnsAsciiEncoding_IfContentTypeIsAnAlias(string charset)
        {
            // Arrange
            var formatter = new TestFormatter();

            formatter.SupportedEncodings.Add(Encoding.UTF32);
            formatter.SupportedEncodings.Add(Encoding.ASCII);

            var context = new InputFormatterContext(
                new DefaultHttpContext(),
                "something",
                new ModelStateDictionary(),
                new EmptyModelMetadataProvider().GetMetadataForType(typeof(object)),
                (stream, encoding) => new StreamReader(stream, encoding));

            context.HttpContext.Request.ContentType = "application/json;charset=\"" + charset + "\"";

            // Act
            var result = formatter.TestSelectCharacterEncoding(context);

            // Assert
            Assert.Equal(Encoding.ASCII, result);
        }
        public void SelectCharacterEncoding_ReturnsFirstEncoding_IfContentTypeIsNotSpecifiedOrDoesNotHaveEncoding(string contentType)
        {
            // Arrange
            var formatter = new TestFormatter();

            formatter.SupportedEncodings.Add(Encoding.UTF8);
            formatter.SupportedEncodings.Add(Encoding.UTF32);

            var context = new InputFormatterContext(
                new DefaultHttpContext(),
                "something",
                new ModelStateDictionary(),
                new EmptyModelMetadataProvider().GetMetadataForType(typeof(object)),
                (stream, encoding) => new StreamReader(stream, encoding));

            context.HttpContext.Request.ContentType = contentType;

            // Act
            var result = formatter.TestSelectCharacterEncoding(context);

            // Assert
            Assert.Equal(Encoding.UTF8, result);
        }
Beispiel #18
0
    public static void TestFormat()
    {
        String s;

        s = String.Format(null, "0 = {0} 1 = {1} 2 = {2} 3 = {3} 4 = {4}", "zero", "one", "two", "three", "four");
        Assert.True(s == "0 = zero 1 = one 2 = two 3 = three 4 = four");

        TestFormatter testFormatter = new TestFormatter();

        s = String.Format(testFormatter, "0 = {0} 1 = {1} 2 = {2} 3 = {3} 4 = {4}", "zero", "one", "two", "three", "four");
        Assert.True(s == "0 = Test: : zero 1 = Test: : one 2 = Test: : two 3 = Test: : three 4 = Test: : four");

        Assert.Throws <ArgumentNullException>(
            delegate()
        {
            s = String.Format(testFormatter, null, 0, 1, 2, 3, 4);
        });

        Assert.Throws <FormatException>(
            delegate()
        {
            s = String.Format(testFormatter, "Missing={5}", 0, 1, 2, 3, 4);
        });
    }
Beispiel #19
0
        public void WriteMember_InvokesProperMethod()
        {
            string calledMethod = null;
            object result = null;
            var f = new TestFormatter { WriteCallback = (name, val) => { calledMethod = name; result = val; } };

            Action<string, object> verify = (expectedMember, expectedValue) =>
            {
                f.WriteMember("Member", expectedValue);
                Assert.Equal(expectedMember, calledMethod);
                Assert.Equal(expectedValue, result);
            };
            verify("WriteBoolean", true);
            verify("WriteByte", (byte)42);
            verify("WriteChar", 'c');
            verify("WriteDateTime", DateTime.Now);
            verify("WriteDecimal", 42m);
            verify("WriteDouble", 1.2);
            verify("WriteInt16", (short)42);
            verify("WriteInt32", 42);
            verify("WriteInt64", (long)42);
            verify("WriteSByte", (sbyte)42);
            verify("WriteSingle", 1.2f);
            verify("WriteUInt16", (ushort)42);
            verify("WriteUInt32", (uint)42);
            verify("WriteUInt64", (ulong)42);
            verify("WriteValueType", new KeyValuePair<int, int>(1, 2));
            // verify("WriteTimeSpan", TimeSpan.FromSeconds(42)); // Fails on both desktop and core, getting routed as a normal ValueType:
            verify("WriteValueType", TimeSpan.FromSeconds(42));
            verify("WriteObjectRef", new ObjectWithIntStringUShortUIntULongAndCustomObjectFields());
            verify("WriteObjectRef", null);

            f.WriteMember("Member", new[] { 1, 2, 3, 4, 5 });
            Assert.Equal("WriteArray", calledMethod);
            Assert.Equal<int>(new[] { 1, 2, 3, 4, 5 }, (int[])result);
        }
Beispiel #20
0
        public void ScheduleAndGetObjects_ExpectedIDsAndOrder()
        {
            var f = new TestFormatter();

            // null values don't count
            long actualId;
            Assert.Equal(0, f.Schedule(null));
            Assert.Equal(0, f.Schedule(null));
            Assert.Null(f.GetNext(out actualId));
            Assert.Equal(0, actualId);

            var objects = new object[] { new object(), new object(), new object() };

            // Add each object for the first time
            long nextExpectedId = 1;
            foreach (var obj in objects)
            {
                Assert.Equal(nextExpectedId++, f.Schedule(obj));
            }

            // Adding them again should produce the same IDs
            nextExpectedId = 1;
            foreach (var obj in objects)
            {
                Assert.Equal(nextExpectedId++, f.Schedule(obj));
            }

            // Now retrieve them all
            nextExpectedId = 1;
            foreach (var obj in objects)
            {
                var actualObj = f.GetNext(out actualId);
                Assert.Same(obj, actualObj);
                Assert.Equal(nextExpectedId++, actualId);
            }
        }
Beispiel #21
0
    public static void TestFormatInvalid()
    {
        TestFormatter testFormatter = new TestFormatter();

        Assert.Throws<ArgumentNullException>("format", () => String.Format(testFormatter, null, 0, 1, 2, 3, 4));

        Assert.Throws<FormatException>(() => String.Format(testFormatter, "Missing={5}", 0, 1, 2, 3, 4));
    }
Beispiel #22
0
    public static void TestFormat()
    {
        String s;
        s = String.Format(null, "0 = {0} 1 = {1} 2 = {2} 3 = {3} 4 = {4}", "zero", "one", "two", "three", "four");
        Assert.Equal("0 = zero 1 = one 2 = two 3 = three 4 = four", s);

        TestFormatter testFormatter = new TestFormatter();
        s = String.Format(testFormatter, "0 = {0} 1 = {1} 2 = {2} 3 = {3} 4 = {4}", "zero", "one", "two", "three", "four");
        Assert.Equal("0 = Test: : zero 1 = Test: : one 2 = Test: : two 3 = Test: : three 4 = Test: : four", s);

        Assert.Throws<ArgumentNullException>(
            delegate ()
            {
                s = String.Format(testFormatter, null, 0, 1, 2, 3, 4);
            });

        Assert.Throws<FormatException>(
            delegate ()
            {
                s = String.Format(testFormatter, "Missing={5}", 0, 1, 2, 3, 4);
            });
    }
Beispiel #23
0
        public static void Format_Invalid()
        {
            var formatter = new TestFormatter();
            var obj1 = new object();
            var obj2 = new object();
            var obj3 = new object();
            var obj4 = new object();

            // Format is null
            Assert.Throws<ArgumentNullException>("format", () => string.Format(null, obj1));
            Assert.Throws<ArgumentNullException>("format", () => string.Format(null, obj1, obj2));
            Assert.Throws<ArgumentNullException>("format", () => string.Format(null, obj1, obj2, obj3));
            Assert.Throws<ArgumentNullException>("format", () => string.Format(null, obj1, obj2, obj3, obj4));

            Assert.Throws<ArgumentNullException>("format", () => string.Format(formatter, null, obj1));
            Assert.Throws<ArgumentNullException>("format", () => string.Format(formatter, null, obj1, obj2));
            Assert.Throws<ArgumentNullException>("format", () => string.Format(formatter, null, obj1, obj2, obj3));

            // Args is null
            Assert.Throws<ArgumentNullException>("args", () => string.Format("", null));
            Assert.Throws<ArgumentNullException>("args", () => string.Format(formatter, "", null));

            // Args and format are null
            Assert.Throws<ArgumentNullException>("format", () => string.Format(null, (object[])null));
            Assert.Throws<ArgumentNullException>("format", () => string.Format(formatter, null, null));

            // Format has value < 0
            Assert.Throws<FormatException>(() => string.Format("{-1}", obj1));
            Assert.Throws<FormatException>(() => string.Format("{-1}", obj1, obj2));
            Assert.Throws<FormatException>(() => string.Format("{-1}", obj1, obj2, obj3));
            Assert.Throws<FormatException>(() => string.Format("{-1}", obj1, obj2, obj3, obj4));
            Assert.Throws<FormatException>(() => string.Format(formatter, "{-1}", obj1));
            Assert.Throws<FormatException>(() => string.Format(formatter, "{-1}", obj1, obj2));
            Assert.Throws<FormatException>(() => string.Format(formatter, "{-1}", obj1, obj2, obj3));
            Assert.Throws<FormatException>(() => string.Format(formatter, "{-1}", obj1, obj2, obj3, obj4));

            // Format has out of range value
            Assert.Throws<FormatException>(() => string.Format("{1}", obj1));
            Assert.Throws<FormatException>(() => string.Format("{2}", obj1, obj2));
            Assert.Throws<FormatException>(() => string.Format("{3}", obj1, obj2, obj3));
            Assert.Throws<FormatException>(() => string.Format("{4}", obj1, obj2, obj3, obj4));
            Assert.Throws<FormatException>(() => string.Format(formatter, "{1}", obj1));
            Assert.Throws<FormatException>(() => string.Format(formatter, "{2}", obj1, obj2));
            Assert.Throws<FormatException>(() => string.Format(formatter, "{3}", obj1, obj2, obj3));
            Assert.Throws<FormatException>(() => string.Format(formatter, "{4}", obj1, obj2, obj3, obj4));
        }
Beispiel #24
0
        public static void Format()
        {
            string s = string.Format(null, "0 = {0} 1 = {1} 2 = {2} 3 = {3} 4 = {4}", "zero", "one", "two", "three", "four");
            Assert.Equal("0 = zero 1 = one 2 = two 3 = three 4 = four", s);

            var testFormatter = new TestFormatter();
            s = string.Format(testFormatter, "0 = {0} 1 = {1} 2 = {2} 3 = {3} 4 = {4}", "zero", "one", "two", "three", "four");
            Assert.Equal("0 = Test: : zero 1 = Test: : one 2 = Test: : two 3 = Test: : three 4 = Test: : four", s);
        }