diff options
author | Andrew Arnott <andrewarnott@gmail.com> | 2009-01-09 21:03:29 -0800 |
---|---|---|
committer | Andrew <andrewarnott@gmail.com> | 2009-01-09 21:03:29 -0800 |
commit | d8abcbe507383d3510ee45ed19f6503c60d7d63b (patch) | |
tree | 64d656b165aed099ef68881c98082d552f5af2e4 /src/DotNetOpenAuth.Test | |
parent | 588d1384431e23827921124bd438569231cbdfa7 (diff) | |
download | DotNetOpenAuth-d8abcbe507383d3510ee45ed19f6503c60d7d63b.zip DotNetOpenAuth-d8abcbe507383d3510ee45ed19f6503c60d7d63b.tar.gz DotNetOpenAuth-d8abcbe507383d3510ee45ed19f6503c60d7d63b.tar.bz2 |
CRLF -> LF line endings change to all .cs files.
Diffstat (limited to 'src/DotNetOpenAuth.Test')
13 files changed, 1288 insertions, 1288 deletions
diff --git a/src/DotNetOpenAuth.Test/Messaging/ChannelTests.cs b/src/DotNetOpenAuth.Test/Messaging/ChannelTests.cs index 6bf7130..29154ed 100644 --- a/src/DotNetOpenAuth.Test/Messaging/ChannelTests.cs +++ b/src/DotNetOpenAuth.Test/Messaging/ChannelTests.cs @@ -1,292 +1,292 @@ -//-----------------------------------------------------------------------
-// <copyright file="ChannelTests.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOpenAuth.Test.Messaging {
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Net;
- using System.Web;
- using DotNetOpenAuth.Messaging;
- using DotNetOpenAuth.Messaging.Bindings;
- using DotNetOpenAuth.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 TestDirectedMessage(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);
-
- UserAgentResponse 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"),
- };
- UserAgentResponse 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 TestDirectedMessage {
- 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 TestMessageFactory(),
- new StandardExpirationBindingElement());
- }
-
- [TestMethod, ExpectedException(typeof(ProtocolException))]
- public void TooManyBindingElementsProvidingSameProtection() {
- Channel channel = new TestChannel(
- new TestMessageFactory(),
- new MockSigningBindingElement(),
- new MockSigningBindingElement());
- Channel_Accessor accessor = Channel_Accessor.AttachShadow(channel);
- accessor.PrepareMessageForSending(new TestSignedDirectedMessage());
- }
-
- [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 TestMessageFactory(),
- 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));
- }
- }
-}
+//----------------------------------------------------------------------- +// <copyright file="ChannelTests.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.Test.Messaging { + using System; + using System.Collections.Generic; + using System.IO; + using System.Net; + using System.Web; + using DotNetOpenAuth.Messaging; + using DotNetOpenAuth.Messaging.Bindings; + using DotNetOpenAuth.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 TestDirectedMessage(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); + + UserAgentResponse 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"), + }; + UserAgentResponse 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 TestDirectedMessage { + 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 TestMessageFactory(), + new StandardExpirationBindingElement()); + } + + [TestMethod, ExpectedException(typeof(ProtocolException))] + public void TooManyBindingElementsProvidingSameProtection() { + Channel channel = new TestChannel( + new TestMessageFactory(), + new MockSigningBindingElement(), + new MockSigningBindingElement()); + Channel_Accessor accessor = Channel_Accessor.AttachShadow(channel); + accessor.PrepareMessageForSending(new TestSignedDirectedMessage()); + } + + [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 TestMessageFactory(), + 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/DotNetOpenAuth.Test/Messaging/CollectionAssert.cs b/src/DotNetOpenAuth.Test/Messaging/CollectionAssert.cs index 1cdefdb..c3273e8 100644 --- a/src/DotNetOpenAuth.Test/Messaging/CollectionAssert.cs +++ b/src/DotNetOpenAuth.Test/Messaging/CollectionAssert.cs @@ -1,26 +1,26 @@ -//-----------------------------------------------------------------------
-// <copyright file="CollectionAssert.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOpenAuth.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);
- }
-
- internal static void AreEquivalentByEquality(ICollection<T> expected, ICollection<T> actual) {
- Assert.AreEqual(expected.Count, actual.Count);
- foreach (T value in expected) {
- Assert.IsTrue(actual.Contains(value));
- }
- }
- }
-}
+//----------------------------------------------------------------------- +// <copyright file="CollectionAssert.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.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); + } + + internal static void AreEquivalentByEquality(ICollection<T> expected, ICollection<T> actual) { + Assert.AreEqual(expected.Count, actual.Count); + foreach (T value in expected) { + Assert.IsTrue(actual.Contains(value)); + } + } + } +} diff --git a/src/DotNetOpenAuth.Test/Messaging/ProtocolExceptionTests.cs b/src/DotNetOpenAuth.Test/Messaging/ProtocolExceptionTests.cs index f245702..21f2928 100644 --- a/src/DotNetOpenAuth.Test/Messaging/ProtocolExceptionTests.cs +++ b/src/DotNetOpenAuth.Test/Messaging/ProtocolExceptionTests.cs @@ -1,97 +1,97 @@ -//-----------------------------------------------------------------------
-// <copyright file="ProtocolExceptionTests.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOpenAuth.Test.Messaging {
- using System;
- using DotNetOpenAuth.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.TestDirectedMessage();
- 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.Version, msg.Version);
- 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.Version, msg.Version);
- Assert.AreEqual(request.Transport, msg.Transport);
- }
-
- [TestMethod, ExpectedException(typeof(InvalidOperationException))]
- public void ProtocolVersionWithoutMessage() {
- ProtocolException ex = new ProtocolException();
- IDirectedProtocolMessage msg = (IDirectedProtocolMessage)ex;
- var temp = msg.Version;
- }
-
- [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();
- }
- }
-}
+//----------------------------------------------------------------------- +// <copyright file="ProtocolExceptionTests.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.Test.Messaging { + using System; + using DotNetOpenAuth.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.TestDirectedMessage(); + 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.Version, msg.Version); + 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.Version, msg.Version); + Assert.AreEqual(request.Transport, msg.Transport); + } + + [TestMethod, ExpectedException(typeof(InvalidOperationException))] + public void ProtocolVersionWithoutMessage() { + ProtocolException ex = new ProtocolException(); + IDirectedProtocolMessage msg = (IDirectedProtocolMessage)ex; + var temp = msg.Version; + } + + [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/DotNetOpenAuth.Test/Mocks/MockOpenIdExtension.cs b/src/DotNetOpenAuth.Test/Mocks/MockOpenIdExtension.cs index 2f9830a..d04e504 100644 --- a/src/DotNetOpenAuth.Test/Mocks/MockOpenIdExtension.cs +++ b/src/DotNetOpenAuth.Test/Mocks/MockOpenIdExtension.cs @@ -1,101 +1,101 @@ -//-----------------------------------------------------------------------
-// <copyright file="MockOpenIdExtension.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOpenAuth.Test.Mocks {
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using DotNetOpenAuth.Messaging;
- using DotNetOpenAuth.OpenId.Extensions;
- using DotNetOpenAuth.OpenId.Messages;
-
- internal class MockOpenIdExtension : IOpenIdMessageExtension {
- internal const string MockTypeUri = "http://mockextension";
-
- internal static readonly OpenIdExtensionFactory.CreateDelegate Factory = (typeUri, data, baseMessage) => {
- if (typeUri == MockTypeUri) {
- return new MockOpenIdExtension();
- }
-
- return null;
- };
-
- private IDictionary<string, string> extraData = new Dictionary<string, string>();
-
- internal MockOpenIdExtension() {
- }
-
- /// <summary>
- /// Initializes a new instance of the <see cref="MockOpenIdExtension"/> class.
- /// </summary>
- /// <param name="partValue">The value of the 'Part' parameter.</param>
- /// <param name="extraValue">The value of the 'data' parameter.</param>
- internal MockOpenIdExtension(string partValue, string extraValue) {
- this.Part = partValue;
- this.Data = extraValue;
- }
-
- #region IOpenIdMessageExtension Members
-
- public string TypeUri {
- get { return MockTypeUri; }
- }
-
- public IEnumerable<string> AdditionalSupportedTypeUris {
- get { return Enumerable.Empty<string>(); }
- }
-
- #endregion
-
- #region IMessage Properties
-
- public Version Version {
- get { return new Version(1, 0); }
- }
-
- public IDictionary<string, string> ExtraData {
- get { return this.extraData; }
- }
-
- #endregion
-
- [MessagePart]
- internal string Part { get; set; }
-
- internal string Data {
- get {
- string data;
- this.extraData.TryGetValue("data", out data);
- return data;
- }
-
- set {
- this.extraData["data"] = value;
- }
- }
-
- public override bool Equals(object obj) {
- MockOpenIdExtension other = obj as MockOpenIdExtension;
- if (other == null) {
- return false;
- }
-
- return this.Part.EqualsNullSafe(other.Part) &&
- this.Data.EqualsNullSafe(other.Data);
- }
-
- public override int GetHashCode() {
- return 1; // mock doesn't need a good hash code algorithm
- }
-
- #region IMessage methods
-
- public void EnsureValidMessage() {
- }
-
- #endregion
- }
-}
+//----------------------------------------------------------------------- +// <copyright file="MockOpenIdExtension.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.Test.Mocks { + using System; + using System.Collections.Generic; + using System.Linq; + using DotNetOpenAuth.Messaging; + using DotNetOpenAuth.OpenId.Extensions; + using DotNetOpenAuth.OpenId.Messages; + + internal class MockOpenIdExtension : IOpenIdMessageExtension { + internal const string MockTypeUri = "http://mockextension"; + + internal static readonly OpenIdExtensionFactory.CreateDelegate Factory = (typeUri, data, baseMessage) => { + if (typeUri == MockTypeUri) { + return new MockOpenIdExtension(); + } + + return null; + }; + + private IDictionary<string, string> extraData = new Dictionary<string, string>(); + + internal MockOpenIdExtension() { + } + + /// <summary> + /// Initializes a new instance of the <see cref="MockOpenIdExtension"/> class. + /// </summary> + /// <param name="partValue">The value of the 'Part' parameter.</param> + /// <param name="extraValue">The value of the 'data' parameter.</param> + internal MockOpenIdExtension(string partValue, string extraValue) { + this.Part = partValue; + this.Data = extraValue; + } + + #region IOpenIdMessageExtension Members + + public string TypeUri { + get { return MockTypeUri; } + } + + public IEnumerable<string> AdditionalSupportedTypeUris { + get { return Enumerable.Empty<string>(); } + } + + #endregion + + #region IMessage Properties + + public Version Version { + get { return new Version(1, 0); } + } + + public IDictionary<string, string> ExtraData { + get { return this.extraData; } + } + + #endregion + + [MessagePart] + internal string Part { get; set; } + + internal string Data { + get { + string data; + this.extraData.TryGetValue("data", out data); + return data; + } + + set { + this.extraData["data"] = value; + } + } + + public override bool Equals(object obj) { + MockOpenIdExtension other = obj as MockOpenIdExtension; + if (other == null) { + return false; + } + + return this.Part.EqualsNullSafe(other.Part) && + this.Data.EqualsNullSafe(other.Data); + } + + public override int GetHashCode() { + return 1; // mock doesn't need a good hash code algorithm + } + + #region IMessage methods + + public void EnsureValidMessage() { + } + + #endregion + } +} diff --git a/src/DotNetOpenAuth.Test/Mocks/TestBaseMessage.cs b/src/DotNetOpenAuth.Test/Mocks/TestBaseMessage.cs index a706d3e..96eeb8d 100644 --- a/src/DotNetOpenAuth.Test/Mocks/TestBaseMessage.cs +++ b/src/DotNetOpenAuth.Test/Mocks/TestBaseMessage.cs @@ -1,56 +1,56 @@ -//-----------------------------------------------------------------------
-// <copyright file="TestBaseMessage.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOpenAuth.Test.Mocks {
- using System;
- using System.Collections.Generic;
- using System.Runtime.Serialization;
- using DotNetOpenAuth.Messaging;
- using DotNetOpenAuth.Messaging.Reflection;
-
- internal interface IBaseMessageExplicitMembers {
- string ExplicitProperty { get; set; }
- }
-
- internal class TestBaseMessage : IProtocolMessage, IBaseMessageExplicitMembers {
- private Dictionary<string, string> extraData = new Dictionary<string, string>();
-
- [MessagePart("age", IsRequired = true)]
- public int Age { get; set; }
-
- [MessagePart]
- public string Name { get; set; }
-
- [MessagePart("explicit")]
- string IBaseMessageExplicitMembers.ExplicitProperty { get; set; }
-
- Version IMessage.Version {
- get { return new Version(1, 0); }
- }
-
- MessageProtections IProtocolMessage.RequiredProtection {
- get { return MessageProtections.None; }
- }
-
- MessageTransport IProtocolMessage.Transport {
- get { return MessageTransport.Indirect; }
- }
-
- IDictionary<string, string> IMessage.ExtraData {
- get { return this.extraData; }
- }
-
- internal string PrivatePropertyAccessor {
- get { return this.PrivateProperty; }
- set { this.PrivateProperty = value; }
- }
-
- [MessagePart("private")]
- private string PrivateProperty { get; set; }
-
- void IMessage.EnsureValidMessage() { }
- }
-}
+//----------------------------------------------------------------------- +// <copyright file="TestBaseMessage.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.Test.Mocks { + using System; + using System.Collections.Generic; + using System.Runtime.Serialization; + using DotNetOpenAuth.Messaging; + using DotNetOpenAuth.Messaging.Reflection; + + internal interface IBaseMessageExplicitMembers { + string ExplicitProperty { get; set; } + } + + internal class TestBaseMessage : IProtocolMessage, IBaseMessageExplicitMembers { + private Dictionary<string, string> extraData = new Dictionary<string, string>(); + + [MessagePart("age", IsRequired = true)] + public int Age { get; set; } + + [MessagePart] + public string Name { get; set; } + + [MessagePart("explicit")] + string IBaseMessageExplicitMembers.ExplicitProperty { get; set; } + + Version IMessage.Version { + get { return new Version(1, 0); } + } + + MessageProtections IProtocolMessage.RequiredProtection { + get { return MessageProtections.None; } + } + + MessageTransport IProtocolMessage.Transport { + get { return MessageTransport.Indirect; } + } + + IDictionary<string, string> IMessage.ExtraData { + get { return this.extraData; } + } + + internal string PrivatePropertyAccessor { + get { return this.PrivateProperty; } + set { this.PrivateProperty = value; } + } + + [MessagePart("private")] + private string PrivateProperty { get; set; } + + void IMessage.EnsureValidMessage() { } + } +} diff --git a/src/DotNetOpenAuth.Test/Mocks/TestMessage.cs b/src/DotNetOpenAuth.Test/Mocks/TestMessage.cs index 68df8bb..7da6ff3 100644 --- a/src/DotNetOpenAuth.Test/Mocks/TestMessage.cs +++ b/src/DotNetOpenAuth.Test/Mocks/TestMessage.cs @@ -1,73 +1,73 @@ -//-----------------------------------------------------------------------
-// <copyright file="TestMessage.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOpenAuth.Test.Mocks {
- using System;
- using System.Collections.Generic;
- using System.Runtime.Serialization;
- using DotNetOpenAuth.Messaging;
- using DotNetOpenAuth.Messaging.Reflection;
-
- internal abstract class TestMessage : IDirectResponseProtocolMessage {
- private MessageTransport transport;
- private Dictionary<string, string> extraData = new Dictionary<string, string>();
-
- protected TestMessage()
- : this(MessageTransport.Direct) {
- }
-
- protected TestMessage(MessageTransport transport) {
- this.transport = transport;
- }
-
- [MessagePart("age", IsRequired = true)]
- public int Age { get; set; }
- [MessagePart("Name")]
- public string Name { get; set; }
- [MessagePart]
- public string EmptyMember { get; set; }
- [MessagePart(null)] // null name tests that Location is still the name.
- public Uri Location { get; set; }
- [MessagePart(IsRequired = true)]
- public DateTime Timestamp { get; set; }
-
- #region IProtocolMessage Properties
-
- Version IMessage.Version {
- get { return new Version(1, 0); }
- }
-
- MessageProtections IProtocolMessage.RequiredProtection {
- get { return MessageProtections.None; }
- }
-
- MessageTransport IProtocolMessage.Transport {
- get { return this.transport; }
- }
-
- IDictionary<string, string> IMessage.ExtraData {
- get { return this.extraData; }
- }
-
- #endregion
-
- #region IDirectResponseProtocolMessage Members
-
- public IDirectedProtocolMessage OriginatingRequest { get; set; }
-
- #endregion
-
- #region IMessage Methods
-
- void IMessage.EnsureValidMessage() {
- if (this.EmptyMember != null || this.Age < 0) {
- throw new ProtocolException();
- }
- }
-
- #endregion
- }
-}
+//----------------------------------------------------------------------- +// <copyright file="TestMessage.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.Test.Mocks { + using System; + using System.Collections.Generic; + using System.Runtime.Serialization; + using DotNetOpenAuth.Messaging; + using DotNetOpenAuth.Messaging.Reflection; + + internal abstract class TestMessage : IDirectResponseProtocolMessage { + private MessageTransport transport; + private Dictionary<string, string> extraData = new Dictionary<string, string>(); + + protected TestMessage() + : this(MessageTransport.Direct) { + } + + protected TestMessage(MessageTransport transport) { + this.transport = transport; + } + + [MessagePart("age", IsRequired = true)] + public int Age { get; set; } + [MessagePart("Name")] + public string Name { get; set; } + [MessagePart] + public string EmptyMember { get; set; } + [MessagePart(null)] // null name tests that Location is still the name. + public Uri Location { get; set; } + [MessagePart(IsRequired = true)] + public DateTime Timestamp { get; set; } + + #region IProtocolMessage Properties + + Version IMessage.Version { + get { return new Version(1, 0); } + } + + MessageProtections IProtocolMessage.RequiredProtection { + get { return MessageProtections.None; } + } + + MessageTransport IProtocolMessage.Transport { + get { return this.transport; } + } + + IDictionary<string, string> IMessage.ExtraData { + get { return this.extraData; } + } + + #endregion + + #region IDirectResponseProtocolMessage Members + + public IDirectedProtocolMessage OriginatingRequest { get; set; } + + #endregion + + #region IMessage Methods + + void IMessage.EnsureValidMessage() { + if (this.EmptyMember != null || this.Age < 0) { + throw new ProtocolException(); + } + } + + #endregion + } +} diff --git a/src/DotNetOpenAuth.Test/OpenId/ChannelElements/OpenIdChannelTests.cs b/src/DotNetOpenAuth.Test/OpenId/ChannelElements/OpenIdChannelTests.cs index a548969..60cbe3e 100644 --- a/src/DotNetOpenAuth.Test/OpenId/ChannelElements/OpenIdChannelTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/ChannelElements/OpenIdChannelTests.cs @@ -1,102 +1,102 @@ -//-----------------------------------------------------------------------
-// <copyright file="OpenIdChannelTests.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOpenAuth.Test.OpenId.ChannelElements {
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Linq;
- using System.Net;
- using System.Text;
- using DotNetOpenAuth.Messaging;
- using DotNetOpenAuth.Messaging.Bindings;
- using DotNetOpenAuth.Messaging.Reflection;
- using DotNetOpenAuth.OpenId;
- using DotNetOpenAuth.OpenId.ChannelElements;
- using Microsoft.VisualStudio.TestTools.UnitTesting;
-
- [TestClass]
- public class OpenIdChannelTests : TestBase {
- private static readonly TimeSpan maximumMessageAge = TimeSpan.FromHours(3); // good for tests, too long for production
- private OpenIdChannel channel;
- private OpenIdChannel_Accessor accessor;
- private Mocks.TestWebRequestHandler webHandler;
-
- [TestInitialize]
- public void Setup() {
- this.webHandler = new Mocks.TestWebRequestHandler();
- this.channel = new OpenIdChannel(new AssociationMemoryStore<Uri>(), new NonceMemoryStore(maximumMessageAge), new PrivateSecretMemoryStore());
- this.accessor = OpenIdChannel_Accessor.AttachShadow(this.channel);
- this.channel.WebRequestHandler = this.webHandler;
- }
-
- [TestMethod]
- public void Ctor() {
- // Verify that the channel stack includes the expected types.
- // While other binding elements may be substituted for these, we'd then have
- // to test them. Since we're not testing them in the OpenID battery of tests,
- // we make sure they are the standard ones so that we trust they are tested
- // elsewhere by the testing library.
- var replayElement = (StandardReplayProtectionBindingElement)this.channel.BindingElements.SingleOrDefault(el => el is StandardReplayProtectionBindingElement);
- Assert.IsTrue(this.channel.BindingElements.Any(el => el is StandardExpirationBindingElement));
- Assert.IsNotNull(replayElement);
-
- // Verify that empty nonces are allowed, since OpenID 2.0 allows this.
- Assert.IsTrue(replayElement.AllowZeroLengthNonce);
- }
-
- /// <summary>
- /// Verifies that the channel sends direct message requests as HTTP POST requests.
- /// </summary>
- [TestMethod]
- public void DirectRequestsUsePost() {
- IDirectedProtocolMessage requestMessage = new Mocks.TestDirectedMessage(MessageTransport.Direct) {
- Recipient = new Uri("http://host"),
- Name = "Andrew",
- };
- HttpWebRequest httpRequest = this.accessor.CreateHttpRequest(requestMessage);
- Assert.AreEqual("POST", httpRequest.Method);
- StringAssert.Contains(this.webHandler.RequestEntityAsString, "Name=Andrew");
- }
-
- /// <summary>
- /// Verifies that direct response messages are encoded using Key Value Form.
- /// </summary>
- /// <remarks>
- /// The validity of the actual KVF encoding is not checked here. We assume that the KVF encoding
- /// class is verified elsewhere. We're only checking that the KVF class is being used by the
- /// <see cref="OpenIdChannel.SendDirectMessageResponse"/> method.
- /// </remarks>
- [TestMethod]
- public void DirectResponsesSentUsingKeyValueForm() {
- IProtocolMessage message = MessagingTestBase.GetStandardTestMessage(MessagingTestBase.FieldFill.AllRequired);
- MessageDictionary messageFields = new MessageDictionary(message);
- byte[] expectedBytes = KeyValueFormEncoding.GetBytes(messageFields);
- string expectedContentType = OpenIdChannel_Accessor.KeyValueFormContentType;
-
- UserAgentResponse directResponse = this.accessor.SendDirectMessageResponse(message);
- Assert.AreEqual(expectedContentType, directResponse.Headers[HttpResponseHeader.ContentType]);
- byte[] actualBytes = new byte[directResponse.ResponseStream.Length];
- directResponse.ResponseStream.Read(actualBytes, 0, actualBytes.Length);
- Assert.IsTrue(MessagingUtilities.AreEquivalent(expectedBytes, actualBytes));
- }
-
- /// <summary>
- /// Verifies that direct message responses are read in using the Key Value Form decoder.
- /// </summary>
- [TestMethod]
- public void DirectResponsesReceivedAsKeyValueForm() {
- var fields = new Dictionary<string, string> {
- { "var1", "value1" },
- { "var2", "value2" },
- };
- var response = new DirectWebResponse {
- ResponseStream = new MemoryStream(KeyValueFormEncoding.GetBytes(fields)),
- };
- Assert.IsTrue(MessagingUtilities.AreEquivalent(fields, this.accessor.ReadFromResponseInternal(response)));
- }
- }
-}
+//----------------------------------------------------------------------- +// <copyright file="OpenIdChannelTests.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.Test.OpenId.ChannelElements { + using System; + using System.Collections.Generic; + using System.IO; + using System.Linq; + using System.Net; + using System.Text; + using DotNetOpenAuth.Messaging; + using DotNetOpenAuth.Messaging.Bindings; + using DotNetOpenAuth.Messaging.Reflection; + using DotNetOpenAuth.OpenId; + using DotNetOpenAuth.OpenId.ChannelElements; + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class OpenIdChannelTests : TestBase { + private static readonly TimeSpan maximumMessageAge = TimeSpan.FromHours(3); // good for tests, too long for production + private OpenIdChannel channel; + private OpenIdChannel_Accessor accessor; + private Mocks.TestWebRequestHandler webHandler; + + [TestInitialize] + public void Setup() { + this.webHandler = new Mocks.TestWebRequestHandler(); + this.channel = new OpenIdChannel(new AssociationMemoryStore<Uri>(), new NonceMemoryStore(maximumMessageAge), new PrivateSecretMemoryStore()); + this.accessor = OpenIdChannel_Accessor.AttachShadow(this.channel); + this.channel.WebRequestHandler = this.webHandler; + } + + [TestMethod] + public void Ctor() { + // Verify that the channel stack includes the expected types. + // While other binding elements may be substituted for these, we'd then have + // to test them. Since we're not testing them in the OpenID battery of tests, + // we make sure they are the standard ones so that we trust they are tested + // elsewhere by the testing library. + var replayElement = (StandardReplayProtectionBindingElement)this.channel.BindingElements.SingleOrDefault(el => el is StandardReplayProtectionBindingElement); + Assert.IsTrue(this.channel.BindingElements.Any(el => el is StandardExpirationBindingElement)); + Assert.IsNotNull(replayElement); + + // Verify that empty nonces are allowed, since OpenID 2.0 allows this. + Assert.IsTrue(replayElement.AllowZeroLengthNonce); + } + + /// <summary> + /// Verifies that the channel sends direct message requests as HTTP POST requests. + /// </summary> + [TestMethod] + public void DirectRequestsUsePost() { + IDirectedProtocolMessage requestMessage = new Mocks.TestDirectedMessage(MessageTransport.Direct) { + Recipient = new Uri("http://host"), + Name = "Andrew", + }; + HttpWebRequest httpRequest = this.accessor.CreateHttpRequest(requestMessage); + Assert.AreEqual("POST", httpRequest.Method); + StringAssert.Contains(this.webHandler.RequestEntityAsString, "Name=Andrew"); + } + + /// <summary> + /// Verifies that direct response messages are encoded using Key Value Form. + /// </summary> + /// <remarks> + /// The validity of the actual KVF encoding is not checked here. We assume that the KVF encoding + /// class is verified elsewhere. We're only checking that the KVF class is being used by the + /// <see cref="OpenIdChannel.SendDirectMessageResponse"/> method. + /// </remarks> + [TestMethod] + public void DirectResponsesSentUsingKeyValueForm() { + IProtocolMessage message = MessagingTestBase.GetStandardTestMessage(MessagingTestBase.FieldFill.AllRequired); + MessageDictionary messageFields = new MessageDictionary(message); + byte[] expectedBytes = KeyValueFormEncoding.GetBytes(messageFields); + string expectedContentType = OpenIdChannel_Accessor.KeyValueFormContentType; + + UserAgentResponse directResponse = this.accessor.SendDirectMessageResponse(message); + Assert.AreEqual(expectedContentType, directResponse.Headers[HttpResponseHeader.ContentType]); + byte[] actualBytes = new byte[directResponse.ResponseStream.Length]; + directResponse.ResponseStream.Read(actualBytes, 0, actualBytes.Length); + Assert.IsTrue(MessagingUtilities.AreEquivalent(expectedBytes, actualBytes)); + } + + /// <summary> + /// Verifies that direct message responses are read in using the Key Value Form decoder. + /// </summary> + [TestMethod] + public void DirectResponsesReceivedAsKeyValueForm() { + var fields = new Dictionary<string, string> { + { "var1", "value1" }, + { "var2", "value2" }, + }; + var response = new DirectWebResponse { + ResponseStream = new MemoryStream(KeyValueFormEncoding.GetBytes(fields)), + }; + Assert.IsTrue(MessagingUtilities.AreEquivalent(fields, this.accessor.ReadFromResponseInternal(response))); + } + } +} diff --git a/src/DotNetOpenAuth.Test/OpenId/DiffieHellmanTests.cs b/src/DotNetOpenAuth.Test/OpenId/DiffieHellmanTests.cs index b60631b..7ffaf1b 100644 --- a/src/DotNetOpenAuth.Test/OpenId/DiffieHellmanTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/DiffieHellmanTests.cs @@ -1,64 +1,64 @@ -//-----------------------------------------------------------------------
-// <copyright file="DiffieHellmanTests.cs" company="Jason Alexander, Andrew Arnott">
-// Copyright (c) Jason Alexander, Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOpenAuth.Test.OpenId {
- using System;
- using System.IO;
- using DotNetOpenAuth.OpenId;
- using DotNetOpenAuth.OpenId.Messages;
- using Microsoft.VisualStudio.TestTools.UnitTesting;
- using Org.Mentalis.Security.Cryptography;
-
- [TestClass]
- public class DiffieHellmanTests {
- [TestMethod]
- public void Test() {
- string s1 = Test1();
- string s2 = Test1();
-
- Assert.AreNotEqual(s1, s2, "Secret keys should NOT be the same.");
- }
-
- [TestMethod]
- public void TestPublic() {
- TextReader reader = new StringReader(TestSupport.LoadEmbeddedFile("dhpriv.txt"));
-
- try {
- string line;
- while ((line = reader.ReadLine()) != null) {
- string[] parts = line.Trim().Split(' ');
- byte[] x = Convert.FromBase64String(parts[0]);
- DiffieHellmanManaged dh = new DiffieHellmanManaged(AssociateDiffieHellmanRequest.DefaultMod, AssociateDiffieHellmanRequest.DefaultGen, x);
- byte[] pub = dh.CreateKeyExchange();
- byte[] y = Convert.FromBase64String(parts[1]);
-
- if (y[0] == 0 && y[1] <= 127) {
- y.CopyTo(y, 1);
- }
-
- Assert.AreEqual(
- Convert.ToBase64String(y),
- Convert.ToBase64String(DiffieHellmanUtilities.EnsurePositive(pub)),
- line);
- }
- } finally {
- reader.Close();
- }
- }
-
- private static string Test1() {
- DiffieHellman dh1 = new DiffieHellmanManaged();
- DiffieHellman dh2 = new DiffieHellmanManaged();
-
- string secret1 = Convert.ToBase64String(dh1.DecryptKeyExchange(dh2.CreateKeyExchange()));
- string secret2 = Convert.ToBase64String(dh2.DecryptKeyExchange(dh1.CreateKeyExchange()));
-
- Assert.AreEqual(secret1, secret2, "Secret keys do not match for some reason.");
-
- return secret1;
- }
- }
-}
+//----------------------------------------------------------------------- +// <copyright file="DiffieHellmanTests.cs" company="Jason Alexander, Andrew Arnott"> +// Copyright (c) Jason Alexander, Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.Test.OpenId { + using System; + using System.IO; + using DotNetOpenAuth.OpenId; + using DotNetOpenAuth.OpenId.Messages; + using Microsoft.VisualStudio.TestTools.UnitTesting; + using Org.Mentalis.Security.Cryptography; + + [TestClass] + public class DiffieHellmanTests { + [TestMethod] + public void Test() { + string s1 = Test1(); + string s2 = Test1(); + + Assert.AreNotEqual(s1, s2, "Secret keys should NOT be the same."); + } + + [TestMethod] + public void TestPublic() { + TextReader reader = new StringReader(TestSupport.LoadEmbeddedFile("dhpriv.txt")); + + try { + string line; + while ((line = reader.ReadLine()) != null) { + string[] parts = line.Trim().Split(' '); + byte[] x = Convert.FromBase64String(parts[0]); + DiffieHellmanManaged dh = new DiffieHellmanManaged(AssociateDiffieHellmanRequest.DefaultMod, AssociateDiffieHellmanRequest.DefaultGen, x); + byte[] pub = dh.CreateKeyExchange(); + byte[] y = Convert.FromBase64String(parts[1]); + + if (y[0] == 0 && y[1] <= 127) { + y.CopyTo(y, 1); + } + + Assert.AreEqual( + Convert.ToBase64String(y), + Convert.ToBase64String(DiffieHellmanUtilities.EnsurePositive(pub)), + line); + } + } finally { + reader.Close(); + } + } + + private static string Test1() { + DiffieHellman dh1 = new DiffieHellmanManaged(); + DiffieHellman dh2 = new DiffieHellmanManaged(); + + string secret1 = Convert.ToBase64String(dh1.DecryptKeyExchange(dh2.CreateKeyExchange())); + string secret2 = Convert.ToBase64String(dh2.DecryptKeyExchange(dh1.CreateKeyExchange())); + + Assert.AreEqual(secret1, secret2, "Secret keys do not match for some reason."); + + return secret1; + } + } +} diff --git a/src/DotNetOpenAuth.Test/OpenId/Extensions/SimpleRegistration/ClaimsRequestTests.cs b/src/DotNetOpenAuth.Test/OpenId/Extensions/SimpleRegistration/ClaimsRequestTests.cs index 8da2c7a..feb1450 100644 --- a/src/DotNetOpenAuth.Test/OpenId/Extensions/SimpleRegistration/ClaimsRequestTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/Extensions/SimpleRegistration/ClaimsRequestTests.cs @@ -1,62 +1,62 @@ -//-----------------------------------------------------------------------
-// <copyright file="ClaimsRequestTests.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOpenAuth.Test.OpenId.Extensions {
- using DotNetOpenAuth.Messaging.Reflection;
- using DotNetOpenAuth.OpenId.Extensions.SimpleRegistration;
- using DotNetOpenAuth.OpenId.Messages;
- using Microsoft.VisualStudio.TestTools.UnitTesting;
-
- [TestClass]
- public class ClaimsRequestTests : OpenIdTestBase {
- [TestMethod]
- public void CreateResponse() {
- // some unofficial type URIs...
- this.ParameterizedTypeUriPreservedTest("http://openid.net/sreg/1.0");
- this.ParameterizedTypeUriPreservedTest("http://openid.net/sreg/1.1");
- // and the official one.
- this.ParameterizedTypeUriPreservedTest("http://openid.net/extensions/sreg/1.1");
- }
-
- [TestMethod]
- public void RequiredOptionalLists() {
- ClaimsRequest req = new ClaimsRequest();
- MessageDictionary dictionary = new MessageDictionary(req);
- Assert.AreEqual(string.Empty, dictionary["required"]);
- Assert.AreEqual(string.Empty, dictionary["optional"]);
-
- req.BirthDate = DemandLevel.Request;
- req.Nickname = DemandLevel.Require;
- Assert.AreEqual("dob", dictionary["optional"]);
- Assert.AreEqual("nickname", dictionary["required"]);
-
- req.PostalCode = DemandLevel.Require;
- req.Gender = DemandLevel.Request;
- Assert.AreEqual("dob,gender", dictionary["optional"]);
- Assert.AreEqual("nickname,postcode", dictionary["required"]);
- }
-
- [TestMethod]
- public void EqualityTests() {
- ClaimsRequest req1 = new ClaimsRequest();
- ClaimsRequest req2 = new ClaimsRequest();
- Assert.AreEqual(req1, req2);
-
- req1.BirthDate = DemandLevel.Request;
- Assert.AreNotEqual(req1, req2);
-
- req2.BirthDate = DemandLevel.Request;
- req1.Country = DemandLevel.Request;
- Assert.AreNotEqual(req1, req2);
- }
-
- private void ParameterizedTypeUriPreservedTest(string typeUri) {
- ClaimsRequest request = new ClaimsRequest(typeUri);
- ClaimsResponse response = request.CreateResponse();
- Assert.AreEqual(typeUri, ((IOpenIdMessageExtension)response).TypeUri);
- }
- }
-}
+//----------------------------------------------------------------------- +// <copyright file="ClaimsRequestTests.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.Test.OpenId.Extensions { + using DotNetOpenAuth.Messaging.Reflection; + using DotNetOpenAuth.OpenId.Extensions.SimpleRegistration; + using DotNetOpenAuth.OpenId.Messages; + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class ClaimsRequestTests : OpenIdTestBase { + [TestMethod] + public void CreateResponse() { + // some unofficial type URIs... + this.ParameterizedTypeUriPreservedTest("http://openid.net/sreg/1.0"); + this.ParameterizedTypeUriPreservedTest("http://openid.net/sreg/1.1"); + // and the official one. + this.ParameterizedTypeUriPreservedTest("http://openid.net/extensions/sreg/1.1"); + } + + [TestMethod] + public void RequiredOptionalLists() { + ClaimsRequest req = new ClaimsRequest(); + MessageDictionary dictionary = new MessageDictionary(req); + Assert.AreEqual(string.Empty, dictionary["required"]); + Assert.AreEqual(string.Empty, dictionary["optional"]); + + req.BirthDate = DemandLevel.Request; + req.Nickname = DemandLevel.Require; + Assert.AreEqual("dob", dictionary["optional"]); + Assert.AreEqual("nickname", dictionary["required"]); + + req.PostalCode = DemandLevel.Require; + req.Gender = DemandLevel.Request; + Assert.AreEqual("dob,gender", dictionary["optional"]); + Assert.AreEqual("nickname,postcode", dictionary["required"]); + } + + [TestMethod] + public void EqualityTests() { + ClaimsRequest req1 = new ClaimsRequest(); + ClaimsRequest req2 = new ClaimsRequest(); + Assert.AreEqual(req1, req2); + + req1.BirthDate = DemandLevel.Request; + Assert.AreNotEqual(req1, req2); + + req2.BirthDate = DemandLevel.Request; + req1.Country = DemandLevel.Request; + Assert.AreNotEqual(req1, req2); + } + + private void ParameterizedTypeUriPreservedTest(string typeUri) { + ClaimsRequest request = new ClaimsRequest(typeUri); + ClaimsResponse response = request.CreateResponse(); + Assert.AreEqual(typeUri, ((IOpenIdMessageExtension)response).TypeUri); + } + } +} diff --git a/src/DotNetOpenAuth.Test/OpenId/Extensions/SimpleRegistration/ClaimsResponseTests.cs b/src/DotNetOpenAuth.Test/OpenId/Extensions/SimpleRegistration/ClaimsResponseTests.cs index 94cf55b..6dbfa4f 100644 --- a/src/DotNetOpenAuth.Test/OpenId/Extensions/SimpleRegistration/ClaimsResponseTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/Extensions/SimpleRegistration/ClaimsResponseTests.cs @@ -1,146 +1,146 @@ -//-----------------------------------------------------------------------
-// <copyright file="ClaimsResponseTests.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOpenAuth.Test.OpenId.Extensions {
- using System;
- using System.Globalization;
- using System.IO;
- using System.Runtime.Serialization;
- using System.Runtime.Serialization.Formatters.Binary;
- using System.Xml.Serialization;
- using DotNetOpenAuth.OpenId.Extensions.SimpleRegistration;
- using Microsoft.VisualStudio.TestTools.UnitTesting;
-
- [TestClass]
- public class ClaimsResponseTests {
- [TestMethod]
- public void EmptyMailAddress() {
- ClaimsResponse response = new ClaimsResponse(Constants.sreg_ns);
- response.Email = string.Empty;
- Assert.IsNull(response.MailAddress);
- }
-
- [TestMethod, Ignore] // serialization no longer supported
- public void BinarySerialization() {
- ClaimsResponse fields = this.GetFilledData();
- MemoryStream ms = new MemoryStream();
- IFormatter formatter = new BinaryFormatter();
- formatter.Serialize(ms, fields);
-
- ms.Position = 0;
- ClaimsResponse fields2 = (ClaimsResponse)formatter.Deserialize(ms);
- Assert.AreEqual(fields, fields2);
- }
-
- [TestMethod, Ignore] // serialization no longer supported
- public void XmlSerialization() {
- ClaimsResponse fields = this.GetFilledData();
- MemoryStream ms = new MemoryStream();
- XmlSerializer xs = new XmlSerializer(typeof(ClaimsResponse));
- xs.Serialize(ms, fields);
-
- ms.Position = 0;
- ClaimsResponse fields2 = (ClaimsResponse)xs.Deserialize(ms);
- Assert.AreEqual(fields, fields2);
- }
-
- [TestMethod]
- public void EqualityTest() {
- ClaimsResponse fields1 = this.GetFilledData();
-
- Assert.AreNotEqual(fields1, null);
- Assert.AreNotEqual(fields1, "string");
-
- ClaimsResponse fields2 = this.GetFilledData();
- Assert.AreNotSame(fields1, fields2, "Test sanity check.");
- Assert.AreEqual(fields1, fields2);
-
- // go through each property and change it slightly and make sure it causes inequality.
- fields2.Email += "q";
- Assert.AreNotEqual(fields1, fields2);
- fields1.Email = fields2.Email;
- Assert.AreEqual(fields1, fields2, "Test sanity check.");
- fields2.BirthDate = DateTime.Now;
- Assert.AreNotEqual(fields1, fields2);
- fields2.BirthDate = fields1.BirthDate;
- Assert.AreEqual(fields1, fields2, "Test sanity check.");
- fields2.Country += "q";
- Assert.AreNotEqual(fields1, fields2);
- fields2.Country = fields1.Country;
- Assert.AreEqual(fields1, fields2, "Test sanity check.");
- fields2.FullName += "q";
- Assert.AreNotEqual(fields1, fields2);
- fields2.FullName = fields1.FullName;
- Assert.AreEqual(fields1, fields2, "Test sanity check.");
- fields2.Gender = Gender.Female;
- Assert.AreNotEqual(fields1, fields2);
- fields2.Gender = fields1.Gender;
- Assert.AreEqual(fields1, fields2, "Test sanity check.");
- fields2.Language = "gb";
- Assert.AreNotEqual(fields1, fields2);
- fields2.Language = fields1.Language;
- Assert.AreEqual(fields1, fields2, "Test sanity check.");
- fields2.Nickname += "q";
- Assert.AreNotEqual(fields1, fields2);
- fields2.Nickname = fields1.Nickname;
- Assert.AreEqual(fields1, fields2, "Test sanity check.");
- fields2.PostalCode += "q";
- Assert.AreNotEqual(fields1, fields2);
- fields2.PostalCode = fields1.PostalCode;
- Assert.AreEqual(fields1, fields2, "Test sanity check.");
- fields2.TimeZone += "q";
- Assert.AreNotEqual(fields1, fields2);
- }
-
- [TestMethod]
- public void Birthdates() {
- var response = new ClaimsResponse();
- // Verify that they both start out as null
- Assert.IsNull(response.BirthDateRaw);
- Assert.IsFalse(response.BirthDate.HasValue);
-
- // Verify that null can be set.
- response.BirthDate = null;
- response.BirthDateRaw = null;
- Assert.IsNull(response.BirthDateRaw);
- Assert.IsFalse(response.BirthDate.HasValue);
-
- // Verify that the strong-typed BirthDate property can be set and that it affects the raw property.
- response.BirthDate = DateTime.Parse("April 4, 1984");
- Assert.AreEqual(4, response.BirthDate.Value.Month);
- Assert.AreEqual("1984-04-04", response.BirthDateRaw);
-
- // Verify that the raw property can be set with a complete birthdate and that it affects the strong-typed property.
- response.BirthDateRaw = "1998-05-08";
- Assert.AreEqual("1998-05-08", response.BirthDateRaw);
- Assert.AreEqual(DateTime.Parse("May 8, 1998", CultureInfo.InvariantCulture), response.BirthDate);
-
- // Verify that an partial raw birthdate works, and sets the strong-typed property to null since it cannot be represented.
- response.BirthDateRaw = "2000-00-00";
- Assert.AreEqual("2000-00-00", response.BirthDateRaw);
- Assert.IsFalse(response.BirthDate.HasValue);
- }
-
- [TestMethod, ExpectedException(typeof(ArgumentException))]
- public void InvalidRawBirthdate() {
- var response = new ClaimsResponse();
- response.BirthDateRaw = "2008";
- }
-
- private ClaimsResponse GetFilledData() {
- return new ClaimsResponse(Constants.sreg_ns) {
- BirthDate = new DateTime(2005, 2, 3),
- Culture = new System.Globalization.CultureInfo("en-US"),
- Email = "a@b.com",
- FullName = "Jimmy buffet",
- Gender = Gender.Male,
- Nickname = "Jimbo",
- PostalCode = "12345",
- TimeZone = "PST",
- };
- }
- }
-}
+//----------------------------------------------------------------------- +// <copyright file="ClaimsResponseTests.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.Test.OpenId.Extensions { + using System; + using System.Globalization; + using System.IO; + using System.Runtime.Serialization; + using System.Runtime.Serialization.Formatters.Binary; + using System.Xml.Serialization; + using DotNetOpenAuth.OpenId.Extensions.SimpleRegistration; + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class ClaimsResponseTests { + [TestMethod] + public void EmptyMailAddress() { + ClaimsResponse response = new ClaimsResponse(Constants.sreg_ns); + response.Email = string.Empty; + Assert.IsNull(response.MailAddress); + } + + [TestMethod, Ignore] // serialization no longer supported + public void BinarySerialization() { + ClaimsResponse fields = this.GetFilledData(); + MemoryStream ms = new MemoryStream(); + IFormatter formatter = new BinaryFormatter(); + formatter.Serialize(ms, fields); + + ms.Position = 0; + ClaimsResponse fields2 = (ClaimsResponse)formatter.Deserialize(ms); + Assert.AreEqual(fields, fields2); + } + + [TestMethod, Ignore] // serialization no longer supported + public void XmlSerialization() { + ClaimsResponse fields = this.GetFilledData(); + MemoryStream ms = new MemoryStream(); + XmlSerializer xs = new XmlSerializer(typeof(ClaimsResponse)); + xs.Serialize(ms, fields); + + ms.Position = 0; + ClaimsResponse fields2 = (ClaimsResponse)xs.Deserialize(ms); + Assert.AreEqual(fields, fields2); + } + + [TestMethod] + public void EqualityTest() { + ClaimsResponse fields1 = this.GetFilledData(); + + Assert.AreNotEqual(fields1, null); + Assert.AreNotEqual(fields1, "string"); + + ClaimsResponse fields2 = this.GetFilledData(); + Assert.AreNotSame(fields1, fields2, "Test sanity check."); + Assert.AreEqual(fields1, fields2); + + // go through each property and change it slightly and make sure it causes inequality. + fields2.Email += "q"; + Assert.AreNotEqual(fields1, fields2); + fields1.Email = fields2.Email; + Assert.AreEqual(fields1, fields2, "Test sanity check."); + fields2.BirthDate = DateTime.Now; + Assert.AreNotEqual(fields1, fields2); + fields2.BirthDate = fields1.BirthDate; + Assert.AreEqual(fields1, fields2, "Test sanity check."); + fields2.Country += "q"; + Assert.AreNotEqual(fields1, fields2); + fields2.Country = fields1.Country; + Assert.AreEqual(fields1, fields2, "Test sanity check."); + fields2.FullName += "q"; + Assert.AreNotEqual(fields1, fields2); + fields2.FullName = fields1.FullName; + Assert.AreEqual(fields1, fields2, "Test sanity check."); + fields2.Gender = Gender.Female; + Assert.AreNotEqual(fields1, fields2); + fields2.Gender = fields1.Gender; + Assert.AreEqual(fields1, fields2, "Test sanity check."); + fields2.Language = "gb"; + Assert.AreNotEqual(fields1, fields2); + fields2.Language = fields1.Language; + Assert.AreEqual(fields1, fields2, "Test sanity check."); + fields2.Nickname += "q"; + Assert.AreNotEqual(fields1, fields2); + fields2.Nickname = fields1.Nickname; + Assert.AreEqual(fields1, fields2, "Test sanity check."); + fields2.PostalCode += "q"; + Assert.AreNotEqual(fields1, fields2); + fields2.PostalCode = fields1.PostalCode; + Assert.AreEqual(fields1, fields2, "Test sanity check."); + fields2.TimeZone += "q"; + Assert.AreNotEqual(fields1, fields2); + } + + [TestMethod] + public void Birthdates() { + var response = new ClaimsResponse(); + // Verify that they both start out as null + Assert.IsNull(response.BirthDateRaw); + Assert.IsFalse(response.BirthDate.HasValue); + + // Verify that null can be set. + response.BirthDate = null; + response.BirthDateRaw = null; + Assert.IsNull(response.BirthDateRaw); + Assert.IsFalse(response.BirthDate.HasValue); + + // Verify that the strong-typed BirthDate property can be set and that it affects the raw property. + response.BirthDate = DateTime.Parse("April 4, 1984"); + Assert.AreEqual(4, response.BirthDate.Value.Month); + Assert.AreEqual("1984-04-04", response.BirthDateRaw); + + // Verify that the raw property can be set with a complete birthdate and that it affects the strong-typed property. + response.BirthDateRaw = "1998-05-08"; + Assert.AreEqual("1998-05-08", response.BirthDateRaw); + Assert.AreEqual(DateTime.Parse("May 8, 1998", CultureInfo.InvariantCulture), response.BirthDate); + + // Verify that an partial raw birthdate works, and sets the strong-typed property to null since it cannot be represented. + response.BirthDateRaw = "2000-00-00"; + Assert.AreEqual("2000-00-00", response.BirthDateRaw); + Assert.IsFalse(response.BirthDate.HasValue); + } + + [TestMethod, ExpectedException(typeof(ArgumentException))] + public void InvalidRawBirthdate() { + var response = new ClaimsResponse(); + response.BirthDateRaw = "2008"; + } + + private ClaimsResponse GetFilledData() { + return new ClaimsResponse(Constants.sreg_ns) { + BirthDate = new DateTime(2005, 2, 3), + Culture = new System.Globalization.CultureInfo("en-US"), + Email = "a@b.com", + FullName = "Jimmy buffet", + Gender = Gender.Male, + Nickname = "Jimbo", + PostalCode = "12345", + TimeZone = "PST", + }; + } + } +} diff --git a/src/DotNetOpenAuth.Test/OpenId/RelyingParty/OpenIdRelyingPartyTests.cs b/src/DotNetOpenAuth.Test/OpenId/RelyingParty/OpenIdRelyingPartyTests.cs index d53810a..3f8ff22 100644 --- a/src/DotNetOpenAuth.Test/OpenId/RelyingParty/OpenIdRelyingPartyTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/RelyingParty/OpenIdRelyingPartyTests.cs @@ -1,35 +1,35 @@ -//-----------------------------------------------------------------------
-// <copyright file="OpenIdRelyingPartyTests.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOpenAuth.Test.OpenId.RelyingParty {
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using DotNetOpenAuth.Messaging.Bindings;
- using DotNetOpenAuth.OpenId;
- using DotNetOpenAuth.OpenId.RelyingParty;
- using Microsoft.VisualStudio.TestTools.UnitTesting;
-
- [TestClass]
- public class OpenIdRelyingPartyTests : OpenIdTestBase {
- [TestInitialize]
- public override void SetUp() {
- base.SetUp();
- }
-
- [TestMethod, Ignore] // ignored, pending work to make dumb mode a supported scenario.
- public void CtorNullAssociationStore() {
- new OpenIdRelyingParty(null, null, null);
- }
-
- [TestMethod, ExpectedException(typeof(ArgumentNullException))]
- public void SecuritySettingsSetNull() {
- var rp = new OpenIdRelyingParty(new AssociationMemoryStore<Uri>(), new NonceMemoryStore(TimeSpan.FromMinutes(5)), new PrivateSecretMemoryStore());
- rp.SecuritySettings = null;
- }
- }
-}
+//----------------------------------------------------------------------- +// <copyright file="OpenIdRelyingPartyTests.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.Test.OpenId.RelyingParty { + using System; + using System.Collections.Generic; + using System.Linq; + using System.Text; + using DotNetOpenAuth.Messaging.Bindings; + using DotNetOpenAuth.OpenId; + using DotNetOpenAuth.OpenId.RelyingParty; + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class OpenIdRelyingPartyTests : OpenIdTestBase { + [TestInitialize] + public override void SetUp() { + base.SetUp(); + } + + [TestMethod, Ignore] // ignored, pending work to make dumb mode a supported scenario. + public void CtorNullAssociationStore() { + new OpenIdRelyingParty(null, null, null); + } + + [TestMethod, ExpectedException(typeof(ArgumentNullException))] + public void SecuritySettingsSetNull() { + var rp = new OpenIdRelyingParty(new AssociationMemoryStore<Uri>(), new NonceMemoryStore(TimeSpan.FromMinutes(5)), new PrivateSecretMemoryStore()); + rp.SecuritySettings = null; + } + } +} diff --git a/src/DotNetOpenAuth.Test/OpenId/RelyingParty/PositiveAuthenticationResponseTests.cs b/src/DotNetOpenAuth.Test/OpenId/RelyingParty/PositiveAuthenticationResponseTests.cs index 7a194b7..048deba 100644 --- a/src/DotNetOpenAuth.Test/OpenId/RelyingParty/PositiveAuthenticationResponseTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/RelyingParty/PositiveAuthenticationResponseTests.cs @@ -1,60 +1,60 @@ -//-----------------------------------------------------------------------
-// <copyright file="PositiveAuthenticationResponseTests.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOpenAuth.Test.OpenId.RelyingParty {
- using System;
- using DotNetOpenAuth.Messaging;
- using DotNetOpenAuth.OpenId;
- using DotNetOpenAuth.OpenId.Messages;
- using DotNetOpenAuth.OpenId.RelyingParty;
- using Microsoft.VisualStudio.TestTools.UnitTesting;
-
- [TestClass]
- public class PositiveAuthenticationResponseTests : OpenIdTestBase {
- private readonly Realm realm = new Realm(TestSupport.GetFullUrl(TestSupport.ConsumerPage).AbsoluteUri);
- private readonly Uri returnTo = TestSupport.GetFullUrl(TestSupport.ConsumerPage);
-
- [TestInitialize]
- public override void SetUp() {
- base.SetUp();
- }
-
- /// <summary>
- /// Verifies good, positive assertions are accepted.
- /// </summary>
- [TestMethod]
- public void Valid() {
- PositiveAssertionResponse assertion = this.GetPositiveAssertion();
- var rp = CreateRelyingParty();
- var authResponse = new PositiveAuthenticationResponse(assertion, rp);
- Assert.AreEqual(AuthenticationStatus.Authenticated, authResponse.Status);
- }
-
- /// <summary>
- /// Verifies that the RP rejects signed solicited assertions by an OP that
- /// makes up a claimed Id that was not part of the original request, and
- /// that the OP has no authority to assert positively regarding.
- /// </summary>
- [TestMethod, ExpectedException(typeof(ProtocolException))]
- public void SpoofedClaimedIdDetectionSolicited() {
- PositiveAssertionResponse assertion = this.GetPositiveAssertion();
- assertion.ProviderEndpoint = new Uri("http://rogueOP");
- var rp = CreateRelyingParty();
- var authResponse = new PositiveAuthenticationResponse(assertion, rp);
- Assert.AreEqual(AuthenticationStatus.Failed, authResponse.Status);
- }
-
- private PositiveAssertionResponse GetPositiveAssertion() {
- Protocol protocol = Protocol.Default;
- PositiveAssertionResponse assertion = new PositiveAssertionResponse(protocol.Version, this.returnTo);
- assertion.ClaimedIdentifier = TestSupport.GetMockIdentifier(TestSupport.Scenarios.AutoApproval, this.MockResponder, protocol.ProtocolVersion);
- assertion.LocalIdentifier = TestSupport.GetDelegateUrl(TestSupport.Scenarios.AutoApproval);
- assertion.ReturnTo = this.returnTo;
- assertion.ProviderEndpoint = TestSupport.GetFullUrl("/" + TestSupport.ProviderPage, null, false);
- return assertion;
- }
- }
-}
+//----------------------------------------------------------------------- +// <copyright file="PositiveAuthenticationResponseTests.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.Test.OpenId.RelyingParty { + using System; + using DotNetOpenAuth.Messaging; + using DotNetOpenAuth.OpenId; + using DotNetOpenAuth.OpenId.Messages; + using DotNetOpenAuth.OpenId.RelyingParty; + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class PositiveAuthenticationResponseTests : OpenIdTestBase { + private readonly Realm realm = new Realm(TestSupport.GetFullUrl(TestSupport.ConsumerPage).AbsoluteUri); + private readonly Uri returnTo = TestSupport.GetFullUrl(TestSupport.ConsumerPage); + + [TestInitialize] + public override void SetUp() { + base.SetUp(); + } + + /// <summary> + /// Verifies good, positive assertions are accepted. + /// </summary> + [TestMethod] + public void Valid() { + PositiveAssertionResponse assertion = this.GetPositiveAssertion(); + var rp = CreateRelyingParty(); + var authResponse = new PositiveAuthenticationResponse(assertion, rp); + Assert.AreEqual(AuthenticationStatus.Authenticated, authResponse.Status); + } + + /// <summary> + /// Verifies that the RP rejects signed solicited assertions by an OP that + /// makes up a claimed Id that was not part of the original request, and + /// that the OP has no authority to assert positively regarding. + /// </summary> + [TestMethod, ExpectedException(typeof(ProtocolException))] + public void SpoofedClaimedIdDetectionSolicited() { + PositiveAssertionResponse assertion = this.GetPositiveAssertion(); + assertion.ProviderEndpoint = new Uri("http://rogueOP"); + var rp = CreateRelyingParty(); + var authResponse = new PositiveAuthenticationResponse(assertion, rp); + Assert.AreEqual(AuthenticationStatus.Failed, authResponse.Status); + } + + private PositiveAssertionResponse GetPositiveAssertion() { + Protocol protocol = Protocol.Default; + PositiveAssertionResponse assertion = new PositiveAssertionResponse(protocol.Version, this.returnTo); + assertion.ClaimedIdentifier = TestSupport.GetMockIdentifier(TestSupport.Scenarios.AutoApproval, this.MockResponder, protocol.ProtocolVersion); + assertion.LocalIdentifier = TestSupport.GetDelegateUrl(TestSupport.Scenarios.AutoApproval); + assertion.ReturnTo = this.returnTo; + assertion.ProviderEndpoint = TestSupport.GetFullUrl("/" + TestSupport.ProviderPage, null, false); + return assertion; + } + } +} diff --git a/src/DotNetOpenAuth.Test/OpenId/RelyingParty/ServiceEndpointTests.cs b/src/DotNetOpenAuth.Test/OpenId/RelyingParty/ServiceEndpointTests.cs index 897904c..3d41623 100644 --- a/src/DotNetOpenAuth.Test/OpenId/RelyingParty/ServiceEndpointTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/RelyingParty/ServiceEndpointTests.cs @@ -1,174 +1,174 @@ -//-----------------------------------------------------------------------
-// <copyright file="ServiceEndpointTests.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOpenAuth.Test.OpenId.RelyingParty {
- using System;
- using System.Collections.Generic;
- using System.Diagnostics;
- using System.IO;
- using System.Text;
- using DotNetOpenAuth.Messaging;
- using DotNetOpenAuth.OpenId;
- using DotNetOpenAuth.OpenId.RelyingParty;
- using DotNetOpenAuth.Test.Messaging;
- using Microsoft.VisualStudio.TestTools.UnitTesting;
-
- [TestClass]
- public class ServiceEndpointTests : OpenIdTestBase {
- private UriIdentifier claimedId = new UriIdentifier("http://claimedid.justatest.com");
- private XriIdentifier claimedXri = new XriIdentifier("=!9B72.7DD1.50A9.5CCD");
- private XriIdentifier userSuppliedXri = new XriIdentifier("=Arnot");
- private Uri providerEndpoint = new Uri("http://someprovider.com");
- private Identifier localId = "http://localid.someprovider.com";
- private string[] v20TypeUris = { Protocol.V20.ClaimedIdentifierServiceTypeURI };
- private string[] v11TypeUris = { Protocol.V11.ClaimedIdentifierServiceTypeURI };
- private int servicePriority = 10;
- private int uriPriority = 10;
-
- [TestMethod]
- public void Ctor() {
- ServiceEndpoint se = ServiceEndpoint.CreateForClaimedIdentifier(this.claimedId, this.localId, new ProviderEndpointDescription(this.providerEndpoint, this.v20TypeUris), this.servicePriority, this.uriPriority);
- Assert.AreSame(this.claimedId, se.ClaimedIdentifier);
- Assert.AreSame(this.providerEndpoint, se.ProviderEndpoint);
- Assert.AreSame(this.localId, se.ProviderLocalIdentifier);
- CollectionAssert<string>.AreEquivalent(this.v20TypeUris, se.ProviderSupportedServiceTypeUris);
- Assert.AreEqual(this.servicePriority, ((IXrdsProviderEndpoint)se).ServicePriority);
- }
-
- [TestMethod]
- public void CtorImpliedLocalIdentifier() {
- ServiceEndpoint se = ServiceEndpoint.CreateForClaimedIdentifier(this.claimedId, null, new ProviderEndpointDescription(this.providerEndpoint, this.v20TypeUris), this.servicePriority, this.uriPriority);
- Assert.AreSame(this.claimedId, se.ClaimedIdentifier);
- Assert.AreSame(this.providerEndpoint, se.ProviderEndpoint);
- Assert.AreSame(this.claimedId, se.ProviderLocalIdentifier);
- CollectionAssert<string>.AreEquivalent(this.v20TypeUris, se.ProviderSupportedServiceTypeUris);
- }
-
- [TestMethod]
- public void ProtocolDetection() {
- ServiceEndpoint se = ServiceEndpoint.CreateForClaimedIdentifier(this.claimedId, this.localId, new ProviderEndpointDescription(this.providerEndpoint, this.v20TypeUris), this.servicePriority, this.uriPriority);
- Assert.AreSame(Protocol.V20, se.Protocol);
- se = ServiceEndpoint.CreateForClaimedIdentifier(
- this.claimedId,
- this.localId,
- new ProviderEndpointDescription(this.providerEndpoint, new[] { Protocol.V20.OPIdentifierServiceTypeURI }),
- this.servicePriority,
- this.uriPriority);
- Assert.AreSame(Protocol.V20, se.Protocol);
- se = ServiceEndpoint.CreateForClaimedIdentifier(this.claimedId, this.localId, new ProviderEndpointDescription(this.providerEndpoint, this.v11TypeUris), this.servicePriority, this.uriPriority);
- Assert.AreSame(Protocol.V11, se.Protocol);
- }
-
- [TestMethod, ExpectedException(typeof(ProtocolException))]
- public void ProtocolDetectionWithoutClues() {
- ServiceEndpoint se = ServiceEndpoint.CreateForClaimedIdentifier(
- this.claimedId,
- this.localId,
- new ProviderEndpointDescription(this.providerEndpoint, new[] { Protocol.V20.HtmlDiscoveryLocalIdKey }), // random type URI irrelevant to detection
- this.servicePriority,
- this.uriPriority);
- }
-
- [TestMethod]
- public void SerializationWithUri() {
- ServiceEndpoint se = ServiceEndpoint.CreateForClaimedIdentifier(this.claimedId, this.localId, new ProviderEndpointDescription(this.providerEndpoint, this.v20TypeUris), this.servicePriority, this.uriPriority);
- StringBuilder sb = new StringBuilder();
- using (StringWriter sw = new StringWriter(sb)) {
- se.Serialize(sw);
- }
- using (StringReader sr = new StringReader(sb.ToString())) {
- ServiceEndpoint se2 = ServiceEndpoint.Deserialize(sr);
- Assert.AreEqual(se, se2);
- Assert.AreEqual(se.Protocol.Version, se2.Protocol.Version, "Particularly interested in this, since type URIs are not serialized but version info is.");
- Assert.AreEqual(se.UserSuppliedIdentifier, se2.UserSuppliedIdentifier);
- Assert.AreEqual(se.FriendlyIdentifierForDisplay, se2.FriendlyIdentifierForDisplay);
- }
- }
-
- [TestMethod]
- public void SerializationWithXri() {
- ServiceEndpoint se = ServiceEndpoint.CreateForClaimedIdentifier(this.claimedXri, this.userSuppliedXri, this.localId, new ProviderEndpointDescription(this.providerEndpoint, this.v20TypeUris), this.servicePriority, this.uriPriority);
- StringBuilder sb = new StringBuilder();
- using (StringWriter sw = new StringWriter(sb)) {
- se.Serialize(sw);
- }
- using (StringReader sr = new StringReader(sb.ToString())) {
- ServiceEndpoint se2 = ServiceEndpoint.Deserialize(sr);
- Assert.AreEqual(se, se2);
- Assert.AreEqual(se.Protocol.Version, se2.Protocol.Version, "Particularly interested in this, since type URIs are not serialized but version info is.");
- Assert.AreEqual(se.UserSuppliedIdentifier, se2.UserSuppliedIdentifier);
- Assert.AreEqual(se.FriendlyIdentifierForDisplay, se2.FriendlyIdentifierForDisplay);
- }
- }
-
- [TestMethod]
- public void EqualsTests() {
- ServiceEndpoint se = ServiceEndpoint.CreateForClaimedIdentifier(this.claimedId, this.localId, new ProviderEndpointDescription(this.providerEndpoint, this.v20TypeUris), this.servicePriority, this.uriPriority);
- ServiceEndpoint se2 = ServiceEndpoint.CreateForClaimedIdentifier(this.claimedId, this.localId, new ProviderEndpointDescription(this.providerEndpoint, this.v20TypeUris), (int?)null, (int?)null);
- Assert.AreEqual(se2, se);
- Assert.AreNotEqual(se, null);
- Assert.AreNotEqual(null, se);
-
- ServiceEndpoint se3 = ServiceEndpoint.CreateForClaimedIdentifier(new UriIdentifier(this.claimedId + "a"), this.localId, new ProviderEndpointDescription(this.providerEndpoint, this.v20TypeUris), this.servicePriority, this.uriPriority);
- Assert.AreNotEqual(se, se3);
- se3 = ServiceEndpoint.CreateForClaimedIdentifier(this.claimedId, this.localId, new ProviderEndpointDescription(new Uri(this.providerEndpoint.AbsoluteUri + "a"), this.v20TypeUris), this.servicePriority, this.uriPriority);
- Assert.AreNotEqual(se, se3);
- se3 = ServiceEndpoint.CreateForClaimedIdentifier(this.claimedId, this.localId + "a", new ProviderEndpointDescription(this.providerEndpoint, this.v20TypeUris), this.servicePriority, this.uriPriority);
- Assert.AreNotEqual(se, se3);
- se3 = ServiceEndpoint.CreateForClaimedIdentifier(this.claimedId, this.localId, new ProviderEndpointDescription(this.providerEndpoint, this.v11TypeUris), this.servicePriority, this.uriPriority);
- Assert.AreNotEqual(se, se3);
-
- // make sure that Collection<T>.Contains works as desired.
- List<ServiceEndpoint> list = new List<ServiceEndpoint>();
- list.Add(se);
- Assert.IsTrue(list.Contains(se2));
- }
-
- [TestMethod]
- public void FriendlyIdentifierForDisplay() {
- Uri providerEndpoint = new Uri("http://someprovider");
- Identifier localId = "someuser";
- string[] serviceTypeUris = new string[] {
- Protocol.V20.ClaimedIdentifierServiceTypeURI,
- };
- ServiceEndpoint se;
-
- // strip of protocol and fragment
- se = ServiceEndpoint.CreateForClaimedIdentifier(
- "http://someprovider.somedomain.com:79/someuser#frag",
- localId,
- new ProviderEndpointDescription(providerEndpoint, serviceTypeUris),
- null,
- null);
- Assert.AreEqual("someprovider.somedomain.com:79/someuser", se.FriendlyIdentifierForDisplay);
-
- // unescape characters
- Uri foreignUri = new Uri("http://server崎/村");
- se = ServiceEndpoint.CreateForClaimedIdentifier(foreignUri, localId, new ProviderEndpointDescription(providerEndpoint, serviceTypeUris), null, null);
- Assert.AreEqual("server崎/村", se.FriendlyIdentifierForDisplay);
-
- // restore user supplied identifier to XRIs
- se = ServiceEndpoint.CreateForClaimedIdentifier(
- new XriIdentifier("=!9B72.7DD1.50A9.5CCD"),
- new XriIdentifier("=Arnott崎村"),
- localId,
- new ProviderEndpointDescription(providerEndpoint, serviceTypeUris),
- null,
- null);
- Assert.AreEqual("=Arnott崎村", se.FriendlyIdentifierForDisplay);
-
- // If UserSuppliedIdentifier is the same as the ClaimedIdentifier, don't display it twice...
- se = ServiceEndpoint.CreateForClaimedIdentifier(
- new XriIdentifier("=!9B72.7DD1.50A9.5CCD"),
- new XriIdentifier("=!9B72.7DD1.50A9.5CCD"),
- localId,
- new ProviderEndpointDescription(providerEndpoint, serviceTypeUris),
- null,
- null);
- Assert.AreEqual("=!9B72.7DD1.50A9.5CCD", se.FriendlyIdentifierForDisplay);
- }
- }
-}
+//----------------------------------------------------------------------- +// <copyright file="ServiceEndpointTests.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.Test.OpenId.RelyingParty { + using System; + using System.Collections.Generic; + using System.Diagnostics; + using System.IO; + using System.Text; + using DotNetOpenAuth.Messaging; + using DotNetOpenAuth.OpenId; + using DotNetOpenAuth.OpenId.RelyingParty; + using DotNetOpenAuth.Test.Messaging; + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class ServiceEndpointTests : OpenIdTestBase { + private UriIdentifier claimedId = new UriIdentifier("http://claimedid.justatest.com"); + private XriIdentifier claimedXri = new XriIdentifier("=!9B72.7DD1.50A9.5CCD"); + private XriIdentifier userSuppliedXri = new XriIdentifier("=Arnot"); + private Uri providerEndpoint = new Uri("http://someprovider.com"); + private Identifier localId = "http://localid.someprovider.com"; + private string[] v20TypeUris = { Protocol.V20.ClaimedIdentifierServiceTypeURI }; + private string[] v11TypeUris = { Protocol.V11.ClaimedIdentifierServiceTypeURI }; + private int servicePriority = 10; + private int uriPriority = 10; + + [TestMethod] + public void Ctor() { + ServiceEndpoint se = ServiceEndpoint.CreateForClaimedIdentifier(this.claimedId, this.localId, new ProviderEndpointDescription(this.providerEndpoint, this.v20TypeUris), this.servicePriority, this.uriPriority); + Assert.AreSame(this.claimedId, se.ClaimedIdentifier); + Assert.AreSame(this.providerEndpoint, se.ProviderEndpoint); + Assert.AreSame(this.localId, se.ProviderLocalIdentifier); + CollectionAssert<string>.AreEquivalent(this.v20TypeUris, se.ProviderSupportedServiceTypeUris); + Assert.AreEqual(this.servicePriority, ((IXrdsProviderEndpoint)se).ServicePriority); + } + + [TestMethod] + public void CtorImpliedLocalIdentifier() { + ServiceEndpoint se = ServiceEndpoint.CreateForClaimedIdentifier(this.claimedId, null, new ProviderEndpointDescription(this.providerEndpoint, this.v20TypeUris), this.servicePriority, this.uriPriority); + Assert.AreSame(this.claimedId, se.ClaimedIdentifier); + Assert.AreSame(this.providerEndpoint, se.ProviderEndpoint); + Assert.AreSame(this.claimedId, se.ProviderLocalIdentifier); + CollectionAssert<string>.AreEquivalent(this.v20TypeUris, se.ProviderSupportedServiceTypeUris); + } + + [TestMethod] + public void ProtocolDetection() { + ServiceEndpoint se = ServiceEndpoint.CreateForClaimedIdentifier(this.claimedId, this.localId, new ProviderEndpointDescription(this.providerEndpoint, this.v20TypeUris), this.servicePriority, this.uriPriority); + Assert.AreSame(Protocol.V20, se.Protocol); + se = ServiceEndpoint.CreateForClaimedIdentifier( + this.claimedId, + this.localId, + new ProviderEndpointDescription(this.providerEndpoint, new[] { Protocol.V20.OPIdentifierServiceTypeURI }), + this.servicePriority, + this.uriPriority); + Assert.AreSame(Protocol.V20, se.Protocol); + se = ServiceEndpoint.CreateForClaimedIdentifier(this.claimedId, this.localId, new ProviderEndpointDescription(this.providerEndpoint, this.v11TypeUris), this.servicePriority, this.uriPriority); + Assert.AreSame(Protocol.V11, se.Protocol); + } + + [TestMethod, ExpectedException(typeof(ProtocolException))] + public void ProtocolDetectionWithoutClues() { + ServiceEndpoint se = ServiceEndpoint.CreateForClaimedIdentifier( + this.claimedId, + this.localId, + new ProviderEndpointDescription(this.providerEndpoint, new[] { Protocol.V20.HtmlDiscoveryLocalIdKey }), // random type URI irrelevant to detection + this.servicePriority, + this.uriPriority); + } + + [TestMethod] + public void SerializationWithUri() { + ServiceEndpoint se = ServiceEndpoint.CreateForClaimedIdentifier(this.claimedId, this.localId, new ProviderEndpointDescription(this.providerEndpoint, this.v20TypeUris), this.servicePriority, this.uriPriority); + StringBuilder sb = new StringBuilder(); + using (StringWriter sw = new StringWriter(sb)) { + se.Serialize(sw); + } + using (StringReader sr = new StringReader(sb.ToString())) { + ServiceEndpoint se2 = ServiceEndpoint.Deserialize(sr); + Assert.AreEqual(se, se2); + Assert.AreEqual(se.Protocol.Version, se2.Protocol.Version, "Particularly interested in this, since type URIs are not serialized but version info is."); + Assert.AreEqual(se.UserSuppliedIdentifier, se2.UserSuppliedIdentifier); + Assert.AreEqual(se.FriendlyIdentifierForDisplay, se2.FriendlyIdentifierForDisplay); + } + } + + [TestMethod] + public void SerializationWithXri() { + ServiceEndpoint se = ServiceEndpoint.CreateForClaimedIdentifier(this.claimedXri, this.userSuppliedXri, this.localId, new ProviderEndpointDescription(this.providerEndpoint, this.v20TypeUris), this.servicePriority, this.uriPriority); + StringBuilder sb = new StringBuilder(); + using (StringWriter sw = new StringWriter(sb)) { + se.Serialize(sw); + } + using (StringReader sr = new StringReader(sb.ToString())) { + ServiceEndpoint se2 = ServiceEndpoint.Deserialize(sr); + Assert.AreEqual(se, se2); + Assert.AreEqual(se.Protocol.Version, se2.Protocol.Version, "Particularly interested in this, since type URIs are not serialized but version info is."); + Assert.AreEqual(se.UserSuppliedIdentifier, se2.UserSuppliedIdentifier); + Assert.AreEqual(se.FriendlyIdentifierForDisplay, se2.FriendlyIdentifierForDisplay); + } + } + + [TestMethod] + public void EqualsTests() { + ServiceEndpoint se = ServiceEndpoint.CreateForClaimedIdentifier(this.claimedId, this.localId, new ProviderEndpointDescription(this.providerEndpoint, this.v20TypeUris), this.servicePriority, this.uriPriority); + ServiceEndpoint se2 = ServiceEndpoint.CreateForClaimedIdentifier(this.claimedId, this.localId, new ProviderEndpointDescription(this.providerEndpoint, this.v20TypeUris), (int?)null, (int?)null); + Assert.AreEqual(se2, se); + Assert.AreNotEqual(se, null); + Assert.AreNotEqual(null, se); + + ServiceEndpoint se3 = ServiceEndpoint.CreateForClaimedIdentifier(new UriIdentifier(this.claimedId + "a"), this.localId, new ProviderEndpointDescription(this.providerEndpoint, this.v20TypeUris), this.servicePriority, this.uriPriority); + Assert.AreNotEqual(se, se3); + se3 = ServiceEndpoint.CreateForClaimedIdentifier(this.claimedId, this.localId, new ProviderEndpointDescription(new Uri(this.providerEndpoint.AbsoluteUri + "a"), this.v20TypeUris), this.servicePriority, this.uriPriority); + Assert.AreNotEqual(se, se3); + se3 = ServiceEndpoint.CreateForClaimedIdentifier(this.claimedId, this.localId + "a", new ProviderEndpointDescription(this.providerEndpoint, this.v20TypeUris), this.servicePriority, this.uriPriority); + Assert.AreNotEqual(se, se3); + se3 = ServiceEndpoint.CreateForClaimedIdentifier(this.claimedId, this.localId, new ProviderEndpointDescription(this.providerEndpoint, this.v11TypeUris), this.servicePriority, this.uriPriority); + Assert.AreNotEqual(se, se3); + + // make sure that Collection<T>.Contains works as desired. + List<ServiceEndpoint> list = new List<ServiceEndpoint>(); + list.Add(se); + Assert.IsTrue(list.Contains(se2)); + } + + [TestMethod] + public void FriendlyIdentifierForDisplay() { + Uri providerEndpoint = new Uri("http://someprovider"); + Identifier localId = "someuser"; + string[] serviceTypeUris = new string[] { + Protocol.V20.ClaimedIdentifierServiceTypeURI, + }; + ServiceEndpoint se; + + // strip of protocol and fragment + se = ServiceEndpoint.CreateForClaimedIdentifier( + "http://someprovider.somedomain.com:79/someuser#frag", + localId, + new ProviderEndpointDescription(providerEndpoint, serviceTypeUris), + null, + null); + Assert.AreEqual("someprovider.somedomain.com:79/someuser", se.FriendlyIdentifierForDisplay); + + // unescape characters + Uri foreignUri = new Uri("http://server崎/村"); + se = ServiceEndpoint.CreateForClaimedIdentifier(foreignUri, localId, new ProviderEndpointDescription(providerEndpoint, serviceTypeUris), null, null); + Assert.AreEqual("server崎/村", se.FriendlyIdentifierForDisplay); + + // restore user supplied identifier to XRIs + se = ServiceEndpoint.CreateForClaimedIdentifier( + new XriIdentifier("=!9B72.7DD1.50A9.5CCD"), + new XriIdentifier("=Arnott崎村"), + localId, + new ProviderEndpointDescription(providerEndpoint, serviceTypeUris), + null, + null); + Assert.AreEqual("=Arnott崎村", se.FriendlyIdentifierForDisplay); + + // If UserSuppliedIdentifier is the same as the ClaimedIdentifier, don't display it twice... + se = ServiceEndpoint.CreateForClaimedIdentifier( + new XriIdentifier("=!9B72.7DD1.50A9.5CCD"), + new XriIdentifier("=!9B72.7DD1.50A9.5CCD"), + localId, + new ProviderEndpointDescription(providerEndpoint, serviceTypeUris), + null, + null); + Assert.AreEqual("=!9B72.7DD1.50A9.5CCD", se.FriendlyIdentifierForDisplay); + } + } +} |