summaryrefslogtreecommitdiffstats
path: root/src/DotNetOAuth.Test/Messaging
diff options
context:
space:
mode:
Diffstat (limited to 'src/DotNetOAuth.Test/Messaging')
-rw-r--r--src/DotNetOAuth.Test/Messaging/Bindings/StandardExpirationBindingElementTests.cs39
-rw-r--r--src/DotNetOAuth.Test/Messaging/ChannelTests.cs290
-rw-r--r--src/DotNetOAuth.Test/Messaging/CollectionAssert.cs19
-rw-r--r--src/DotNetOAuth.Test/Messaging/HttpRequestInfoTests.cs36
-rw-r--r--src/DotNetOAuth.Test/Messaging/MessageSerializerTests.cs130
-rw-r--r--src/DotNetOAuth.Test/Messaging/MessagingTestBase.cs188
-rw-r--r--src/DotNetOAuth.Test/Messaging/MessagingUtilitiesTests.cs99
-rw-r--r--src/DotNetOAuth.Test/Messaging/ProtocolExceptionTests.cs97
-rw-r--r--src/DotNetOAuth.Test/Messaging/Reflection/MessageDescriptionTests.cs24
-rw-r--r--src/DotNetOAuth.Test/Messaging/Reflection/MessageDictionaryTests.cs347
-rw-r--r--src/DotNetOAuth.Test/Messaging/Reflection/MessagePartTests.cs101
-rw-r--r--src/DotNetOAuth.Test/Messaging/Reflection/ValueMappingTests.cs24
-rw-r--r--src/DotNetOAuth.Test/Messaging/ResponseTests.cs39
13 files changed, 0 insertions, 1433 deletions
diff --git a/src/DotNetOAuth.Test/Messaging/Bindings/StandardExpirationBindingElementTests.cs b/src/DotNetOAuth.Test/Messaging/Bindings/StandardExpirationBindingElementTests.cs
deleted file mode 100644
index 6c05434..0000000
--- a/src/DotNetOAuth.Test/Messaging/Bindings/StandardExpirationBindingElementTests.cs
+++ /dev/null
@@ -1,39 +0,0 @@
-//-----------------------------------------------------------------------
-// <copyright file="StandardExpirationBindingElementTests.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOAuth.Test.Messaging.Bindings {
- using System;
- using DotNetOAuth.Messaging;
- using DotNetOAuth.Messaging.Bindings;
- using DotNetOAuth.Test.Mocks;
- using Microsoft.VisualStudio.TestTools.UnitTesting;
-
- [TestClass]
- public class StandardExpirationBindingElementTests : MessagingTestBase {
- [TestMethod]
- public void SendSetsTimestamp() {
- TestExpiringMessage message = new TestExpiringMessage(MessageTransport.Indirect);
- message.Recipient = new Uri("http://localtest");
- ((IExpiringProtocolMessage)message).UtcCreationDate = DateTime.Parse("1/1/1990");
-
- Channel channel = CreateChannel(MessageProtections.Expiration);
- channel.Send(message);
- Assert.IsTrue(DateTime.UtcNow - ((IExpiringProtocolMessage)message).UtcCreationDate < TimeSpan.FromSeconds(3), "The timestamp on the message was not set on send.");
- }
-
- [TestMethod]
- public void VerifyGoodTimestampIsAccepted() {
- this.Channel = CreateChannel(MessageProtections.Expiration);
- this.ParameterizedReceiveProtectedTest(DateTime.UtcNow, false);
- }
-
- [TestMethod, ExpectedException(typeof(ExpiredMessageException))]
- public void VerifyBadTimestampIsRejected() {
- this.Channel = CreateChannel(MessageProtections.Expiration);
- this.ParameterizedReceiveProtectedTest(DateTime.UtcNow - StandardExpirationBindingElement.DefaultMaximumMessageAge - TimeSpan.FromSeconds(1), false);
- }
- }
-}
diff --git a/src/DotNetOAuth.Test/Messaging/ChannelTests.cs b/src/DotNetOAuth.Test/Messaging/ChannelTests.cs
deleted file mode 100644
index e142c82..0000000
--- a/src/DotNetOAuth.Test/Messaging/ChannelTests.cs
+++ /dev/null
@@ -1,290 +0,0 @@
-//-----------------------------------------------------------------------
-// <copyright file="ChannelTests.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOAuth.Test.Messaging {
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Net;
- using System.Web;
- using DotNetOAuth.Messaging;
- using DotNetOAuth.Messaging.Bindings;
- using DotNetOAuth.Test.Mocks;
- using Microsoft.VisualStudio.TestTools.UnitTesting;
-
- [TestClass]
- public class ChannelTests : MessagingTestBase {
- [TestMethod, ExpectedException(typeof(ArgumentNullException))]
- public void CtorNull() {
- // This bad channel is deliberately constructed to pass null to
- // its protected base class' constructor.
- new TestBadChannel(true);
- }
-
- [TestMethod]
- public void ReadFromRequestQueryString() {
- this.ParameterizedReceiveTest("GET");
- }
-
- [TestMethod]
- public void ReadFromRequestForm() {
- this.ParameterizedReceiveTest("POST");
- }
-
- [TestMethod, ExpectedException(typeof(ArgumentNullException))]
- public void SendNull() {
- this.Channel.Send(null);
- }
-
- [TestMethod, ExpectedException(typeof(ArgumentException))]
- public void SendIndirectedUndirectedMessage() {
- IProtocolMessage message = new TestMessage(MessageTransport.Indirect);
- this.Channel.Send(message);
- }
-
- [TestMethod, ExpectedException(typeof(ArgumentException))]
- public void SendDirectedNoRecipientMessage() {
- IProtocolMessage message = new TestDirectedMessage(MessageTransport.Indirect);
- this.Channel.Send(message);
- }
-
- [TestMethod, ExpectedException(typeof(ArgumentException))]
- public void SendInvalidMessageTransport() {
- IProtocolMessage message = new TestDirectedMessage((MessageTransport)100);
- this.Channel.Send(message);
- }
-
- [TestMethod]
- public void SendIndirectMessage301Get() {
- TestDirectedMessage message = new TestDirectedMessage(MessageTransport.Indirect);
- GetStandardTestMessage(FieldFill.CompleteBeforeBindings, message);
- message.Recipient = new Uri("http://provider/path");
- var expected = GetStandardTestFields(FieldFill.CompleteBeforeBindings);
-
- Response response = this.Channel.Send(message);
- Assert.AreEqual(HttpStatusCode.Redirect, response.Status);
- StringAssert.StartsWith(response.Headers[HttpResponseHeader.Location], "http://provider/path");
- foreach (var pair in expected) {
- string key = HttpUtility.UrlEncode(pair.Key);
- string value = HttpUtility.UrlEncode(pair.Value);
- string substring = string.Format("{0}={1}", key, value);
- StringAssert.Contains(response.Headers[HttpResponseHeader.Location], substring);
- }
- }
-
- [TestMethod, ExpectedException(typeof(ArgumentNullException))]
- public void SendIndirectMessage301GetNullMessage() {
- TestBadChannel badChannel = new TestBadChannel(false);
- badChannel.Create301RedirectResponse(null, new Dictionary<string, string>());
- }
-
- [TestMethod, ExpectedException(typeof(ArgumentException))]
- public void SendIndirectMessage301GetEmptyRecipient() {
- TestBadChannel badChannel = new TestBadChannel(false);
- var message = new TestDirectedMessage(MessageTransport.Indirect);
- badChannel.Create301RedirectResponse(message, new Dictionary<string, string>());
- }
-
- [TestMethod, ExpectedException(typeof(ArgumentNullException))]
- public void SendIndirectMessage301GetNullFields() {
- TestBadChannel badChannel = new TestBadChannel(false);
- var message = new TestDirectedMessage(MessageTransport.Indirect);
- message.Recipient = new Uri("http://someserver");
- badChannel.Create301RedirectResponse(message, null);
- }
-
- [TestMethod]
- public void SendIndirectMessageFormPost() {
- // We craft a very large message to force fallback to form POST.
- // We'll also stick some HTML reserved characters in the string value
- // to test proper character escaping.
- var message = new TestDirectedMessage(MessageTransport.Indirect) {
- Age = 15,
- Name = "c<b" + new string('a', 10 * 1024),
- Location = new Uri("http://host/path"),
- Recipient = new Uri("http://provider/path"),
- };
- Response response = this.Channel.Send(message);
- Assert.AreEqual(HttpStatusCode.OK, response.Status, "A form redirect should be an HTTP successful response.");
- Assert.IsNull(response.Headers[HttpResponseHeader.Location], "There should not be a redirection header in the response.");
- string body = response.Body;
- StringAssert.Contains(body, "<form ");
- StringAssert.Contains(body, "action=\"http://provider/path\"");
- StringAssert.Contains(body, "method=\"post\"");
- StringAssert.Contains(body, "<input type=\"hidden\" name=\"age\" value=\"15\" />");
- StringAssert.Contains(body, "<input type=\"hidden\" name=\"Location\" value=\"http://host/path\" />");
- StringAssert.Contains(body, "<input type=\"hidden\" name=\"Name\" value=\"" + HttpUtility.HtmlEncode(message.Name) + "\" />");
- StringAssert.Contains(body, ".submit()", "There should be some javascript to automate form submission.");
- }
-
- [TestMethod, ExpectedException(typeof(ArgumentNullException))]
- public void SendIndirectMessageFormPostNullMessage() {
- TestBadChannel badChannel = new TestBadChannel(false);
- badChannel.CreateFormPostResponse(null, new Dictionary<string, string>());
- }
-
- [TestMethod, ExpectedException(typeof(ArgumentException))]
- public void SendIndirectMessageFormPostEmptyRecipient() {
- TestBadChannel badChannel = new TestBadChannel(false);
- var message = new TestDirectedMessage(MessageTransport.Indirect);
- badChannel.CreateFormPostResponse(message, new Dictionary<string, string>());
- }
-
- [TestMethod, ExpectedException(typeof(ArgumentNullException))]
- public void SendIndirectMessageFormPostNullFields() {
- TestBadChannel badChannel = new TestBadChannel(false);
- var message = new TestDirectedMessage(MessageTransport.Indirect);
- message.Recipient = new Uri("http://someserver");
- badChannel.CreateFormPostResponse(message, null);
- }
-
- /// <summary>
- /// Tests that a direct message is sent when the appropriate message type is provided.
- /// </summary>
- /// <remarks>
- /// Since this is a mock channel that doesn't actually formulate a direct message response,
- /// we just check that the right method was called.
- /// </remarks>
- [TestMethod, ExpectedException(typeof(NotImplementedException), "SendDirectMessageResponse")]
- public void SendDirectMessageResponse() {
- IProtocolMessage message = new TestMessage {
- Age = 15,
- Name = "Andrew",
- Location = new Uri("http://host/path"),
- };
- this.Channel.Send(message);
- }
-
- [TestMethod, ExpectedException(typeof(ArgumentNullException))]
- public void SendIndirectMessageNull() {
- TestBadChannel badChannel = new TestBadChannel(false);
- badChannel.SendIndirectMessage(null);
- }
-
- [TestMethod, ExpectedException(typeof(ArgumentNullException))]
- public void ReceiveNull() {
- TestBadChannel badChannel = new TestBadChannel(false);
- badChannel.Receive(null, null);
- }
-
- [TestMethod]
- public void ReceiveUnrecognizedMessage() {
- TestBadChannel badChannel = new TestBadChannel(false);
- Assert.IsNull(badChannel.Receive(new Dictionary<string, string>(), null));
- }
-
- [TestMethod]
- public void ReadFromRequestWithContext() {
- var fields = GetStandardTestFields(FieldFill.AllRequired);
- TestMessage expectedMessage = GetStandardTestMessage(FieldFill.AllRequired);
- HttpRequest request = new HttpRequest("somefile", "http://someurl", MessagingUtilities.CreateQueryString(fields));
- HttpContext.Current = new HttpContext(request, new HttpResponse(new StringWriter()));
- IProtocolMessage message = this.Channel.ReadFromRequest();
- Assert.IsNotNull(message);
- Assert.IsInstanceOfType(message, typeof(TestMessage));
- Assert.AreEqual(expectedMessage.Age, ((TestMessage)message).Age);
- }
-
- [TestMethod, ExpectedException(typeof(InvalidOperationException))]
- public void ReadFromRequestNoContext() {
- TestBadChannel badChannel = new TestBadChannel(false);
- badChannel.ReadFromRequest();
- }
-
- [TestMethod, ExpectedException(typeof(ArgumentNullException))]
- public void ReadFromRequestNull() {
- TestBadChannel badChannel = new TestBadChannel(false);
- badChannel.ReadFromRequest(null);
- }
-
- [TestMethod]
- public void SendReplayProtectedMessageSetsNonce() {
- TestReplayProtectedMessage message = new TestReplayProtectedMessage(MessageTransport.Indirect);
- message.Recipient = new Uri("http://localtest");
-
- this.Channel = CreateChannel(MessageProtections.ReplayProtection);
- this.Channel.Send(message);
- Assert.IsNotNull(((IReplayProtectedProtocolMessage)message).Nonce);
- }
-
- [TestMethod, ExpectedException(typeof(InvalidSignatureException))]
- public void ReceivedInvalidSignature() {
- this.Channel = CreateChannel(MessageProtections.TamperProtection);
- this.ParameterizedReceiveProtectedTest(DateTime.UtcNow, true);
- }
-
- [TestMethod]
- public void ReceivedReplayProtectedMessageJustOnce() {
- this.Channel = CreateChannel(MessageProtections.ReplayProtection);
- this.ParameterizedReceiveProtectedTest(DateTime.UtcNow, false);
- }
-
- [TestMethod, ExpectedException(typeof(ReplayedMessageException))]
- public void ReceivedReplayProtectedMessageTwice() {
- this.Channel = CreateChannel(MessageProtections.ReplayProtection);
- this.ParameterizedReceiveProtectedTest(DateTime.UtcNow, false);
- this.ParameterizedReceiveProtectedTest(DateTime.UtcNow, false);
- }
-
- [TestMethod, ExpectedException(typeof(ProtocolException))]
- public void MessageExpirationWithoutTamperResistance() {
- new TestChannel(
- new TestMessageTypeProvider(),
- new StandardExpirationBindingElement());
- }
-
- [TestMethod, ExpectedException(typeof(ProtocolException))]
- public void TooManyBindingElementsProvidingSameProtection() {
- new TestChannel(
- new TestMessageTypeProvider(),
- new MockSigningBindingElement(),
- new MockSigningBindingElement());
- }
-
- [TestMethod]
- public void BindingElementsOrdering() {
- IChannelBindingElement transformA = new MockTransformationBindingElement("a");
- IChannelBindingElement transformB = new MockTransformationBindingElement("b");
- IChannelBindingElement sign = new MockSigningBindingElement();
- IChannelBindingElement replay = new MockReplayProtectionBindingElement();
- IChannelBindingElement expire = new StandardExpirationBindingElement();
-
- Channel channel = new TestChannel(
- new TestMessageTypeProvider(),
- sign,
- replay,
- expire,
- transformB,
- transformA);
-
- Assert.AreEqual(5, channel.BindingElements.Count);
- Assert.AreSame(transformB, channel.BindingElements[0]);
- Assert.AreSame(transformA, channel.BindingElements[1]);
- Assert.AreSame(replay, channel.BindingElements[2]);
- Assert.AreSame(expire, channel.BindingElements[3]);
- Assert.AreSame(sign, channel.BindingElements[4]);
- }
-
- [TestMethod, ExpectedException(typeof(UnprotectedMessageException))]
- public void InsufficientlyProtectedMessageSent() {
- var message = new TestSignedDirectedMessage(MessageTransport.Direct);
- message.Recipient = new Uri("http://localtest");
- this.Channel.Send(message);
- }
-
- [TestMethod, ExpectedException(typeof(UnprotectedMessageException))]
- public void InsufficientlyProtectedMessageReceived() {
- this.Channel = CreateChannel(MessageProtections.None, MessageProtections.TamperProtection);
- this.ParameterizedReceiveProtectedTest(DateTime.Now, false);
- }
-
- [TestMethod, ExpectedException(typeof(ProtocolException))]
- public void IncomingMessageMissingRequiredParameters() {
- var fields = GetStandardTestFields(FieldFill.IdentifiableButNotAllRequired);
- this.Channel.ReadFromRequest(CreateHttpRequestInfo("GET", fields));
- }
- }
-}
diff --git a/src/DotNetOAuth.Test/Messaging/CollectionAssert.cs b/src/DotNetOAuth.Test/Messaging/CollectionAssert.cs
deleted file mode 100644
index b9f3da5..0000000
--- a/src/DotNetOAuth.Test/Messaging/CollectionAssert.cs
+++ /dev/null
@@ -1,19 +0,0 @@
-//-----------------------------------------------------------------------
-// <copyright file="CollectionAssert.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOAuth.Test.Messaging {
- using System.Collections;
- using System.Collections.Generic;
- using Microsoft.VisualStudio.TestTools.UnitTesting;
-
- internal class CollectionAssert<T> {
- internal static void AreEquivalent(ICollection<T> expected, ICollection<T> actual) {
- ICollection expectedNonGeneric = new List<T>(expected);
- ICollection actualNonGeneric = new List<T>(actual);
- CollectionAssert.AreEquivalent(expectedNonGeneric, actualNonGeneric);
- }
- }
-}
diff --git a/src/DotNetOAuth.Test/Messaging/HttpRequestInfoTests.cs b/src/DotNetOAuth.Test/Messaging/HttpRequestInfoTests.cs
deleted file mode 100644
index 70fa1d0..0000000
--- a/src/DotNetOAuth.Test/Messaging/HttpRequestInfoTests.cs
+++ /dev/null
@@ -1,36 +0,0 @@
-//-----------------------------------------------------------------------
-// <copyright file="HttpRequestInfoTests.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOAuth.Test.Messaging {
- using System.Web;
- using DotNetOAuth.Messaging;
- using Microsoft.VisualStudio.TestTools.UnitTesting;
-
- [TestClass]
- public class HttpRequestInfoTests : TestBase {
- [TestMethod]
- public void CtorRequest() {
- HttpRequest request = new HttpRequest("file", "http://someserver?a=b", "a=b");
- ////request.Headers["headername"] = "headervalue"; // PlatformNotSupportedException prevents us mocking this up
- HttpRequestInfo info = new HttpRequestInfo(request);
- Assert.AreEqual(request.Headers["headername"], info.Headers["headername"]);
- Assert.AreEqual(request.Url.Query, info.Query);
- Assert.AreEqual(request.QueryString["a"], info.QueryString["a"]);
- Assert.AreEqual(request.Url, info.Url);
- Assert.AreEqual(request.HttpMethod, info.HttpMethod);
- }
-
- /// <summary>
- /// Checks that a property dependent on another null property
- /// doesn't generate a NullReferenceException.
- /// </summary>
- [TestMethod]
- public void QueryBeforeSettingUrl() {
- HttpRequestInfo info = new HttpRequestInfo();
- Assert.IsNull(info.Query);
- }
- }
-}
diff --git a/src/DotNetOAuth.Test/Messaging/MessageSerializerTests.cs b/src/DotNetOAuth.Test/Messaging/MessageSerializerTests.cs
deleted file mode 100644
index d2d87e1..0000000
--- a/src/DotNetOAuth.Test/Messaging/MessageSerializerTests.cs
+++ /dev/null
@@ -1,130 +0,0 @@
-//-----------------------------------------------------------------------
-// <copyright file="MessageSerializerTests.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOAuth.Test.Messaging {
- using System;
- using System.Collections.Generic;
- using System.Xml;
- using DotNetOAuth.Messaging;
- using Microsoft.VisualStudio.TestTools.UnitTesting;
-
- /// <summary>
- /// Tests for the <see cref="MessageSerializer"/> class.
- /// </summary>
- [TestClass()]
- public class MessageSerializerTests : MessagingTestBase {
- [TestMethod, ExpectedException(typeof(ArgumentNullException))]
- public void SerializeNull() {
- var serializer = MessageSerializer.Get(typeof(Mocks.TestMessage));
- serializer.Serialize(null);
- }
-
- [TestMethod, ExpectedException(typeof(ArgumentException))]
- public void GetInvalidMessageType() {
- MessageSerializer.Get(typeof(string));
- }
-
- [TestMethod, ExpectedException(typeof(ArgumentNullException))]
- public void GetNullType() {
- MessageSerializer.Get(null);
- }
-
- [TestMethod()]
- public void SerializeTest() {
- var serializer = MessageSerializer.Get(typeof(Mocks.TestMessage));
- var message = GetStandardTestMessage(FieldFill.CompleteBeforeBindings);
- var expected = GetStandardTestFields(FieldFill.CompleteBeforeBindings);
- IDictionary<string, string> actual = serializer.Serialize(message);
- Assert.AreEqual(4, actual.Count);
-
- // Test case sensitivity of generated dictionary
- Assert.IsFalse(actual.ContainsKey("Age"));
- Assert.IsTrue(actual.ContainsKey("age"));
-
- // Test contents of dictionary
- Assert.AreEqual(expected["age"], actual["age"]);
- Assert.AreEqual(expected["Name"], actual["Name"]);
- Assert.AreEqual(expected["Location"], actual["Location"]);
- Assert.AreEqual(expected["Timestamp"], actual["Timestamp"]);
- Assert.IsFalse(actual.ContainsKey("EmptyMember"));
- }
-
- [TestMethod, ExpectedException(typeof(ArgumentNullException))]
- public void DeserializeNull() {
- var serializer = MessageSerializer.Get(typeof(Mocks.TestMessage));
- serializer.Deserialize(null, null);
- }
-
- [TestMethod]
- public void DeserializeSimple() {
- var serializer = MessageSerializer.Get(typeof(Mocks.TestMessage));
- Dictionary<string, string> fields = new Dictionary<string, string>(StringComparer.Ordinal);
- fields["Name"] = "Andrew";
- fields["age"] = "15";
- fields["Timestamp"] = "1990-01-01T00:00:00";
- var actual = (Mocks.TestMessage)serializer.Deserialize(fields, null);
- Assert.AreEqual(15, actual.Age);
- Assert.AreEqual("Andrew", actual.Name);
- Assert.AreEqual(DateTime.Parse("1/1/1990"), actual.Timestamp);
- Assert.IsNull(actual.EmptyMember);
- }
-
- /// <summary>
- /// This tests deserialization of a message that is comprised of [MessagePart]'s
- /// that are defined in multiple places in the inheritance tree.
- /// </summary>
- /// <remarks>
- /// The element sorting rules are first inheritance order, then alphabetical order.
- /// This test validates correct behavior on both.
- /// </remarks>
- [TestMethod]
- public void DeserializeVerifyElementOrdering() {
- var serializer = MessageSerializer.Get(typeof(Mocks.TestDerivedMessage));
- Dictionary<string, string> fields = new Dictionary<string, string>(StringComparer.Ordinal);
- // We deliberately do this OUT of order,
- // since DataContractSerializer demands elements to be in
- // 1) inheritance then 2) alphabetical order.
- // Proper xml element order would be: Name, age, Second..., TheFirst...
- fields["TheFirstDerivedElement"] = "first";
- fields["age"] = "15";
- fields["Name"] = "Andrew";
- fields["SecondDerivedElement"] = "second";
- fields["explicit"] = "explicitValue";
- fields["private"] = "privateValue";
- var actual = (Mocks.TestDerivedMessage)serializer.Deserialize(fields, null);
- Assert.AreEqual(15, actual.Age);
- Assert.AreEqual("Andrew", actual.Name);
- Assert.AreEqual("first", actual.TheFirstDerivedElement);
- Assert.AreEqual("second", actual.SecondDerivedElement);
- Assert.AreEqual("explicitValue", ((Mocks.IBaseMessageExplicitMembers)actual).ExplicitProperty);
- Assert.AreEqual("privateValue", actual.PrivatePropertyAccessor);
- }
-
- [TestMethod]
- public void DeserializeWithExtraFields() {
- var serializer = MessageSerializer.Get(typeof(Mocks.TestMessage));
- Dictionary<string, string> fields = new Dictionary<string, string>(StringComparer.Ordinal);
- fields["age"] = "15";
- fields["Name"] = "Andrew";
- fields["Timestamp"] = XmlConvert.ToString(DateTime.UtcNow, XmlDateTimeSerializationMode.Utc);
- // Add some field that is not recognized by the class. This simulates a querystring with
- // more parameters than are actually interesting to the protocol message.
- fields["someExtraField"] = "asdf";
- var actual = (Mocks.TestMessage)serializer.Deserialize(fields, null);
- Assert.AreEqual(15, actual.Age);
- Assert.AreEqual("Andrew", actual.Name);
- Assert.IsNull(actual.EmptyMember);
- }
-
- [TestMethod, ExpectedException(typeof(ProtocolException))]
- public void DeserializeInvalidMessage() {
- var serializer = MessageSerializer.Get(typeof(Mocks.TestMessage));
- var fields = GetStandardTestFields(FieldFill.AllRequired);
- fields["age"] = "-1"; // Set an disallowed value.
- serializer.Deserialize(fields, null);
- }
- }
-}
diff --git a/src/DotNetOAuth.Test/Messaging/MessagingTestBase.cs b/src/DotNetOAuth.Test/Messaging/MessagingTestBase.cs
deleted file mode 100644
index 403cd25..0000000
--- a/src/DotNetOAuth.Test/Messaging/MessagingTestBase.cs
+++ /dev/null
@@ -1,188 +0,0 @@
-//-----------------------------------------------------------------------
-// <copyright file="MessagingTestBase.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOAuth.Test {
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Net;
- using System.Xml;
- using DotNetOAuth.Messaging;
- using DotNetOAuth.Messaging.Bindings;
- using DotNetOAuth.Test.Mocks;
- using Microsoft.VisualStudio.TestTools.UnitTesting;
-
- /// <summary>
- /// The base class that all messaging test classes inherit from.
- /// </summary>
- public class MessagingTestBase : TestBase {
- internal enum FieldFill {
- /// <summary>
- /// An empty dictionary is returned.
- /// </summary>
- None,
-
- /// <summary>
- /// Only enough fields for the <see cref="TestMessageTypeProvider"/>
- /// to identify the message are included.
- /// </summary>
- IdentifiableButNotAllRequired,
-
- /// <summary>
- /// All fields marked as required are included.
- /// </summary>
- AllRequired,
-
- /// <summary>
- /// All user-fillable fields in the message, leaving out those whose
- /// values are to be set by channel binding elements.
- /// </summary>
- CompleteBeforeBindings,
- }
-
- internal Channel Channel { get; set; }
-
- [TestInitialize]
- public override void SetUp() {
- base.SetUp();
-
- this.Channel = new TestChannel();
- }
-
- internal static HttpRequestInfo CreateHttpRequestInfo(string method, IDictionary<string, string> fields) {
- string query = MessagingUtilities.CreateQueryString(fields);
- UriBuilder requestUri = new UriBuilder("http://localhost/path");
- WebHeaderCollection headers = new WebHeaderCollection();
- MemoryStream ms = new MemoryStream();
- if (method == "POST") {
- headers.Add(HttpRequestHeader.ContentType, "application/x-www-form-urlencoded");
- StreamWriter sw = new StreamWriter(ms);
- sw.Write(query);
- sw.Flush();
- ms.Position = 0;
- } else if (method == "GET") {
- requestUri.Query = query;
- } else {
- throw new ArgumentOutOfRangeException("method", method, "Expected POST or GET");
- }
- HttpRequestInfo request = new HttpRequestInfo {
- HttpMethod = method,
- Url = requestUri.Uri,
- Headers = headers,
- InputStream = ms,
- };
-
- return request;
- }
-
- internal static Channel CreateChannel(MessageProtections capabilityAndRecognition) {
- return CreateChannel(capabilityAndRecognition, capabilityAndRecognition);
- }
-
- internal static Channel CreateChannel(MessageProtections capability, MessageProtections recognition) {
- var bindingElements = new List<IChannelBindingElement>();
- if (capability >= MessageProtections.TamperProtection) {
- bindingElements.Add(new MockSigningBindingElement());
- }
- if (capability >= MessageProtections.Expiration) {
- bindingElements.Add(new StandardExpirationBindingElement());
- }
- if (capability >= MessageProtections.ReplayProtection) {
- bindingElements.Add(new MockReplayProtectionBindingElement());
- }
-
- bool signing = false, expiration = false, replay = false;
- if (recognition >= MessageProtections.TamperProtection) {
- signing = true;
- }
- if (recognition >= MessageProtections.Expiration) {
- expiration = true;
- }
- if (recognition >= MessageProtections.ReplayProtection) {
- replay = true;
- }
-
- var typeProvider = new TestMessageTypeProvider(signing, expiration, replay);
- return new TestChannel(typeProvider, bindingElements.ToArray());
- }
-
- internal static IDictionary<string, string> GetStandardTestFields(FieldFill fill) {
- TestMessage expectedMessage = GetStandardTestMessage(fill);
-
- var fields = new Dictionary<string, string>();
- if (fill >= FieldFill.IdentifiableButNotAllRequired) {
- fields.Add("age", expectedMessage.Age.ToString());
- }
- if (fill >= FieldFill.AllRequired) {
- fields.Add("Timestamp", XmlConvert.ToString(expectedMessage.Timestamp, XmlDateTimeSerializationMode.Utc));
- }
- if (fill >= FieldFill.CompleteBeforeBindings) {
- fields.Add("Name", expectedMessage.Name);
- fields.Add("Location", expectedMessage.Location.AbsoluteUri);
- }
-
- return fields;
- }
-
- internal static TestMessage GetStandardTestMessage(FieldFill fill) {
- TestMessage message = new TestMessage();
- GetStandardTestMessage(fill, message);
- return message;
- }
-
- internal static void GetStandardTestMessage(FieldFill fill, TestMessage message) {
- if (message == null) {
- throw new ArgumentNullException("message");
- }
-
- if (fill >= FieldFill.IdentifiableButNotAllRequired) {
- message.Age = 15;
- }
- if (fill >= FieldFill.AllRequired) {
- message.Timestamp = DateTime.SpecifyKind(DateTime.Parse("9/19/2008 8 AM"), DateTimeKind.Utc);
- }
- if (fill >= FieldFill.CompleteBeforeBindings) {
- message.Name = "Andrew";
- message.Location = new Uri("http://localtest/path");
- }
- }
-
- internal void ParameterizedReceiveTest(string method) {
- var fields = GetStandardTestFields(FieldFill.CompleteBeforeBindings);
- TestMessage expectedMessage = GetStandardTestMessage(FieldFill.CompleteBeforeBindings);
-
- IProtocolMessage requestMessage = this.Channel.ReadFromRequest(CreateHttpRequestInfo(method, fields));
- Assert.IsNotNull(requestMessage);
- Assert.IsInstanceOfType(requestMessage, typeof(TestMessage));
- TestMessage actualMessage = (TestMessage)requestMessage;
- Assert.AreEqual(expectedMessage.Age, actualMessage.Age);
- Assert.AreEqual(expectedMessage.Name, actualMessage.Name);
- Assert.AreEqual(expectedMessage.Location, actualMessage.Location);
- }
-
- internal void ParameterizedReceiveProtectedTest(DateTime? utcCreatedDate, bool invalidSignature) {
- TestMessage expectedMessage = GetStandardTestMessage(FieldFill.CompleteBeforeBindings);
- var fields = GetStandardTestFields(FieldFill.CompleteBeforeBindings);
- fields.Add("Signature", invalidSignature ? "badsig" : MockSigningBindingElement.MessageSignature);
- fields.Add("Nonce", "someNonce");
- if (utcCreatedDate.HasValue) {
- utcCreatedDate = DateTime.Parse(utcCreatedDate.Value.ToUniversalTime().ToString()); // round off the milliseconds so comparisons work later
- fields.Add("created_on", XmlConvert.ToString(utcCreatedDate.Value, XmlDateTimeSerializationMode.Utc));
- }
- IProtocolMessage requestMessage = this.Channel.ReadFromRequest(CreateHttpRequestInfo("GET", fields));
- Assert.IsNotNull(requestMessage);
- Assert.IsInstanceOfType(requestMessage, typeof(TestSignedDirectedMessage));
- TestSignedDirectedMessage actualMessage = (TestSignedDirectedMessage)requestMessage;
- Assert.AreEqual(expectedMessage.Age, actualMessage.Age);
- Assert.AreEqual(expectedMessage.Name, actualMessage.Name);
- Assert.AreEqual(expectedMessage.Location, actualMessage.Location);
- if (utcCreatedDate.HasValue) {
- IExpiringProtocolMessage expiringMessage = (IExpiringProtocolMessage)requestMessage;
- Assert.AreEqual(utcCreatedDate.Value, expiringMessage.UtcCreationDate);
- }
- }
- }
-}
diff --git a/src/DotNetOAuth.Test/Messaging/MessagingUtilitiesTests.cs b/src/DotNetOAuth.Test/Messaging/MessagingUtilitiesTests.cs
deleted file mode 100644
index f5c5248..0000000
--- a/src/DotNetOAuth.Test/Messaging/MessagingUtilitiesTests.cs
+++ /dev/null
@@ -1,99 +0,0 @@
-//-----------------------------------------------------------------------
-// <copyright file="MessagingUtilitiesTests.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOAuth.Test.Messaging
-{
- using System;
- using System.Collections.Generic;
- using System.Collections.Specialized;
- using System.IO;
- using System.Net;
- using System.Web;
- using DotNetOAuth.Messaging;
- using Microsoft.VisualStudio.TestTools.UnitTesting;
-
- [TestClass]
- public class MessagingUtilitiesTests : TestBase {
- [TestMethod]
- public void CreateQueryString() {
- var args = new Dictionary<string, string>();
- args.Add("a", "b");
- args.Add("c/d", "e/f");
- Assert.AreEqual("a=b&c%2fd=e%2ff", MessagingUtilities.CreateQueryString(args));
- }
-
- [TestMethod]
- public void CreateQueryStringEmptyCollection() {
- Assert.AreEqual(0, MessagingUtilities.CreateQueryString(new Dictionary<string, string>()).Length);
- }
-
- [TestMethod, ExpectedException(typeof(ArgumentNullException))]
- public void CreateQueryStringNullDictionary() {
- MessagingUtilities.CreateQueryString(null);
- }
-
- [TestMethod]
- public void AppendQueryArgs() {
- UriBuilder uri = new UriBuilder("http://baseline.org/page");
- var args = new Dictionary<string, string>();
- args.Add("a", "b");
- args.Add("c/d", "e/f");
- MessagingUtilities.AppendQueryArgs(uri, args);
- Assert.AreEqual("http://baseline.org/page?a=b&c%2fd=e%2ff", uri.Uri.AbsoluteUri);
- args.Clear();
- args.Add("g", "h");
- MessagingUtilities.AppendQueryArgs(uri, args);
- Assert.AreEqual("http://baseline.org/page?a=b&c%2fd=e%2ff&g=h", uri.Uri.AbsoluteUri);
- }
-
- [TestMethod, ExpectedException(typeof(ArgumentNullException))]
- public void AppendQueryArgsNullUriBuilder() {
- MessagingUtilities.AppendQueryArgs(null, new Dictionary<string, string>());
- }
-
- [TestMethod]
- public void AppendQueryArgsNullDictionary() {
- MessagingUtilities.AppendQueryArgs(new UriBuilder(), null);
- }
-
- [TestMethod]
- public void ToDictionary() {
- NameValueCollection nvc = new NameValueCollection();
- nvc["a"] = "b";
- nvc["c"] = "d";
- Dictionary<string, string> actual = MessagingUtilities.ToDictionary(nvc);
- Assert.AreEqual(nvc.Count, actual.Count);
- Assert.AreEqual(nvc["a"], actual["a"]);
- Assert.AreEqual(nvc["c"], actual["c"]);
- }
-
- [TestMethod]
- public void ToDictionaryNull() {
- Assert.IsNull(MessagingUtilities.ToDictionary(null));
- }
-
- [TestMethod, ExpectedException(typeof(ArgumentNullException))]
- public void ApplyHeadersToResponseNullResponse() {
- MessagingUtilities.ApplyHeadersToResponse(new WebHeaderCollection(), null);
- }
-
- [TestMethod, ExpectedException(typeof(ArgumentNullException))]
- public void ApplyHeadersToResponseNullHeaders() {
- MessagingUtilities.ApplyHeadersToResponse(null, new HttpResponse(new StringWriter()));
- }
-
- [TestMethod]
- public void ApplyHeadersToResponse() {
- var headers = new WebHeaderCollection();
- headers[HttpResponseHeader.ContentType] = "application/binary";
-
- var response = new HttpResponse(new StringWriter());
- MessagingUtilities.ApplyHeadersToResponse(headers, response);
-
- Assert.AreEqual(headers[HttpResponseHeader.ContentType], response.ContentType);
- }
- }
-}
diff --git a/src/DotNetOAuth.Test/Messaging/ProtocolExceptionTests.cs b/src/DotNetOAuth.Test/Messaging/ProtocolExceptionTests.cs
deleted file mode 100644
index 0e01e33..0000000
--- a/src/DotNetOAuth.Test/Messaging/ProtocolExceptionTests.cs
+++ /dev/null
@@ -1,97 +0,0 @@
-//-----------------------------------------------------------------------
-// <copyright file="ProtocolExceptionTests.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOAuth.Test.Messaging {
- using System;
- using DotNetOAuth.Messaging;
- using Microsoft.VisualStudio.TestTools.UnitTesting;
-
- [TestClass]
- public class ProtocolExceptionTests : TestBase {
- [TestMethod]
- public void CtorDefault() {
- ProtocolException ex = new ProtocolException();
- }
-
- [TestMethod]
- public void CtorWithTextMessage() {
- ProtocolException ex = new ProtocolException("message");
- Assert.AreEqual("message", ex.Message);
- }
-
- [TestMethod]
- public void CtorWithTextMessageAndInnerException() {
- Exception innerException = new Exception();
- ProtocolException ex = new ProtocolException("message", innerException);
- Assert.AreEqual("message", ex.Message);
- Assert.AreSame(innerException, ex.InnerException);
- }
-
- [TestMethod]
- public void CtorWithProtocolMessage() {
- IProtocolMessage request = new Mocks.TestMessage();
- Uri receiver = new Uri("http://receiver");
- ProtocolException ex = new ProtocolException("some error occurred", request, receiver);
- IDirectedProtocolMessage msg = (IDirectedProtocolMessage)ex;
- Assert.AreEqual("some error occurred", ex.Message);
- Assert.AreSame(receiver, msg.Recipient);
- Assert.AreEqual(request.ProtocolVersion, msg.ProtocolVersion);
- Assert.AreEqual(request.Transport, msg.Transport);
- msg.EnsureValidMessage();
- }
-
- [TestMethod, ExpectedException(typeof(ArgumentNullException))]
- public void CtorWithNullProtocolMessage() {
- new ProtocolException("message", null, new Uri("http://receiver"));
- }
-
- [TestMethod, ExpectedException(typeof(ArgumentNullException))]
- public void CtorWithNullReceiver() {
- new ProtocolException("message", new Mocks.TestDirectedMessage(MessageTransport.Indirect), null);
- }
-
- /// <summary>
- /// Tests that exceptions being sent as direct responses do not need an explicit receiver.
- /// </summary>
- [TestMethod]
- public void CtorUndirectedMessageWithNullReceiver() {
- IProtocolMessage request = new Mocks.TestDirectedMessage(MessageTransport.Direct);
- ProtocolException ex = new ProtocolException("message", request, null);
- IDirectedProtocolMessage msg = (IDirectedProtocolMessage)ex;
- Assert.IsNull(msg.Recipient);
- Assert.AreEqual(request.ProtocolVersion, msg.ProtocolVersion);
- Assert.AreEqual(request.Transport, msg.Transport);
- }
-
- [TestMethod, ExpectedException(typeof(InvalidOperationException))]
- public void ProtocolVersionWithoutMessage() {
- ProtocolException ex = new ProtocolException();
- IDirectedProtocolMessage msg = (IDirectedProtocolMessage)ex;
- var temp = msg.ProtocolVersion;
- }
-
- [TestMethod, ExpectedException(typeof(InvalidOperationException))]
- public void TransportWithoutMessage() {
- ProtocolException ex = new ProtocolException();
- IDirectedProtocolMessage msg = (IDirectedProtocolMessage)ex;
- var temp = msg.Transport;
- }
-
- [TestMethod, ExpectedException(typeof(InvalidOperationException))]
- public void RecipientWithoutMessage() {
- ProtocolException ex = new ProtocolException();
- IDirectedProtocolMessage msg = (IDirectedProtocolMessage)ex;
- var temp = msg.Recipient;
- }
-
- [TestMethod, ExpectedException(typeof(InvalidOperationException))]
- public void EnsureValidMessageWithoutMessage() {
- ProtocolException ex = new ProtocolException();
- IDirectedProtocolMessage msg = (IDirectedProtocolMessage)ex;
- msg.EnsureValidMessage();
- }
- }
-}
diff --git a/src/DotNetOAuth.Test/Messaging/Reflection/MessageDescriptionTests.cs b/src/DotNetOAuth.Test/Messaging/Reflection/MessageDescriptionTests.cs
deleted file mode 100644
index 90c64dc..0000000
--- a/src/DotNetOAuth.Test/Messaging/Reflection/MessageDescriptionTests.cs
+++ /dev/null
@@ -1,24 +0,0 @@
-//-----------------------------------------------------------------------
-// <copyright file="MessageDescriptionTests.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOAuth.Test.Messaging.Reflection {
- using System;
- using DotNetOAuth.Messaging.Reflection;
- using Microsoft.VisualStudio.TestTools.UnitTesting;
-
- [TestClass]
- public class MessageDescriptionTests : MessagingTestBase {
- [TestMethod, ExpectedException(typeof(ArgumentNullException))]
- public void GetNull() {
- MessageDescription.Get(null);
- }
-
- [TestMethod, ExpectedException(typeof(ArgumentException))]
- public void GetNonMessageType() {
- MessageDescription.Get(typeof(string));
- }
- }
-}
diff --git a/src/DotNetOAuth.Test/Messaging/Reflection/MessageDictionaryTests.cs b/src/DotNetOAuth.Test/Messaging/Reflection/MessageDictionaryTests.cs
deleted file mode 100644
index 143e6b8..0000000
--- a/src/DotNetOAuth.Test/Messaging/Reflection/MessageDictionaryTests.cs
+++ /dev/null
@@ -1,347 +0,0 @@
-//-----------------------------------------------------------------------
-// <copyright file="MessageDictionaryTests.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOAuth.Test.Messaging.Reflection {
- using System;
- using System.Collections;
- using System.Collections.Generic;
- using System.Collections.ObjectModel;
- using System.Xml;
- using DotNetOAuth.Messaging;
- using DotNetOAuth.Messaging.Reflection;
- using Microsoft.VisualStudio.TestTools.UnitTesting;
-
- [TestClass]
- public class MessageDictionaryTests : MessagingTestBase {
- private Mocks.TestMessage message;
-
- [TestInitialize]
- public override void SetUp() {
- base.SetUp();
-
- this.message = new Mocks.TestMessage();
- }
-
- [TestMethod, ExpectedException(typeof(ArgumentNullException))]
- public void CtorNull() {
- new MessageDictionary(null);
- }
-
- /// <summary>
- /// A test for System.Collections.Generic.IDictionary&lt;System.String,System.String>.Values
- /// </summary>
- [TestMethod]
- public void Values() {
- IDictionary<string, string> target = new MessageDictionary(this.message);
- Collection<string> expected = new Collection<string> {
- this.message.Age.ToString(),
- XmlConvert.ToString(DateTime.SpecifyKind(this.message.Timestamp, DateTimeKind.Utc), XmlDateTimeSerializationMode.Utc),
- };
- CollectionAssert<string>.AreEquivalent(expected, target.Values);
-
- this.message.Age = 15;
- this.message.Location = new Uri("http://localtest");
- this.message.Name = "Andrew";
- target["extra"] = "a";
- expected = new Collection<string> {
- this.message.Age.ToString(),
- this.message.Location.AbsoluteUri,
- this.message.Name,
- XmlConvert.ToString(DateTime.SpecifyKind(this.message.Timestamp, DateTimeKind.Utc), XmlDateTimeSerializationMode.Utc),
- "a",
- };
- CollectionAssert<string>.AreEquivalent(expected, target.Values);
- }
-
- /// <summary>
- /// A test for System.Collections.Generic.IDictionary&lt;System.String,System.String>.Keys
- /// </summary>
- [TestMethod]
- public void Keys() {
- // We expect that non-nullable value type fields will automatically have keys
- // in the dictionary for them.
- IDictionary<string, string> target = new MessageDictionary(this.message);
- Collection<string> expected = new Collection<string> {
- "age",
- "Timestamp",
- };
- CollectionAssert<string>.AreEquivalent(expected, target.Keys);
-
- this.message.Name = "Andrew";
- expected.Add("Name");
- target["extraField"] = string.Empty;
- expected.Add("extraField");
- CollectionAssert<string>.AreEquivalent(expected, target.Keys);
- }
-
- /// <summary>
- /// A test for System.Collections.Generic.IDictionary&lt;System.String,System.String>.Item
- /// </summary>
- [TestMethod]
- public void Item() {
- IDictionary<string, string> target = new MessageDictionary(this.message);
-
- // Test setting of declared message properties.
- this.message.Age = 15;
- Assert.AreEqual("15", target["age"]);
- target["age"] = "13";
- Assert.AreEqual(13, this.message.Age);
-
- // Test setting extra fields
- target["extra"] = "fun";
- Assert.AreEqual("fun", target["extra"]);
- Assert.AreEqual("fun", ((IProtocolMessage)this.message).ExtraData["extra"]);
-
- // Test clearing extra fields
- target["extra"] = null;
- Assert.IsFalse(target.ContainsKey("extra"));
- }
-
- /// <summary>
- /// A test for System.Collections.Generic.ICollection&lt;System.Collections.Generic.KeyValuePair&lt;System.String,System.String&lt;&lt;.IsReadOnly
- /// </summary>
- [TestMethod]
- public void IsReadOnly() {
- ICollection<KeyValuePair<string, string>> target = new MessageDictionary(this.message);
- Assert.IsFalse(target.IsReadOnly);
- }
-
- /// <summary>
- /// A test for System.Collections.Generic.ICollection&lt;System.Collections.Generic.KeyValuePair&lt;System.String,System.String&lt;&lt;.Count
- /// </summary>
- [TestMethod]
- public void Count() {
- ICollection<KeyValuePair<string, string>> target = new MessageDictionary(this.message);
- IDictionary<string, string> targetDictionary = (IDictionary<string, string>)target;
- Assert.AreEqual(targetDictionary.Keys.Count, target.Count);
- targetDictionary["extraField"] = "hi";
- Assert.AreEqual(targetDictionary.Keys.Count, target.Count);
- }
-
- /// <summary>
- /// A test for System.Collections.Generic.IEnumerable&lt;System.Collections.Generic.KeyValuePair&lt;System.String,System.String&lt;&lt;.GetEnumerator
- /// </summary>
- [TestMethod]
- public void GetEnumerator() {
- IEnumerable<KeyValuePair<string, string>> target = new MessageDictionary(this.message);
- IDictionary<string, string> targetDictionary = (IDictionary<string, string>)target;
- var keys = targetDictionary.Keys.GetEnumerator();
- var values = targetDictionary.Values.GetEnumerator();
- IEnumerator<KeyValuePair<string, string>> actual = target.GetEnumerator();
-
- bool keysLast = true, valuesLast = true, actualLast = true;
- while (true) {
- keysLast = keys.MoveNext();
- valuesLast = values.MoveNext();
- actualLast = actual.MoveNext();
- if (!keysLast || !valuesLast || !actualLast) {
- break;
- }
-
- Assert.AreEqual(keys.Current, actual.Current.Key);
- Assert.AreEqual(values.Current, actual.Current.Value);
- }
- Assert.IsTrue(keysLast == valuesLast && keysLast == actualLast);
- }
-
- [TestMethod]
- public void GetEnumeratorUntyped() {
- IEnumerable target = new MessageDictionary(this.message);
- IDictionary<string, string> targetDictionary = (IDictionary<string, string>)target;
- var keys = targetDictionary.Keys.GetEnumerator();
- var values = targetDictionary.Values.GetEnumerator();
- IEnumerator actual = target.GetEnumerator();
-
- bool keysLast = true, valuesLast = true, actualLast = true;
- while (true) {
- keysLast = keys.MoveNext();
- valuesLast = values.MoveNext();
- actualLast = actual.MoveNext();
- if (!keysLast || !valuesLast || !actualLast) {
- break;
- }
-
- KeyValuePair<string, string> current = (KeyValuePair<string, string>)actual.Current;
- Assert.AreEqual(keys.Current, current.Key);
- Assert.AreEqual(values.Current, current.Value);
- }
- Assert.IsTrue(keysLast == valuesLast && keysLast == actualLast);
- }
-
- /// <summary>
- /// A test for System.Collections.Generic.IDictionary&lt;System.String,System.String>.TryGetValue
- /// </summary>
- [TestMethod]
- public void TryGetValue() {
- IDictionary<string, string> target = new MessageDictionary(this.message);
- this.message.Name = "andrew";
- string name;
- Assert.IsTrue(target.TryGetValue("Name", out name));
- Assert.AreEqual(this.message.Name, name);
-
- Assert.IsFalse(target.TryGetValue("name", out name));
- Assert.IsNull(name);
-
- target["extra"] = "value";
- string extra;
- Assert.IsTrue(target.TryGetValue("extra", out extra));
- Assert.AreEqual("value", extra);
- }
-
- /// <summary>
- /// A test for System.Collections.Generic.IDictionary&lt;System.String,System.String>.Remove
- /// </summary>
- [TestMethod]
- public void RemoveTest1() {
- IDictionary<string, string> target = new MessageDictionary(this.message);
- this.message.Name = "andrew";
- Assert.IsTrue(target.Remove("Name"));
- Assert.IsNull(this.message.Name);
- Assert.IsFalse(target.Remove("Name"));
-
- Assert.IsFalse(target.Remove("extra"));
- target["extra"] = "value";
- Assert.IsTrue(target.Remove("extra"));
- Assert.IsFalse(target.ContainsKey("extra"));
- }
-
- /// <summary>
- /// A test for System.Collections.Generic.IDictionary&lt;System.String,System.String>.ContainsKey
- /// </summary>
- [TestMethod]
- public void ContainsKey() {
- IDictionary<string, string> target = new MessageDictionary(this.message);
- Assert.IsTrue(target.ContainsKey("age"), "Value type declared element should have a key.");
- Assert.IsFalse(target.ContainsKey("Name"), "Null declared element should NOT have a key.");
-
- Assert.IsFalse(target.ContainsKey("extra"));
- target["extra"] = "value";
- Assert.IsTrue(target.ContainsKey("extra"));
- }
-
- /// <summary>
- /// A test for System.Collections.Generic.IDictionary&lt;System.String,System.String&gt;.Add
- /// </summary>
- [TestMethod]
- public void AddByKeyAndValue() {
- IDictionary<string, string> target = new MessageDictionary(this.message);
- target.Add("extra", "value");
- Assert.IsTrue(target.Contains(new KeyValuePair<string, string>("extra", "value")));
- target.Add("Name", "Andrew");
- Assert.AreEqual("Andrew", this.message.Name);
- }
-
- [TestMethod, ExpectedException(typeof(ArgumentNullException))]
- public void AddNullValue() {
- IDictionary<string, string> target = new MessageDictionary(this.message);
- target.Add("extra", null);
- }
-
- /// <summary>
- /// A test for System.Collections.Generic.ICollection&lt;System.Collections.Generic.KeyValuePair&lt;System.String,System.String&lt;&lt;.Add
- /// </summary>
- [TestMethod]
- public void AddByKeyValuePair() {
- IDictionary<string, string> target = new MessageDictionary(this.message);
- target.Add(new KeyValuePair<string, string>("extra", "value"));
- Assert.IsTrue(target.Contains(new KeyValuePair<string, string>("extra", "value")));
- }
-
- [TestMethod, ExpectedException(typeof(ArgumentException))]
- public void AddExtraFieldThatAlreadyExists() {
- IDictionary<string, string> target = new MessageDictionary(this.message);
- target.Add("extra", "value");
- target.Add("extra", "value");
- }
-
- [TestMethod, ExpectedException(typeof(ArgumentException))]
- public void AddDeclaredValueThatAlreadyExists() {
- IDictionary<string, string> target = new MessageDictionary(this.message);
- target.Add("Name", "andrew");
- target.Add("Name", "andrew");
- }
-
- [TestMethod]
- public void DefaultReferenceTypeDeclaredPropertyHasNoKey() {
- IDictionary<string, string> target = new MessageDictionary(this.message);
- Assert.IsFalse(target.ContainsKey("Name"), "A null value should result in no key.");
- Assert.IsFalse(target.Keys.Contains("Name"), "A null value should result in no key.");
- }
-
- [TestMethod]
- public void RemoveStructDeclaredProperty() {
- IDictionary<string, string> target = new MessageDictionary(this.message);
- this.message.Age = 5;
- Assert.IsTrue(target.ContainsKey("age"));
- target.Remove("age");
- Assert.IsTrue(target.ContainsKey("age"));
- Assert.AreEqual(0, this.message.Age);
- }
-
- /// <summary>
- /// A test for System.Collections.Generic.ICollection&lt;System.Collections.Generic.KeyValuePair&lt;System.String,System.String&lt;&lt;.Remove
- /// </summary>
- [TestMethod]
- public void RemoveByKeyValuePair() {
- ICollection<KeyValuePair<string, string>> target = new MessageDictionary(this.message);
- this.message.Name = "Andrew";
- Assert.IsFalse(target.Remove(new KeyValuePair<string, string>("Name", "andrew")));
- Assert.AreEqual("Andrew", this.message.Name);
- Assert.IsTrue(target.Remove(new KeyValuePair<string, string>("Name", "Andrew")));
- Assert.IsNull(this.message.Name);
- }
-
- /// <summary>
- /// A test for System.Collections.Generic.ICollection&lt;System.Collections.Generic.KeyValuePair&lt;System.String,System.String&lt;&lt;.CopyTo
- /// </summary>
- [TestMethod]
- public void CopyTo() {
- ICollection<KeyValuePair<string, string>> target = new MessageDictionary(this.message);
- IDictionary<string, string> targetAsDictionary = ((IDictionary<string, string>)target);
- KeyValuePair<string, string>[] array = new KeyValuePair<string, string>[target.Count + 1];
- int arrayIndex = 1;
- target.CopyTo(array, arrayIndex);
- Assert.AreEqual(new KeyValuePair<string, string>(), array[0]);
- for (int i = 1; i < array.Length; i++) {
- Assert.IsNotNull(array[i].Key);
- Assert.AreEqual(targetAsDictionary[array[i].Key], array[i].Value);
- }
- }
-
- /// <summary>
- /// A test for System.Collections.Generic.ICollection&lt;System.Collections.Generic.KeyValuePair&lt;System.String,System.String&lt;&lt;.Contains
- /// </summary>
- [TestMethod]
- public void ContainsKeyValuePair() {
- ICollection<KeyValuePair<string, string>> target = new MessageDictionary(this.message);
- IDictionary<string, string> targetAsDictionary = ((IDictionary<string, string>)target);
- Assert.IsFalse(target.Contains(new KeyValuePair<string, string>("age", "1")));
- Assert.IsTrue(target.Contains(new KeyValuePair<string, string>("age", "0")));
-
- targetAsDictionary["extra"] = "value";
- Assert.IsFalse(target.Contains(new KeyValuePair<string, string>("extra", "Value")));
- Assert.IsTrue(target.Contains(new KeyValuePair<string, string>("extra", "value")));
- Assert.IsFalse(target.Contains(new KeyValuePair<string, string>("wayoff", "value")));
- }
-
- /// <summary>
- /// A test for System.Collections.Generic.ICollection&lt;System.Collections.Generic.KeyValuePair&lt;System.String,System.String&lt;&lt;.Clear
- /// </summary>
- [TestMethod]
- public void Clear() {
- ICollection<KeyValuePair<string, string>> target = new MessageDictionary(this.message);
- IDictionary<string, string> targetAsDictionary = ((IDictionary<string, string>)target);
- this.message.Name = "Andrew";
- this.message.Age = 15;
- targetAsDictionary["extra"] = "value";
- target.Clear();
- Assert.AreEqual(2, target.Count, "Clearing should remove all keys except for declared non-nullable structs.");
- Assert.IsFalse(targetAsDictionary.ContainsKey("extra"));
- Assert.IsNull(this.message.Name);
- Assert.AreEqual(0, this.message.Age);
- }
- }
-}
diff --git a/src/DotNetOAuth.Test/Messaging/Reflection/MessagePartTests.cs b/src/DotNetOAuth.Test/Messaging/Reflection/MessagePartTests.cs
deleted file mode 100644
index 90ccca4..0000000
--- a/src/DotNetOAuth.Test/Messaging/Reflection/MessagePartTests.cs
+++ /dev/null
@@ -1,101 +0,0 @@
-//-----------------------------------------------------------------------
-// <copyright file="MessagePartTests.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOAuth.Test.Messaging.Reflection {
- using System;
- using System.Linq;
- using System.Reflection;
- using DotNetOAuth.Messaging;
- using DotNetOAuth.Messaging.Reflection;
- using DotNetOAuth.Test.Mocks;
- using Microsoft.VisualStudio.TestTools.UnitTesting;
-
- [TestClass]
- public class MessagePartTests : MessagingTestBase {
- [TestMethod, ExpectedException(typeof(ArgumentException))]
- public void OptionalNonNullableStruct() {
- this.ParameterizedMessageTypeTest(typeof(MessageWithNonNullableOptionalStruct));
- }
-
- [TestMethod]
- public void RequiredNonNullableStruct() {
- this.ParameterizedMessageTypeTest(typeof(MessageWithNonNullableRequiredStruct));
- }
-
- [TestMethod]
- public void OptionalNullableStruct() {
- this.ParameterizedMessageTypeTest(typeof(MessageWithNullableOptionalStruct));
- }
-
- [TestMethod]
- public void RequiredNullableStruct() {
- this.ParameterizedMessageTypeTest(typeof(MessageWithNullableRequiredStruct));
- }
-
- [TestMethod, ExpectedException(typeof(ArgumentNullException))]
- public void CtorNullMember() {
- new MessagePart(null, new MessagePartAttribute());
- }
-
- [TestMethod, ExpectedException(typeof(ArgumentNullException))]
- public void CtorNullAttribute() {
- PropertyInfo field = typeof(MessageWithNullableOptionalStruct).GetProperty("OptionalInt", BindingFlags.NonPublic | BindingFlags.Instance);
- new MessagePart(field, null);
- }
-
- [TestMethod]
- public void SetValue() {
- var message = new MessageWithNonNullableRequiredStruct();
- MessagePart part = this.ParameterizedMessageTypeTest(message.GetType());
- part.SetValue(message, "5");
- Assert.AreEqual(5, message.OptionalInt);
- }
-
- [TestMethod]
- public void GetValue() {
- var message = new MessageWithNonNullableRequiredStruct();
- message.OptionalInt = 8;
- MessagePart part = this.ParameterizedMessageTypeTest(message.GetType());
- Assert.AreEqual("8", part.GetValue(message));
- }
-
- [TestMethod, ExpectedException(typeof(ArgumentException))]
- public void NonFieldOrPropertyMember() {
- MemberInfo method = typeof(MessageWithNullableOptionalStruct).GetMethod("Equals", BindingFlags.Public | BindingFlags.Instance);
- new MessagePart(method, new MessagePartAttribute());
- }
-
- private MessagePart ParameterizedMessageTypeTest(Type messageType) {
- PropertyInfo field = messageType.GetProperty("OptionalInt", BindingFlags.NonPublic | BindingFlags.Instance);
- MessagePartAttribute attribute = field.GetCustomAttributes(typeof(MessagePartAttribute), true).OfType<MessagePartAttribute>().Single();
- return new MessagePart(field, attribute);
- }
-
- private class MessageWithNonNullableOptionalStruct : TestMessage {
- // Optional structs like int must be nullable for Optional to make sense.
- [MessagePart(IsRequired = false)]
- internal int OptionalInt { get; set; }
- }
-
- private class MessageWithNonNullableRequiredStruct : TestMessage {
- // This should work because a required field will always have a value so it
- // need not be nullable.
- [MessagePart(IsRequired = true)]
- internal int OptionalInt { get; set; }
- }
-
- private class MessageWithNullableOptionalStruct : TestMessage {
- // Optional structs like int must be nullable for Optional to make sense.
- [MessagePart(IsRequired = false)]
- internal int? OptionalInt { get; set; }
- }
-
- private class MessageWithNullableRequiredStruct : TestMessage {
- [MessagePart(IsRequired = true)]
- private int? OptionalInt { get; set; }
- }
- }
-}
diff --git a/src/DotNetOAuth.Test/Messaging/Reflection/ValueMappingTests.cs b/src/DotNetOAuth.Test/Messaging/Reflection/ValueMappingTests.cs
deleted file mode 100644
index 5def394..0000000
--- a/src/DotNetOAuth.Test/Messaging/Reflection/ValueMappingTests.cs
+++ /dev/null
@@ -1,24 +0,0 @@
-//-----------------------------------------------------------------------
-// <copyright file="ValueMappingTests.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOAuth.Test.Messaging.Reflection {
- using System;
- using DotNetOAuth.Messaging.Reflection;
- using Microsoft.VisualStudio.TestTools.UnitTesting;
-
- [TestClass]
- public class ValueMappingTests {
- [TestMethod, ExpectedException(typeof(ArgumentNullException))]
- public void CtorNullToString() {
- new ValueMapping(null, str => new object());
- }
-
- [TestMethod, ExpectedException(typeof(ArgumentNullException))]
- public void CtorNullToObject() {
- new ValueMapping(obj => obj.ToString(), null);
- }
- }
-}
diff --git a/src/DotNetOAuth.Test/Messaging/ResponseTests.cs b/src/DotNetOAuth.Test/Messaging/ResponseTests.cs
deleted file mode 100644
index 5020d7e..0000000
--- a/src/DotNetOAuth.Test/Messaging/ResponseTests.cs
+++ /dev/null
@@ -1,39 +0,0 @@
-//-----------------------------------------------------------------------
-// <copyright file="ResponseTests.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOAuth.Test.Messaging {
- using System;
- using System.IO;
- using System.Web;
- using DotNetOAuth.Messaging;
- using Microsoft.VisualStudio.TestTools.UnitTesting;
-
- [TestClass]
- public class ResponseTests : TestBase {
- [TestMethod, ExpectedException(typeof(InvalidOperationException))]
- public void SendWithoutAspNetContext() {
- new Response().Send();
- }
-
- [TestMethod]
- public void Send() {
- StringWriter writer = new StringWriter();
- HttpRequest httpRequest = new HttpRequest("file", "http://server", string.Empty);
- HttpResponse httpResponse = new HttpResponse(writer);
- HttpContext context = new HttpContext(httpRequest, httpResponse);
- HttpContext.Current = context;
-
- Response response = new Response();
- response.Status = System.Net.HttpStatusCode.OK;
- response.Headers["someHeaderName"] = "someHeaderValue";
- response.Body = "some body";
- response.Send();
- string results = writer.ToString();
- // For some reason the only output in test is the body... the headers require a web host
- Assert.AreEqual(response.Body, results);
- }
- }
-}