Imported Upstream version 3.6.0

Former-commit-id: da6be194a6b1221998fc28233f2503bd61dd9d14
This commit is contained in:
Jo Shields
2014-08-13 10:39:27 +01:00
commit a575963da9
50588 changed files with 8155799 additions and 0 deletions

View File

@ -0,0 +1,106 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Net.Http.Formatting.DataSets.Types;
using System.Net.Http.Headers;
using System.Text;
using Microsoft.TestCommon;
namespace System.Net.Http.Formatting.DataSets
{
public class HttpUnitTestDataSets
{
public static TestData<HttpMethod> AllHttpMethods { get { return HttpTestData.AllHttpMethods; } }
public static TestData<HttpMethod> StandardHttpMethods { get { return HttpTestData.StandardHttpMethods; } }
public static TestData<HttpMethod> CustomHttpMethods { get { return HttpTestData.CustomHttpMethods; } }
public static TestData<HttpStatusCode> AllHttpStatusCodes { get { return HttpTestData.AllHttpStatusCodes; } }
public static TestData<HttpStatusCode> CustomHttpStatusCodes { get { return HttpTestData.CustomHttpStatusCodes; } }
public static ReadOnlyCollection<TestData> ConvertablePrimitiveValueTypes { get { return HttpTestData.ConvertablePrimitiveValueTypes; } }
public static ReadOnlyCollection<TestData> ConvertableEnumTypes { get { return HttpTestData.ConvertableEnumTypes; } }
public static ReadOnlyCollection<TestData> ConvertableValueTypes { get { return HttpTestData.ConvertableValueTypes; } }
public static TestData<MediaTypeHeaderValue> StandardJsonMediaTypes { get { return HttpTestData.StandardJsonMediaTypes; } }
public static TestData<MediaTypeHeaderValue> StandardXmlMediaTypes { get { return HttpTestData.StandardXmlMediaTypes; } }
public static TestData<MediaTypeHeaderValue> StandardODataMediaTypes { get { return HttpTestData.StandardODataMediaTypes; } }
public static TestData<MediaTypeHeaderValue> StandardFormUrlEncodedMediaTypes { get { return HttpTestData.StandardFormUrlEncodedMediaTypes; } }
public static TestData<MediaTypeWithQualityHeaderValue> StandardMediaTypesWithQuality { get { return HttpTestData.StandardMediaTypesWithQuality; } }
public static TestData<string> StandardJsonMediaTypeStrings { get { return HttpTestData.StandardXmlMediaTypeStrings; } }
public static TestData<string> StandardXmlMediaTypeStrings { get { return HttpTestData.StandardXmlMediaTypeStrings; } }
public static TestData<string> LegalMediaTypeStrings { get { return HttpTestData.LegalMediaTypeStrings; } }
public static TestData<string> IllegalMediaTypeStrings { get { return HttpTestData.IllegalMediaTypeStrings; } }
public static TestData<Encoding> StandardEncodings { get { return HttpTestData.StandardEncodings; } }
public static TestData<MediaTypeHeaderValue> LegalMediaTypeHeaderValues { get { return HttpTestData.LegalMediaTypeHeaderValues; } }
public static TestData<HttpContent> StandardHttpContents { get { return HttpTestData.StandardHttpContents; } }
public static TestData<MediaTypeMapping> StandardMediaTypeMappings { get { return HttpTestData.StandardMediaTypeMappings; } }
public static TestData<QueryStringMapping> QueryStringMappings { get { return HttpTestData.QueryStringMappings; } }
public static TestData<MediaRangeMapping> MediaRangeMappings { get { return HttpTestData.MediaRangeMappings; } }
public static TestData<string> LegalUriPathExtensions { get { return HttpTestData.LegalUriPathExtensions; } }
public static TestData<string> LegalQueryStringParameterNames { get { return HttpTestData.LegalQueryStringParameterNames; } }
public static TestData<string> LegalQueryStringParameterValues { get { return HttpTestData.LegalQueryStringParameterValues; } }
public static TestData<string> LegalHttpHeaderNames { get { return HttpTestData.LegalHttpHeaderNames; } }
public static TestData<string> LegalHttpHeaderValues { get { return HttpTestData.LegalHttpHeaderValues; } }
public static TestData<string> LegalMediaRangeStrings { get { return HttpTestData.LegalMediaRangeStrings; } }
public static TestData<MediaTypeHeaderValue> LegalMediaRangeValues { get { return HttpTestData.LegalMediaRangeValues; } }
public static TestData<MediaTypeWithQualityHeaderValue> MediaRangeValuesWithQuality { get { return HttpTestData.MediaRangeValuesWithQuality; } }
public static TestData<string> IllegalMediaRangeStrings { get { return HttpTestData.IllegalMediaRangeStrings; } }
public static TestData<MediaTypeHeaderValue> IllegalMediaRangeValues { get { return HttpTestData.IllegalMediaRangeValues; } }
public static TestData<MediaTypeFormatter> StandardFormatters { get { return HttpTestData.StandardFormatters; } }
public static TestData<Type> StandardFormatterTypes { get { return HttpTestData.StandardFormatterTypes; } }
public static TestData<MediaTypeFormatter> DerivedFormatters { get { return HttpTestData.DerivedFormatters; } }
public static TestData<IEnumerable<MediaTypeFormatter>> AllFormatterCollections { get { return HttpTestData.AllFormatterCollections; } }
public static TestData<string> LegalHttpAddresses { get { return HttpTestData.LegalHttpAddresses; } }
public static TestData<string> AddressesWithIllegalSchemes { get { return HttpTestData.AddressesWithIllegalSchemes; } }
public static TestData<HttpRequestMessage> NullContentHttpRequestMessages { get { return HttpTestData.NullContentHttpRequestMessages; } }
public static ReadOnlyCollection<TestData> RepresentativeValueAndRefTypeTestDataCollection { get { return HttpTestData.RepresentativeValueAndRefTypeTestDataCollection; } }
public static TestData<string> LegalHttpParameterNames { get { return HttpTestData.LegalHttpParameterNames; } }
public static TestData<Type> LegalHttpParameterTypes { get { return HttpTestData.LegalHttpParameterTypes; } }
public static RefTypeTestData<Uri> Uris { get { return HttpTestData.UriTestData; } }
public static RefTypeTestData<string> UriStrings { get { return HttpTestData.UriTestDataStrings; } }
public static RefTypeTestData<WcfPocoType> PocoTypesWithNull { get { return HttpTestData.WcfPocoTypeTestDataWithNull; } }
}
}

View File

@ -0,0 +1,18 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Runtime.Serialization;
namespace System.Net.Http.Formatting.DataSets.Types
{
[DataContract]
public enum DataContractEnum
{
[EnumMember]
First,
[EnumMember]
Second,
Third
}
}

View File

@ -0,0 +1,77 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.Xml.Serialization;
using Microsoft.TestCommon.Types;
namespace System.Net.Http.Formatting.DataSets.Types
{
[DataContract]
[KnownType(typeof(DerivedDataContractType))]
[XmlInclude(typeof(DerivedDataContractType))]
public class DataContractType : INameAndIdContainer
{
private int id;
private string name;
public DataContractType()
{
}
public DataContractType(int id, string name)
{
this.id = id;
this.name = name;
}
[DataMember]
public int Id
{
get
{
return this.id;
}
set
{
this.IdSet = true;
this.id = value;
}
}
[DataMember]
public string Name
{
get
{
return this.name;
}
set
{
this.NameSet = true;
this.name = value;
}
}
[XmlIgnore]
public bool IdSet { get; private set; }
[XmlIgnore]
public bool NameSet { get; private set; }
public static IEnumerable<DataContractType> GetTestData()
{
return new DataContractType[] { new DataContractType(), new DataContractType(1, "SomeName") };
}
public static IEnumerable<DerivedDataContractType> GetDerivedTypeTestData()
{
return new DerivedDataContractType[] {
new DerivedDataContractType(),
new DerivedDataContractType(1, "SomeName", null),
new DerivedDataContractType(1, "SomeName", new WcfPocoType(2, "SomeOtherName"))};
}
}
}

View File

@ -0,0 +1,61 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.Xml.Serialization;
namespace System.Net.Http.Formatting.DataSets.Types
{
[DataContract]
[KnownType(typeof(DerivedWcfPocoType))]
[KnownType(typeof(DerivedDataContractType))]
[XmlInclude(typeof(DerivedWcfPocoType))]
[XmlInclude(typeof(DerivedDataContractType))]
public class DerivedDataContractType : DataContractType
{
private WcfPocoType reference;
public DerivedDataContractType()
{
}
public DerivedDataContractType(int id, string name, WcfPocoType reference)
: base(id, name)
{
this.reference = reference;
}
[DataMember]
public WcfPocoType Reference
{
get
{
return this.reference;
}
set
{
this.ReferenceSet = true;
this.reference = value;
}
}
[XmlIgnore]
public bool ReferenceSet { get; private set; }
public static new IEnumerable<DerivedDataContractType> GetTestData()
{
return new DerivedDataContractType[] {
new DerivedDataContractType(),
new DerivedDataContractType(1, "SomeName", new WcfPocoType(2, "SomeOtherName")) };
}
public static IEnumerable<DerivedDataContractType> GetKnownTypeTestData()
{
return new DerivedDataContractType[] {
new DerivedDataContractType(),
new DerivedDataContractType(1, "SomeName", null),
new DerivedDataContractType(1, "SomeName", new DerivedWcfPocoType(2, "SomeOtherName", null))};
}
}
}

View File

@ -0,0 +1,9 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
namespace System.Net.Http.Formatting.DataSets.Types
{
public class DerivedFormUrlEncodedMediaTypeFormatter : FormUrlEncodedMediaTypeFormatter
{
}
}

View File

@ -0,0 +1,9 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
namespace System.Net.Http.Formatting.DataSets.Types
{
public class DerivedJsonMediaTypeFormatter : JsonMediaTypeFormatter
{
}
}

View File

@ -0,0 +1,40 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Runtime.Serialization;
using System.Xml.Serialization;
namespace System.Net.Http.Formatting.DataSets.Types
{
public class DerivedWcfPocoType : WcfPocoType
{
private WcfPocoType reference;
public DerivedWcfPocoType()
{
}
public DerivedWcfPocoType(int id, string name, WcfPocoType reference)
: base(id, name)
{
this.reference = reference;
}
public WcfPocoType Reference
{
get
{
return this.reference;
}
set
{
this.ReferenceSet = true;
this.reference = value;
}
}
[IgnoreDataMember]
[XmlIgnore]
public bool ReferenceSet { get; private set; }
}
}

View File

@ -0,0 +1,9 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
namespace System.Net.Http.Formatting.DataSets.Types
{
public class DerivedXmlMediaTypeFormatter : XmlMediaTypeFormatter
{
}
}

View File

@ -0,0 +1,58 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.Xml.Serialization;
namespace System.Net.Http.Formatting.DataSets.Types
{
[KnownType(typeof(DerivedWcfPocoType))]
[XmlInclude(typeof(DerivedWcfPocoType))]
public class DerivedXmlSerializableType : XmlSerializableType, INotJsonSerializable
{
private WcfPocoType reference;
public DerivedXmlSerializableType()
{
}
public DerivedXmlSerializableType(int id, string name, WcfPocoType reference)
: base(id, name)
{
this.reference = reference;
}
[XmlElement]
public WcfPocoType Reference
{
get
{
return this.reference;
}
set
{
this.ReferenceSet = true;
this.reference = value;
}
}
[XmlIgnore]
public bool ReferenceSet { get; private set; }
public static new IEnumerable<DerivedXmlSerializableType> GetTestData()
{
return new DerivedXmlSerializableType[] {
new DerivedXmlSerializableType(),
new DerivedXmlSerializableType(1, "SomeName", new WcfPocoType(2, "SomeOtherName")) };
}
public static IEnumerable<DerivedXmlSerializableType> GetKnownTypeTestData()
{
return new DerivedXmlSerializableType[] {
new DerivedXmlSerializableType(),
new DerivedXmlSerializableType(1, "SomeName", null),
new DerivedXmlSerializableType(1, "SomeName", new DerivedWcfPocoType(2, "SomeOtherName", null))};
}
}
}

View File

@ -0,0 +1,442 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Net.Http.Headers;
using System.Text;
using Microsoft.TestCommon;
namespace System.Net.Http.Formatting.DataSets.Types
{
public static class HttpTestData
{
public static readonly TestData<HttpMethod> AllHttpMethods = new RefTypeTestData<HttpMethod>(() =>
StandardHttpMethods.Concat(CustomHttpMethods).ToList());
public static readonly TestData<HttpMethod> StandardHttpMethods = new RefTypeTestData<HttpMethod>(() => new List<HttpMethod>()
{
HttpMethod.Head,
HttpMethod.Get,
HttpMethod.Post,
HttpMethod.Put,
HttpMethod.Delete,
HttpMethod.Options,
HttpMethod.Trace,
});
public static readonly TestData<HttpMethod> CustomHttpMethods = new RefTypeTestData<HttpMethod>(() => new List<HttpMethod>()
{
new HttpMethod("Custom")
});
public static readonly TestData<HttpStatusCode> AllHttpStatusCodes = new ValueTypeTestData<HttpStatusCode>(new HttpStatusCode[]
{
HttpStatusCode.Accepted,
HttpStatusCode.Ambiguous,
HttpStatusCode.BadGateway,
HttpStatusCode.BadRequest,
HttpStatusCode.Conflict,
HttpStatusCode.Continue,
HttpStatusCode.Created,
HttpStatusCode.ExpectationFailed,
HttpStatusCode.Forbidden,
HttpStatusCode.Found,
HttpStatusCode.GatewayTimeout,
HttpStatusCode.Gone,
HttpStatusCode.HttpVersionNotSupported,
HttpStatusCode.InternalServerError,
HttpStatusCode.LengthRequired,
HttpStatusCode.MethodNotAllowed,
HttpStatusCode.Moved,
HttpStatusCode.MovedPermanently,
HttpStatusCode.MultipleChoices,
HttpStatusCode.NoContent,
HttpStatusCode.NonAuthoritativeInformation,
HttpStatusCode.NotAcceptable,
HttpStatusCode.NotFound,
HttpStatusCode.NotImplemented,
HttpStatusCode.NotModified,
HttpStatusCode.OK,
HttpStatusCode.PartialContent,
HttpStatusCode.PaymentRequired,
HttpStatusCode.PreconditionFailed,
HttpStatusCode.ProxyAuthenticationRequired,
HttpStatusCode.Redirect,
HttpStatusCode.RedirectKeepVerb,
HttpStatusCode.RedirectMethod,
HttpStatusCode.RequestedRangeNotSatisfiable,
HttpStatusCode.RequestEntityTooLarge,
HttpStatusCode.RequestTimeout,
HttpStatusCode.RequestUriTooLong,
HttpStatusCode.ResetContent,
HttpStatusCode.SeeOther,
HttpStatusCode.ServiceUnavailable,
HttpStatusCode.SwitchingProtocols,
HttpStatusCode.TemporaryRedirect,
HttpStatusCode.Unauthorized,
HttpStatusCode.UnsupportedMediaType,
HttpStatusCode.Unused,
HttpStatusCode.UseProxy
});
public static readonly TestData<HttpStatusCode> CustomHttpStatusCodes = new ValueTypeTestData<HttpStatusCode>(new HttpStatusCode[]
{
(HttpStatusCode)199,
(HttpStatusCode)299,
(HttpStatusCode)399,
(HttpStatusCode)499,
(HttpStatusCode)599,
(HttpStatusCode)699,
(HttpStatusCode)799,
(HttpStatusCode)899,
(HttpStatusCode)999,
});
public static readonly ReadOnlyCollection<TestData> ConvertablePrimitiveValueTypes = new ReadOnlyCollection<TestData>(new TestData[] {
TestData.CharTestData,
TestData.IntTestData,
TestData.UintTestData,
TestData.ShortTestData,
TestData.UshortTestData,
TestData.LongTestData,
TestData.UlongTestData,
TestData.ByteTestData,
TestData.SByteTestData,
TestData.BoolTestData,
TestData.DoubleTestData,
TestData.FloatTestData,
TestData.DecimalTestData,
TestData.TimeSpanTestData,
TestData.GuidTestData,
TestData.DateTimeTestData,
TestData.DateTimeOffsetTestData});
public static readonly ReadOnlyCollection<TestData> ConvertableEnumTypes = new ReadOnlyCollection<TestData>(new TestData[] {
TestData.SimpleEnumTestData,
TestData.LongEnumTestData,
TestData.FlagsEnumTestData,
DataContractEnumTestData});
public static readonly ReadOnlyCollection<TestData> ConvertableValueTypes = new ReadOnlyCollection<TestData>(
ConvertablePrimitiveValueTypes.Concat(ConvertableEnumTypes).ToList());
public static readonly TestData<MediaTypeHeaderValue> StandardJsonMediaTypes = new RefTypeTestData<MediaTypeHeaderValue>(() => new List<MediaTypeHeaderValue>()
{
new MediaTypeHeaderValue("application/json"),
new MediaTypeHeaderValue("text/json")
});
public static readonly TestData<MediaTypeHeaderValue> StandardXmlMediaTypes = new RefTypeTestData<MediaTypeHeaderValue>(() => new List<MediaTypeHeaderValue>()
{
new MediaTypeHeaderValue("application/xml"),
new MediaTypeHeaderValue("text/xml")
});
public static readonly TestData<MediaTypeHeaderValue> StandardODataMediaTypes = new RefTypeTestData<MediaTypeHeaderValue>(() => new List<MediaTypeHeaderValue>()
{
new MediaTypeHeaderValue("application/atom+xml"),
new MediaTypeHeaderValue("application/json"),
});
public static readonly TestData<MediaTypeHeaderValue> StandardFormUrlEncodedMediaTypes = new RefTypeTestData<MediaTypeHeaderValue>(() => new List<MediaTypeHeaderValue>()
{
new MediaTypeHeaderValue("application/x-www-form-urlencoded")
});
public static readonly TestData<string> StandardJsonMediaTypeStrings = new RefTypeTestData<string>(() => new List<string>()
{
"application/json",
"text/json"
});
public static readonly TestData<string> StandardXmlMediaTypeStrings = new RefTypeTestData<string>(() => new List<string>()
{
"application/xml",
"text/xml"
});
public static readonly TestData<string> LegalMediaTypeStrings = new RefTypeTestData<string>(() =>
StandardXmlMediaTypeStrings.Concat(StandardJsonMediaTypeStrings).ToList());
// Illegal media type strings. These will cause the MediaTypeHeaderValue ctor to throw FormatException
public static readonly TestData<string> IllegalMediaTypeStrings = new RefTypeTestData<string>(() => new List<string>()
{
"\0",
"9\r\n"
});
public static readonly TestData<Encoding> StandardEncodings = new RefTypeTestData<Encoding>(() => new List<Encoding>()
{
new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true),
new UnicodeEncoding(bigEndian: false, byteOrderMark: true, throwOnInvalidBytes: true),
});
public static IEnumerable<object[]> ReadAndWriteCorrectCharacterEncoding
{
get
{
yield return new object[] { "This is a test 激光這兩個字是甚麼意思 string written using utf-8", "utf-8", true };
yield return new object[] { "This is a test 激光這兩個字是甚麼意思 string written using utf-16", "utf-16", true };
yield return new object[] { "This is a test 激光這兩個字是甚麼意思 string written using utf-32", "utf-32", false };
yield return new object[] { "This is a test 激光這兩個字是甚麼意思 string written using shift_jis", "shift_jis", false };
yield return new object[] { "This is a test æøå string written using iso-8859-1", "iso-8859-1", false };
yield return new object[] { "This is a test 레이저 단어 뜻 string written using iso-2022-kr", "iso-2022-kr", false };
}
}
//// TODO: complete this list
// Legal MediaTypeHeaderValues
public static readonly TestData<MediaTypeHeaderValue> LegalMediaTypeHeaderValues = new RefTypeTestData<MediaTypeHeaderValue>(
() => LegalMediaTypeStrings.Select<string, MediaTypeHeaderValue>((mediaType) => new MediaTypeHeaderValue(mediaType)).ToList());
public static readonly TestData<MediaTypeWithQualityHeaderValue> StandardMediaTypesWithQuality = new RefTypeTestData<MediaTypeWithQualityHeaderValue>(() => new List<MediaTypeWithQualityHeaderValue>()
{
new MediaTypeWithQualityHeaderValue("application/json", .1) { CharSet="utf-8"},
new MediaTypeWithQualityHeaderValue("text/json", .2) { CharSet="utf-8"},
new MediaTypeWithQualityHeaderValue("application/xml", .3) { CharSet="utf-8"},
new MediaTypeWithQualityHeaderValue("text/xml", .4) { CharSet="utf-8"},
new MediaTypeWithQualityHeaderValue("application/atom+xml", .5) { CharSet="utf-8"},
});
public static readonly TestData<HttpContent> StandardHttpContents = new RefTypeTestData<HttpContent>(() => new List<HttpContent>()
{
new ByteArrayContent(new byte[0]),
new FormUrlEncodedContent(new KeyValuePair<string, string>[0]),
new MultipartContent(),
new StringContent(""),
new StreamContent(new MemoryStream())
});
//// TODO: make this list compose from other data?
// Collection of legal instances of all standard MediaTypeMapping types
public static readonly TestData<MediaTypeMapping> StandardMediaTypeMappings = new RefTypeTestData<MediaTypeMapping>(() =>
QueryStringMappings.Cast<MediaTypeMapping>().Concat(
MediaRangeMappings.Cast<MediaTypeMapping>()).ToList()
);
public static readonly TestData<QueryStringMapping> QueryStringMappings = new RefTypeTestData<QueryStringMapping>(() => new List<QueryStringMapping>()
{
new QueryStringMapping("format", "json", new MediaTypeHeaderValue("application/json"))
});
public static readonly TestData<MediaRangeMapping> MediaRangeMappings = new RefTypeTestData<MediaRangeMapping>(() => new List<MediaRangeMapping>()
{
new MediaRangeMapping(new MediaTypeHeaderValue("application/*"), new MediaTypeHeaderValue("application/xml"))
});
public static readonly TestData<string> LegalUriPathExtensions = new RefTypeTestData<string>(() => new List<string>()
{
"xml",
"json"
});
public static readonly TestData<string> LegalQueryStringParameterNames = new RefTypeTestData<string>(() => new List<string>()
{
"format",
"fmt"
});
public static readonly TestData<string> LegalHttpHeaderNames = new RefTypeTestData<string>(() => new List<string>()
{
"x-requested-with",
"some-random-name"
});
public static readonly TestData<string> LegalHttpHeaderValues = new RefTypeTestData<string>(() => new List<string>()
{
"1",
"XMLHttpRequest",
"\"quoted-string\""
});
public static readonly TestData<string> LegalQueryStringParameterValues = new RefTypeTestData<string>(() => new List<string>()
{
"xml",
"json"
});
public static readonly TestData<string> LegalMediaRangeStrings = new RefTypeTestData<string>(() => new List<string>()
{
"application/*",
"text/*"
});
public static readonly TestData<MediaTypeHeaderValue> LegalMediaRangeValues = new RefTypeTestData<MediaTypeHeaderValue>(() =>
LegalMediaRangeStrings.Select<string, MediaTypeHeaderValue>((s) => new MediaTypeHeaderValue(s)).ToList()
);
public static readonly TestData<MediaTypeWithQualityHeaderValue> MediaRangeValuesWithQuality = new RefTypeTestData<MediaTypeWithQualityHeaderValue>(() => new List<MediaTypeWithQualityHeaderValue>()
{
new MediaTypeWithQualityHeaderValue("application/*", .1),
new MediaTypeWithQualityHeaderValue("text/*", .2),
});
public static readonly TestData<string> IllegalMediaRangeStrings = new RefTypeTestData<string>(() => new List<string>()
{
"application/xml",
"text/xml"
});
public static readonly TestData<MediaTypeHeaderValue> IllegalMediaRangeValues = new RefTypeTestData<MediaTypeHeaderValue>(() =>
IllegalMediaRangeStrings.Select<string, MediaTypeHeaderValue>((s) => new MediaTypeHeaderValue(s)).ToList()
);
public static readonly TestData<MediaTypeFormatter> StandardFormatters = new RefTypeTestData<MediaTypeFormatter>(() => new List<MediaTypeFormatter>()
{
new XmlMediaTypeFormatter(),
new JsonMediaTypeFormatter(),
new FormUrlEncodedMediaTypeFormatter()
});
public static readonly TestData<Type> StandardFormatterTypes = new RefTypeTestData<Type>(() =>
StandardFormatters.Select<MediaTypeFormatter, Type>((m) => m.GetType()));
public static readonly TestData<MediaTypeFormatter> DerivedFormatters = new RefTypeTestData<MediaTypeFormatter>(() => new List<MediaTypeFormatter>()
{
new DerivedXmlMediaTypeFormatter(),
new DerivedJsonMediaTypeFormatter(),
new DerivedFormUrlEncodedMediaTypeFormatter(),
});
public static readonly TestData<IEnumerable<MediaTypeFormatter>> AllFormatterCollections =
new RefTypeTestData<IEnumerable<MediaTypeFormatter>>(() => new List<IEnumerable<MediaTypeFormatter>>()
{
new MediaTypeFormatter[0],
StandardFormatters,
DerivedFormatters,
});
public static readonly TestData<string> LegalHttpAddresses = new RefTypeTestData<string>(() => new List<string>()
{
"http://somehost",
"https://somehost",
});
public static readonly TestData<string> AddressesWithIllegalSchemes = new RefTypeTestData<string>(() => new List<string>()
{
"net.tcp://somehost",
"file://somehost",
"net.pipe://somehost",
"mailto:somehost",
"ftp://somehost",
"news://somehost",
"ws://somehost",
"abc://somehost"
});
/// <summary>
/// A read-only collection of representative values and reference type test data.
/// Uses where exhaustive coverage is not required. It includes null values.
/// </summary>
public static readonly ReadOnlyCollection<TestData> RepresentativeValueAndRefTypeTestDataCollection = new ReadOnlyCollection<TestData>(new TestData[] {
TestData.ByteTestData,
TestData.IntTestData,
TestData.BoolTestData,
TestData.SimpleEnumTestData,
TestData.StringTestData,
TestData.DateTimeTestData,
TestData.DateTimeOffsetTestData,
TestData.TimeSpanTestData,
WcfPocoTypeTestDataWithNull
});
public static readonly TestData<HttpRequestMessage> NullContentHttpRequestMessages = new RefTypeTestData<HttpRequestMessage>(() => new List<HttpRequestMessage>()
{
new HttpRequestMessage() { Content = null },
});
public static readonly TestData<string> LegalHttpParameterNames = new RefTypeTestData<string>(() => new List<string>()
{
"文",
"A",
"a",
"b",
" a",
"arg1",
"arg2",
"1",
"@",
"!"
});
public static readonly TestData<Type> LegalHttpParameterTypes = new RefTypeTestData<Type>(() => new List<Type>()
{
typeof(string),
typeof(byte[]),
typeof(byte[][]),
typeof(byte[][]),
typeof(char),
typeof(DateTime),
typeof(decimal),
typeof(double),
typeof(Guid),
typeof(Int16),
typeof(Int32),
typeof(object),
typeof(sbyte),
typeof(Single),
typeof(TimeSpan),
typeof(UInt16),
typeof(UInt32),
typeof(UInt64),
typeof(Uri),
typeof(Enum),
typeof(Collection<object>),
typeof(IList<object>),
typeof(System.Runtime.Serialization.ISerializable),
typeof(System.Data.DataSet),
typeof(System.Xml.Serialization.IXmlSerializable),
typeof(Nullable),
typeof(Nullable<DateTime>),
typeof(Stream),
typeof(HttpRequestMessage),
typeof(HttpResponseMessage),
typeof(ObjectContent),
typeof(ObjectContent<object>),
typeof(HttpContent),
typeof(Delegate),
typeof(Action),
typeof(System.Threading.Tasks.Task<object>),
typeof(System.Threading.Tasks.Task),
typeof(List<dynamic>)
});
/// <summary>
/// Common <see cref="TestData"/> for an <c>enum</c> decorated with a <see cref="DataContractAttribute"/>.
/// </summary>
public static readonly ValueTypeTestData<DataContractEnum> DataContractEnumTestData = new ValueTypeTestData<DataContractEnum>(
DataContractEnum.First,
DataContractEnum.Second);
/// <summary>
/// Common <see cref="TestData"/> for the string form of a <see cref="Uri"/>.
/// </summary>
public static readonly RefTypeTestData<string> UriTestDataStrings = new RefTypeTestData<string>(() => new List<string>(){
"http://somehost",
"http://somehost:8080",
"http://somehost/",
"http://somehost:8080/",
"http://somehost/somepath",
"http://somehost/somepath/",
"http://somehost/somepath?somequery=somevalue"});
/// <summary>
/// Common <see cref="TestData"/> for a <see cref="Uri"/>.
/// </summary>
public static readonly RefTypeTestData<Uri> UriTestData = new RefTypeTestData<Uri>(() =>
UriTestDataStrings.Select<string, Uri>((s) => new Uri(s)).ToList());
/// <summary>
/// Common <see cref="TestData"/> for a POCO class type that includes null values
/// for both the base class and derived classes.
/// </summary>
public static readonly RefTypeTestData<WcfPocoType> WcfPocoTypeTestDataWithNull = new RefTypeTestData<WcfPocoType>(
WcfPocoType.GetTestDataWithNull,
WcfPocoType.GetDerivedTypeTestDataWithNull,
null);
}
}

View File

@ -0,0 +1,11 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
namespace System.Net.Http.Formatting.DataSets.Types
{
/// <summary>
/// Tagging interface to indicate types which we know Json cannot serialize.
/// </summary>
public interface INotJsonSerializable
{
}
}

View File

@ -0,0 +1,88 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Xml.Serialization;
using Microsoft.TestCommon.Types;
namespace System.Net.Http.Formatting.DataSets.Types
{
[KnownType(typeof(DerivedWcfPocoType))]
[XmlInclude(typeof(DerivedWcfPocoType))]
public class WcfPocoType : INameAndIdContainer
{
private int id;
private string name;
public WcfPocoType()
{
}
public WcfPocoType(int id, string name)
{
this.id = id;
this.name = name;
}
public int Id
{
get
{
return this.id;
}
set
{
this.IdSet = true;
this.id = value;
}
}
public string Name
{
get
{
return this.name;
}
set
{
this.NameSet = true;
this.name = value;
}
}
[IgnoreDataMember]
[XmlIgnore]
public bool IdSet { get; private set; }
[IgnoreDataMember]
[XmlIgnore]
public bool NameSet { get; private set; }
public static IEnumerable<WcfPocoType> GetTestData()
{
return new WcfPocoType[] { new WcfPocoType(), new WcfPocoType(1, "SomeName") };
}
public static IEnumerable<WcfPocoType> GetTestDataWithNull()
{
return GetTestData().Concat(new WcfPocoType[] { null });
}
public static IEnumerable<DerivedWcfPocoType> GetDerivedTypeTestData()
{
return new DerivedWcfPocoType[] {
new DerivedWcfPocoType(),
new DerivedWcfPocoType(1, "SomeName", null),
new DerivedWcfPocoType(1, "SomeName", new WcfPocoType(2, "SomeOtherName"))};
}
public static IEnumerable<DerivedWcfPocoType> GetDerivedTypeTestDataWithNull()
{
return GetDerivedTypeTestData().Concat(new DerivedWcfPocoType[] { null });
}
}
}

View File

@ -0,0 +1,98 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.Xml.Serialization;
using Microsoft.TestCommon.Types;
namespace System.Net.Http.Formatting.DataSets.Types
{
[KnownType(typeof(DerivedXmlSerializableType))]
[XmlInclude(typeof(DerivedXmlSerializableType))]
public class XmlSerializableType : INameAndIdContainer
{
private int id;
private string name;
public XmlSerializableType()
{
}
public XmlSerializableType(int id, string name)
{
this.id = id;
this.name = name;
}
[XmlAttribute]
public int Id
{
get
{
return this.id;
}
set
{
this.IdSet = true;
this.id = value;
}
}
[XmlElement]
public string Name
{
get
{
return this.name;
}
set
{
this.NameSet = true;
this.name = value;
}
}
[XmlIgnore]
public bool IdSet { get; private set; }
[XmlIgnore]
public bool NameSet { get; private set; }
public override bool Equals(object obj)
{
if (Object.ReferenceEquals(this, obj))
{
return true;
}
XmlSerializableType other = obj as XmlSerializableType;
if (Object.ReferenceEquals(other, null))
{
return false;
}
return String.Equals(this.Name, other.Name, StringComparison.Ordinal) && this.Id == other.Id;
}
public override int GetHashCode()
{
return base.GetHashCode();
}
public static IEnumerable<XmlSerializableType> GetTestData()
{
return new XmlSerializableType[] { new XmlSerializableType(), new XmlSerializableType(1, "SomeName") };
}
public static IEnumerable<DerivedXmlSerializableType> GetDerivedTypeTestData()
{
return new DerivedXmlSerializableType[] {
new DerivedXmlSerializableType(),
new DerivedXmlSerializableType(1, "SomeName", null),
new DerivedXmlSerializableType(1, "SomeName", new WcfPocoType(2, "SomeOtherName"))};
}
}
}

View File

@ -0,0 +1,199 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http.Formatting.DataSets.Types;
using System.Net.Http.Headers;
using System.Text;
using Xunit;
using Assert = Microsoft.TestCommon.AssertEx;
using Xunit.Extensions;
using System.Threading.Tasks;
namespace System.Net.Http.Formatting
{
public class BufferedMediaTypeFormatterTests : MediaTypeFormatterTestBase<MockBufferedMediaTypeFormatter>
{
private const string ExpectedSupportedMediaType = "text/test";
private const string TestData = "Hello World Hello World Hello World Hello World Hello World Hello World";
public static IEnumerable<object[]> ReadAndWriteCorrectCharacterEncoding
{
get { return HttpTestData.ReadAndWriteCorrectCharacterEncoding; }
}
public override IEnumerable<MediaTypeHeaderValue> ExpectedSupportedMediaTypes
{
get { return new List<MediaTypeHeaderValue> { new MediaTypeHeaderValue(ExpectedSupportedMediaType) }; }
}
public override IEnumerable<Encoding> ExpectedSupportedEncodings
{
get { return HttpTestData.StandardEncodings; }
}
public override byte[] ExpectedSampleTypeByteRepresentation
{
get { return ExpectedSupportedEncodings.ElementAt(0).GetBytes("System.Net.Http.Formatting.MediaTypeFormatterTestBase`1+SampleType[System.Net.Http.Formatting.MockBufferedMediaTypeFormatter]"); }
}
[Fact]
public void BufferSize_RoundTrips()
{
Assert.Reflection.IntegerProperty(
new MockBufferedMediaTypeFormatter(),
c => c.BufferSize,
expectedDefaultValue: 16 * 1024,
minLegalValue: 0,
illegalLowerValue: -1,
maxLegalValue: null,
illegalUpperValue: null,
roundTripTestValue: 1024);
}
[Fact]
public void WriteToStreamAsync_WhenTypeParameterIsNull_ThrowsException()
{
BufferedMediaTypeFormatter formatter = new MockBufferedMediaTypeFormatter();
Assert.ThrowsArgumentNull(
() => formatter.WriteToStreamAsync(null, new object(), new MemoryStream(), null, null), "type");
}
[Fact]
public void WriteToStreamAsync_WhenStreamParameterIsNull_ThrowsException()
{
BufferedMediaTypeFormatter formatter = new MockBufferedMediaTypeFormatter();
Assert.ThrowsArgumentNull(
() => formatter.WriteToStreamAsync(typeof(object), new object(), null, null, null), "stream");
}
[Fact]
public void ReadFromStreamAsync_WhenTypeParamterIsNull_ThrowsException()
{
BufferedMediaTypeFormatter formatter = new MockBufferedMediaTypeFormatter();
Assert.ThrowsArgumentNull(() => formatter.ReadFromStreamAsync(null, new MemoryStream(), null, null), "type");
}
[Fact]
public void ReadFromStreamAsync_WhenStreamParamterIsNull_ThrowsException()
{
BufferedMediaTypeFormatter formatter = new MockBufferedMediaTypeFormatter();
Assert.ThrowsArgumentNull(() => formatter.ReadFromStreamAsync(typeof(object), null, null, null), "stream");
}
[Fact]
public void BufferedWrite()
{
// Arrange. Specifically use the base class with async signatures.
MediaTypeFormatter formatter = new MockBufferedMediaTypeFormatter();
MemoryStream output = new MemoryStream();
// Act. Call the async signature.
formatter.WriteToStreamAsync(TestData.GetType(), TestData, output, null, null).Wait();
// Assert
byte[] expectedBytes = ExpectedSupportedEncodings.ElementAt(0).GetBytes(TestData);
byte[] actualBytes = output.ToArray();
Assert.Equal(expectedBytes, actualBytes);
}
[Fact]
public void BufferedRead()
{
// Arrange. Specifically use the base class with async signatures.
MediaTypeFormatter formatter = new MockBufferedMediaTypeFormatter();
byte[] expectedBytes = ExpectedSupportedEncodings.ElementAt(0).GetBytes(TestData);
MemoryStream input = new MemoryStream(expectedBytes);
// Act. Call the async signature.
object result = formatter.ReadFromStreamAsync(TestData.GetType(), input, null, null).Result;
// Assert
Assert.Equal(TestData, result);
}
[Theory]
[PropertyData("ReadAndWriteCorrectCharacterEncoding")]
public override Task ReadFromStreamAsync_UsesCorrectCharacterEncoding(string content, string encoding, bool isDefaultEncoding)
{
// Arrange
MediaTypeFormatter formatter = new MockBufferedMediaTypeFormatter();
string mediaType = string.Format("{0}; charset={1}", ExpectedSupportedMediaType, encoding);
// Act & assert
return ReadFromStreamAsync_UsesCorrectCharacterEncodingHelper(formatter, content, content, mediaType, encoding, isDefaultEncoding);
}
[Theory]
[PropertyData("ReadAndWriteCorrectCharacterEncoding")]
public override Task WriteToStreamAsync_UsesCorrectCharacterEncoding(string content, string encoding, bool isDefaultEncoding)
{
// Arrange
MediaTypeFormatter formatter = new MockBufferedMediaTypeFormatter();
string mediaType = string.Format("{0}; charset={1}", ExpectedSupportedMediaType, encoding);
// Act & assert
return WriteToStreamAsync_UsesCorrectCharacterEncodingHelper(formatter, content, content, mediaType, encoding, isDefaultEncoding);
}
}
public class MockBufferedMediaTypeFormatter : BufferedMediaTypeFormatter
{
private const string SupportedMediaType = "text/test";
public MockBufferedMediaTypeFormatter()
{
SupportedMediaTypes.Add(new MediaTypeHeaderValue(SupportedMediaType));
// Set default supported character encodings
SupportedEncodings.Add(new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true));
SupportedEncodings.Add(new UnicodeEncoding(bigEndian: false, byteOrderMark: true, throwOnInvalidBytes: true));
}
public override bool CanReadType(Type type)
{
return true;
}
public override bool CanWriteType(Type type)
{
return true;
}
public override object ReadFromStream(Type type, Stream stream, HttpContentHeaders contentHeaders, IFormatterLogger formatterLogger)
{
object result = null;
Encoding effectiveEncoding = SelectCharacterEncoding(contentHeaders);
using (StreamReader sReader = new StreamReader(stream, effectiveEncoding))
{
if (type == typeof(BufferedMediaTypeFormatterTests.SampleType))
{
return new BufferedMediaTypeFormatterTests.SampleType { Number = 42 };
}
else
{
result = sReader.ReadToEnd();
}
}
return result;
}
public override void WriteToStream(Type type, object value, Stream stream, HttpContentHeaders contentHeaders)
{
Encoding effectiveEncoding = SelectCharacterEncoding(contentHeaders);
using (StreamWriter sWriter = new StreamWriter(stream, effectiveEncoding))
{
if (value != null)
{
sWriter.Write(value.ToString());
}
else
{
sWriter.Write("null!");
}
}
}
}
}

View File

@ -0,0 +1,35 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Net.Http.Headers;
using Moq;
using Xunit;
using Assert = Microsoft.TestCommon.AssertEx;
namespace System.Net.Http.Formatting
{
public class ContentNegotiationResultTest
{
private readonly MediaTypeFormatter _formatter = new Mock<MediaTypeFormatter>().Object;
private readonly MediaTypeHeaderValue _mediaType = new MediaTypeHeaderValue("app/json");
[Fact]
public void Constructor_WhenFormatterParameterIsNull_Throws()
{
Assert.ThrowsArgumentNull(() => new ContentNegotiationResult(formatter: null, mediaType: null), "formatter");
}
[Fact]
public void MediaTypeProperty()
{
Assert.Reflection.Property(new ContentNegotiationResult(_formatter, _mediaType),
nr => nr.MediaType, _mediaType, allowNull: true, roundTripTestValue: new MediaTypeHeaderValue("foo/bar"));
}
[Fact]
public void FormatterProperty()
{
Assert.Reflection.Property(new ContentNegotiationResult(_formatter, _mediaType),
nr => nr.Formatter, _formatter, allowNull: false, roundTripTestValue: new JsonMediaTypeFormatter());
}
}
}

View File

@ -0,0 +1,239 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http.Formatting.DataSets.Types;
using System.Net.Http.Headers;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Threading.Tasks;
using Microsoft.TestCommon;
using Xunit;
using Xunit.Extensions;
using Assert = Microsoft.TestCommon.AssertEx;
namespace System.Net.Http.Formatting
{
public class DataContractJsonMediaTypeFormatter : JsonMediaTypeFormatter
{
public DataContractJsonMediaTypeFormatter()
{
UseDataContractJsonSerializer = true;
}
}
public class DataContractJsonMediaTypeFormatterTests : MediaTypeFormatterTestBase<DataContractJsonMediaTypeFormatter>
{
public static IEnumerable<object[]> ReadAndWriteCorrectCharacterEncoding
{
get { return HttpTestData.ReadAndWriteCorrectCharacterEncoding; }
}
public static IEnumerable<TestData> ValueAndRefTypeTestDataCollectionExceptULong
{
get
{
return CommonUnitTestDataSets.ValueAndRefTypeTestDataCollection.Except(new[] { CommonUnitTestDataSets.Ulongs });
}
}
public override IEnumerable<MediaTypeHeaderValue> ExpectedSupportedMediaTypes
{
get { return HttpTestData.StandardJsonMediaTypes; }
}
public override IEnumerable<Encoding> ExpectedSupportedEncodings
{
get { return HttpTestData.StandardEncodings; }
}
public override byte[] ExpectedSampleTypeByteRepresentation
{
get { return ExpectedSupportedEncodings.ElementAt(0).GetBytes("{\"Number\":42}"); }
}
[Fact]
public void DefaultMediaType_ReturnsApplicationJson()
{
MediaTypeHeaderValue mediaType = DataContractJsonMediaTypeFormatter.DefaultMediaType;
Assert.NotNull(mediaType);
Assert.Equal("application/json", mediaType.MediaType);
}
[Fact]
public void Indent_RoundTrips()
{
Assert.Reflection.BooleanProperty(
new XmlMediaTypeFormatter(),
c => c.Indent,
expectedDefaultValue: false);
}
[Fact]
public void MaxDepth_RoundTrips()
{
Assert.Reflection.IntegerProperty(
new DataContractJsonMediaTypeFormatter(),
c => c.MaxDepth,
expectedDefaultValue: 256,
minLegalValue: 1,
illegalLowerValue: 0,
maxLegalValue: null,
illegalUpperValue: null,
roundTripTestValue: 256);
}
[Theory]
[TestDataSet(typeof(CommonUnitTestDataSets), "RepresentativeValueAndRefTypeTestDataCollection")]
public void CanReadType_ReturnsExpectedValues(Type variationType, object testData)
{
TestJsonMediaTypeFormatter formatter = new TestJsonMediaTypeFormatter();
bool isSerializable = IsTypeSerializableWithJsonSerializer(variationType, testData);
bool canSupport = formatter.CanReadTypeProxy(variationType);
// If we don't agree, we assert only if the DCJ serializer says it cannot support something we think it should
Assert.False(isSerializable != canSupport && isSerializable, String.Format("CanReadType returned wrong value for '{0}'.", variationType));
// Ask a 2nd time to probe whether the cached result is treated the same
canSupport = formatter.CanReadTypeProxy(variationType);
Assert.False(isSerializable != canSupport && isSerializable, String.Format("2nd CanReadType returned wrong value for '{0}'.", variationType));
}
[Theory]
[InlineData(typeof(IQueryable<string>))]
[InlineData(typeof(IEnumerable<string>))]
public void UseJsonFormatterWithNull(Type type)
{
JsonMediaTypeFormatter xmlFormatter = new DataContractJsonMediaTypeFormatter();
MemoryStream memoryStream = new MemoryStream();
HttpContentHeaders contentHeaders = FormattingUtilities.CreateEmptyContentHeaders();
Assert.Task.Succeeds(xmlFormatter.WriteToStreamAsync(type, null, memoryStream, contentHeaders, transportContext: null));
memoryStream.Position = 0;
string serializedString = new StreamReader(memoryStream).ReadToEnd();
Assert.True(serializedString.Contains("null"), "Using Json formatter to serialize null should emit 'null'.");
}
[Theory]
[TestDataSet(typeof(CommonUnitTestDataSets), "RepresentativeValueAndRefTypeTestDataCollection")]
[TestDataSet(typeof(JsonMediaTypeFormatterTests), "ValueAndRefTypeTestDataCollectionExceptULong")]
public void ReadFromStreamAsync_RoundTripsWriteToStreamAsync(Type variationType, object testData)
{
TestJsonMediaTypeFormatter formatter = new TestJsonMediaTypeFormatter();
HttpContentHeaders contentHeaders = FormattingUtilities.CreateEmptyContentHeaders();
bool canSerialize = IsTypeSerializableWithJsonSerializer(variationType, testData) && Assert.Http.CanRoundTrip(variationType);
if (canSerialize)
{
object readObj = null;
Assert.Stream.WriteAndRead(
stream =>
{
Assert.Task.Succeeds(formatter.WriteToStreamAsync(variationType, testData, stream, contentHeaders, transportContext: null));
contentHeaders.ContentLength = stream.Length;
},
stream => readObj = Assert.Task.SucceedsWithResult(formatter.ReadFromStreamAsync(variationType, stream, contentHeaders, null)));
Assert.Equal(testData, readObj);
}
}
[Fact]
public void UseDataContractJsonSerializer_True()
{
DataContractJsonMediaTypeFormatter jsonFormatter = new DataContractJsonMediaTypeFormatter();
MemoryStream memoryStream = new MemoryStream();
HttpContentHeaders contentHeaders = FormattingUtilities.CreateEmptyContentHeaders();
Assert.Task.Succeeds(jsonFormatter.WriteToStreamAsync(typeof(XmlMediaTypeFormatterTests.SampleType), new XmlMediaTypeFormatterTests.SampleType(), memoryStream, contentHeaders, transportContext: null));
memoryStream.Position = 0;
string serializedString = new StreamReader(memoryStream).ReadToEnd();
Assert.False(serializedString.Contains("\r\n"), "Using DCJS should emit data without indentation by default.");
}
[Fact]
[Trait("Description", "UseDataContractJsonSerializer property with Indent throws when set to true.")]
public void UseDataContractJsonSerializer_True_Indent_Throws()
{
DataContractJsonMediaTypeFormatter jsonFormatter = new DataContractJsonMediaTypeFormatter { Indent = true };
MemoryStream memoryStream = new MemoryStream();
HttpContentHeaders contentHeaders = FormattingUtilities.CreateEmptyContentHeaders();
Assert.Throws<NotSupportedException>(
() => jsonFormatter.WriteToStreamAsync(typeof(XmlMediaTypeFormatterTests.SampleType),
new XmlMediaTypeFormatterTests.SampleType(),
memoryStream, contentHeaders, transportContext: null));
}
[Theory]
[PropertyData("ReadAndWriteCorrectCharacterEncoding")]
public override Task ReadFromStreamAsync_UsesCorrectCharacterEncoding(string content, string encoding, bool isDefaultEncoding)
{
if (!isDefaultEncoding)
{
// XmlDictionaryReader/Writer only supports utf-8 and 16
return TaskHelpers.Completed();
}
// Arrange
DataContractJsonMediaTypeFormatter formatter = new DataContractJsonMediaTypeFormatter();
string formattedContent = "\"" + content + "\"";
string mediaType = string.Format("application/json; charset={0}", encoding);
// Act & assert
return ReadContentUsingCorrectCharacterEncodingHelper(
formatter, content, formattedContent, mediaType, encoding, isDefaultEncoding);
}
[Theory]
[PropertyData("ReadAndWriteCorrectCharacterEncoding")]
public override Task WriteToStreamAsync_UsesCorrectCharacterEncoding(string content, string encoding, bool isDefaultEncoding)
{
// DataContractJsonSerializer does not honor the value of byteOrderMark in the UnicodeEncoding ctor.
// It doesn't include the BOM when byteOrderMark is set to true.
if (!isDefaultEncoding || encoding != "utf-8")
{
// XmlDictionaryReader/Writer only supports utf-8 and 16
return TaskHelpers.Completed();
}
// Arrange
DataContractJsonMediaTypeFormatter formatter = new DataContractJsonMediaTypeFormatter();
string formattedContent = "\"" + content + "\"";
string mediaType = string.Format("application/json; charset={0}", encoding);
// Act & assert
return WriteContentUsingCorrectCharacterEncodingHelper(
formatter, content, formattedContent, mediaType, encoding, isDefaultEncoding);
}
public class TestJsonMediaTypeFormatter : DataContractJsonMediaTypeFormatter
{
public bool CanReadTypeProxy(Type type)
{
return CanReadType(type);
}
public bool CanWriteTypeProxy(Type type)
{
return CanWriteType(type);
}
}
private bool IsTypeSerializableWithJsonSerializer(Type type, object obj)
{
try
{
new DataContractJsonSerializer(type);
if (obj != null && obj.GetType() != type)
{
new DataContractJsonSerializer(obj.GetType());
}
}
catch
{
return false;
}
return !Assert.Http.IsKnownUnserializable(type, obj, (t) => typeof(INotJsonSerializable).IsAssignableFrom(t));
}
}
}

View File

@ -0,0 +1,257 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Formatting.Mocks;
using System.Net.Http.Headers;
using System.Text;
using Microsoft.TestCommon;
using Newtonsoft.Json.Linq;
using Xunit;
using Assert = Microsoft.TestCommon.AssertEx;
namespace System.Net.Http.Formatting
{
public class DefaultContentNegotiatorTests
{
private readonly DefaultContentNegotiator _negotiator = new DefaultContentNegotiator();
private readonly HttpRequestMessage _request = new HttpRequestMessage();
[Fact]
public void TypeIsCorrect()
{
Assert.Type.HasProperties(typeof(DefaultContentNegotiator), TypeAssert.TypeProperties.IsPublicVisibleClass);
}
[Fact]
public void Negotiate_WhenTypeParameterIsNull_ThrowsException()
{
Assert.ThrowsArgumentNull(() => _negotiator.Negotiate(null, _request, Enumerable.Empty<MediaTypeFormatter>()), "type");
}
[Fact]
public void Negotiate_WhenRequestParameterIsNull_ThrowsException()
{
Assert.ThrowsArgumentNull(() => _negotiator.Negotiate(typeof(string), null, Enumerable.Empty<MediaTypeFormatter>()), "request");
}
[Fact]
public void Negotiate_WhenFormattersParameterIsNull_ThrowsException()
{
Assert.ThrowsArgumentNull(() => _negotiator.Negotiate(typeof(string), _request, null), "formatters");
}
[Fact]
public void Negotiate_ForEmptyFormatterCollection_ReturnsNull()
{
var result = _negotiator.Negotiate(typeof(string), _request, Enumerable.Empty<MediaTypeFormatter>());
Assert.Null(result);
}
[Fact]
public void MediaTypeMappingTakesPrecedenceOverAcceptHeader()
{
// Prepare the request message
_request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml"));
_request.Headers.Add("Browser", "IE");
_request.Headers.Add("Cookie", "ABC");
// Prepare the formatters
List<MediaTypeFormatter> formatters = new List<MediaTypeFormatter>();
formatters.Add(new JsonMediaTypeFormatter());
formatters.Add(new XmlMediaTypeFormatter());
PlainTextFormatter frmtr = new PlainTextFormatter();
frmtr.SupportedMediaTypes.Clear();
frmtr.MediaTypeMappings.Clear();
frmtr.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/xml"));
frmtr.MediaTypeMappings.Add(new MyMediaTypeMapping(new MediaTypeHeaderValue(("application/xml"))));
formatters.Add(frmtr);
// Act
var result = _negotiator.Negotiate(typeof(string), _request, formatters);
// Assert
Assert.NotNull(result);
Assert.Equal("application/xml", result.MediaType.MediaType);
Assert.IsType<PlainTextFormatter>(result.Formatter);
}
[Fact]
public void Negotiate_ForRequestReturnsFirstMatchingFormatter()
{
MediaTypeHeaderValue mediaType = new MediaTypeHeaderValue("application/myMediaType");
MediaTypeFormatter formatter1 = new MockMediaTypeFormatter()
{
CanWriteTypeCallback = (Type t) => false
};
MediaTypeFormatter formatter2 = new MockMediaTypeFormatter()
{
CanWriteTypeCallback = (Type t) => true
};
formatter2.SupportedMediaTypes.Add(mediaType);
MediaTypeFormatterCollection collection = new MediaTypeFormatterCollection(
new MediaTypeFormatter[]
{
formatter1,
formatter2
});
_request.Content = new StringContent("test", Encoding.Default, mediaType.MediaType);
var result = _negotiator.Negotiate(typeof(string), _request, collection);
Assert.Same(formatter2, result.Formatter);
Assert.MediaType.AreEqual(mediaType, result.MediaType, "Expected the formatter's media type to be returned.");
}
[Fact]
public void Negotiate_SelectsJsonAsDefaultFormatter()
{
// Arrange
_request.Content = new StringContent("test");
// Act
var result = _negotiator.Negotiate(typeof(string), _request, new MediaTypeFormatterCollection());
// Assert
Assert.IsType<JsonMediaTypeFormatter>(result.Formatter);
Assert.Equal(MediaTypeConstants.ApplicationJsonMediaType.MediaType, result.MediaType.MediaType);
}
[Fact]
public void Negotiate_SelectsXmlFormatter_ForXhrRequestThatAcceptsXml()
{
// Arrange
_request.Content = new StringContent("test");
_request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml"));
_request.Headers.Add("x-requested-with", "XMLHttpRequest");
// Act
var result = _negotiator.Negotiate(typeof(string), _request, new MediaTypeFormatterCollection());
// Assert
Assert.Equal("application/xml", result.MediaType.MediaType);
Assert.IsType<XmlMediaTypeFormatter>(result.Formatter);
}
[Fact]
public void Negotiate_SelectsJsonFormatter_ForXhrRequestThatDoesNotSpecifyAcceptHeaders()
{
// Arrange
_request.Content = new StringContent("test");
_request.Headers.Add("x-requested-with", "XMLHttpRequest");
// Act
var result = _negotiator.Negotiate(typeof(string), _request, new MediaTypeFormatterCollection());
// Assert
Assert.Equal("application/json", result.MediaType.MediaType);
Assert.IsType<JsonMediaTypeFormatter>(result.Formatter);
}
[Fact]
public void Negotiate_RespectsFormatterOrdering_ForXhrRequestThatDoesNotSpecifyAcceptHeaders()
{
// Arrange
_request.Content = new StringContent("test");
_request.Headers.Add("x-requested-with", "XMLHttpRequest");
MediaTypeFormatterCollection formatters = new MediaTypeFormatterCollection(new MediaTypeFormatter[]
{
new XmlMediaTypeFormatter(),
new JsonMediaTypeFormatter(),
new FormUrlEncodedMediaTypeFormatter()
});
// Act
var result = _negotiator.Negotiate(typeof(string), _request, formatters);
// Assert
Assert.Equal("application/json", result.MediaType.MediaType);
Assert.IsType<JsonMediaTypeFormatter>(result.Formatter);
}
[Fact]
public void Negotiate_SelectsJsonFormatter_ForXHRAndJsonValueResponse()
{
// Arrange
_request.Content = new StringContent("test");
_request.Headers.Add("x-requested-with", "XMLHttpRequest");
// Act
var result = _negotiator.Negotiate(typeof(JToken), _request, new MediaTypeFormatterCollection());
Assert.Equal("application/json", result.MediaType.MediaType);
Assert.IsType<JsonMediaTypeFormatter>(result.Formatter);
}
[Fact]
public void Negotiate_SelectsJsonFormatter_ForXHRAndMatchAllAcceptHeader()
{
// Accept
_request.Content = new StringContent("test");
_request.Headers.Add("x-requested-with", "XMLHttpRequest");
_request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("*/*"));
// Act
var result = _negotiator.Negotiate(typeof(string), _request, new MediaTypeFormatterCollection());
// Assert
Assert.Equal("application/json", result.MediaType.MediaType);
Assert.IsType<JsonMediaTypeFormatter>(result.Formatter);
}
[Fact]
public void Negotiate_UsesRequestedFormatterForXHRAndMatchAllPlusOtherAcceptHeader()
{
// Arrange
_request.Content = new StringContent("test");
_request.Headers.Add("x-requested-with", "XMLHttpRequest");
_request.Headers.Accept.ParseAdd("text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); // XHR header sent by Firefox 3b5
// Act
var result = _negotiator.Negotiate(typeof(string), _request, new MediaTypeFormatterCollection());
// Assert
Assert.Equal("application/xml", result.MediaType.MediaType);
Assert.IsType<XmlMediaTypeFormatter>(result.Formatter);
}
private class PlainTextFormatter : MediaTypeFormatter
{
public override bool CanReadType(Type type)
{
return true;
}
public override bool CanWriteType(Type type)
{
return true;
}
}
private class MyMediaTypeMapping : MediaTypeMapping
{
public MyMediaTypeMapping(MediaTypeHeaderValue mediaType)
: base(mediaType)
{
}
public override double TryMatchMediaType(HttpRequestMessage request)
{
if (request.Headers.Contains("Cookie"))
{
return 1.0;
}
else
{
return 0;
}
}
}
}
}

View File

@ -0,0 +1,150 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using Xunit;
using Xunit.Extensions;
using Assert = Microsoft.TestCommon.AssertEx;
namespace System.Net.Http.Formatting
{
public class FormDataCollectionTests
{
[Fact]
public void CreateFromUri()
{
FormDataCollection form = new FormDataCollection(new Uri("http://foo.com/?x=1&y=2"));
Assert.Equal("1", form.Get("x"));
Assert.Equal("2", form.Get("y"));
}
[Fact]
public void CreateFromEmptyUri()
{
FormDataCollection form = new FormDataCollection(new Uri("http://foo.com"));
Assert.Empty(form);
}
[Fact]
public void UriConstructorThrowsNull()
{
Assert.Throws<ArgumentNullException>(() => new FormDataCollection((Uri)null));
}
[Fact]
public void CreateFromEmptyString()
{
FormDataCollection form = new FormDataCollection("");
Assert.Empty(form);
}
[Fact]
public void CreateFromNullString()
{
FormDataCollection form = new FormDataCollection((string) null);
Assert.Empty(form);
}
[Fact]
public void PairConstructorThrowsNull()
{
var arg = (IEnumerable<KeyValuePair<string, string>>)null;
Assert.Throws<ArgumentNullException>(() => new FormDataCollection(arg));
}
[Fact]
public void CreateFromPairs()
{
Dictionary<string, string> pairs = new Dictionary<string,string>
{
{ "x", "1"},
{ "y" , "2"}
};
var form = new FormDataCollection(pairs);
Assert.Equal("1", form.Get("x"));
Assert.Equal("2", form.Get("y"));
}
[Fact]
public void Enumeration()
{
FormDataCollection form = new FormDataCollection(new Uri("http://foo.com/?x=1&y=2"));
// Enumeration should be ordered
String s = "";
foreach (KeyValuePair<string, string> kv in form)
{
s += string.Format("{0}={1};", kv.Key, kv.Value);
}
Assert.Equal("x=1;y=2;", s);
}
[Fact]
public void GetValues()
{
FormDataCollection form = new FormDataCollection(new Uri("http://foo.com/?x=1&x=2&x=3"));
Assert.Equal(new string [] { "1", "2", "3"}, form.GetValues("x"));
}
[Fact]
public void CaseInSensitive()
{
FormDataCollection form = new FormDataCollection(new Uri("http://foo.com/?x=1&Y=2"));
NameValueCollection nvc = form.ReadAsNameValueCollection();
Assert.Equal(2, nvc.Count);
Assert.Equal("1", nvc.Get("x"));
Assert.Equal("2", nvc.Get("y"));
}
[Fact]
public void ToNameValueCollection()
{
FormDataCollection form = new FormDataCollection(new Uri("http://foo.com/?x=1a&y=2&x=1b&=ValueOnly&KeyOnly"));
NameValueCollection nvc = form.ReadAsNameValueCollection();
// y=2
// x=1a;x=1b
// =ValueOnly
// KeyOnly
Assert.Equal(4, nvc.Count);
Assert.Equal(new string[] { "1a", "1b"}, nvc.GetValues("x"));
Assert.Equal("1a,1b", nvc.Get("x"));
Assert.Equal("2", nvc.Get("y"));
Assert.Equal("", nvc.Get("KeyOnly"));
Assert.Equal("ValueOnly", nvc.Get(""));
}
const string SPACE = " "; // single literal space character
[Theory]
[InlineData("x=abc", "abc")] // normal
[InlineData("x", "")] // key only
[InlineData("x=", "")] // rhs only
[InlineData("x=%20", SPACE)] // escaped space
[InlineData("x=" + SPACE, SPACE)] // literal space
[InlineData("x=+", SPACE)] //
[InlineData("x=null", "null")] // null literal, not escaped
[InlineData("x=undefined", "undefined")] // undefined literal, not escaped
[InlineData("x=\"null\"", "\"null\"")] // quoted null, preserved as is
public void Whitespace(string queryString, string expected)
{
FormDataCollection fd = new FormDataCollection(queryString);
Assert.Equal(1, fd.Count());
Assert.Equal(expected, fd.Get("x"));
}
}
}

View File

@ -0,0 +1,77 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Collections.Generic;
using Microsoft.TestCommon;
using Newtonsoft.Json.Linq;
using Xunit;
using Assert = Microsoft.TestCommon.AssertEx;
namespace System.Net.Http.Formatting
{
public class FormUrlEncodedJsonTests
{
[Fact]
public void TypeIsCorrect()
{
Assert.Type.HasProperties(typeof(FormUrlEncodedJson), TypeAssert.TypeProperties.IsClass | TypeAssert.TypeProperties.IsStatic);
}
[Fact]
public void ParseThrowsOnNull()
{
Assert.ThrowsArgumentNull(() => FormUrlEncodedJson.Parse(null), null);
}
[Fact]
public void ParseThrowsInvalidMaxDepth()
{
Assert.ThrowsArgumentGreaterThan(() => FormUrlEncodedJson.Parse(CreateQuery(), -1), "maxDepth", "0", -1);
Assert.ThrowsArgumentGreaterThan(() => FormUrlEncodedJson.Parse(CreateQuery(), 0), "maxDepth", "0", 0);
}
[Fact]
public void ParseThrowsMaxDepthExceeded()
{
// Depth of 'a[b]=1' is 3
IEnumerable<KeyValuePair<string, string>> query = CreateQuery(new KeyValuePair<string, string>("a[b]", "1"));
Assert.ThrowsArgument(() => { FormUrlEncodedJson.Parse(query, 2); }, null);
// This should succeed
Assert.NotNull(FormUrlEncodedJson.Parse(query, 3));
}
[Fact]
public void TryParseThrowsOnNull()
{
JObject value;
Assert.ThrowsArgumentNull(() => FormUrlEncodedJson.TryParse(null, out value), null);
}
[Fact]
public void TryParseThrowsInvalidMaxDepth()
{
JObject value;
Assert.ThrowsArgumentGreaterThan(() => FormUrlEncodedJson.TryParse(CreateQuery(), -1, out value), "maxDepth", "0", -1);
Assert.ThrowsArgumentGreaterThan(() => FormUrlEncodedJson.TryParse(CreateQuery(), 0, out value), "maxDepth", "0", 0);
}
[Fact]
public void TryParseReturnsFalseMaxDepthExceeded()
{
JObject value;
// Depth of 'a[b]=1' is 3
IEnumerable<KeyValuePair<string, string>> query = CreateQuery(new KeyValuePair<string, string>("a[b]", "1"));
Assert.False(FormUrlEncodedJson.TryParse(query, 2, out value), "Parse should have failed due to too high depth.");
// This should succeed
Assert.True(FormUrlEncodedJson.TryParse(query, 3, out value), "Expected non-null JsonObject instance");
Assert.NotNull(value);
}
private static IEnumerable<KeyValuePair<string, string>> CreateQuery(params KeyValuePair<string, string>[] namevaluepairs)
{
return new List<KeyValuePair<string, string>>(namevaluepairs);
}
}
}

View File

@ -0,0 +1,200 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.IO;
using System.Net.Http.Formatting.DataSets;
using System.Net.Http.Headers;
using System.Text;
using Microsoft.TestCommon;
using Newtonsoft.Json.Linq;
using Xunit;
using Xunit.Extensions;
using Assert = Microsoft.TestCommon.AssertEx;
namespace System.Net.Http.Formatting
{
public class FormUrlEncodedMediaTypeFormatterTests
{
private const int MinBufferSize = 256;
private const int DefaultBufferSize = 32 * 1024;
private const int DefaultMaxDepth = 1024;
[Fact]
[Trait("Description", "FormUrlEncodedMediaTypeFormatter is public, concrete, and unsealed.")]
public void TypeIsCorrect()
{
Assert.Type.HasProperties(typeof(FormUrlEncodedMediaTypeFormatter), TypeAssert.TypeProperties.IsPublicVisibleClass);
}
[Theory]
[TestDataSet(typeof(HttpUnitTestDataSets), "StandardFormUrlEncodedMediaTypes")]
[Trait("Description", "FormUrlEncodedMediaTypeFormatter() constructor sets standard form URL encoded media types in SupportedMediaTypes.")]
public void Constructor(MediaTypeHeaderValue mediaType)
{
FormUrlEncodedMediaTypeFormatter formatter = new FormUrlEncodedMediaTypeFormatter();
Assert.True(formatter.SupportedMediaTypes.Contains(mediaType), String.Format("SupportedMediaTypes should have included {0}.", mediaType.ToString()));
}
[Fact]
[Trait("Description", "DefaultMediaType property returns application/x-www-form-urlencoded.")]
public void DefaultMediaTypeReturnsApplicationJson()
{
MediaTypeHeaderValue mediaType = FormUrlEncodedMediaTypeFormatter.DefaultMediaType;
Assert.NotNull(mediaType);
Assert.Equal("application/x-www-form-urlencoded", mediaType.MediaType);
}
[Fact]
public void ReadBufferSize_RoundTrips()
{
Assert.Reflection.IntegerProperty(
new FormUrlEncodedMediaTypeFormatter(),
c => c.ReadBufferSize,
expectedDefaultValue: 32 * 1024,
minLegalValue: 256,
illegalLowerValue: 255,
maxLegalValue: null,
illegalUpperValue: null,
roundTripTestValue: 1024);
}
[Fact]
[Trait("Description", "MaxDepth return correct value.")]
public void MaxDepthReturnsCorrectValue()
{
Assert.Reflection.IntegerProperty(
new FormUrlEncodedMediaTypeFormatter(),
f => f.MaxDepth,
expectedDefaultValue: 256,
minLegalValue: 1,
illegalLowerValue: 0,
maxLegalValue: null,
illegalUpperValue: null,
roundTripTestValue: 10);
}
[Fact]
[Trait("Description", "Deeply nested objects throws.")]
public void ReadDeeplyNestedObjectThrows()
{
FormUrlEncodedMediaTypeFormatter formatter = new FormUrlEncodedMediaTypeFormatter() { MaxDepth = 100 };
StringContent content = new StringContent(GetDeeplyNestedObject(125));
content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
Assert.ThrowsArgument(
() => formatter.ReadFromStreamAsync(typeof(JToken), content.ReadAsStreamAsync().Result, content.Headers, null).Result,
null);
}
[Fact]
[Trait("Description", "Read DeeplyNestedobject WithBigDepthQuota should work")]
public void ReadDeeplyNestedObjectWithBigDepthQuotaWorks()
{
FormUrlEncodedMediaTypeFormatter formatter = new FormUrlEncodedMediaTypeFormatter() { MaxDepth = 150 };
StringContent content = new StringContent(GetDeeplyNestedObject(125));
content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
JToken result = (JToken)formatter.ReadFromStreamAsync(typeof(JToken), content.ReadAsStreamAsync().Result, content.Headers, null).Result;
Assert.NotNull(result);
}
static string GetDeeplyNestedObject(int depth)
{
StringBuilder sb = new StringBuilder("a");
for (int i = 0; i < depth; i++)
{
sb.Append("[a]");
}
sb.Append("=1");
return sb.ToString();
}
[Fact]
[Trait("Description", "CanReadType() throws on null.")]
public void CanReadTypeThrowsOnNull()
{
TestFormUrlEncodedMediaTypeFormatter formatter = new TestFormUrlEncodedMediaTypeFormatter();
Assert.ThrowsArgumentNull(() => { formatter.CanReadType(null); }, "type");
}
[Theory]
[InlineData(typeof(FormDataCollection))]
[InlineData(typeof(JToken))]
public void CanReadTypeTrue(Type type)
{
TestFormUrlEncodedMediaTypeFormatter formatter = new TestFormUrlEncodedMediaTypeFormatter();
Assert.True(formatter.CanReadType(type));
}
[Theory]
[TestDataSet(typeof(CommonUnitTestDataSets), "RepresentativeValueAndRefTypeTestDataCollection")]
[Trait("Description", "CanReadType(Type) returns false.")]
public void CanReadTypeReturnsFalse(Type variationType, object testData)
{
TestFormUrlEncodedMediaTypeFormatter formatter = new TestFormUrlEncodedMediaTypeFormatter();
Assert.False(formatter.CanReadType(variationType));
// Ask a 2nd time to probe whether the cached result is treated the same
Assert.False(formatter.CanReadType(variationType));
}
[Fact]
[Trait("Description", "CanWriteType(Type) throws on null.")]
public void CanWriteTypeThrowsOnNull()
{
TestFormUrlEncodedMediaTypeFormatter formatter = new TestFormUrlEncodedMediaTypeFormatter();
Assert.ThrowsArgumentNull(() => { formatter.CanWriteType(null); }, "type");
}
[Theory]
[TestDataSet(typeof(CommonUnitTestDataSets), "RepresentativeValueAndRefTypeTestDataCollection")]
[Trait("Description", "CanWriteType() returns false.")]
public void CanWriteTypeReturnsFalse(Type variationType, object testData)
{
TestFormUrlEncodedMediaTypeFormatter formatter = new TestFormUrlEncodedMediaTypeFormatter();
Assert.False(formatter.CanWriteType(variationType), "formatter should have returned false.");
// Ask a 2nd time to probe whether the cached result is treated the same
Assert.False(formatter.CanWriteType(variationType), "formatter should have returned false on 2nd try as well.");
}
[Fact]
[Trait("Description", "ReadFromStreamAsync() throws on null.")]
public void ReadFromStreamThrowsOnNull()
{
TestFormUrlEncodedMediaTypeFormatter formatter = new TestFormUrlEncodedMediaTypeFormatter();
Assert.ThrowsArgumentNull(() => { formatter.ReadFromStreamAsync(null, Stream.Null, null, null); }, "type");
Assert.ThrowsArgumentNull(() => { formatter.ReadFromStreamAsync(typeof(object), null, null, null); }, "stream");
}
[Fact]
[Trait("Description", "WriteToStreamAsync() throws not implemented.")]
public void WriteToStreamAsyncThrowsNotImplemented()
{
FormUrlEncodedMediaTypeFormatter formatter = new FormUrlEncodedMediaTypeFormatter();
Assert.Throws<NotSupportedException>(
() => formatter.WriteToStreamAsync(typeof(object), new object(), Stream.Null, null, null),
"The media type formatter of type 'FormUrlEncodedMediaTypeFormatter' does not support writing because it does not implement the WriteToStreamAsync method.");
}
public class TestFormUrlEncodedMediaTypeFormatter : FormUrlEncodedMediaTypeFormatter
{
public new bool CanReadType(Type type)
{
return base.CanReadType(type);
}
public new bool CanWriteType(Type type)
{
return base.CanWriteType(type);
}
}
}
}

Some files were not shown because too many files have changed in this diff Show More