diff options
Diffstat (limited to 'src/DotNetOpenAuth.Test/OpenId')
68 files changed, 1759 insertions, 1372 deletions
diff --git a/src/DotNetOpenAuth.Test/OpenId/AssociationHandshakeTests.cs b/src/DotNetOpenAuth.Test/OpenId/AssociationHandshakeTests.cs index af3b1b1..8c2b5bd 100644 --- a/src/DotNetOpenAuth.Test/OpenId/AssociationHandshakeTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/AssociationHandshakeTests.cs @@ -12,21 +12,21 @@ namespace DotNetOpenAuth.Test.OpenId { using DotNetOpenAuth.OpenId.Provider; using DotNetOpenAuth.OpenId.RelyingParty; using DotNetOpenAuth.Test.Mocks; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; - [TestClass] + [TestFixture] public class AssociationHandshakeTests : OpenIdTestBase { - [TestInitialize] + [SetUp] public override void SetUp() { base.SetUp(); } - [TestMethod] + [TestCase] public void AssociateUnencrypted() { this.ParameterizedAssociationTest(new Uri("https://host")); } - [TestMethod] + [TestCase] public void AssociateDiffieHellmanOverHttp() { this.ParameterizedAssociationTest(new Uri("http://host")); } @@ -38,7 +38,7 @@ namespace DotNetOpenAuth.Test.OpenId { /// Some OPs out there flatly refuse to do this, and the spec doesn't forbid /// putting the two together, so we verify that DNOI can handle it. /// </remarks> - [TestMethod] + [TestCase] public void AssociateDiffieHellmanOverHttps() { Protocol protocol = Protocol.V20; OpenIdCoordinator coordinator = new OpenIdCoordinator( @@ -62,7 +62,7 @@ namespace DotNetOpenAuth.Test.OpenId { /// Verifies that the RP and OP can renegotiate an association type if the RP's /// initial request for an association is for a type the OP doesn't support. /// </summary> - [TestMethod] + [TestCase] public void AssociateRenegotiateBitLength() { Protocol protocol = Protocol.V20; @@ -80,7 +80,7 @@ namespace DotNetOpenAuth.Test.OpenId { op.SecuritySettings.MaximumHashBitLength = 160; // Force OP to reject HMAC-SHA256 // Receive initial request for an HMAC-SHA256 association. - AutoResponsiveRequest req = (AutoResponsiveRequest) op.GetRequest(); + AutoResponsiveRequest req = (AutoResponsiveRequest)op.GetRequest(); AutoResponsiveRequest_Accessor reqAccessor = AutoResponsiveRequest_Accessor.AttachShadow(req); AssociateRequest associateRequest = (AssociateRequest)reqAccessor.RequestMessage; Assert.AreEqual(protocol.Args.SignatureAlgorithm.HMAC_SHA256, associateRequest.AssociationType); @@ -110,7 +110,7 @@ namespace DotNetOpenAuth.Test.OpenId { /// <remarks> /// Verifies OP's compliance with OpenID 2.0 section 8.4.1. /// </remarks> - [TestMethod] + [TestCase] public void OPRejectsHttpNoEncryptionAssociateRequests() { Protocol protocol = Protocol.V20; OpenIdCoordinator coordinator = new OpenIdCoordinator( @@ -131,7 +131,7 @@ namespace DotNetOpenAuth.Test.OpenId { /// Verifies that the OP rejects an associate request /// when the HMAC and DH bit lengths do not match. /// </summary> - [TestMethod] + [TestCase] public void OPRejectsMismatchingAssociationAndSessionTypes() { Protocol protocol = Protocol.V20; OpenIdCoordinator coordinator = new OpenIdCoordinator( @@ -154,7 +154,7 @@ namespace DotNetOpenAuth.Test.OpenId { /// <summary> /// Verifies that the RP quietly rejects an OP that suggests an unknown association type. /// </summary> - [TestMethod] + [TestCase] public void RPRejectsUnrecognizedAssociationType() { Protocol protocol = Protocol.V20; OpenIdCoordinator coordinator = new OpenIdCoordinator( @@ -181,7 +181,7 @@ namespace DotNetOpenAuth.Test.OpenId { /// <remarks> /// Verifies RP's compliance with OpenID 2.0 section 8.4.1. /// </remarks> - [TestMethod] + [TestCase] public void RPRejectsUnencryptedSuggestion() { Protocol protocol = Protocol.V20; OpenIdCoordinator coordinator = new OpenIdCoordinator( @@ -206,7 +206,7 @@ namespace DotNetOpenAuth.Test.OpenId { /// Verifies that the RP rejects an associate renegotiate request /// when the HMAC and DH bit lengths do not match. /// </summary> - [TestMethod] + [TestCase] public void RPRejectsMismatchingAssociationAndSessionBitLengths() { Protocol protocol = Protocol.V20; OpenIdCoordinator coordinator = new OpenIdCoordinator( @@ -231,7 +231,7 @@ namespace DotNetOpenAuth.Test.OpenId { /// Verifies that the RP cannot get caught in an infinite loop if a bad OP /// keeps sending it association retry messages. /// </summary> - [TestMethod] + [TestCase] public void RPOnlyRenegotiatesOnce() { Protocol protocol = Protocol.V20; OpenIdCoordinator coordinator = new OpenIdCoordinator( @@ -264,7 +264,7 @@ namespace DotNetOpenAuth.Test.OpenId { /// <summary> /// Verifies security settings limit RP's acceptance of OP's counter-suggestion /// </summary> - [TestMethod] + [TestCase] public void AssociateRenegotiateLimitedByRPSecuritySettings() { Protocol protocol = Protocol.V20; OpenIdCoordinator coordinator = new OpenIdCoordinator( @@ -284,7 +284,7 @@ namespace DotNetOpenAuth.Test.OpenId { /// Verifies that the RP can recover from an invalid or non-existent /// response from the OP, for example in the HTTP timeout case. /// </summary> - [TestMethod] + [TestCase] public void AssociateQuietlyFailsAfterHttpError() { this.MockResponder.RegisterMockNotFound(OPUri); var rp = this.CreateRelyingParty(); @@ -318,9 +318,9 @@ namespace DotNetOpenAuth.Test.OpenId { private void ParameterizedAssociationTest( ProviderEndpointDescription opDescription, string expectedAssociationType) { - Protocol protocol = Protocol.Lookup(opDescription.ProtocolVersion); + Protocol protocol = Protocol.Lookup(Protocol.Lookup(opDescription.Version).ProtocolVersion); bool expectSuccess = expectedAssociationType != null; - bool expectDiffieHellman = !opDescription.Endpoint.IsTransportSecure(); + bool expectDiffieHellman = !opDescription.Uri.IsTransportSecure(); Association rpAssociation = null, opAssociation; AssociateSuccessfulResponse associateSuccessfulResponse = null; AssociateUnsuccessfulResponse associateUnsuccessfulResponse = null; @@ -337,7 +337,7 @@ namespace DotNetOpenAuth.Test.OpenId { op.SendResponse(req); }); coordinator.IncomingMessageFilter = message => { - Assert.AreSame(opDescription.ProtocolVersion, message.Version, "The message was recognized as version {0} but was expected to be {1}.", message.Version, opDescription.ProtocolVersion); + Assert.AreSame(opDescription.Version, message.Version, "The message was recognized as version {0} but was expected to be {1}.", message.Version, Protocol.Lookup(opDescription.Version).ProtocolVersion); var associateSuccess = message as AssociateSuccessfulResponse; var associateFailed = message as AssociateUnsuccessfulResponse; if (associateSuccess != null) { @@ -348,7 +348,7 @@ namespace DotNetOpenAuth.Test.OpenId { } }; coordinator.OutgoingMessageFilter = message => { - Assert.AreSame(opDescription.ProtocolVersion, message.Version, "The message was for version {0} but was expected to be for {1}.", message.Version, opDescription.ProtocolVersion); + Assert.AreEqual(opDescription.Version, message.Version, "The message was for version {0} but was expected to be for {1}.", message.Version, opDescription.Version); }; coordinator.Run(); @@ -356,7 +356,7 @@ namespace DotNetOpenAuth.Test.OpenId { if (expectSuccess) { Assert.IsNotNull(rpAssociation); - Assert.AreSame(rpAssociation, associationManagerAccessor.associationStore.GetAssociation(opDescription.Endpoint, rpAssociation.Handle)); + Assert.AreSame(rpAssociation, associationManagerAccessor.associationStore.GetAssociation(opDescription.Uri, rpAssociation.Handle)); opAssociation = coordinator.Provider.AssociationStore.GetAssociation(AssociationRelyingPartyType.Smart, rpAssociation.Handle); Assert.IsNotNull(opAssociation, "The Provider should have stored the association."); @@ -367,15 +367,15 @@ namespace DotNetOpenAuth.Test.OpenId { Assert.IsTrue(MessagingUtilities.AreEquivalent(opAssociation.SecretKey, rpAssociation.SecretKey)); if (expectDiffieHellman) { - Assert.IsInstanceOfType(associateSuccessfulResponse, typeof(AssociateDiffieHellmanResponse)); + Assert.IsInstanceOf<AssociateDiffieHellmanResponse>(associateSuccessfulResponse); var diffieHellmanResponse = (AssociateDiffieHellmanResponse)associateSuccessfulResponse; Assert.IsFalse(MessagingUtilities.AreEquivalent(diffieHellmanResponse.EncodedMacKey, rpAssociation.SecretKey), "Key should have been encrypted."); } else { - Assert.IsInstanceOfType(associateSuccessfulResponse, typeof(AssociateUnencryptedResponse)); + Assert.IsInstanceOf<AssociateUnencryptedResponse>(associateSuccessfulResponse); var unencryptedResponse = (AssociateUnencryptedResponse)associateSuccessfulResponse; } } else { - Assert.IsNull(associationManagerAccessor.associationStore.GetAssociation(opDescription.Endpoint, new RelyingPartySecuritySettings())); + Assert.IsNull(associationManagerAccessor.associationStore.GetAssociation(opDescription.Uri, new RelyingPartySecuritySettings())); Assert.IsNull(coordinator.Provider.AssociationStore.GetAssociation(AssociationRelyingPartyType.Smart, new ProviderSecuritySettings())); } } diff --git a/src/DotNetOpenAuth.Test/OpenId/AssociationTests.cs b/src/DotNetOpenAuth.Test/OpenId/AssociationTests.cs index 6881255..a70189f 100644 --- a/src/DotNetOpenAuth.Test/OpenId/AssociationTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/AssociationTests.cs @@ -12,16 +12,16 @@ namespace DotNetOpenAuth.Test.OpenId { using System.Text; using DotNetOpenAuth.Messaging; using DotNetOpenAuth.OpenId; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; - [TestClass] + [TestFixture] public class AssociationTests : OpenIdTestBase { private static readonly TimeSpan deltaDateTime = TimeSpan.FromSeconds(2); private static readonly HashAlgorithm sha1 = DiffieHellmanUtilities.Lookup(Protocol.Default, Protocol.Default.Args.SessionType.DH_SHA1); private byte[] sha1Secret; private byte[] sha1Secret2; - [TestInitialize] + [SetUp] public override void SetUp() { base.SetUp(); @@ -35,7 +35,7 @@ namespace DotNetOpenAuth.Test.OpenId { this.sha1Secret2[1] = 0xcc; } - [TestMethod] + [TestCase] public void Properties() { string handle = "somehandle"; TimeSpan lifetime = TimeSpan.FromMinutes(2); @@ -49,7 +49,7 @@ namespace DotNetOpenAuth.Test.OpenId { Assert.AreEqual(0, assoc.Issued.Millisecond, "No milliseconds because this can be cut off in conversions."); } - [TestMethod] + [TestCase] public void Sign() { Association assoc1 = HmacShaAssociation.Create(Protocol.Default, Protocol.Default.Args.SignatureAlgorithm.HMAC_SHA1, "h1", this.sha1Secret, TimeSpan.FromMinutes(2)); Association assoc2 = HmacShaAssociation.Create(Protocol.Default, Protocol.Default.Args.SignatureAlgorithm.HMAC_SHA1, "h2", this.sha1Secret2, TimeSpan.FromMinutes(2)); diff --git a/src/DotNetOpenAuth.Test/OpenId/AssociationsTests.cs b/src/DotNetOpenAuth.Test/OpenId/AssociationsTests.cs index a0c4770..b3d7e4d 100644 --- a/src/DotNetOpenAuth.Test/OpenId/AssociationsTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/AssociationsTests.cs @@ -11,31 +11,31 @@ namespace DotNetOpenAuth.Test.OpenId { using System.Security.Cryptography; using System.Text; using DotNetOpenAuth.OpenId; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; - [TestClass] + [TestFixture] public class AssociationsTests : OpenIdTestBase { private static readonly HashAlgorithm sha1 = DiffieHellmanUtilities.Lookup(Protocol.Default, Protocol.Default.Args.SessionType.DH_SHA1); private byte[] sha1Secret; private Associations assocs; - [TestInitialize] + [TestFixtureSetUp] public override void SetUp() { this.sha1Secret = new byte[sha1.HashSize / 8]; this.assocs = new Associations(); } - [TestMethod] + [TestCase] public void GetNonexistentHandle() { Assert.IsNull(this.assocs.Get("someinvalidhandle")); } - [TestMethod] + [TestCase] public void RemoveNonexistentHandle() { Assert.IsFalse(this.assocs.Remove("someinvalidhandle")); } - [TestMethod] + [TestCase] public void HandleLifecycle() { Association a = HmacShaAssociation.Create( Protocol.Default, @@ -50,7 +50,7 @@ namespace DotNetOpenAuth.Test.OpenId { Assert.IsFalse(this.assocs.Remove(a.Handle)); } - [TestMethod] + [TestCase] public void Best() { Association a = HmacShaAssociation.Create( Protocol.Default, diff --git a/src/DotNetOpenAuth.Test/OpenId/AuthenticationTests.cs b/src/DotNetOpenAuth.Test/OpenId/AuthenticationTests.cs index 7de2a8b..27db93e 100644 --- a/src/DotNetOpenAuth.Test/OpenId/AuthenticationTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/AuthenticationTests.cs @@ -14,16 +14,16 @@ namespace DotNetOpenAuth.Test.OpenId { using DotNetOpenAuth.OpenId.Provider; using DotNetOpenAuth.OpenId.RelyingParty; using DotNetOpenAuth.Test.Mocks; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; - [TestClass] + [TestFixture] public class AuthenticationTests : OpenIdTestBase { - [TestInitialize] + [SetUp] public override void SetUp() { base.SetUp(); } - [TestMethod] + [TestCase] public void SharedAssociationPositive() { this.ParameterizedAuthenticationTest(true, true, false); } @@ -31,17 +31,17 @@ namespace DotNetOpenAuth.Test.OpenId { /// <summary> /// Verifies that a shared association protects against tampering. /// </summary> - [TestMethod] + [TestCase] public void SharedAssociationTampered() { this.ParameterizedAuthenticationTest(true, true, true); } - [TestMethod] + [TestCase] public void SharedAssociationNegative() { this.ParameterizedAuthenticationTest(true, false, false); } - [TestMethod] + [TestCase] public void PrivateAssociationPositive() { this.ParameterizedAuthenticationTest(false, true, false); } @@ -49,17 +49,17 @@ namespace DotNetOpenAuth.Test.OpenId { /// <summary> /// Verifies that a private association protects against tampering. /// </summary> - [TestMethod] + [TestCase] public void PrivateAssociationTampered() { this.ParameterizedAuthenticationTest(false, true, true); } - [TestMethod] + [TestCase] public void NoAssociationNegative() { this.ParameterizedAuthenticationTest(false, false, false); } - [TestMethod] + [TestCase] public void UnsolicitedAssertion() { this.MockResponder.RegisterMockRPDiscovery(); OpenIdCoordinator coordinator = new OpenIdCoordinator( @@ -77,7 +77,7 @@ namespace DotNetOpenAuth.Test.OpenId { coordinator.Run(); } - [TestMethod] + [TestCase] public void UnsolicitedAssertionRejected() { this.MockResponder.RegisterMockRPDiscovery(); OpenIdCoordinator coordinator = new OpenIdCoordinator( @@ -100,7 +100,7 @@ namespace DotNetOpenAuth.Test.OpenId { /// Verifies that delegating identifiers are rejected in unsolicited assertions /// when the appropriate security setting is set. /// </summary> - [TestMethod] + [TestCase] public void UnsolicitedDelegatingIdentifierRejection() { this.MockResponder.RegisterMockRPDiscovery(); OpenIdCoordinator coordinator = new OpenIdCoordinator( diff --git a/src/DotNetOpenAuth.Test/OpenId/ChannelElements/ExtensionsBindingElementTests.cs b/src/DotNetOpenAuth.Test/OpenId/ChannelElements/ExtensionsBindingElementTests.cs index 29797dc..5edd51f 100644 --- a/src/DotNetOpenAuth.Test/OpenId/ChannelElements/ExtensionsBindingElementTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/ChannelElements/ExtensionsBindingElementTests.cs @@ -18,15 +18,15 @@ namespace DotNetOpenAuth.Test.OpenId.ChannelElements { using DotNetOpenAuth.OpenId.RelyingParty; using DotNetOpenAuth.Test.Mocks; using DotNetOpenAuth.Test.OpenId.Extensions; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; - [TestClass] + [TestFixture] public class ExtensionsBindingElementTests : OpenIdTestBase { private StandardOpenIdExtensionFactory factory; private ExtensionsBindingElement rpElement; private IProtocolMessageWithExtensions request; - [TestInitialize] + [SetUp] public override void SetUp() { base.SetUp(); @@ -37,7 +37,7 @@ namespace DotNetOpenAuth.Test.OpenId.ChannelElements { this.request = new SignedResponseRequest(Protocol.Default.Version, OpenIdTestBase.OPUri, AuthenticationRequestMode.Immediate); } - [TestMethod] + [TestCase] public void RoundTripFullStackTest() { IOpenIdMessageExtension request = new MockOpenIdExtension("requestPart", "requestData"); IOpenIdMessageExtension response = new MockOpenIdExtension("responsePart", "responseData"); @@ -47,12 +47,12 @@ namespace DotNetOpenAuth.Test.OpenId.ChannelElements { new IOpenIdMessageExtension[] { response }); } - [TestMethod] + [TestCase] public void ExtensionFactory() { Assert.AreSame(this.factory, this.rpElement.ExtensionFactory); } - [TestMethod, ExpectedException(typeof(ArgumentNullException))] + [TestCase, ExpectedException(typeof(ArgumentNullException))] public void PrepareMessageForSendingNull() { this.rpElement.ProcessOutgoingMessage(null); } @@ -60,13 +60,13 @@ namespace DotNetOpenAuth.Test.OpenId.ChannelElements { /// <summary> /// Verifies that false is returned when a non-extendable message is sent. /// </summary> - [TestMethod] + [TestCase] public void PrepareMessageForSendingNonExtendableMessage() { IProtocolMessage request = new AssociateDiffieHellmanRequest(Protocol.Default.Version, OpenIdTestBase.OPUri); Assert.IsNull(this.rpElement.ProcessOutgoingMessage(request)); } - [TestMethod] + [TestCase] public void PrepareMessageForSending() { this.request.Extensions.Add(new MockOpenIdExtension("part", "extra")); Assert.IsNotNull(this.rpElement.ProcessOutgoingMessage(this.request)); @@ -77,7 +77,7 @@ namespace DotNetOpenAuth.Test.OpenId.ChannelElements { Assert.AreEqual("extra", this.request.ExtraData["openid." + alias + ".data"]); } - [TestMethod] + [TestCase] public void PrepareMessageForReceiving() { this.request.ExtraData["openid.ns.mock"] = MockOpenIdExtension.MockTypeUri; this.request.ExtraData["openid.mock.Part"] = "part"; @@ -91,7 +91,7 @@ namespace DotNetOpenAuth.Test.OpenId.ChannelElements { /// <summary> /// Verifies that extension responses are included in the OP's signature. /// </summary> - [TestMethod] + [TestCase] public void ExtensionResponsesAreSigned() { Protocol protocol = Protocol.Default; var op = this.CreateProvider(); @@ -113,7 +113,7 @@ namespace DotNetOpenAuth.Test.OpenId.ChannelElements { /// <summary> /// Verifies that unsigned extension responses (where any or all fields are unsigned) are ignored. /// </summary> - [TestMethod] + [TestCase] public void ExtensionsAreIdentifiedAsSignedOrUnsigned() { Protocol protocol = Protocol.Default; OpenIdCoordinator coordinator = new OpenIdCoordinator( @@ -144,7 +144,7 @@ namespace DotNetOpenAuth.Test.OpenId.ChannelElements { /// OpenID Authentication 2.0 section 12 states that /// "A namespace MUST NOT be assigned more than one alias in the same message". /// </remarks> - [TestMethod] + [TestCase] public void TwoExtensionsSameTypeUri() { IOpenIdMessageExtension request1 = new MockOpenIdExtension("requestPart1", "requestData1"); IOpenIdMessageExtension request2 = new MockOpenIdExtension("requestPart2", "requestData2"); @@ -154,8 +154,8 @@ namespace DotNetOpenAuth.Test.OpenId.ChannelElements { new IOpenIdMessageExtension[] { request1, request2 }, new IOpenIdMessageExtension[0]); Assert.Fail("Expected ProtocolException not thrown."); - } catch (AssertFailedException ex) { - Assert.IsInstanceOfType(ex.InnerException, typeof(ProtocolException)); + } catch (AssertionException ex) { + Assert.IsInstanceOf<ProtocolException>(ex.InnerException); } } diff --git a/src/DotNetOpenAuth.Test/OpenId/ChannelElements/KeyValueFormEncodingTests.cs b/src/DotNetOpenAuth.Test/OpenId/ChannelElements/KeyValueFormEncodingTests.cs index 92170c4..75ac503 100644 --- a/src/DotNetOpenAuth.Test/OpenId/ChannelElements/KeyValueFormEncodingTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/ChannelElements/KeyValueFormEncodingTests.cs @@ -14,9 +14,9 @@ namespace DotNetOpenAuth.Test.OpenId.ChannelElements { using DotNetOpenAuth.Messaging; using DotNetOpenAuth.Messaging.Reflection; using DotNetOpenAuth.OpenId.ChannelElements; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; - [TestClass] + [TestFixture] public class KeyValueFormEncodingTests : TestBase { private Dictionary<string, string> sampleData = new Dictionary<string, string> { { "key1", "value1" }, @@ -33,7 +33,7 @@ namespace DotNetOpenAuth.Test.OpenId.ChannelElements { Both = 0x3, } - [TestMethod] + [TestCase] public void BasicEncodingTest() { byte[] kvfBytes = KeyValueFormEncoding.GetBytes(this.sampleData); string responseString = Encoding.UTF8.GetString(kvfBytes); @@ -69,7 +69,7 @@ namespace DotNetOpenAuth.Test.OpenId.ChannelElements { } } - [TestMethod] + [TestCase] public void EncodeDecode() { this.KVDictTest(UTF8Encoding.UTF8.GetBytes(string.Empty), new Dictionary<string, string>(), TestMode.Both); @@ -117,35 +117,35 @@ namespace DotNetOpenAuth.Test.OpenId.ChannelElements { this.KVDictTest(UTF8Encoding.UTF8.GetBytes("east:west\nnorth:south"), d10, TestMode.Decoder); } - [TestMethod, ExpectedException(typeof(FormatException))] + [TestCase, ExpectedException(typeof(FormatException))] public void NoValue() { this.Illegal("x\n", KeyValueFormConformanceLevel.OpenId11); } - [TestMethod, ExpectedException(typeof(FormatException))] + [TestCase, ExpectedException(typeof(FormatException))] public void NoValueLoose() { Dictionary<string, string> d = new Dictionary<string, string>(); this.KVDictTest(Encoding.UTF8.GetBytes("x\n"), d, TestMode.Decoder); } - [TestMethod, ExpectedException(typeof(FormatException))] + [TestCase, ExpectedException(typeof(FormatException))] public void EmptyLine() { this.Illegal("x:b\n\n", KeyValueFormConformanceLevel.OpenId20); } - [TestMethod] + [TestCase] public void EmptyLineLoose() { Dictionary<string, string> d = new Dictionary<string, string>(); d.Add("x", "b"); this.KVDictTest(Encoding.UTF8.GetBytes("x:b\n\n"), d, TestMode.Decoder); } - [TestMethod, ExpectedException(typeof(FormatException))] + [TestCase, ExpectedException(typeof(FormatException))] public void LastLineNotTerminated() { this.Illegal("x:y\na:b", KeyValueFormConformanceLevel.OpenId11); } - [TestMethod] + [TestCase] public void LastLineNotTerminatedLoose() { Dictionary<string, string> d = new Dictionary<string, string>(); d.Add("x", "y"); diff --git a/src/DotNetOpenAuth.Test/OpenId/ChannelElements/OpenIdChannelTests.cs b/src/DotNetOpenAuth.Test/OpenId/ChannelElements/OpenIdChannelTests.cs index 385cd19..97a40e8 100644 --- a/src/DotNetOpenAuth.Test/OpenId/ChannelElements/OpenIdChannelTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/ChannelElements/OpenIdChannelTests.cs @@ -18,16 +18,16 @@ namespace DotNetOpenAuth.Test.OpenId.ChannelElements { using DotNetOpenAuth.OpenId.ChannelElements; using DotNetOpenAuth.OpenId.RelyingParty; using DotNetOpenAuth.Test.Mocks; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; - [TestClass] + [TestFixture] 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] + [SetUp] public void Setup() { this.webHandler = new Mocks.TestWebRequestHandler(); this.channel = new OpenIdChannel(new AssociationMemoryStore<Uri>(), new NonceMemoryStore(maximumMessageAge), new RelyingPartySecuritySettings()); @@ -35,7 +35,7 @@ namespace DotNetOpenAuth.Test.OpenId.ChannelElements { this.channel.WebRequestHandler = this.webHandler; } - [TestMethod] + [TestCase] 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 @@ -53,7 +53,7 @@ namespace DotNetOpenAuth.Test.OpenId.ChannelElements { /// <summary> /// Verifies that the channel sends direct message requests as HTTP POST requests. /// </summary> - [TestMethod] + [TestCase] public void DirectRequestsUsePost() { IDirectedProtocolMessage requestMessage = new Mocks.TestDirectedMessage(MessageTransport.Direct) { Recipient = new Uri("http://host"), @@ -61,7 +61,7 @@ namespace DotNetOpenAuth.Test.OpenId.ChannelElements { }; HttpWebRequest httpRequest = this.accessor.CreateHttpRequest(requestMessage); Assert.AreEqual("POST", httpRequest.Method); - StringAssert.Contains(this.webHandler.RequestEntityAsString, "Name=Andrew"); + StringAssert.Contains("Name=Andrew", this.webHandler.RequestEntityAsString); } /// <summary> @@ -73,7 +73,7 @@ namespace DotNetOpenAuth.Test.OpenId.ChannelElements { /// class is verified elsewhere. We're only checking that the KVF class is being used by the /// <see cref="OpenIdChannel.SendDirectMessageResponse"/> method. /// </remarks> - [TestMethod] + [TestCase] public void DirectResponsesSentUsingKeyValueForm() { IProtocolMessage message = MessagingTestBase.GetStandardTestMessage(MessagingTestBase.FieldFill.AllRequired); MessageDictionary messageFields = this.MessageDescriptions.GetAccessor(message); @@ -90,7 +90,7 @@ namespace DotNetOpenAuth.Test.OpenId.ChannelElements { /// <summary> /// Verifies that direct message responses are read in using the Key Value Form decoder. /// </summary> - [TestMethod] + [TestCase] public void DirectResponsesReceivedAsKeyValueForm() { var fields = new Dictionary<string, string> { { "var1", "value1" }, @@ -105,7 +105,7 @@ namespace DotNetOpenAuth.Test.OpenId.ChannelElements { /// <summary> /// Verifies that messages asking for special HTTP status codes get them. /// </summary> - [TestMethod] + [TestCase] public void SendDirectMessageResponseHonorsHttpStatusCodes() { IProtocolMessage message = MessagingTestBase.GetStandardTestMessage(MessagingTestBase.FieldFill.AllRequired); OutgoingWebResponse directResponse = this.accessor.PrepareDirectResponse(message); diff --git a/src/DotNetOpenAuth.Test/OpenId/ChannelElements/SigningBindingElementTests.cs b/src/DotNetOpenAuth.Test/OpenId/ChannelElements/SigningBindingElementTests.cs index 3ab6559..6160680 100644 --- a/src/DotNetOpenAuth.Test/OpenId/ChannelElements/SigningBindingElementTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/ChannelElements/SigningBindingElementTests.cs @@ -12,16 +12,16 @@ namespace DotNetOpenAuth.Test.OpenId.ChannelElements { using DotNetOpenAuth.OpenId.Messages; using DotNetOpenAuth.OpenId.Provider; using DotNetOpenAuth.Test.Mocks; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; - [TestClass] + [TestFixture] public class SigningBindingElementTests : OpenIdTestBase { /// <summary> /// Verifies that the signatures generated match Known Good signatures. /// </summary> - [TestMethod] + [TestCase] public void SignaturesMatchKnownGood() { - Protocol protocol = Protocol.Default; + Protocol protocol = Protocol.V20; var settings = new ProviderSecuritySettings(); var store = new AssociationMemoryStore<AssociationRelyingPartyType>(); byte[] associationSecret = Convert.FromBase64String("rsSwv1zPWfjPRQU80hciu8FPDC+GONAMJQ/AvSo1a2M="); @@ -42,7 +42,7 @@ namespace DotNetOpenAuth.Test.OpenId.ChannelElements { /// <summary> /// Verifies that all parameters in ExtraData in signed responses are signed. /// </summary> - [TestMethod] + [TestCase] public void SignedResponsesIncludeExtraDataInSignature() { Protocol protocol = Protocol.Default; SigningBindingElement sbe = new SigningBindingElement(new AssociationMemoryStore<AssociationRelyingPartyType>(), new ProviderSecuritySettings()); diff --git a/src/DotNetOpenAuth.Test/OpenId/DiffieHellmanTests.cs b/src/DotNetOpenAuth.Test/OpenId/DiffieHellmanTests.cs index 426e19a..9e89b03 100644 --- a/src/DotNetOpenAuth.Test/OpenId/DiffieHellmanTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/DiffieHellmanTests.cs @@ -9,12 +9,12 @@ namespace DotNetOpenAuth.Test.OpenId { using System.IO; using DotNetOpenAuth.OpenId; using DotNetOpenAuth.OpenId.Messages; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; using Org.Mentalis.Security.Cryptography; - [TestClass] + [TestFixture] public class DiffieHellmanTests : OpenIdTestBase { - [TestMethod] + [TestCase] public void Test() { string s1 = Test1(); string s2 = Test1(); @@ -22,7 +22,7 @@ namespace DotNetOpenAuth.Test.OpenId { Assert.AreNotEqual(s1, s2, "Secret keys should NOT be the same."); } - [TestMethod, Timeout(15000)] + [TestCase, Timeout(15000), Category("Slow"), Category("Performance")] public void TestPublic() { TextReader reader = new StringReader(OpenIdTestBase.LoadEmbeddedFile("dhpriv.txt")); @@ -30,7 +30,7 @@ namespace DotNetOpenAuth.Test.OpenId { string line; int lineNumber = 0; while ((line = reader.ReadLine()) != null) { - TestContext.WriteLine("\tLine {0}", ++lineNumber); + TestUtilities.TestLogger.InfoFormat("\tLine {0}", ++lineNumber); string[] parts = line.Trim().Split(' '); byte[] x = Convert.FromBase64String(parts[0]); DiffieHellmanManaged dh = new DiffieHellmanManaged(AssociateDiffieHellmanRequest.DefaultMod, AssociateDiffieHellmanRequest.DefaultGen, x); diff --git a/src/DotNetOpenAuth.Test/OpenId/Discovery/htmldiscovery/html20provWithBadXrds.html b/src/DotNetOpenAuth.Test/OpenId/Discovery/htmldiscovery/html20provWithBadXrds.html new file mode 100644 index 0000000..e695116 --- /dev/null +++ b/src/DotNetOpenAuth.Test/OpenId/Discovery/htmldiscovery/html20provWithBadXrds.html @@ -0,0 +1,10 @@ +<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> +<html xmlns="http://www.w3.org/1999/xhtml"> +<head> + <title>Untitled Page</title> + <meta http-equiv="X-XRDS-Location" content="http://localhost/xrds-notfound.xml"/> + <link rel="openid2.provider" href="http://a/b" /> +</head> +<body> +</body> +</html> diff --git a/src/DotNetOpenAuth.Test/OpenId/Discovery/htmldiscovery/html20provWithEmptyXrds.html b/src/DotNetOpenAuth.Test/OpenId/Discovery/htmldiscovery/html20provWithEmptyXrds.html new file mode 100644 index 0000000..97ad7dc --- /dev/null +++ b/src/DotNetOpenAuth.Test/OpenId/Discovery/htmldiscovery/html20provWithEmptyXrds.html @@ -0,0 +1,10 @@ +<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> +<html xmlns="http://www.w3.org/1999/xhtml"> +<head> + <title>Untitled Page</title> + <meta http-equiv="X-XRDS-Location" content="http://localhost/xrds-irrelevant.xml"/> + <link rel="openid2.provider" href="http://a/b" /> +</head> +<body> +</body> +</html> diff --git a/src/DotNetOpenAuth.Test/OpenId/Discovery/xrdsdiscovery/xrds20dual.xml b/src/DotNetOpenAuth.Test/OpenId/Discovery/xrdsdiscovery/xrds20dual.xml new file mode 100644 index 0000000..9e6a66b --- /dev/null +++ b/src/DotNetOpenAuth.Test/OpenId/Discovery/xrdsdiscovery/xrds20dual.xml @@ -0,0 +1,13 @@ +<?xml version="1.0" encoding="UTF-8"?> +<xrds:XRDS + xmlns:xrds="xri://$xrds" + xmlns:openid="http://openid.net/xmlns/1.0" + xmlns="xri://$xrd*($v*2.0)"> + <XRD> + <Service priority="10"> + <Type>http://specs.openid.net/auth/2.0/signon</Type> + <Type>http://specs.openid.net/auth/2.0/server</Type> + <URI>http://a/b</URI> + </Service> + </XRD> +</xrds:XRDS> diff --git a/src/DotNetOpenAuth.Test/OpenId/DiscoveryServices/UriDiscoveryServiceTests.cs b/src/DotNetOpenAuth.Test/OpenId/DiscoveryServices/UriDiscoveryServiceTests.cs new file mode 100644 index 0000000..1050b4b --- /dev/null +++ b/src/DotNetOpenAuth.Test/OpenId/DiscoveryServices/UriDiscoveryServiceTests.cs @@ -0,0 +1,303 @@ +//----------------------------------------------------------------------- +// <copyright file="UriDiscoveryServiceTests.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.Test.OpenId.DiscoveryServices { + using System; + using System.Collections.Generic; + using System.Linq; + using System.Net; + using System.Text; + using System.Web; + using DotNetOpenAuth.Messaging; + using DotNetOpenAuth.OpenId; + using DotNetOpenAuth.OpenId.Extensions.SimpleRegistration; + using DotNetOpenAuth.OpenId.RelyingParty; + using NUnit.Framework; + + [TestFixture] + public class UriDiscoveryServiceTests : OpenIdTestBase { + [TestCase] + public void DiscoveryWithRedirects() { + Identifier claimedId = this.GetMockIdentifier(ProtocolVersion.V20, false); + + // Add a couple of chained redirect pages that lead to the claimedId. + Uri userSuppliedUri = new Uri("https://localhost/someSecurePage"); + Uri insecureMidpointUri = new Uri("http://localhost/insecureStop"); + this.MockResponder.RegisterMockRedirect(userSuppliedUri, insecureMidpointUri); + this.MockResponder.RegisterMockRedirect(insecureMidpointUri, new Uri(claimedId.ToString())); + + // don't require secure SSL discovery for this test. + Identifier userSuppliedIdentifier = new UriIdentifier(userSuppliedUri, false); + Assert.AreEqual(1, this.Discover(userSuppliedIdentifier).Count()); + } + + [TestCase] + public void DiscoverRequireSslWithSecureRedirects() { + Identifier claimedId = this.GetMockIdentifier(ProtocolVersion.V20, true); + + // Add a couple of chained redirect pages that lead to the claimedId. + // All redirects should be secure. + Uri userSuppliedUri = new Uri("https://localhost/someSecurePage"); + Uri secureMidpointUri = new Uri("https://localhost/secureStop"); + this.MockResponder.RegisterMockRedirect(userSuppliedUri, secureMidpointUri); + this.MockResponder.RegisterMockRedirect(secureMidpointUri, new Uri(claimedId.ToString())); + + Identifier userSuppliedIdentifier = new UriIdentifier(userSuppliedUri, true); + Assert.AreEqual(1, this.Discover(userSuppliedIdentifier).Count()); + } + + [TestCase, ExpectedException(typeof(ProtocolException))] + public void DiscoverRequireSslWithInsecureRedirect() { + Identifier claimedId = this.GetMockIdentifier(ProtocolVersion.V20, true); + + // Add a couple of chained redirect pages that lead to the claimedId. + // Include an insecure HTTP jump in those redirects to verify that + // the ultimate endpoint is never found as a result of high security profile. + Uri userSuppliedUri = new Uri("https://localhost/someSecurePage"); + Uri insecureMidpointUri = new Uri("http://localhost/insecureStop"); + this.MockResponder.RegisterMockRedirect(userSuppliedUri, insecureMidpointUri); + this.MockResponder.RegisterMockRedirect(insecureMidpointUri, new Uri(claimedId.ToString())); + + Identifier userSuppliedIdentifier = new UriIdentifier(userSuppliedUri, true); + this.Discover(userSuppliedIdentifier); + } + + [TestCase] + public void DiscoveryRequireSslWithInsecureXrdsInSecureHtmlHead() { + var insecureXrdsSource = this.GetMockIdentifier(ProtocolVersion.V20, false); + Uri secureClaimedUri = new Uri("https://localhost/secureId"); + + string html = string.Format("<html><head><meta http-equiv='X-XRDS-Location' content='{0}'/></head><body></body></html>", insecureXrdsSource); + this.MockResponder.RegisterMockResponse(secureClaimedUri, "text/html", html); + + Identifier userSuppliedIdentifier = new UriIdentifier(secureClaimedUri, true); + Assert.AreEqual(0, this.Discover(userSuppliedIdentifier).Count()); + } + + [TestCase] + public void DiscoveryRequireSslWithInsecureXrdsInSecureHttpHeader() { + var insecureXrdsSource = this.GetMockIdentifier(ProtocolVersion.V20, false); + + string html = "<html><head></head><body></body></html>"; + WebHeaderCollection headers = new WebHeaderCollection { + { "X-XRDS-Location", insecureXrdsSource } + }; + this.MockResponder.RegisterMockResponse(VanityUriSsl, VanityUriSsl, "text/html", headers, html); + + Identifier userSuppliedIdentifier = new UriIdentifier(VanityUriSsl, true); + Assert.AreEqual(0, this.Discover(userSuppliedIdentifier).Count()); + } + + [TestCase] + public void DiscoveryRequireSslWithInsecureXrdsButSecureLinkTags() { + var insecureXrdsSource = this.GetMockIdentifier(ProtocolVersion.V20, false); + string html = string.Format( + @" + <html><head> + <meta http-equiv='X-XRDS-Location' content='{0}'/> <!-- this one will be insecure and ignored --> + <link rel='openid2.provider' href='{1}' /> + <link rel='openid2.local_id' href='{2}' /> + </head><body></body></html>", + HttpUtility.HtmlEncode(insecureXrdsSource), + HttpUtility.HtmlEncode(OPUriSsl.AbsoluteUri), + HttpUtility.HtmlEncode(OPLocalIdentifiersSsl[1].AbsoluteUri)); + this.MockResponder.RegisterMockResponse(VanityUriSsl, "text/html", html); + + Identifier userSuppliedIdentifier = new UriIdentifier(VanityUriSsl, true); + + // We verify that the XRDS was ignored and the LINK tags were used + // because the XRDS OP-LocalIdentifier uses different local identifiers. + Assert.AreEqual(OPLocalIdentifiersSsl[1].AbsoluteUri, this.Discover(userSuppliedIdentifier).Single().ProviderLocalIdentifier.ToString()); + } + + [TestCase] + public void DiscoveryRequiresSslIgnoresInsecureEndpointsInXrds() { + var insecureEndpoint = GetServiceEndpoint(0, ProtocolVersion.V20, 10, false); + var secureEndpoint = GetServiceEndpoint(1, ProtocolVersion.V20, 20, true); + UriIdentifier secureClaimedId = new UriIdentifier(VanityUriSsl, true); + this.MockResponder.RegisterMockXrdsResponse(secureClaimedId, new IdentifierDiscoveryResult[] { insecureEndpoint, secureEndpoint }); + Assert.AreEqual(secureEndpoint.ProviderLocalIdentifier, this.Discover(secureClaimedId).Single().ProviderLocalIdentifier); + } + + [TestCase] + public void XrdsDirectDiscovery_10() { + this.FailDiscoverXrds("xrds-irrelevant"); + this.DiscoverXrds("xrds10", ProtocolVersion.V10, null, "http://a/b"); + this.DiscoverXrds("xrds11", ProtocolVersion.V11, null, "http://a/b"); + this.DiscoverXrds("xrds1020", ProtocolVersion.V10, null, "http://a/b"); + } + + [TestCase] + public void XrdsDirectDiscovery_20() { + this.DiscoverXrds("xrds20", ProtocolVersion.V20, null, "http://a/b"); + this.DiscoverXrds("xrds2010a", ProtocolVersion.V20, null, "http://a/b"); + this.DiscoverXrds("xrds2010b", ProtocolVersion.V20, null, "http://a/b"); + } + + [TestCase] + public void HtmlDiscover_11() { + this.DiscoverHtml("html10prov", ProtocolVersion.V11, null, "http://a/b"); + this.DiscoverHtml("html10both", ProtocolVersion.V11, "http://c/d", "http://a/b"); + this.FailDiscoverHtml("html10del"); + + // Verify that HTML discovery generates the 1.x endpoints when appropriate + this.DiscoverHtml("html2010", ProtocolVersion.V11, "http://g/h", "http://e/f"); + this.DiscoverHtml("html1020", ProtocolVersion.V11, "http://g/h", "http://e/f"); + this.DiscoverHtml("html2010combinedA", ProtocolVersion.V11, "http://c/d", "http://a/b"); + this.DiscoverHtml("html2010combinedB", ProtocolVersion.V11, "http://c/d", "http://a/b"); + this.DiscoverHtml("html2010combinedC", ProtocolVersion.V11, "http://c/d", "http://a/b"); + } + + [TestCase] + public void HtmlDiscover_20() { + this.DiscoverHtml("html20prov", ProtocolVersion.V20, null, "http://a/b"); + this.DiscoverHtml("html20both", ProtocolVersion.V20, "http://c/d", "http://a/b"); + this.FailDiscoverHtml("html20del"); + this.DiscoverHtml("html2010", ProtocolVersion.V20, "http://c/d", "http://a/b"); + this.DiscoverHtml("html1020", ProtocolVersion.V20, "http://c/d", "http://a/b"); + this.DiscoverHtml("html2010combinedA", ProtocolVersion.V20, "http://c/d", "http://a/b"); + this.DiscoverHtml("html2010combinedB", ProtocolVersion.V20, "http://c/d", "http://a/b"); + this.DiscoverHtml("html2010combinedC", ProtocolVersion.V20, "http://c/d", "http://a/b"); + this.FailDiscoverHtml("html20relative"); + } + + [TestCase] + public void XrdsDiscoveryFromHead() { + this.MockResponder.RegisterMockResponse(new Uri("http://localhost/xrds1020.xml"), "application/xrds+xml", LoadEmbeddedFile("/Discovery/xrdsdiscovery/xrds1020.xml")); + this.DiscoverXrds("XrdsReferencedInHead.html", ProtocolVersion.V10, null, "http://a/b"); + } + + [TestCase] + public void XrdsDiscoveryFromHttpHeader() { + WebHeaderCollection headers = new WebHeaderCollection(); + headers.Add("X-XRDS-Location", new Uri("http://localhost/xrds1020.xml").AbsoluteUri); + this.MockResponder.RegisterMockResponse(new Uri("http://localhost/xrds1020.xml"), "application/xrds+xml", LoadEmbeddedFile("/Discovery/xrdsdiscovery/xrds1020.xml")); + this.DiscoverXrds("XrdsReferencedInHttpHeader.html", ProtocolVersion.V10, null, "http://a/b", headers); + } + + /// <summary> + /// Verifies HTML discovery proceeds if an XRDS document is referenced that doesn't contain OpenID endpoints. + /// </summary> + [TestCase] + public void HtmlDiscoveryProceedsIfXrdsIsEmpty() { + this.MockResponder.RegisterMockResponse(new Uri("http://localhost/xrds-irrelevant.xml"), "application/xrds+xml", LoadEmbeddedFile("/Discovery/xrdsdiscovery/xrds-irrelevant.xml")); + this.DiscoverHtml("html20provWithEmptyXrds", ProtocolVersion.V20, null, "http://a/b"); + } + + /// <summary> + /// Verifies HTML discovery proceeds if the XRDS that is referenced cannot be found. + /// </summary> + [TestCase] + public void HtmlDiscoveryProceedsIfXrdsIsBadOrMissing() { + this.DiscoverHtml("html20provWithBadXrds", ProtocolVersion.V20, null, "http://a/b"); + } + + /// <summary> + /// Verifies that a dual identifier yields only one service endpoint by default. + /// </summary> + [TestCase] + public void DualIdentifierOffByDefault() { + this.MockResponder.RegisterMockResponse(VanityUri, "application/xrds+xml", LoadEmbeddedFile("/Discovery/xrdsdiscovery/xrds20dual.xml")); + var results = this.Discover(VanityUri).ToList(); + Assert.AreEqual(1, results.Count(r => r.ClaimedIdentifier == r.Protocol.ClaimedIdentifierForOPIdentifier), "OP Identifier missing from discovery results."); + Assert.AreEqual(1, results.Count, "Unexpected additional services discovered."); + } + + /// <summary> + /// Verifies that a dual identifier yields two service endpoints when that feature is turned on. + /// </summary> + [TestCase] + public void DualIdentifier() { + this.MockResponder.RegisterMockResponse(VanityUri, "application/xrds+xml", LoadEmbeddedFile("/Discovery/xrdsdiscovery/xrds20dual.xml")); + var rp = this.CreateRelyingParty(true); + rp.Channel.WebRequestHandler = this.RequestHandler; + rp.SecuritySettings.AllowDualPurposeIdentifiers = true; + var results = rp.Discover(VanityUri).ToList(); + Assert.AreEqual(1, results.Count(r => r.ClaimedIdentifier == r.Protocol.ClaimedIdentifierForOPIdentifier), "OP Identifier missing from discovery results."); + Assert.AreEqual(1, results.Count(r => r.ClaimedIdentifier == VanityUri), "Claimed identifier missing from discovery results."); + Assert.AreEqual(2, results.Count, "Unexpected additional services discovered."); + } + + private void Discover(string url, ProtocolVersion version, Identifier expectedLocalId, string providerEndpoint, bool expectSreg, bool useRedirect) { + this.Discover(url, version, expectedLocalId, providerEndpoint, expectSreg, useRedirect, null); + } + + private void Discover(string url, ProtocolVersion version, Identifier expectedLocalId, string providerEndpoint, bool expectSreg, bool useRedirect, WebHeaderCollection headers) { + Protocol protocol = Protocol.Lookup(version); + Uri baseUrl = new Uri("http://localhost/"); + UriIdentifier claimedId = new Uri(baseUrl, url); + UriIdentifier userSuppliedIdentifier = new Uri(baseUrl, "Discovery/htmldiscovery/redirect.aspx?target=" + url); + if (expectedLocalId == null) { + expectedLocalId = claimedId; + } + Identifier idToDiscover = useRedirect ? userSuppliedIdentifier : claimedId; + + string contentType; + if (url.EndsWith("html")) { + contentType = "text/html"; + } else if (url.EndsWith("xml")) { + contentType = "application/xrds+xml"; + } else { + throw new InvalidOperationException(); + } + this.MockResponder.RegisterMockResponse(new Uri(idToDiscover), claimedId, contentType, headers ?? new WebHeaderCollection(), LoadEmbeddedFile(url)); + + IdentifierDiscoveryResult expected = IdentifierDiscoveryResult.CreateForClaimedIdentifier( + claimedId, + expectedLocalId, + new ProviderEndpointDescription(new Uri(providerEndpoint), new string[] { protocol.ClaimedIdentifierServiceTypeURI }), // services aren't checked by Equals + null, + null); + + IdentifierDiscoveryResult se = this.Discover(idToDiscover).FirstOrDefault(ep => ep.Equals(expected)); + Assert.IsNotNull(se, url + " failed to be discovered."); + + // Do extra checking of service type URIs, which aren't included in + // the ServiceEndpoint.Equals method. + Assert.AreEqual(expectSreg ? 2 : 1, se.Capabilities.Count); + Assert.IsTrue(se.Capabilities.Contains(protocol.ClaimedIdentifierServiceTypeURI)); + Assert.AreEqual(expectSreg, se.IsExtensionSupported<ClaimsRequest>()); + } + + private void DiscoverXrds(string page, ProtocolVersion version, Identifier expectedLocalId, string providerEndpoint) { + this.DiscoverXrds(page, version, expectedLocalId, providerEndpoint, null); + } + + private void DiscoverXrds(string page, ProtocolVersion version, Identifier expectedLocalId, string providerEndpoint, WebHeaderCollection headers) { + if (!page.Contains(".")) { + page += ".xml"; + } + this.Discover("/Discovery/xrdsdiscovery/" + page, version, expectedLocalId, providerEndpoint, true, false, headers); + this.Discover("/Discovery/xrdsdiscovery/" + page, version, expectedLocalId, providerEndpoint, true, true, headers); + } + + private void DiscoverHtml(string page, ProtocolVersion version, Identifier expectedLocalId, string providerEndpoint, bool useRedirect) { + this.Discover("/Discovery/htmldiscovery/" + page, version, expectedLocalId, providerEndpoint, false, useRedirect); + } + + private void DiscoverHtml(string scenario, ProtocolVersion version, Identifier expectedLocalId, string providerEndpoint) { + string page = scenario + ".html"; + this.DiscoverHtml(page, version, expectedLocalId, providerEndpoint, false); + this.DiscoverHtml(page, version, expectedLocalId, providerEndpoint, true); + } + + private void FailDiscover(string url) { + UriIdentifier userSuppliedId = new Uri(new Uri("http://localhost"), url); + + this.MockResponder.RegisterMockResponse(new Uri(userSuppliedId), userSuppliedId, "text/html", LoadEmbeddedFile(url)); + + Assert.AreEqual(0, this.Discover(userSuppliedId).Count()); // ... but that no endpoint info is discoverable + } + + private void FailDiscoverHtml(string scenario) { + this.FailDiscover("/Discovery/htmldiscovery/" + scenario + ".html"); + } + + private void FailDiscoverXrds(string scenario) { + this.FailDiscover("/Discovery/xrdsdiscovery/" + scenario + ".xml"); + } + } +} diff --git a/src/DotNetOpenAuth.Test/OpenId/DiscoveryServices/XriDiscoveryProxyServiceTests.cs b/src/DotNetOpenAuth.Test/OpenId/DiscoveryServices/XriDiscoveryProxyServiceTests.cs new file mode 100644 index 0000000..5d914f5 --- /dev/null +++ b/src/DotNetOpenAuth.Test/OpenId/DiscoveryServices/XriDiscoveryProxyServiceTests.cs @@ -0,0 +1,394 @@ +//----------------------------------------------------------------------- +// <copyright file="XriDiscoveryProxyServiceTests.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.Test.OpenId.DiscoveryServices { + using System; + using System.Collections.Generic; + using System.Linq; + using System.Text; + using DotNetOpenAuth.OpenId; + using DotNetOpenAuth.OpenId.RelyingParty; + using NUnit.Framework; + + [TestFixture] + public class XriDiscoveryProxyServiceTests : OpenIdTestBase { + [TestCase] + public void Discover() { + string xrds = @"<?xml version='1.0' encoding='UTF-8'?> +<XRD version='2.0' xmlns='xri://$xrd*($v*2.0)'> + <Query>*Arnott</Query> + <Status ceid='off' cid='verified' code='100'/> + <Expires>2008-07-14T02:03:24.000Z</Expires> + <ProviderID>xri://=</ProviderID> + <LocalID>!9b72.7dd1.50a9.5ccd</LocalID> + <CanonicalID>=!9B72.7DD1.50A9.5CCD</CanonicalID> + + <Service priority='10'> + <ProviderID>xri://!!1008</ProviderID> + <Type select='true'>xri://+i-service*(+contact)*($v*1.0)</Type> + <Type match='default' select='false'/> + <Path select='true'>(+contact)</Path> + <Path match='null' select='false'/> + <URI append='qxri' priority='1'>http://1id.com/contact/</URI> + + </Service> + <Service priority='10'> + <ProviderID>xri://!!1008</ProviderID> + <Type select='true'>xri://+i-service*(+forwarding)*($v*1.0)</Type> + <Type match='null' select='false'/> + <URI append='qxri' priority='1'>http://1id.com/</URI> + </Service> + + <Service priority='10'> + <ProviderID>xri://!!1008</ProviderID> + <Type select='true'>http://openid.net/signon/1.0</Type> + <URI append='none' priority='10'>http://1id.com/sso</URI> + </Service> +</XRD>"; + Dictionary<string, string> mocks = new Dictionary<string, string> { + { "https://xri.net/=Arnott?_xrd_r=application/xrd%2Bxml;sep=false", xrds }, + { "https://xri.net/=!9B72.7DD1.50A9.5CCD?_xrd_r=application/xrd%2Bxml;sep=false", xrds }, + }; + this.MockResponder.RegisterMockXrdsResponses(mocks); + + string expectedCanonicalId = "=!9B72.7DD1.50A9.5CCD"; + IdentifierDiscoveryResult se = this.VerifyCanonicalId("=Arnott", expectedCanonicalId); + Assert.AreEqual(Protocol.V10, Protocol.Lookup(se.Version)); + Assert.AreEqual("http://1id.com/sso", se.ProviderEndpoint.ToString()); + Assert.AreEqual(se.ClaimedIdentifier, se.ProviderLocalIdentifier); + Assert.AreEqual("=Arnott", se.FriendlyIdentifierForDisplay); + } + + [TestCase] + public void DiscoverCommunityInameCanonicalIDs() { + string llliResponse = @"<?xml version='1.0' encoding='UTF-8'?> +<XRD version='2.0' xmlns='xri://$xrd*($v*2.0)'> + <Query>*llli</Query> + <Status ceid='off' cid='verified' code='100'/> + <Expires>2008-07-14T02:21:06.000Z</Expires> + <ProviderID>xri://@</ProviderID> + <LocalID>!72cd.a072.157e.a9c6</LocalID> + <CanonicalID>@!72CD.A072.157E.A9C6</CanonicalID> + <Service priority='10'> + <ProviderID>xri://!!1003!103</ProviderID> + <Type select='true'>http://openid.net/signon/1.0</Type> + <URI append='none' priority='1'>https://login.llli.org/server/</URI> + </Service> + <Service priority='1'> + <ProviderID>xri://!!1003!103</ProviderID> + <Type match='null' select='false'/> + <Type select='true'>xri://+i-service*(+forwarding)*($v*1.0)</Type> + <Path match='default'/> + <Path>(+index)</Path> + <URI append='qxri' priority='1'>http://linksafe-forward.ezibroker.net/forwarding/</URI> + </Service> + <Service priority='10'> + <ProviderID>xri://!!1003!103</ProviderID> + <Type select='true'>xri://$res*auth*($v*2.0)</Type> + <MediaType>application/xrds+xml;trust=none</MediaType> + <URI priority='10'>http://resolve.ezibroker.net/resolve/@llli/</URI> + </Service> + <Service priority='10'> + <ProviderID>xri://!!1003!103</ProviderID> + <Type select='true'>xri://+i-service*(+contact)*($v*1.0)</Type> + <Type match='null'/> + <Path select='true'>(+contact)</Path> + <Path match='null'/> + <URI append='authority' priority='1'>http://linksafe-contact.ezibroker.net/contact/</URI> + </Service> +</XRD> +"; + string llliAreaResponse = @"<?xml version='1.0' encoding='UTF-8'?> +<XRD xmlns='xri://$xrd*($v*2.0)'> + <Query>*area</Query> + <Status cid='verified' code='100'>SUCCESS</Status> + <ServerStatus code='100'>SUCCESS</ServerStatus> + <Expires>2008-07-15T01:21:07.000Z</Expires> + <ProviderID>xri://!!1003</ProviderID> + <LocalID>0000.0000.3B9A.CA0C</LocalID> + <CanonicalID>@!72CD.A072.157E.A9C6!0000.0000.3B9A.CA0C</CanonicalID> + <Service> + <ProviderID>xri://!!1003!103</ProviderID> + <Type select='true'>http://openid.net/signon/1.0</Type> + <URI append='none' priority='1'>https://login.llli.org/server/</URI> + </Service> + <Service> + <ProviderID>xri://!!1003!103</ProviderID> + <Type select='true'>xri://+i-service*(+contact)*($v*1.0)</Type> + <Type match='null'/> + <Path select='true'>(+contact)</Path> + <Path match='null'/> + <URI append='authority' priority='1'>http://linksafe-contact.ezibroker.net/contact/</URI> + </Service> + <Service priority='1'> + <ProviderID>xri://!!1003!103</ProviderID> + <Type select='true'>xri://+i-service*(+forwarding)*($v*1.0)</Type> + <Type match='null' select='false'/> + <Path>(+index)</Path> + <Path match='default'/> + <URI append='qxri' priority='1'>http://linksafe-forward.ezibroker.net/forwarding/</URI> + </Service> + <Service> + <ProviderID>xri://!!1003!103</ProviderID> + <Type select='true'>xri://$res*auth*($v*2.0)</Type> + <MediaType>application/xrds+xml;trust=none</MediaType> + <URI>http://resolve.ezibroker.net/resolve/@llli*area/</URI> + </Service> +</XRD>"; + string llliAreaCanadaUnattachedResponse = @"<?xml version='1.0' encoding='UTF-8'?> +<XRD xmlns='xri://$xrd*($v*2.0)'> + <Query>*canada.unattached</Query> + <Status cid='verified' code='100'>SUCCESS</Status> + <ServerStatus code='100'>SUCCESS</ServerStatus> + <Expires>2008-07-15T01:21:08.000Z</Expires> + <ProviderID>xri://!!1003</ProviderID> + <LocalID>0000.0000.3B9A.CA41</LocalID> + <CanonicalID>@!72CD.A072.157E.A9C6!0000.0000.3B9A.CA0C!0000.0000.3B9A.CA41</CanonicalID> + <Service> + <ProviderID>xri://!!1003!103</ProviderID> + <Type select='true'>http://openid.net/signon/1.0</Type> + <URI append='none' priority='1'>https://login.llli.org/server/</URI> + </Service> + <Service> + <ProviderID>xri://!!1003!103</ProviderID> + <Type select='true'>xri://+i-service*(+contact)*($v*1.0)</Type> + <Type match='null'/> + <Path select='true'>(+contact)</Path> + <Path match='null'/> + <URI append='authority' priority='1'>http://linksafe-contact.ezibroker.net/contact/</URI> + </Service> + <Service priority='1'> + <ProviderID>xri://!!1003!103</ProviderID> + <Type select='true'>xri://+i-service*(+forwarding)*($v*1.0)</Type> + <Type match='null' select='false'/> + <Path>(+index)</Path> + <Path match='default'/> + <URI append='qxri' priority='1'>http://linksafe-forward.ezibroker.net/forwarding/</URI> + </Service> + <Service> + <ProviderID>xri://!!1003!103</ProviderID> + <Type select='true'>xri://$res*auth*($v*2.0)</Type> + <MediaType>application/xrds+xml;trust=none</MediaType> + <URI>http://resolve.ezibroker.net/resolve/@llli*area*canada.unattached/</URI> + </Service> +</XRD>"; + string llliAreaCanadaUnattachedAdaResponse = @"<?xml version='1.0' encoding='UTF-8'?> +<XRD xmlns='xri://$xrd*($v*2.0)'> + <Query>*ada</Query> + <Status cid='verified' code='100'>SUCCESS</Status> + <ServerStatus code='100'>SUCCESS</ServerStatus> + <Expires>2008-07-15T01:21:10.000Z</Expires> + <ProviderID>xri://!!1003</ProviderID> + <LocalID>0000.0000.3B9A.CA01</LocalID> + <CanonicalID>@!72CD.A072.157E.A9C6!0000.0000.3B9A.CA0C!0000.0000.3B9A.CA41!0000.0000.3B9A.CA01</CanonicalID> + <Service> + <ProviderID>xri://!!1003!103</ProviderID> + <Type select='true'>http://openid.net/signon/1.0</Type> + <URI append='none' priority='1'>https://login.llli.org/server/</URI> + </Service> + <Service> + <ProviderID>xri://!!1003!103</ProviderID> + <Type select='true'>xri://+i-service*(+contact)*($v*1.0)</Type> + <Type match='null'/> + <Path select='true'>(+contact)</Path> + <Path match='null'/> + <URI append='authority' priority='1'>http://linksafe-contact.ezibroker.net/contact/</URI> + </Service> + <Service priority='1'> + <ProviderID>xri://!!1003!103</ProviderID> + <Type select='true'>xri://+i-service*(+forwarding)*($v*1.0)</Type> + <Type match='null' select='false'/> + <Path>(+index)</Path> + <Path match='default'/> + <URI append='qxri' priority='1'>http://linksafe-forward.ezibroker.net/forwarding/</URI> + </Service> +</XRD>"; + string webResponse = @"<?xml version='1.0' encoding='UTF-8'?> +<XRD version='2.0' xmlns='xri://$xrd*($v*2.0)'> + <Query>*Web</Query> + <Status ceid='off' cid='verified' code='100'/> + <Expires>2008-07-14T02:21:12.000Z</Expires> + <ProviderID>xri://=</ProviderID> + <LocalID>!91f2.8153.f600.ae24</LocalID> + <CanonicalID>=!91F2.8153.F600.AE24</CanonicalID> + <Service priority='10'> + <Type select='true'>xri://+i-service*(+locator)*($v*1.0)</Type> + <Path select='true'>(+locator)</Path> + <MediaType match='default' select='false'/> + <URI append='qxri'>http://locator.fullxri.com/locator/</URI> + </Service> + <Service priority='10'> + <ProviderID>xri://=web</ProviderID> + <Type select='true'>xri://$res*auth*($v*2.0)</Type> + <Type select='true'>xri://$res*auth*($v*2.0)</Type> + <MediaType select='true'>application/xrds+xml</MediaType> + <URI append='qxri' priority='1'>https://resolve.freexri.com/ns/=web/</URI> + <URI append='qxri' priority='2'>http://resolve.freexri.com/ns/=web/</URI> + </Service> + <Service priority='10'> + <Type select='true'>http://openid.net/signon/1.0</Type> + <Type select='true'>http://specs.openid.net/auth/2.0/signon</Type> + <Path select='true'>(+login)</Path> + <Path match='default' select='false'/> + <MediaType match='default' select='false'/> + <URI append='none' priority='2'>http://authn.fullxri.com/authentication/</URI> + <URI append='none' priority='1'>https://authn.fullxri.com/authentication/</URI> + </Service> + <Service priority='10'> + <Type select='true'>xri://+i-service*(+contact)*($v*1.0)</Type> + <Type match='null' select='false'/> + <Path select='true'>(+contact)</Path> + <Path match='null' select='false'/> + <MediaType match='default' select='false'/> + <URI append='qxri'>http://contact.fullxri.com/contact/</URI> + </Service> + <KeyInfo xmlns='http://www.w3.org/2000/09/xmldsig#'> + <X509Data> + <X509Certificate> +MIIExzCCA6+gAwIBAgIJAM+MlFr0Sth6MA0GCSqGSIb3DQEBBQUAMIGdMR8wHQYD +VQQDExZTdXBlcnZpbGxhaW46IFRoZSBSb290MQswCQYDVQQGEwJVUzERMA8GA1UE +CBMITmV3IFlvcmsxDzANBgNVBAcTBkdvdGhhbTEgMB4GA1UEChMXU3VwZXJ2aWxs +YWluIFVuaXZlcnNpdHkxJzAlBgkqhkiG9w0BCQEWGHBlbmd1aW5Ac3VwZXJ2aWxs +YWluLmVkdTAeFw0wNjA4MTcxOTU5NTNaFw0xMTA4MTYxOTU5NTNaMIGdMR8wHQYD +VQQDExZTdXBlcnZpbGxhaW46IFRoZSBSb290MQswCQYDVQQGEwJVUzERMA8GA1UE +CBMITmV3IFlvcmsxDzANBgNVBAcTBkdvdGhhbTEgMB4GA1UEChMXU3VwZXJ2aWxs +YWluIFVuaXZlcnNpdHkxJzAlBgkqhkiG9w0BCQEWGHBlbmd1aW5Ac3VwZXJ2aWxs +YWluLmVkdTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAL6uFqas4dK6 +A2wTZL0viRQNJrPyFnFBDSZGib/2ijhgzed/vvmZIBM9sFpwahcuR5hvyKUe37/c +/RSZXoNDi/eiNOx4qb0l9UB6bd8qvc4V1PnLE7L+ZYcmwrvTKm4x8qXMgEv1wca2 +FPsreHNPdLiTUZ8v0tDTWi3Mgi7y47VTzJaTkcfmO1nL6xAtln5sLdH0PbMM3LAp +T1d3nwI3VdbhqqZ+6+OKEuC8gk5iH4lfrbr6C9bYS6vzIKrotHpZ3N2aIC3NMjJD +PMw/mfCuADfRNlHXgZW+0zyUkwGTMDea8qgsoAMWJGdeTIw8I1I3RhnbgLzdsNQl +b/1ZXx1uJRUCAwEAAaOCAQYwggECMB0GA1UdDgQWBBQe+xSjYTrlfraJARjMxscb +j36jvDCB0gYDVR0jBIHKMIHHgBQe+xSjYTrlfraJARjMxscbj36jvKGBo6SBoDCB +nTEfMB0GA1UEAxMWU3VwZXJ2aWxsYWluOiBUaGUgUm9vdDELMAkGA1UEBhMCVVMx +ETAPBgNVBAgTCE5ldyBZb3JrMQ8wDQYDVQQHEwZHb3RoYW0xIDAeBgNVBAoTF1N1 +cGVydmlsbGFpbiBVbml2ZXJzaXR5MScwJQYJKoZIhvcNAQkBFhhwZW5ndWluQHN1 +cGVydmlsbGFpbi5lZHWCCQDPjJRa9ErYejAMBgNVHRMEBTADAQH/MA0GCSqGSIb3 +DQEBBQUAA4IBAQC4SPBDGYAxfbXd8N5OvG0drM7a5hjXfcCZpiILlPSRpxp79yh7 +I5vVWxBxUfolwbei7PTBVy7CE27SUbSICeqWjcDCfjNjiZk6mLS80rm/TdLrHSyM ++Ujlw9MGcBGaLI+sdziDUMtTQDpeAyQTaGVbh1mx5874Hlo1VXqGYNo0RwR+iLfs +x48VuO6GbWVyxtktkE2ypz1KLWiyI056YynydRvuBCBHeRqGUixPlH9CrmeSCP2S +sfbiKnMOGXjIYbvbsTAMdW2iqg6IWa/fgxhvZoAXChM9bkhisJQc0qD0J5TJQwgr +uEyb50RJ7DWmXctSC0b3eymZ2lSXxAWNOsNy + </X509Certificate> + </X509Data> + </KeyInfo> +</XRD>"; + this.MockResponder.RegisterMockXrdsResponses(new Dictionary<string, string> { + { "https://xri.net/@llli?_xrd_r=application/xrd%2Bxml;sep=false", llliResponse }, + { "https://xri.net/@llli*area?_xrd_r=application/xrd%2Bxml;sep=false", llliAreaResponse }, + { "https://xri.net/@llli*area*canada.unattached?_xrd_r=application/xrd%2Bxml;sep=false", llliAreaCanadaUnattachedResponse }, + { "https://xri.net/@llli*area*canada.unattached*ada?_xrd_r=application/xrd%2Bxml;sep=false", llliAreaCanadaUnattachedAdaResponse }, + { "https://xri.net/=Web?_xrd_r=application/xrd%2Bxml;sep=false", webResponse }, + }); + this.VerifyCanonicalId("@llli", "@!72CD.A072.157E.A9C6"); + this.VerifyCanonicalId("@llli*area", "@!72CD.A072.157E.A9C6!0000.0000.3B9A.CA0C"); + this.VerifyCanonicalId("@llli*area*canada.unattached", "@!72CD.A072.157E.A9C6!0000.0000.3B9A.CA0C!0000.0000.3B9A.CA41"); + this.VerifyCanonicalId("@llli*area*canada.unattached*ada", "@!72CD.A072.157E.A9C6!0000.0000.3B9A.CA0C!0000.0000.3B9A.CA41!0000.0000.3B9A.CA01"); + this.VerifyCanonicalId("=Web", "=!91F2.8153.F600.AE24"); + } + + [TestCase] + public void DiscoveryCommunityInameDelegateWithoutCanonicalID() { + this.MockResponder.RegisterMockXrdsResponses(new Dictionary<string, string> { + { "https://xri.net/=Web*andrew.arnott?_xrd_r=application/xrd%2Bxml;sep=false", @"<?xml version='1.0' encoding='UTF-8'?> +<XRD xmlns='xri://$xrd*($v*2.0)'> + <Query>*andrew.arnott</Query> + <Status cid='absent' code='100'>Success</Status> + <ServerStatus code='100'>Success</ServerStatus> + <Expires>2008-07-14T03:30:59.722Z</Expires> + <ProviderID>=!91F2.8153.F600.AE24</ProviderID> + <Service> + <Type select='true'>http://openid.net/signon/1.0</Type> + <Path select='true'>(+login)</Path> + <Path match='default'/> + <MediaType match='default'/> + <URI append='none' priority='2'>http://www.myopenid.com/server</URI> + <openid:Delegate xmlns:openid='http://openid.net/xmlns/1.0'>http://blog.nerdbank.net</openid:Delegate> + </Service> + <Service> + <ProviderID>@!7F6F.F50.A4E4.1133</ProviderID> + <Type select='true'>xri://+i-service*(+contact)*($v*1.0)</Type> + <Type match='null'/> + <Path select='true'>(+contact)</Path> + <Path match='null'/> + <MediaType match='default'/> + <URI append='qxri'>http://contact.freexri.com/contact/</URI> + </Service> + <Service> + <ProviderID>@!7F6F.F50.A4E4.1133</ProviderID> + <Type select='true'>xri://+i-service*(+forwarding)*($v*1.0)</Type> + <Path select='true'>(+index)</Path> + <Path match='default'/> + <MediaType match='default'/> + <URI append='qxri'>http://forwarding.freexri.com/forwarding/</URI> + </Service> + <Service> + <ProviderID>@!7F6F.F50.A4E4.1133</ProviderID> + <Type select='true'>http://openid.net/signon/1.0</Type> + <Path select='true'>(+login)</Path> + <Path match='default'/> + <MediaType match='default'/> + <URI append='none' priority='2'>http://authn.freexri.com/authentication/</URI> + <URI append='none' priority='1'>https://authn.freexri.com/authentication/</URI> + </Service> + <ServedBy>OpenXRI</ServedBy> +</XRD>" }, + { "https://xri.net/@id*andrewarnott?_xrd_r=application/xrd%2Bxml;sep=false", @"<?xml version='1.0' encoding='UTF-8'?> +<XRD xmlns='xri://$xrd*($v*2.0)'> + <Query>*andrewarnott</Query> + <Status cid='absent' code='100'>Success</Status> + <ServerStatus code='100'>Success</ServerStatus> + <Expires>2008-07-14T03:31:00.466Z</Expires> + <ProviderID>@!B1E8.C27B.E41C.25C3</ProviderID> + <Service> + <Type select='true'>http://openid.net/signon/1.0</Type> + <Path select='true'>(+login)</Path> + <Path match='default'/> + <MediaType match='default'/> + <URI append='none' priority='2'>http://www.myopenid.com/server</URI> + <openid:Delegate xmlns:openid='http://openid.net/xmlns/1.0'>http://blog.nerdbank.net</openid:Delegate> + </Service> + <Service> + <ProviderID>@!7F6F.F50.A4E4.1133</ProviderID> + <Type select='true'>xri://+i-service*(+contact)*($v*1.0)</Type> + <Type match='null'/> + <Path select='true'>(+contact)</Path> + <Path match='null'/> + <MediaType match='default'/> + <URI append='qxri'>http://contact.freexri.com/contact/</URI> + </Service> + <Service> + <ProviderID>@!7F6F.F50.A4E4.1133</ProviderID> + <Type select='true'>xri://+i-service*(+forwarding)*($v*1.0)</Type> + <Path select='true'>(+index)</Path> + <Path match='default'/> + <MediaType match='default'/> + <URI append='qxri'>http://forwarding.freexri.com/forwarding/</URI> + </Service> + <ServedBy>OpenXRI</ServedBy> +</XRD>" }, + }); + // Consistent with spec section 7.3.2.3, we do not permit + // delegation on XRI discovery when there is no CanonicalID present. + this.VerifyCanonicalId("=Web*andrew.arnott", null); + this.VerifyCanonicalId("@id*andrewarnott", null); + } + + private IdentifierDiscoveryResult VerifyCanonicalId(Identifier iname, string expectedClaimedIdentifier) { + var se = this.Discover(iname).FirstOrDefault(); + if (expectedClaimedIdentifier != null) { + Assert.IsNotNull(se); + Assert.AreEqual(expectedClaimedIdentifier, se.ClaimedIdentifier.ToString(), "i-name {0} discovery resulted in unexpected CanonicalId", iname); + Assert.IsTrue(se.Capabilities.Count > 0); + } else { + Assert.IsNull(se); + } + return se; + } + } +} diff --git a/src/DotNetOpenAuth.Test/OpenId/Extensions/AttributeExchange/AttributeExchangeRoundtripTests.cs b/src/DotNetOpenAuth.Test/OpenId/Extensions/AttributeExchange/AttributeExchangeRoundtripTests.cs index fa05e94..3433cfa 100644 --- a/src/DotNetOpenAuth.Test/OpenId/Extensions/AttributeExchange/AttributeExchangeRoundtripTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/Extensions/AttributeExchange/AttributeExchangeRoundtripTests.cs @@ -7,16 +7,16 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions { using DotNetOpenAuth.OpenId; using DotNetOpenAuth.OpenId.Extensions.AttributeExchange; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; - [TestClass] + [TestFixture] public class AttributeExchangeRoundtripTests : OpenIdTestBase { private const string NicknameTypeUri = WellKnownAttributes.Name.Alias; private const string EmailTypeUri = WellKnownAttributes.Contact.Email; private const string IncrementingAttribute = "http://incatt"; private int incrementingAttributeValue = 1; - [TestMethod] + [TestCase] public void Fetch() { var request = new FetchRequest(); request.Attributes.Add(new AttributeRequest(NicknameTypeUri)); @@ -29,7 +29,7 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions { ExtensionTestUtilities.Roundtrip(Protocol.Default, new[] { request }, new[] { response }); } - [TestMethod] + [TestCase] public void Store() { var request = new StoreRequest(); var newAttribute = new AttributeValues( diff --git a/src/DotNetOpenAuth.Test/OpenId/Extensions/AttributeExchange/AttributeRequestTests.cs b/src/DotNetOpenAuth.Test/OpenId/Extensions/AttributeExchange/AttributeRequestTests.cs index 48b5727..5cc8ec1 100644 --- a/src/DotNetOpenAuth.Test/OpenId/Extensions/AttributeExchange/AttributeRequestTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/Extensions/AttributeExchange/AttributeRequestTests.cs @@ -8,11 +8,11 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions { using System; using DotNetOpenAuth.OpenId.Extensions.AttributeExchange; using DotNetOpenAuth.Test.OpenId; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; - [TestClass] + [TestFixture] public class AttributeRequestTests : OpenIdTestBase { - [TestMethod] + [TestCase] public void CtorDefault() { AttributeRequest req = new AttributeRequest(); Assert.AreEqual(1, req.Count); @@ -20,27 +20,27 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions { Assert.IsFalse(req.IsRequired); } - [TestMethod, ExpectedException(typeof(ArgumentException))] + [TestCase, ExpectedException(typeof(ArgumentException))] public void CtorEmptyTypeUri() { new AttributeRequest(string.Empty); } - [TestMethod, ExpectedException(typeof(ArgumentException))] + [TestCase, ExpectedException(typeof(ArgumentException))] public void CtorNullTypeUri() { new AttributeRequest(null); } - [TestMethod, ExpectedException(typeof(ArgumentOutOfRangeException))] + [TestCase, ExpectedException(typeof(ArgumentOutOfRangeException))] public void CtorCountZero() { new AttributeRequest(WellKnownAttributes.Contact.Email, false, 0); } - [TestMethod, ExpectedException(typeof(ArgumentOutOfRangeException))] + [TestCase, ExpectedException(typeof(ArgumentOutOfRangeException))] public void CtorCountNegative() { new AttributeRequest(WellKnownAttributes.Contact.Email, false, -1); } - [TestMethod] + [TestCase] public void CtorFull() { var req = new AttributeRequest(WellKnownAttributes.Contact.Email, true, 5); Assert.AreEqual(WellKnownAttributes.Contact.Email, req.TypeUri); @@ -48,19 +48,19 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions { Assert.AreEqual(5, req.Count); } - [TestMethod, ExpectedException(typeof(ArgumentOutOfRangeException))] + [TestCase, ExpectedException(typeof(ArgumentOutOfRangeException))] public void SetCountZero() { var req = new AttributeRequest(); req.Count = 0; } - [TestMethod, ExpectedException(typeof(ArgumentOutOfRangeException))] + [TestCase, ExpectedException(typeof(ArgumentOutOfRangeException))] public void SetCountNegative() { var req = new AttributeRequest(); req.Count = -1; } - [TestMethod] + [TestCase] public void EqualityTests() { var req1 = new AttributeRequest(); var req2 = new AttributeRequest(); diff --git a/src/DotNetOpenAuth.Test/OpenId/Extensions/AttributeExchange/AttributeValuesTests.cs b/src/DotNetOpenAuth.Test/OpenId/Extensions/AttributeExchange/AttributeValuesTests.cs index 1f7e17c..6c28461 100644 --- a/src/DotNetOpenAuth.Test/OpenId/Extensions/AttributeExchange/AttributeValuesTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/Extensions/AttributeExchange/AttributeValuesTests.cs @@ -10,11 +10,11 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions.AttributeExchange { using System.Linq; using System.Text; using DotNetOpenAuth.OpenId.Extensions.AttributeExchange; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; - [TestClass] + [TestFixture] public class AttributeValuesTests : OpenIdTestBase { - [TestMethod] + [TestCase] public void Ctor() { var att = new AttributeValues(); Assert.IsNull(att.TypeUri); @@ -37,7 +37,7 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions.AttributeExchange { /// <summary> /// Verifies the Equals method. /// </summary> - [TestMethod] + [TestCase] public void EqualityTests() { var att1 = new AttributeValues(); var att2 = new AttributeValues(); diff --git a/src/DotNetOpenAuth.Test/OpenId/Extensions/AttributeExchange/FetchRequestTests.cs b/src/DotNetOpenAuth.Test/OpenId/Extensions/AttributeExchange/FetchRequestTests.cs index 43eba3f..2388798 100644 --- a/src/DotNetOpenAuth.Test/OpenId/Extensions/AttributeExchange/FetchRequestTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/Extensions/AttributeExchange/FetchRequestTests.cs @@ -9,35 +9,35 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions { using System.IO; using DotNetOpenAuth.OpenId.Extensions.AttributeExchange; using DotNetOpenAuth.Test.OpenId; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; - [TestClass] + [TestFixture] public class FetchRequestTests : OpenIdTestBase { - [TestMethod, ExpectedException(typeof(ArgumentNullException))] + [TestCase, ExpectedException(typeof(ArgumentNullException))] public void AddAttributeRequestNull() { new FetchRequest().Attributes.Add(null); } - [TestMethod] + [TestCase] public void AddAttributeRequest() { var req = new FetchRequest(); req.Attributes.Add(new AttributeRequest() { TypeUri = "http://someUri" }); } - [TestMethod] + [TestCase] public void AddAttributeRequestStrangeUri() { var req = new FetchRequest(); req.Attributes.Add(new AttributeRequest() { TypeUri = "=someUri*who*knows*but*this*is*legal" }); } - [TestMethod, ExpectedException(typeof(ArgumentException))] + [TestCase, ExpectedException(typeof(ArgumentException))] public void AddAttributeRequestAgain() { var req = new FetchRequest(); req.Attributes.Add(new AttributeRequest() { TypeUri = "http://UriTwice" }); req.Attributes.Add(new AttributeRequest() { TypeUri = "http://UriTwice" }); } - [TestMethod] + [TestCase] public void RespondSimpleValue() { var req = new AttributeRequest(); req.TypeUri = "http://someType"; @@ -47,7 +47,7 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions { Assert.AreEqual("value", resp.Values[0]); } - [TestMethod] + [TestCase] public void RespondTwoValues() { var req = new AttributeRequest(); req.TypeUri = "http://someType"; @@ -59,7 +59,7 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions { Assert.AreEqual("value2", resp.Values[1]); } - [TestMethod, ExpectedException(typeof(ArgumentException))] + [TestCase, ExpectedException(typeof(ArgumentException))] public void RespondTooManyValues() { var req = new AttributeRequest(); req.TypeUri = "http://someType"; @@ -67,7 +67,7 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions { req.Respond("value1", "value2"); } - [TestMethod, ExpectedException(typeof(ArgumentNullException))] + [TestCase, ExpectedException(typeof(ArgumentNullException))] public void RespondNull() { var req = new AttributeRequest(); req.TypeUri = "http://someType"; @@ -75,7 +75,7 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions { req.Respond(null); } - [TestMethod] + [TestCase] public void EqualityTests() { var req1 = new FetchRequest(); var req2 = new FetchRequest(); @@ -100,7 +100,7 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions { /// <summary> /// Verifies that the class is serializable. /// </summary> - [TestMethod] + [TestCase] public void Serializable() { var fetch = new FetchRequest(); fetch.Attributes.AddRequired("http://someAttribute"); diff --git a/src/DotNetOpenAuth.Test/OpenId/Extensions/AttributeExchange/FetchResponseTests.cs b/src/DotNetOpenAuth.Test/OpenId/Extensions/AttributeExchange/FetchResponseTests.cs index d7082c3..c545a46 100644 --- a/src/DotNetOpenAuth.Test/OpenId/Extensions/AttributeExchange/FetchResponseTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/Extensions/AttributeExchange/FetchResponseTests.cs @@ -9,37 +9,37 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions { using System.IO; using DotNetOpenAuth.OpenId.Extensions.AttributeExchange; using DotNetOpenAuth.Test.OpenId; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; - [TestClass] + [TestFixture] public class FetchResponseTests : OpenIdTestBase { - [TestMethod] + [TestCase] public void AddAttribute() { var response = new FetchResponse(); response.Attributes.Add(new AttributeValues("http://someattribute", "Value1")); } - [TestMethod] + [TestCase] public void AddTwoAttributes() { var response = new FetchResponse(); response.Attributes.Add(new AttributeValues("http://someattribute", "Value1")); response.Attributes.Add(new AttributeValues("http://someOtherAttribute", "Value2")); } - [TestMethod, ExpectedException(typeof(ArgumentException))] + [TestCase, ExpectedException(typeof(ArgumentException))] public void AddAttributeTwice() { var response = new FetchResponse(); response.Attributes.Add(new AttributeValues("http://someattribute", "Value1")); response.Attributes.Add(new AttributeValues("http://someattribute", "Value1")); } - [TestMethod, ExpectedException(typeof(ArgumentNullException))] + [TestCase, ExpectedException(typeof(ArgumentNullException))] public void AddAttributeNull() { var response = new FetchResponse(); response.Attributes.Add(null); } - [TestMethod] + [TestCase] public void GetAttributeValue() { var response = new FetchResponse(); @@ -55,7 +55,7 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions { Assert.AreEqual("a", response.GetAttributeValue("http://someattribute3")); } - [TestMethod] + [TestCase] public void EqualityTests() { var response1 = new FetchResponse(); var response2 = new FetchResponse(); @@ -80,7 +80,7 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions { /// <summary> /// Verifies that the class is serializable. /// </summary> - [TestMethod] + [TestCase] public void Serializable() { var fetch = new FetchResponse(); fetch.Attributes.Add("http://someAttribute", "val1", "val2"); diff --git a/src/DotNetOpenAuth.Test/OpenId/Extensions/AttributeExchange/StoreRequestTests.cs b/src/DotNetOpenAuth.Test/OpenId/Extensions/AttributeExchange/StoreRequestTests.cs index b11c469..fc486aa 100644 --- a/src/DotNetOpenAuth.Test/OpenId/Extensions/AttributeExchange/StoreRequestTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/Extensions/AttributeExchange/StoreRequestTests.cs @@ -12,14 +12,14 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions.AttributeExchange { using System.Text; using DotNetOpenAuth.Messaging; using DotNetOpenAuth.OpenId.Extensions.AttributeExchange; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; - [TestClass] + [TestFixture] public class StoreRequestTests { /// <summary> /// Verifies the constructor behavior. /// </summary> - [TestMethod] + [TestCase] public void Ctor() { var req = new StoreRequest(); Assert.IsFalse(req.Attributes.Any()); @@ -28,7 +28,7 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions.AttributeExchange { /// <summary> /// Verifies the AddAttribute method. /// </summary> - [TestMethod] + [TestCase] public void AddAttributeByValue() { var req = new StoreRequest(); AttributeValues value = new AttributeValues(); @@ -39,7 +39,7 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions.AttributeExchange { /// <summary> /// Verifies the AddAttribute method. /// </summary> - [TestMethod] + [TestCase] public void AddAttributeByPrimitives() { var req = new StoreRequest(); req.Attributes.Add("http://att1", "value1", "value2"); @@ -51,7 +51,7 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions.AttributeExchange { /// <summary> /// Verifies the Equals method. /// </summary> - [TestMethod] + [TestCase] public void EqualityTests() { var req1 = new StoreRequest(); var req2 = new StoreRequest(); @@ -71,7 +71,7 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions.AttributeExchange { /// <summary> /// Verifies that the class is serializable. /// </summary> - [TestMethod] + [TestCase] public void Serializable() { var store = new StoreRequest(); store.Attributes.Add("http://someAttribute", "val1", "val2"); diff --git a/src/DotNetOpenAuth.Test/OpenId/Extensions/AttributeExchange/StoreResponseTests.cs b/src/DotNetOpenAuth.Test/OpenId/Extensions/AttributeExchange/StoreResponseTests.cs index 4e432e1..564ef7f 100644 --- a/src/DotNetOpenAuth.Test/OpenId/Extensions/AttributeExchange/StoreResponseTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/Extensions/AttributeExchange/StoreResponseTests.cs @@ -7,14 +7,14 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions.AttributeExchange { using System.IO; using DotNetOpenAuth.OpenId.Extensions.AttributeExchange; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; - [TestClass] + [TestFixture] public class StoreResponseTests { /// <summary> /// Verifies the constructor's behavior. /// </summary> - [TestMethod] + [TestCase] public void Ctor() { var response = new StoreResponse(); Assert.IsTrue(response.Succeeded, "The default status should be Succeeded."); @@ -28,7 +28,7 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions.AttributeExchange { /// <summary> /// Verifies the Equals method. /// </summary> - [TestMethod] + [TestCase] public void EqualityTests() { var response1 = new StoreResponse(); var response2 = new StoreResponse(); @@ -51,7 +51,7 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions.AttributeExchange { /// <summary> /// Verifies that the class is serializable. /// </summary> - [TestMethod] + [TestCase] public void Serializable() { var store = new StoreResponse(); store.Succeeded = false; diff --git a/src/DotNetOpenAuth.Test/OpenId/Extensions/ExtensionsInteropHelperOPTests.cs b/src/DotNetOpenAuth.Test/OpenId/Extensions/ExtensionsInteropHelperOPTests.cs index 1fb3160..1b1dd49 100644 --- a/src/DotNetOpenAuth.Test/OpenId/Extensions/ExtensionsInteropHelperOPTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/Extensions/ExtensionsInteropHelperOPTests.cs @@ -14,14 +14,14 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions { using DotNetOpenAuth.OpenId.Extensions.SimpleRegistration; using DotNetOpenAuth.OpenId.Messages; using DotNetOpenAuth.OpenId.Provider; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; - [TestClass] + [TestFixture] public class ExtensionsInteropHelperOPTests : OpenIdTestBase { private AuthenticationRequest request; private IList<IExtensionMessage> extensions; - [TestInitialize] + [SetUp] public override void SetUp() { base.SetUp(); @@ -36,7 +36,7 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions { /// <summary> /// Verifies no extensions appear as no extensions /// </summary> - [TestMethod] + [TestCase] public void NoRequestedExtensions() { var sreg = ExtensionsInteropHelper.UnifyExtensionsAsSreg(this.request); Assert.IsNull(sreg); @@ -51,7 +51,7 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions { Assert.AreSame(sregResponse, extensions.Single()); } - [TestMethod] + [TestCase] public void NegativeResponse() { this.request.IsAuthenticated = false; ExtensionsInteropHelper.ConvertSregToMatchRequest(this.request); @@ -60,7 +60,7 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions { /// <summary> /// Verifies sreg coming in is seen as sreg. /// </summary> - [TestMethod] + [TestCase] public void UnifyExtensionsAsSregWithSreg() { var sregInjected = new ClaimsRequest(DotNetOpenAuth.OpenId.Extensions.SimpleRegistration.Constants.sreg_ns) { Nickname = DemandLevel.Request, @@ -81,7 +81,7 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions { /// <summary> /// Verifies AX coming in looks like sreg. /// </summary> - [TestMethod] + [TestCase] public void UnifyExtensionsAsSregWithAX() { this.ParameterizedAXTest(AXAttributeFormats.AXSchemaOrg); } @@ -89,7 +89,7 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions { /// <summary> /// Verifies AX coming in looks like sreg. /// </summary> - [TestMethod] + [TestCase] public void UnifyExtensionsAsSregWithAXSchemaOpenIdNet() { this.ParameterizedAXTest(AXAttributeFormats.SchemaOpenIdNet); } @@ -97,7 +97,7 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions { /// <summary> /// Verifies sreg and AX in one request has a preserved sreg request. /// </summary> - [TestMethod] + [TestCase] public void UnifyExtensionsAsSregWithBothSregAndAX() { var sregInjected = new ClaimsRequest(DotNetOpenAuth.OpenId.Extensions.SimpleRegistration.Constants.sreg_ns) { Nickname = DemandLevel.Request, diff --git a/src/DotNetOpenAuth.Test/OpenId/Extensions/ExtensionsInteropHelperRPRequestTests.cs b/src/DotNetOpenAuth.Test/OpenId/Extensions/ExtensionsInteropHelperRPRequestTests.cs index 7edec09..44a629a 100644 --- a/src/DotNetOpenAuth.Test/OpenId/Extensions/ExtensionsInteropHelperRPRequestTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/Extensions/ExtensionsInteropHelperRPRequestTests.cs @@ -5,20 +5,21 @@ //----------------------------------------------------------------------- namespace DotNetOpenAuth.Test.OpenId.Extensions { + using System.Collections.ObjectModel; using System.Linq; using DotNetOpenAuth.OpenId; using DotNetOpenAuth.OpenId.Extensions; using DotNetOpenAuth.OpenId.Extensions.AttributeExchange; using DotNetOpenAuth.OpenId.Extensions.SimpleRegistration; using DotNetOpenAuth.OpenId.RelyingParty; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; - [TestClass] + [TestFixture] public class ExtensionsInteropHelperRPRequestTests : OpenIdTestBase { private AuthenticationRequest authReq; private ClaimsRequest sreg; - [TestInitialize] + [SetUp] public override void SetUp() { base.SetUp(); @@ -41,7 +42,7 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions { /// <summary> /// Verifies that without an Sreg extension to copy from, no AX extension request is added. /// </summary> - [TestMethod] + [TestCase] public void SpreadSregToAXNoExtensions() { ExtensionsInteropHelper.SpreadSregToAX(this.authReq, AXAttributeFormats.AXSchemaOrg); Assert.AreEqual(0, this.authReq.AppliedExtensions.Count()); @@ -50,7 +51,7 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions { /// <summary> /// Verifies that Sreg requests are correctly copied to axschema.org AX requests. /// </summary> - [TestMethod] + [TestCase] public void SpreadSregToAXBasic() { this.authReq.AddExtension(this.sreg); ExtensionsInteropHelper.SpreadSregToAX(this.authReq, AXAttributeFormats.AXSchemaOrg); @@ -69,7 +70,7 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions { /// <summary> /// Verifies that sreg can spread to multiple AX schemas. /// </summary> - [TestMethod] + [TestCase] public void SpreadSregToAxMultipleSchemas() { this.authReq.AddExtension(this.sreg); ExtensionsInteropHelper.SpreadSregToAX(this.authReq, AXAttributeFormats.AXSchemaOrg | AXAttributeFormats.SchemaOpenIdNet); @@ -82,7 +83,7 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions { /// <summary> /// Verifies no spread if the OP advertises sreg support. /// </summary> - [TestMethod] + [TestCase] public void SpreadSregToAxNoOpIfOPSupportsSreg() { this.authReq.AddExtension(this.sreg); this.InjectAdvertisedTypeUri(DotNetOpenAuth.OpenId.Extensions.SimpleRegistration.Constants.sreg_ns); @@ -93,7 +94,7 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions { /// <summary> /// Verifies a targeted AX request if the OP advertises a recognized type URI format. /// </summary> - [TestMethod] + [TestCase] public void SpreadSregToAxTargetedAtOPFormat() { this.authReq.AddExtension(this.sreg); this.InjectAdvertisedTypeUri(WellKnownAttributes.Name.FullName); @@ -106,7 +107,7 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions { /// <summary> /// Verifies that TransformAXFormat correctly translates AX schema Type URIs. /// </summary> - [TestMethod] + [TestCase] public void TransformAXFormatTest() { Assert.AreEqual(WellKnownAttributes.Name.Alias, ExtensionsInteropHelper_Accessor.TransformAXFormat(WellKnownAttributes.Name.Alias, AXAttributeFormats.AXSchemaOrg)); Assert.AreEqual("http://schema.openid.net/namePerson/friendly", ExtensionsInteropHelper_Accessor.TransformAXFormat(WellKnownAttributes.Name.Alias, AXAttributeFormats.SchemaOpenIdNet)); @@ -118,11 +119,9 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions { /// </summary> /// <param name="typeUri">The type URI.</param> private void InjectAdvertisedTypeUri(string typeUri) { - var serviceEndpoint = ServiceEndpoint_Accessor.AttachShadow(((ServiceEndpoint)this.authReq.Provider)); - serviceEndpoint.ProviderDescription = ProviderEndpointDescription_Accessor.AttachShadow( - new ProviderEndpointDescription( - serviceEndpoint.ProviderDescription.Endpoint, - serviceEndpoint.ProviderDescription.Capabilities.Concat(new[] { typeUri }))); + var serviceEndpoint = (IdentifierDiscoveryResult)this.authReq.Provider; + serviceEndpoint.SetCapabilitiesForTestHook( + new ReadOnlyCollection<string>(serviceEndpoint.Capabilities.Concat(new[] { typeUri }).ToList())); } } } diff --git a/src/DotNetOpenAuth.Test/OpenId/Extensions/ExtensionsInteropHelperRPResponseTests.cs b/src/DotNetOpenAuth.Test/OpenId/Extensions/ExtensionsInteropHelperRPResponseTests.cs index 655e616..7b528d0 100644 --- a/src/DotNetOpenAuth.Test/OpenId/Extensions/ExtensionsInteropHelperRPResponseTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/Extensions/ExtensionsInteropHelperRPResponseTests.cs @@ -13,14 +13,14 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions { using DotNetOpenAuth.OpenId.Extensions.SimpleRegistration; using DotNetOpenAuth.OpenId.Messages; using DotNetOpenAuth.OpenId.RelyingParty; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; - [TestClass] + [TestFixture] public class ExtensionsInteropHelperRPResponseTests : OpenIdTestBase { private IAuthenticationResponse response; private IList<IExtensionMessage> extensions; - [TestInitialize] + [SetUp] public override void SetUp() { base.SetUp(); @@ -32,7 +32,7 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions { /// <summary> /// Verifies that with no extensions present, UnifyExtensionsAsSreg returns an empty ClaimsResponse. /// </summary> - [TestMethod] + [TestCase] public void UnifyExtensionsAsSregNoExtensions() { var sreg = ExtensionsInteropHelper.UnifyExtensionsAsSreg(this.response, true); Assert.IsNotNull(sreg); @@ -42,7 +42,7 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions { /// <summary> /// Verifies that with sreg and AX extensions present, the sreg extension is returned. /// </summary> - [TestMethod] + [TestCase] public void UnifyExtensionsAsSregWithSreg() { var sregInjected = new ClaimsResponse { Nickname = "andy", @@ -59,7 +59,7 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions { /// <summary> /// Verifies UnifyExtensionsAsSreg correctly converts AX to sreg. /// </summary> - [TestMethod] + [TestCase] public void UnifyExtensionsAsSregFromAXSchemaOrg() { var axInjected = new FetchResponse(); axInjected.Attributes.Add(WellKnownAttributes.Name.Alias, "nate"); @@ -71,7 +71,7 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions { /// <summary> /// Verifies UnifyExtensionsAsSreg correctly converts AX in a non-standard format to sreg. /// </summary> - [TestMethod] + [TestCase] public void UnifyExtensionsasSregFromSchemaOpenIdNet() { var axInjected = new FetchResponse(); axInjected.Attributes.Add(ExtensionsInteropHelper_Accessor.TransformAXFormat(WellKnownAttributes.Name.Alias, AXAttributeFormats.SchemaOpenIdNet), "nate"); diff --git a/src/DotNetOpenAuth.Test/OpenId/Extensions/ProviderAuthenticationPolicy/PapeRoundTripTests.cs b/src/DotNetOpenAuth.Test/OpenId/Extensions/ProviderAuthenticationPolicy/PapeRoundTripTests.cs index 75737ab..6f35f85 100644 --- a/src/DotNetOpenAuth.Test/OpenId/Extensions/ProviderAuthenticationPolicy/PapeRoundTripTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/Extensions/ProviderAuthenticationPolicy/PapeRoundTripTests.cs @@ -9,18 +9,18 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions.ProviderAuthenticationPolicy { using DotNetOpenAuth.OpenId; using DotNetOpenAuth.OpenId.Extensions.ProviderAuthenticationPolicy; using DotNetOpenAuth.Test.OpenId.Extensions; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; - [TestClass] + [TestFixture] public class PapeRoundTripTests : OpenIdTestBase { - [TestMethod] + [TestCase] public void Trivial() { var request = new PolicyRequest(); var response = new PolicyResponse(); ExtensionTestUtilities.Roundtrip(Protocol.Default, new[] { request }, new[] { response }); } - [TestMethod] + [TestCase] public void Full() { var request = new PolicyRequest(); request.MaximumAuthenticationAge = TimeSpan.FromMinutes(10); diff --git a/src/DotNetOpenAuth.Test/OpenId/Extensions/ProviderAuthenticationPolicy/PolicyRequestTests.cs b/src/DotNetOpenAuth.Test/OpenId/Extensions/ProviderAuthenticationPolicy/PolicyRequestTests.cs index 303c747..d75eccc 100644 --- a/src/DotNetOpenAuth.Test/OpenId/Extensions/ProviderAuthenticationPolicy/PolicyRequestTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/Extensions/ProviderAuthenticationPolicy/PolicyRequestTests.cs @@ -13,11 +13,11 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions.ProviderAuthenticationPolicy { using DotNetOpenAuth.Messaging; using DotNetOpenAuth.Messaging.Reflection; using DotNetOpenAuth.OpenId.Extensions.ProviderAuthenticationPolicy; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; - [TestClass] + [TestFixture] public class PolicyRequestTests : OpenIdTestBase { - [TestMethod] + [TestCase] public void Ctor() { PolicyRequest req = new PolicyRequest(); Assert.IsNull(req.MaximumAuthenticationAge); @@ -25,7 +25,7 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions.ProviderAuthenticationPolicy { Assert.AreEqual(0, req.PreferredPolicies.Count); } - [TestMethod] + [TestCase] public void MaximumAuthenticationAgeTest() { PolicyRequest req = new PolicyRequest(); req.MaximumAuthenticationAge = TimeSpan.FromHours(1); @@ -35,7 +35,7 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions.ProviderAuthenticationPolicy { Assert.IsNull(req.MaximumAuthenticationAge); } - [TestMethod] + [TestCase] public void AddPolicies() { PolicyRequest resp = new PolicyRequest(); resp.PreferredPolicies.Add(AuthenticationPolicies.MultiFactor); @@ -45,7 +45,7 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions.ProviderAuthenticationPolicy { Assert.AreEqual(AuthenticationPolicies.PhishingResistant, resp.PreferredPolicies[1]); } - [TestMethod] + [TestCase] public void AddPolicyMultipleTimes() { // Although this isn't really the desired behavior (we'd prefer to see an // exception thrown), since we're using a List<string> internally we can't @@ -57,7 +57,7 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions.ProviderAuthenticationPolicy { Assert.AreEqual(2, resp.PreferredPolicies.Count); } - [TestMethod] + [TestCase] public void AddAuthLevelTypes() { PolicyRequest req = new PolicyRequest(); req.PreferredAuthLevelTypes.Add(Constants.AssuranceLevels.NistTypeUri); @@ -65,7 +65,7 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions.ProviderAuthenticationPolicy { Assert.IsTrue(req.PreferredAuthLevelTypes.Contains(Constants.AssuranceLevels.NistTypeUri)); } - [TestMethod] + [TestCase] public void EqualsTest() { PolicyRequest req = new PolicyRequest(); PolicyRequest req2 = new PolicyRequest(); @@ -104,7 +104,7 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions.ProviderAuthenticationPolicy { Assert.AreEqual(req, req2); } - [TestMethod] + [TestCase] public void Serialize() { PolicyRequest req = new PolicyRequest(); IMessageWithEvents reqEvents = req; diff --git a/src/DotNetOpenAuth.Test/OpenId/Extensions/ProviderAuthenticationPolicy/PolicyResponseTests.cs b/src/DotNetOpenAuth.Test/OpenId/Extensions/ProviderAuthenticationPolicy/PolicyResponseTests.cs index e0faaac..7491e21 100644 --- a/src/DotNetOpenAuth.Test/OpenId/Extensions/ProviderAuthenticationPolicy/PolicyResponseTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/Extensions/ProviderAuthenticationPolicy/PolicyResponseTests.cs @@ -12,15 +12,15 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions.ProviderAuthenticationPolicy { using DotNetOpenAuth.Messaging; using DotNetOpenAuth.Messaging.Reflection; using DotNetOpenAuth.OpenId.Extensions.ProviderAuthenticationPolicy; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; - [TestClass] + [TestFixture] public class PolicyResponseTests : OpenIdTestBase { private static readonly DateTime someLocalTime = new DateTime(2008, 1, 1, 1, 1, 1, 0, DateTimeKind.Local); private static readonly DateTime someUtcTime = new DateTime(2008, 1, 1, 1, 1, 1, 0, DateTimeKind.Utc); private static readonly DateTime someUnspecifiedTime = new DateTime(2008, 1, 1, 1, 1, 1, 0, DateTimeKind.Unspecified); - [TestMethod] + [TestCase] public void Ctor() { PolicyResponse resp = new PolicyResponse(); Assert.IsNotNull(resp.ActualPolicies); @@ -29,7 +29,7 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions.ProviderAuthenticationPolicy { Assert.IsNull(resp.NistAssuranceLevel); } - [TestMethod] + [TestCase] public void AddPolicies() { PolicyResponse resp = new PolicyResponse(); resp.ActualPolicies.Add(AuthenticationPolicies.MultiFactor); @@ -39,7 +39,7 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions.ProviderAuthenticationPolicy { Assert.AreEqual(AuthenticationPolicies.PhishingResistant, resp.ActualPolicies[1]); } - [TestMethod] + [TestCase] public void AddPolicyMultipleTimes() { // Although this isn't really the desired behavior (we'd prefer to see an // exception thrown), since we're using a List<string> internally we can't @@ -51,7 +51,7 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions.ProviderAuthenticationPolicy { Assert.AreEqual(2, resp.ActualPolicies.Count); } - [TestMethod] + [TestCase] public void AuthenticationTimeUtcConvertsToUtc() { PolicyResponse resp = new PolicyResponse(); resp.AuthenticationTimeUtc = someLocalTime; @@ -60,20 +60,20 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions.ProviderAuthenticationPolicy { Assert.AreEqual(someLocalTime.ToUniversalTime(), resp.AuthenticationTimeUtc.Value); } - [TestMethod] + [TestCase] public void AuthenticationTimeUtcSetUtc() { PolicyResponse resp = new PolicyResponse(); resp.AuthenticationTimeUtc = someUtcTime; Assert.AreEqual(someUtcTime, resp.AuthenticationTimeUtc); } - [TestMethod, ExpectedException(typeof(ArgumentException))] + [TestCase, ExpectedException(typeof(ArgumentException))] public void AuthenticationTimeUtcSetUnspecified() { PolicyResponse resp = new PolicyResponse(); resp.AuthenticationTimeUtc = someUnspecifiedTime; } - [TestMethod] + [TestCase] public void AuthenticationTimeUtcSetNull() { PolicyResponse resp = new PolicyResponse(); resp.AuthenticationTimeUtc = null; @@ -84,7 +84,7 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions.ProviderAuthenticationPolicy { Assert.IsNull(resp.AuthenticationTimeUtc); } - [TestMethod] + [TestCase] public void NistAssuranceLevelSetVarious() { PolicyResponse resp = new PolicyResponse(); resp.NistAssuranceLevel = NistAssuranceLevel.Level1; @@ -95,7 +95,7 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions.ProviderAuthenticationPolicy { Assert.AreEqual(NistAssuranceLevel.InsufficientForLevel1, resp.NistAssuranceLevel); } - [TestMethod] + [TestCase] public void AssuranceLevels() { PolicyResponse resp = new PolicyResponse(); Assert.AreEqual(0, resp.AssuranceLevels.Count); @@ -108,7 +108,7 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions.ProviderAuthenticationPolicy { Assert.IsNull(resp.NistAssuranceLevel); } - [TestMethod] + [TestCase] public void EqualsTest() { PolicyResponse resp = new PolicyResponse(); PolicyResponse resp2 = new PolicyResponse(); @@ -164,7 +164,7 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions.ProviderAuthenticationPolicy { Assert.AreEqual(resp, resp2); } - [TestMethod] + [TestCase] public void Serialize() { PolicyResponse resp = new PolicyResponse(); IMessageWithEvents respEvents = resp; diff --git a/src/DotNetOpenAuth.Test/OpenId/Extensions/SimpleRegistration/ClaimsRequestTests.cs b/src/DotNetOpenAuth.Test/OpenId/Extensions/SimpleRegistration/ClaimsRequestTests.cs index 3af54d3..f7a948e 100644 --- a/src/DotNetOpenAuth.Test/OpenId/Extensions/SimpleRegistration/ClaimsRequestTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/Extensions/SimpleRegistration/ClaimsRequestTests.cs @@ -8,11 +8,11 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions { using DotNetOpenAuth.Messaging.Reflection; using DotNetOpenAuth.OpenId.Extensions.SimpleRegistration; using DotNetOpenAuth.OpenId.Messages; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; - [TestClass] + [TestFixture] public class ClaimsRequestTests : OpenIdTestBase { - [TestMethod] + [TestCase] public void CreateResponse() { // some unofficial type URIs... this.ParameterizedTypeUriPreservedTest("http://openid.net/sreg/1.0"); @@ -21,7 +21,7 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions { this.ParameterizedTypeUriPreservedTest("http://openid.net/extensions/sreg/1.1"); } - [TestMethod] + [TestCase] public void RequiredOptionalLists() { ClaimsRequest req = new ClaimsRequest(); MessageDictionary dictionary = this.MessageDescriptions.GetAccessor(req); @@ -39,7 +39,7 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions { Assert.AreEqual("nickname,postcode", dictionary["required"]); } - [TestMethod] + [TestCase] public void EqualityTests() { ClaimsRequest req1 = new ClaimsRequest(); ClaimsRequest req2 = new ClaimsRequest(); diff --git a/src/DotNetOpenAuth.Test/OpenId/Extensions/SimpleRegistration/ClaimsResponseTests.cs b/src/DotNetOpenAuth.Test/OpenId/Extensions/SimpleRegistration/ClaimsResponseTests.cs index 6dbfa4f..0bdc36e 100644 --- a/src/DotNetOpenAuth.Test/OpenId/Extensions/SimpleRegistration/ClaimsResponseTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/Extensions/SimpleRegistration/ClaimsResponseTests.cs @@ -12,18 +12,18 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions { using System.Runtime.Serialization.Formatters.Binary; using System.Xml.Serialization; using DotNetOpenAuth.OpenId.Extensions.SimpleRegistration; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; - [TestClass] + [TestFixture] public class ClaimsResponseTests { - [TestMethod] + [TestCase] public void EmptyMailAddress() { ClaimsResponse response = new ClaimsResponse(Constants.sreg_ns); response.Email = string.Empty; Assert.IsNull(response.MailAddress); } - [TestMethod, Ignore] // serialization no longer supported + [TestCase, Ignore("serialization no longer supported")] public void BinarySerialization() { ClaimsResponse fields = this.GetFilledData(); MemoryStream ms = new MemoryStream(); @@ -35,7 +35,7 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions { Assert.AreEqual(fields, fields2); } - [TestMethod, Ignore] // serialization no longer supported + [TestCase, Ignore("serialization no longer supported")] public void XmlSerialization() { ClaimsResponse fields = this.GetFilledData(); MemoryStream ms = new MemoryStream(); @@ -47,7 +47,7 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions { Assert.AreEqual(fields, fields2); } - [TestMethod] + [TestCase] public void EqualityTest() { ClaimsResponse fields1 = this.GetFilledData(); @@ -95,7 +95,7 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions { Assert.AreNotEqual(fields1, fields2); } - [TestMethod] + [TestCase] public void Birthdates() { var response = new ClaimsResponse(); // Verify that they both start out as null @@ -124,7 +124,7 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions { Assert.IsFalse(response.BirthDate.HasValue); } - [TestMethod, ExpectedException(typeof(ArgumentException))] + [TestCase, ExpectedException(typeof(ArgumentException))] public void InvalidRawBirthdate() { var response = new ClaimsResponse(); response.BirthDateRaw = "2008"; diff --git a/src/DotNetOpenAuth.Test/OpenId/Extensions/UI/UIRequestTests.cs b/src/DotNetOpenAuth.Test/OpenId/Extensions/UI/UIRequestTests.cs index 7a60a32..389fa5d 100644 --- a/src/DotNetOpenAuth.Test/OpenId/Extensions/UI/UIRequestTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/Extensions/UI/UIRequestTests.cs @@ -8,19 +8,36 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions.UI { using System.Globalization; using DotNetOpenAuth.Messaging.Reflection; using DotNetOpenAuth.OpenId.Extensions.UI; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; - [TestClass] + [TestFixture] public class UIRequestTests : OpenIdTestBase { - [TestMethod] + [TestCase] public void Defaults() { - UIRequest request = new UIRequest(); + var request = new UIRequest(); Assert.AreEqual("popup", request.Mode); Assert.AreEqual(1, request.LanguagePreference.Length); Assert.AreEqual(CultureInfo.CurrentUICulture, request.LanguagePreference[0]); + Assert.IsFalse(request.Icon.HasValue); + } + + [TestCase] + public void IconEncodingDecoding() + { + var request = new UIRequest(); + MessageDictionary dictionary = this.MessageDescriptions.GetAccessor(request); + Assert.IsFalse(dictionary.ContainsKey("icon")); + + Assert.IsFalse(request.Icon.HasValue); + dictionary["icon"] = "true"; + Assert.IsTrue(request.Icon.Value); + + dictionary.ClearValues(); + request.Icon = true; + Assert.AreEqual("true", dictionary["icon"]); } - [TestMethod] + [TestCase] public void LanguagePreferenceEncodingDecoding() { var request = new UIRequest(); MessageDictionary dictionary = this.MessageDescriptions.GetAccessor(request); @@ -42,7 +59,7 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions.UI { Assert.AreEqual(new CultureInfo("es-ES"), request.LanguagePreference[1]); } - [TestMethod] + [TestCase] public void ModeEncoding() { var request = new UIRequest(); MessageDictionary dictionary = this.MessageDescriptions.GetAccessor(request); diff --git a/src/DotNetOpenAuth.Test/OpenId/IdentifierTests.cs b/src/DotNetOpenAuth.Test/OpenId/IdentifierTests.cs index cc02265..01e2fdc 100644 --- a/src/DotNetOpenAuth.Test/OpenId/IdentifierTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/IdentifierTests.cs @@ -9,23 +9,23 @@ namespace DotNetOpenAuth.Test.OpenId { using System.Collections.Generic; using System.Linq; using DotNetOpenAuth.OpenId; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; - [TestClass] + [TestFixture] public class IdentifierTests { private string uri = "http://www.yahoo.com/"; private string uriNoScheme = "www.yahoo.com"; private string uriHttps = "https://www.yahoo.com/"; private string xri = "=arnott*andrew"; - [TestMethod] + [TestCase] public void TryParseNoThrow() { Identifier id; Assert.IsFalse(Identifier.TryParse(null, out id)); Assert.IsFalse(Identifier.TryParse(string.Empty, out id)); } - [TestMethod] + [TestCase] public void TryParse() { Identifier id; Assert.IsTrue(Identifier.TryParse("http://host/path", out id)); @@ -34,16 +34,16 @@ namespace DotNetOpenAuth.Test.OpenId { Assert.AreEqual("=arnott", id.ToString()); } - [TestMethod] + [TestCase] public void Parse() { - Assert.IsInstanceOfType(Identifier.Parse(this.uri), typeof(UriIdentifier)); - Assert.IsInstanceOfType(Identifier.Parse(this.xri), typeof(XriIdentifier)); + Assert.IsInstanceOf<UriIdentifier>(Identifier.Parse(this.uri)); + Assert.IsInstanceOf<XriIdentifier>(Identifier.Parse(this.xri)); } /// <summary> /// Tests conformance with 2.0 spec section 7.2#2 /// </summary> - [TestMethod] + [TestCase] public void ParseEndUserSuppliedXriIdentifer() { List<char> symbols = new List<char>(XriIdentifier.GlobalContextSymbols); symbols.Add('('); @@ -52,35 +52,35 @@ namespace DotNetOpenAuth.Test.OpenId { prefixes.AddRange(symbols.Select(s => "xri://" + s.ToString())); foreach (string prefix in prefixes) { var id = Identifier.Parse(prefix + "andrew"); - Assert.IsInstanceOfType(id, typeof(XriIdentifier)); + Assert.IsInstanceOf<XriIdentifier>(id); } } /// <summary> /// Verifies conformance with 2.0 spec section 7.2#3 /// </summary> - [TestMethod] + [TestCase] public void ParseEndUserSuppliedUriIdentifier() { // verify a fully-qualified Uri var id = Identifier.Parse(this.uri); - Assert.IsInstanceOfType(id, typeof(UriIdentifier)); + Assert.IsInstanceOf<UriIdentifier>(id); Assert.AreEqual(this.uri, ((UriIdentifier)id).Uri.AbsoluteUri); // verify an HTTPS Uri id = Identifier.Parse(this.uriHttps); - Assert.IsInstanceOfType(id, typeof(UriIdentifier)); + Assert.IsInstanceOf<UriIdentifier>(id); Assert.AreEqual(this.uriHttps, ((UriIdentifier)id).Uri.AbsoluteUri); // verify that if the scheme is missing it is added automatically id = Identifier.Parse(this.uriNoScheme); - Assert.IsInstanceOfType(id, typeof(UriIdentifier)); + Assert.IsInstanceOf<UriIdentifier>(id); Assert.AreEqual(this.uri, ((UriIdentifier)id).Uri.AbsoluteUri); } - [TestMethod, ExpectedException(typeof(ArgumentException))] + [TestCase, ExpectedException(typeof(ArgumentException))] public void ParseNull() { Identifier.Parse(null); } - [TestMethod, ExpectedException(typeof(ArgumentException))] + [TestCase, ExpectedException(typeof(ArgumentException))] public void ParseEmpty() { Identifier.Parse(string.Empty); } diff --git a/src/DotNetOpenAuth.Test/OpenId/Messages/AssociateDiffieHellmanRequestTests.cs b/src/DotNetOpenAuth.Test/OpenId/Messages/AssociateDiffieHellmanRequestTests.cs index a8648ac..b091062 100644 --- a/src/DotNetOpenAuth.Test/OpenId/Messages/AssociateDiffieHellmanRequestTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/Messages/AssociateDiffieHellmanRequestTests.cs @@ -8,24 +8,24 @@ namespace DotNetOpenAuth.Test.OpenId.Messages { using System; using DotNetOpenAuth.OpenId; using DotNetOpenAuth.OpenId.Messages; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; - [TestClass] + [TestFixture] public class AssociateDiffieHellmanRequestTests { private static readonly Uri Recipient = new Uri("http://host"); private AssociateDiffieHellmanRequest request; - [TestInitialize] + [SetUp] public void Setup() { this.request = new AssociateDiffieHellmanRequest(Protocol.V20.Version, Recipient); } - [TestMethod] + [TestCase] public void Ctor() { Assert.AreEqual(Recipient, this.request.Recipient); } - [TestMethod] + [TestCase] public void Mode() { Assert.AreEqual("associate", this.request.Mode); } diff --git a/src/DotNetOpenAuth.Test/OpenId/Messages/AssociateRequestTests.cs b/src/DotNetOpenAuth.Test/OpenId/Messages/AssociateRequestTests.cs index 0957118..f3c18d9 100644 --- a/src/DotNetOpenAuth.Test/OpenId/Messages/AssociateRequestTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/Messages/AssociateRequestTests.cs @@ -11,31 +11,31 @@ namespace DotNetOpenAuth.Test.OpenId.Messages { using DotNetOpenAuth.OpenId; using DotNetOpenAuth.OpenId.Messages; using DotNetOpenAuth.OpenId.RelyingParty; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; - [TestClass] + [TestFixture] public class AssociateRequestTests : OpenIdTestBase { private readonly Protocol protocol = Protocol.V20; private Uri secureRecipient = new Uri("https://hi"); private Uri insecureRecipient = new Uri("http://hi"); private AssociateRequest request; - [TestInitialize] + [SetUp] public void Setup() { this.request = new AssociateUnencryptedRequest(this.protocol.Version, this.secureRecipient); } - [TestMethod] + [TestCase] public void ConstructorTest() { Assert.AreEqual(this.secureRecipient, this.request.Recipient); } - [TestMethod] + [TestCase] public void Mode() { Assert.AreEqual(this.protocol.Args.Mode.associate, this.request.Mode); } - [TestMethod] + [TestCase] public void MessagePartsTest() { this.request.AssociationType = this.protocol.Args.SignatureAlgorithm.HMAC_SHA1; this.request.SessionType = this.protocol.Args.SessionType.NoEncryption; @@ -51,26 +51,26 @@ namespace DotNetOpenAuth.Test.OpenId.Messages { Assert.AreEqual(this.protocol.Args.SessionType.NoEncryption, dict[this.protocol.openid.session_type]); } - [TestMethod] + [TestCase] public void ValidMessageTest() { this.request = new AssociateUnencryptedRequest(Protocol.V20.Version, this.secureRecipient); this.request.AssociationType = this.protocol.Args.SignatureAlgorithm.HMAC_SHA1; this.request.EnsureValidMessage(); } - [TestMethod, ExpectedException(typeof(ProtocolException))] + [TestCase, ExpectedException(typeof(ProtocolException))] public void InvalidMessageTest() { this.request = new AssociateUnencryptedRequest(Protocol.V20.Version, this.insecureRecipient); this.request.AssociationType = this.protocol.Args.SignatureAlgorithm.HMAC_SHA1; this.request.EnsureValidMessage(); // no-encryption only allowed for secure channels. } - [TestMethod] + [TestCase] public void RequiredProtection() { Assert.AreEqual(MessageProtections.None, this.request.RequiredProtection); } - [TestMethod] + [TestCase] public void Transport() { Assert.AreEqual(MessageTransport.Direct, this.request.Transport); } @@ -78,7 +78,7 @@ namespace DotNetOpenAuth.Test.OpenId.Messages { /// <summary> /// Verifies security settings limit RP's initial associate request /// </summary> - [TestMethod] + [TestCase] public void AssociateRequestDeterminedBySecuritySettings() { Protocol protocol = Protocol.V20; SecuritySettings securitySettings = new RelyingPartySecuritySettings(); diff --git a/src/DotNetOpenAuth.Test/OpenId/Messages/AssociateUnencryptedResponseTests.cs b/src/DotNetOpenAuth.Test/OpenId/Messages/AssociateUnencryptedResponseTests.cs index 1f5e87c..37be1cb 100644 --- a/src/DotNetOpenAuth.Test/OpenId/Messages/AssociateUnencryptedResponseTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/Messages/AssociateUnencryptedResponseTests.cs @@ -9,20 +9,20 @@ namespace DotNetOpenAuth.Test.OpenId.Messages { using DotNetOpenAuth.Messaging; using DotNetOpenAuth.OpenId; using DotNetOpenAuth.OpenId.Messages; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; - [TestClass] + [TestFixture] public class AssociateUnencryptedResponseTests : OpenIdTestBase { private AssociateUnencryptedResponse response; - [TestInitialize] + [SetUp] public override void SetUp() { base.SetUp(); var request = new AssociateUnencryptedRequest(Protocol.V20.Version, new Uri("http://host")); this.response = new AssociateUnencryptedResponse(request.Version, request); } - [TestMethod] + [TestCase] public void ParameterNames() { this.response.AssociationHandle = "HANDLE"; this.response.AssociationType = "HMAC-SHA1"; @@ -38,12 +38,12 @@ namespace DotNetOpenAuth.Test.OpenId.Messages { Assert.AreEqual("50", fields["expires_in"]); } - [TestMethod] + [TestCase] public void RequiredProtection() { Assert.AreEqual(MessageProtections.None, this.response.RequiredProtection); } - [TestMethod] + [TestCase] public void Transport() { Assert.AreEqual(MessageTransport.Direct, this.response.Transport); } diff --git a/src/DotNetOpenAuth.Test/OpenId/Messages/AssociateUnsuccessfulResponseTests.cs b/src/DotNetOpenAuth.Test/OpenId/Messages/AssociateUnsuccessfulResponseTests.cs index a6a691d..9b76473 100644 --- a/src/DotNetOpenAuth.Test/OpenId/Messages/AssociateUnsuccessfulResponseTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/Messages/AssociateUnsuccessfulResponseTests.cs @@ -9,20 +9,20 @@ namespace DotNetOpenAuth.Test.OpenId.Messages { using DotNetOpenAuth.Messaging; using DotNetOpenAuth.OpenId; using DotNetOpenAuth.OpenId.Messages; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; - [TestClass] + [TestFixture] public class AssociateUnsuccessfulResponseTests : OpenIdTestBase { private AssociateUnsuccessfulResponse response; - [TestInitialize] + [SetUp] public override void SetUp() { base.SetUp(); var request = new AssociateUnencryptedRequest(Protocol.V20.Version, new Uri("http://host")); this.response = new AssociateUnsuccessfulResponse(request.Version, request); } - [TestMethod] + [TestCase] public void ParameterNames() { this.response.ErrorMessage = "Some Error"; this.response.AssociationType = "HMAC-SHA1"; diff --git a/src/DotNetOpenAuth.Test/OpenId/Messages/CheckAuthenticationRequestTests.cs b/src/DotNetOpenAuth.Test/OpenId/Messages/CheckAuthenticationRequestTests.cs index 96a2e23..d2d2cc4 100644 --- a/src/DotNetOpenAuth.Test/OpenId/Messages/CheckAuthenticationRequestTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/Messages/CheckAuthenticationRequestTests.cs @@ -6,16 +6,37 @@ namespace DotNetOpenAuth.Test.OpenId.Messages { using System; - using System.Collections.Generic; - using System.Linq; - using System.Text; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using DotNetOpenAuth.OpenId; + using DotNetOpenAuth.OpenId.Messages; + using NUnit.Framework; - [TestClass] + [TestFixture] public class CheckAuthenticationRequestTests : OpenIdTestBase { - [TestInitialize] - public override void SetUp() { - base.SetUp(); + /// <summary> + /// Verifies that the check_auth request is sent preserving EXACTLY (non-normalized) + /// what is in the positive assertion. + /// </summary> + /// <remarks> + /// This is very important because any normalization + /// (like changing https://host:443/ to https://host/) in the message will invalidate the signature + /// and cause the authentication to inappropriately fail. + /// Designed to verify fix to Trac #198. + /// </remarks> + [TestCase] + public void ExactPositiveAssertionPreservation() { + var rp = CreateRelyingParty(true); + + // Initialize the positive assertion response with some data that is NOT in normalized form. + var positiveAssertion = new PositiveAssertionResponse(Protocol.Default.Version, RPUri) + { + ClaimedIdentifier = "https://HOST:443/a", + ProviderEndpoint = new Uri("https://anotherHOST:443/b"), + }; + + var checkAuth = new CheckAuthenticationRequest(positiveAssertion, rp.Channel); + var actual = rp.Channel.MessageDescriptions.GetAccessor(checkAuth); + Assert.AreEqual("https://HOST:443/a", actual["openid.claimed_id"]); + Assert.AreEqual("https://anotherHOST:443/b", actual["openid.op_endpoint"]); } } } diff --git a/src/DotNetOpenAuth.Test/OpenId/Messages/CheckAuthenticationResponseTests.cs b/src/DotNetOpenAuth.Test/OpenId/Messages/CheckAuthenticationResponseTests.cs index 1e773bd..cbe6638 100644 --- a/src/DotNetOpenAuth.Test/OpenId/Messages/CheckAuthenticationResponseTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/Messages/CheckAuthenticationResponseTests.cs @@ -12,16 +12,16 @@ namespace DotNetOpenAuth.Test.OpenId.Messages { using DotNetOpenAuth.Messaging.Reflection; using DotNetOpenAuth.OpenId; using DotNetOpenAuth.OpenId.Messages; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; - [TestClass] + [TestFixture] public class CheckAuthenticationResponseTests : OpenIdTestBase { - [TestInitialize] + [SetUp] public override void SetUp() { base.SetUp(); } - [TestMethod] + [TestCase] public void IsValid() { Protocol protocol = Protocol.Default; var request = new CheckAuthenticationRequest(protocol.Version, OPUri); diff --git a/src/DotNetOpenAuth.Test/OpenId/Messages/CheckIdRequestTests.cs b/src/DotNetOpenAuth.Test/OpenId/Messages/CheckIdRequestTests.cs index 2c9ea12..e33a191 100644 --- a/src/DotNetOpenAuth.Test/OpenId/Messages/CheckIdRequestTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/Messages/CheckIdRequestTests.cs @@ -12,11 +12,11 @@ namespace DotNetOpenAuth.Test.OpenId.Messages { using DotNetOpenAuth.Messaging; using DotNetOpenAuth.OpenId; using DotNetOpenAuth.OpenId.Messages; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; - [TestClass] + [TestFixture] public class CheckIdRequestTests : OpenIdTestBase { - [TestInitialize] + [SetUp] public override void SetUp() { base.SetUp(); } diff --git a/src/DotNetOpenAuth.Test/OpenId/Messages/DirectErrorResponseTests.cs b/src/DotNetOpenAuth.Test/OpenId/Messages/DirectErrorResponseTests.cs index 02fa7df..039748f 100644 --- a/src/DotNetOpenAuth.Test/OpenId/Messages/DirectErrorResponseTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/Messages/DirectErrorResponseTests.cs @@ -10,13 +10,13 @@ namespace DotNetOpenAuth.Test.OpenId.Messages { using DotNetOpenAuth.Messaging; using DotNetOpenAuth.OpenId; using DotNetOpenAuth.OpenId.Messages; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; - [TestClass] + [TestFixture] public class DirectErrorResponseTests : OpenIdTestBase { private DirectErrorResponse response; - [TestInitialize] + [SetUp] public override void SetUp() { base.SetUp(); @@ -24,7 +24,7 @@ namespace DotNetOpenAuth.Test.OpenId.Messages { this.response = new DirectErrorResponse(request.Version, request); } - [TestMethod] + [TestCase] public void ParameterNames() { this.response.ErrorMessage = "Some Error"; this.response.Contact = "Andrew Arnott"; @@ -42,7 +42,7 @@ namespace DotNetOpenAuth.Test.OpenId.Messages { /// Verifies that error messages are created as HTTP 400 errors, /// per OpenID 2.0 section 5.1.2.2. /// </summary> - [TestMethod] + [TestCase] public void ErrorMessagesAsHttp400() { var httpStatusMessage = (IHttpDirectResponse)this.response; Assert.AreEqual(HttpStatusCode.BadRequest, httpStatusMessage.HttpStatusCode); diff --git a/src/DotNetOpenAuth.Test/OpenId/Messages/IndirectErrorResponseTests.cs b/src/DotNetOpenAuth.Test/OpenId/Messages/IndirectErrorResponseTests.cs index fdb08eb..c9fb535 100644 --- a/src/DotNetOpenAuth.Test/OpenId/Messages/IndirectErrorResponseTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/Messages/IndirectErrorResponseTests.cs @@ -10,25 +10,25 @@ namespace DotNetOpenAuth.Test.OpenId.Messages { using DotNetOpenAuth.OpenId; using DotNetOpenAuth.OpenId.Messages; using DotNetOpenAuth.OpenId.RelyingParty; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; - [TestClass] + [TestFixture] public class IndirectErrorResponseTests : OpenIdTestBase { private IndirectErrorResponse response; - [TestInitialize] + [SetUp] public void Setup() { CheckIdRequest request = new CheckIdRequest(Protocol.V20.Version, OPUri, AuthenticationRequestMode.Immediate); request.ReturnTo = RPUri; this.response = new IndirectErrorResponse(request); } - [TestMethod] + [TestCase] public void Ctor() { Assert.AreEqual(RPUri, this.response.Recipient); } - [TestMethod] + [TestCase] public void ParameterNames() { this.response.ErrorMessage = "Some Error"; this.response.Contact = "Andrew Arnott"; diff --git a/src/DotNetOpenAuth.Test/OpenId/Messages/IndirectSignedResponseTests.cs b/src/DotNetOpenAuth.Test/OpenId/Messages/IndirectSignedResponseTests.cs index 8b0937a..ad6b15d 100644 --- a/src/DotNetOpenAuth.Test/OpenId/Messages/IndirectSignedResponseTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/Messages/IndirectSignedResponseTests.cs @@ -16,9 +16,9 @@ namespace DotNetOpenAuth.Test.OpenId.Messages { using DotNetOpenAuth.OpenId.ChannelElements; using DotNetOpenAuth.OpenId.Messages; using DotNetOpenAuth.OpenId.RelyingParty; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; - [TestClass] + [TestFixture] public class IndirectSignedResponseTests : OpenIdTestBase { private const string CreationDateString = "2005-05-15T17:11:51Z"; private readonly DateTime creationDate = DateTime.Parse(CreationDateString, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal); @@ -27,7 +27,7 @@ namespace DotNetOpenAuth.Test.OpenId.Messages { private IndirectSignedResponse unsolicited; private Protocol protocol; - [TestInitialize] + [SetUp] public override void SetUp() { base.SetUp(); @@ -39,7 +39,7 @@ namespace DotNetOpenAuth.Test.OpenId.Messages { this.unsolicited = new IndirectSignedResponse(this.protocol.Version, RPUri); } - [TestMethod] + [TestCase] public void CtorFromRequest() { Assert.AreEqual(this.protocol.Args.Mode.id_res, this.response.Mode); Assert.AreEqual(this.request.Version, this.response.Version); @@ -48,7 +48,7 @@ namespace DotNetOpenAuth.Test.OpenId.Messages { Assert.IsTrue(DateTime.UtcNow - ((ITamperResistantOpenIdMessage)this.response).UtcCreationDate < TimeSpan.FromSeconds(5)); } - [TestMethod] + [TestCase] public void CtorUnsolicited() { Assert.AreEqual(this.protocol.Args.Mode.id_res, this.unsolicited.Mode); Assert.AreEqual(this.protocol.Version, this.unsolicited.Version); @@ -60,7 +60,7 @@ namespace DotNetOpenAuth.Test.OpenId.Messages { Assert.AreEqual(OPUri, this.unsolicited.ProviderEndpoint); } - [TestMethod] + [TestCase] public void ResponseNonceSetter() { const string HybridValue = CreationDateString + "UNIQUE"; var responseAccessor = IndirectSignedResponse_Accessor.AttachShadow(this.response); @@ -74,7 +74,7 @@ namespace DotNetOpenAuth.Test.OpenId.Messages { Assert.IsNull(responseReplay.Nonce); } - [TestMethod] + [TestCase] public void ResponseNonceGetter() { var responseAccessor = IndirectSignedResponse_Accessor.AttachShadow(this.response); IReplayProtectedProtocolMessage responseReplay = this.response; @@ -86,7 +86,7 @@ namespace DotNetOpenAuth.Test.OpenId.Messages { Assert.AreEqual(this.creationDate, responseReplay.UtcCreationDate); } - [TestMethod] + [TestCase] public void UtcCreationDateConvertsToUniversal() { IReplayProtectedProtocolMessage responseReplay = this.response; DateTime local = DateTime.Parse("1982-01-01", CultureInfo.InvariantCulture, DateTimeStyles.AssumeLocal); @@ -109,7 +109,7 @@ namespace DotNetOpenAuth.Test.OpenId.Messages { Assert.AreEqual(this.creationDate.Hour, utcCreationDate.Hour, "The hour should match since both times are UTC time."); } - [TestMethod] + [TestCase] public void ReturnToDoesNotMatchRecipient() { // Make sure its valid first, so we know that when it's invalid // it is due to our tampering. @@ -127,24 +127,24 @@ namespace DotNetOpenAuth.Test.OpenId.Messages { } } - [TestMethod, ExpectedException(typeof(ArgumentException))] + [TestCase, ExpectedException(typeof(ArgumentException))] public void GetReturnToArgumentNullKey() { this.response.GetReturnToArgument(null); } - [TestMethod, ExpectedException(typeof(ArgumentException))] + [TestCase, ExpectedException(typeof(ArgumentException))] public void GetReturnToArgumentEmptyKey() { this.response.GetReturnToArgument(string.Empty); } - [TestMethod] + [TestCase] public void GetReturnToArgumentDoesNotReturnExtraArgs() { this.response.ExtraData["a"] = "b"; Assert.IsNull(this.response.GetReturnToArgument("a")); Assert.AreEqual(0, this.response.GetReturnToParameterNames().Count()); } - [TestMethod] + [TestCase] public void GetReturnToArgumentAndNames() { UriBuilder returnToBuilder = new UriBuilder(this.response.ReturnTo); returnToBuilder.AppendQueryArgs(new Dictionary<string, string> { { "a", "b" } }); diff --git a/src/DotNetOpenAuth.Test/OpenId/Messages/NegativeAssertionResponseTests.cs b/src/DotNetOpenAuth.Test/OpenId/Messages/NegativeAssertionResponseTests.cs index 7876732..c35780d 100644 --- a/src/DotNetOpenAuth.Test/OpenId/Messages/NegativeAssertionResponseTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/Messages/NegativeAssertionResponseTests.cs @@ -13,16 +13,16 @@ namespace DotNetOpenAuth.Test.OpenId.Messages { using DotNetOpenAuth.OpenId; using DotNetOpenAuth.OpenId.Messages; using DotNetOpenAuth.OpenId.RelyingParty; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; - [TestClass] + [TestFixture] public class NegativeAssertionResponseTests : OpenIdTestBase { - [TestInitialize] + [SetUp] public override void SetUp() { base.SetUp(); } - [TestMethod] + [TestCase] public void Mode() { var setupRequestV1 = new CheckIdRequest(Protocol.V10.Version, OPUri, AuthenticationRequestMode.Setup); setupRequestV1.ReturnTo = RPUri; @@ -45,14 +45,14 @@ namespace DotNetOpenAuth.Test.OpenId.Messages { Assert.IsFalse(new NegativeAssertionResponse(setupRequestV2).Immediate); } - [TestMethod, ExpectedException(typeof(ProtocolException))] + [TestCase, ExpectedException(typeof(ProtocolException))] public void UserSetupUrlRequiredInV1Immediate() { var immediateRequestV1 = new CheckIdRequest(Protocol.V10.Version, OPUri, AuthenticationRequestMode.Immediate); immediateRequestV1.ReturnTo = RPUri; new NegativeAssertionResponse(immediateRequestV1).EnsureValidMessage(); } - [TestMethod] + [TestCase] public void UserSetupUrlSetForV1Immediate() { var immediateRequestV1 = new CheckIdRequest(Protocol.V10.Version, OPUri, AuthenticationRequestMode.Immediate); immediateRequestV1.ReturnTo = RPUri; @@ -61,7 +61,7 @@ namespace DotNetOpenAuth.Test.OpenId.Messages { response.EnsureValidMessage(); } - [TestMethod] + [TestCase] public void UserSetupUrlNotRequiredInV1SetupOrV2() { var setupRequestV1 = new CheckIdRequest(Protocol.V10.Version, OPUri, AuthenticationRequestMode.Setup); setupRequestV1.ReturnTo = RPUri; diff --git a/src/DotNetOpenAuth.Test/OpenId/Messages/PositiveAssertionResponseTests.cs b/src/DotNetOpenAuth.Test/OpenId/Messages/PositiveAssertionResponseTests.cs index faa6a91..90d24b1 100644 --- a/src/DotNetOpenAuth.Test/OpenId/Messages/PositiveAssertionResponseTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/Messages/PositiveAssertionResponseTests.cs @@ -15,9 +15,9 @@ namespace DotNetOpenAuth.Test.OpenId.Messages { using DotNetOpenAuth.OpenId; using DotNetOpenAuth.OpenId.Messages; using DotNetOpenAuth.OpenId.RelyingParty; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; - [TestClass] + [TestFixture] public class PositiveAssertionResponseTests : OpenIdTestBase { private const string CreationDateString = "2005-05-15T17:11:51Z"; private readonly DateTime creationDate = DateTime.Parse(CreationDateString, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal); @@ -26,7 +26,7 @@ namespace DotNetOpenAuth.Test.OpenId.Messages { private PositiveAssertionResponse unsolicited; private Protocol protocol; - [TestInitialize] + [SetUp] public override void SetUp() { base.SetUp(); @@ -38,7 +38,7 @@ namespace DotNetOpenAuth.Test.OpenId.Messages { this.unsolicited = new PositiveAssertionResponse(this.protocol.Version, RPUri); } - [TestMethod] + [TestCase] public void CtorFromRequest() { Assert.AreEqual(this.protocol.Args.Mode.id_res, this.response.Mode); Assert.AreEqual(this.request.Version, this.response.Version); @@ -46,7 +46,7 @@ namespace DotNetOpenAuth.Test.OpenId.Messages { Assert.AreEqual(OPUri, this.response.ProviderEndpoint); } - [TestMethod] + [TestCase] public void CtorUnsolicited() { Assert.AreEqual(this.protocol.Args.Mode.id_res, this.unsolicited.Mode); Assert.AreEqual(this.protocol.Version, this.unsolicited.Version); @@ -60,7 +60,7 @@ namespace DotNetOpenAuth.Test.OpenId.Messages { /// <summary> /// Verifies that local_id and claimed_id can either be null or specified. /// </summary> - [TestMethod] + [TestCase] public void ClaimedIdAndLocalIdSpecifiedIsValid() { this.response.LocalIdentifier = "http://local"; this.response.ClaimedIdentifier = "http://claimedid"; diff --git a/src/DotNetOpenAuth.Test/OpenId/Messages/SignedResponseRequestTests.cs b/src/DotNetOpenAuth.Test/OpenId/Messages/SignedResponseRequestTests.cs index 0177685..bc95f8b 100644 --- a/src/DotNetOpenAuth.Test/OpenId/Messages/SignedResponseRequestTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/Messages/SignedResponseRequestTests.cs @@ -10,9 +10,9 @@ namespace DotNetOpenAuth.Test.OpenId.Messages { using DotNetOpenAuth.OpenId; using DotNetOpenAuth.OpenId.Messages; using DotNetOpenAuth.OpenId.RelyingParty; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; - [TestClass] + [TestFixture] public class SignedResponseRequestTests : OpenIdTestBase { private Uri providerEndpoint; private SignedResponseRequest immediatev1; @@ -20,7 +20,7 @@ namespace DotNetOpenAuth.Test.OpenId.Messages { private SignedResponseRequest immediatev2; private SignedResponseRequest setupv2; - [TestInitialize] + [SetUp] public override void SetUp() { base.SetUp(); @@ -55,7 +55,7 @@ namespace DotNetOpenAuth.Test.OpenId.Messages { /// This test does not test all the realm-return_to matching rules as that is done in the Realm tests. /// This test merely checks that the compatibility match occurs at all. /// </remarks> - [TestMethod, ExpectedException(typeof(ProtocolException))] + [TestCase, ExpectedException(typeof(ProtocolException))] public void RealmReturnToMismatchV2() { this.setupv2.Realm = "http://somehost/"; this.setupv2.ReturnTo = new Uri("http://someotherhost/"); @@ -66,7 +66,7 @@ namespace DotNetOpenAuth.Test.OpenId.Messages { /// Verifies that the validation check throws if the return_to and the realm /// values are not compatible. /// </summary> - [TestMethod, ExpectedException(typeof(ProtocolException))] + [TestCase, ExpectedException(typeof(ProtocolException))] public void RealmReturnToMismatchV1() { this.setupv1.Realm = "http://somehost/"; this.setupv1.ReturnTo = new Uri("http://someotherhost/"); diff --git a/src/DotNetOpenAuth.Test/OpenId/NonIdentityTests.cs b/src/DotNetOpenAuth.Test/OpenId/NonIdentityTests.cs index 49bb32c..17ab090 100644 --- a/src/DotNetOpenAuth.Test/OpenId/NonIdentityTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/NonIdentityTests.cs @@ -9,11 +9,11 @@ namespace DotNetOpenAuth.Test.OpenId { using DotNetOpenAuth.OpenId.Messages; using DotNetOpenAuth.OpenId.Provider; using DotNetOpenAuth.OpenId.RelyingParty; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; - [TestClass] + [TestFixture] public class NonIdentityTests : OpenIdTestBase { - [TestMethod] + [TestCase] public void ExtensionOnlyChannelLevel() { Protocol protocol = Protocol.V20; AuthenticationRequestMode mode = AuthenticationRequestMode.Setup; @@ -25,12 +25,12 @@ namespace DotNetOpenAuth.Test.OpenId { }, op => { var request = op.Channel.ReadFromRequest<SignedResponseRequest>(); - Assert.IsNotInstanceOfType(request, typeof(CheckIdRequest)); + Assert.IsNotInstanceOf<CheckIdRequest>(request); }); coordinator.Run(); } - [TestMethod] + [TestCase] public void ExtensionOnlyFacadeLevel() { Protocol protocol = Protocol.V20; var coordinator = new OpenIdCoordinator( @@ -48,7 +48,7 @@ namespace DotNetOpenAuth.Test.OpenId { var request = (IAnonymousRequest)op.GetRequest(); request.IsApproved = true; - Assert.IsNotInstanceOfType(request, typeof(CheckIdRequest)); + Assert.IsNotInstanceOf<CheckIdRequest>(request); op.SendResponse(request); }); coordinator.Run(); diff --git a/src/DotNetOpenAuth.Test/OpenId/OpenIdCoordinator.cs b/src/DotNetOpenAuth.Test/OpenId/OpenIdCoordinator.cs index 0f9d472..d4884e8 100644 --- a/src/DotNetOpenAuth.Test/OpenId/OpenIdCoordinator.cs +++ b/src/DotNetOpenAuth.Test/OpenId/OpenIdCoordinator.cs @@ -57,10 +57,12 @@ namespace DotNetOpenAuth.Test.OpenId { private void EnsurePartiesAreInitialized() { if (this.RelyingParty == null) { this.RelyingParty = new OpenIdRelyingParty(new StandardRelyingPartyApplicationStore()); + this.RelyingParty.DiscoveryServices.Add(new MockIdentifierDiscoveryService()); } if (this.Provider == null) { this.Provider = new OpenIdProvider(new StandardProviderApplicationStore()); + this.Provider.DiscoveryServices.Add(new MockIdentifierDiscoveryService()); } } } diff --git a/src/DotNetOpenAuth.Test/OpenId/OpenIdTestBase.cs b/src/DotNetOpenAuth.Test/OpenId/OpenIdTestBase.cs index 5034b7e..c7df99a 100644 --- a/src/DotNetOpenAuth.Test/OpenId/OpenIdTestBase.cs +++ b/src/DotNetOpenAuth.Test/OpenId/OpenIdTestBase.cs @@ -6,6 +6,7 @@ namespace DotNetOpenAuth.Test.OpenId { using System; + using System.Collections.Generic; using System.IO; using System.Reflection; using DotNetOpenAuth.Configuration; @@ -15,7 +16,7 @@ namespace DotNetOpenAuth.Test.OpenId { using DotNetOpenAuth.OpenId.Provider; using DotNetOpenAuth.OpenId.RelyingParty; using DotNetOpenAuth.Test.Mocks; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; public class OpenIdTestBase : TestBase { internal IDirectWebRequestHandler RequestHandler; @@ -61,7 +62,7 @@ namespace DotNetOpenAuth.Test.OpenId { protected ProviderSecuritySettings ProviderSecuritySettings { get; private set; } - [TestInitialize] + [SetUp] public override void SetUp() { base.SetUp(); @@ -74,7 +75,7 @@ namespace DotNetOpenAuth.Test.OpenId { Identifier.EqualityOnStrings = true; } - [TestCleanup] + [TearDown] public override void Cleanup() { base.Cleanup(); @@ -116,17 +117,17 @@ namespace DotNetOpenAuth.Test.OpenId { } } - internal static ServiceEndpoint GetServiceEndpoint(int user, ProtocolVersion providerVersion, int servicePriority, bool useSsl) { + internal static IdentifierDiscoveryResult GetServiceEndpoint(int user, ProtocolVersion providerVersion, int servicePriority, bool useSsl) { return GetServiceEndpoint(user, providerVersion, servicePriority, useSsl, false); } - internal static ServiceEndpoint GetServiceEndpoint(int user, ProtocolVersion providerVersion, int servicePriority, bool useSsl, bool delegating) { + internal static IdentifierDiscoveryResult GetServiceEndpoint(int user, ProtocolVersion providerVersion, int servicePriority, bool useSsl, bool delegating) { var providerEndpoint = new ProviderEndpointDescription( useSsl ? OpenIdTestBase.OPUriSsl : OpenIdTestBase.OPUri, new string[] { Protocol.Lookup(providerVersion).ClaimedIdentifierServiceTypeURI }); var local_id = useSsl ? OPLocalIdentifiersSsl[user] : OPLocalIdentifiers[user]; var claimed_id = delegating ? (useSsl ? VanityUriSsl : VanityUri) : local_id; - return ServiceEndpoint.CreateForClaimedIdentifier( + return IdentifierDiscoveryResult.CreateForClaimedIdentifier( claimed_id, claimed_id, local_id, @@ -176,6 +177,12 @@ namespace DotNetOpenAuth.Test.OpenId { } } + internal IEnumerable<IdentifierDiscoveryResult> Discover(Identifier identifier) { + var rp = this.CreateRelyingParty(true); + rp.Channel.WebRequestHandler = this.RequestHandler; + return rp.Discover(identifier); + } + protected Realm GetMockRealm(bool useSsl) { var rpDescription = new RelyingPartyEndpointDescription(useSsl ? RPUriSsl : RPUri, new string[] { Protocol.V20.RPReturnToTypeURI }); return new MockRealm(useSsl ? RPRealmUriSsl : RPRealmUri, rpDescription); @@ -190,9 +197,21 @@ namespace DotNetOpenAuth.Test.OpenId { } protected Identifier GetMockIdentifier(ProtocolVersion providerVersion, bool useSsl, bool delegating) { - ServiceEndpoint se = GetServiceEndpoint(0, providerVersion, 10, useSsl, delegating); + var se = GetServiceEndpoint(0, providerVersion, 10, useSsl, delegating); UriIdentifier identityUri = (UriIdentifier)se.ClaimedIdentifier; - return new MockIdentifier(identityUri, this.MockResponder, new ServiceEndpoint[] { se }); + return new MockIdentifier(identityUri, this.MockResponder, new IdentifierDiscoveryResult[] { se }); + } + + protected Identifier GetMockDualIdentifier() { + Protocol protocol = Protocol.Default; + var opDesc = new ProviderEndpointDescription(OPUri, protocol.Version); + var dualResults = new IdentifierDiscoveryResult[] { + IdentifierDiscoveryResult.CreateForClaimedIdentifier(VanityUri.AbsoluteUri, OPLocalIdentifiers[0], opDesc, 10, 10), + IdentifierDiscoveryResult.CreateForProviderIdentifier(protocol.ClaimedIdentifierForOPIdentifier, opDesc, 20, 20), + }; + + Identifier dualId = new MockIdentifier(VanityUri, this.MockResponder, dualResults); + return dualId; } /// <summary> @@ -211,6 +230,7 @@ namespace DotNetOpenAuth.Test.OpenId { protected OpenIdRelyingParty CreateRelyingParty(bool stateless) { var rp = new OpenIdRelyingParty(stateless ? null : new StandardRelyingPartyApplicationStore()); rp.Channel.WebRequestHandler = this.MockResponder.MockWebRequestHandler; + rp.DiscoveryServices.Add(new MockIdentifierDiscoveryService()); return rp; } @@ -221,6 +241,7 @@ namespace DotNetOpenAuth.Test.OpenId { protected OpenIdProvider CreateProvider() { var op = new OpenIdProvider(new StandardProviderApplicationStore()); op.Channel.WebRequestHandler = this.MockResponder.MockWebRequestHandler; + op.DiscoveryServices.Add(new MockIdentifierDiscoveryService()); return op; } } diff --git a/src/DotNetOpenAuth.Test/OpenId/OpenIdUtilitiesTests.cs b/src/DotNetOpenAuth.Test/OpenId/OpenIdUtilitiesTests.cs new file mode 100644 index 0000000..fefb852 --- /dev/null +++ b/src/DotNetOpenAuth.Test/OpenId/OpenIdUtilitiesTests.cs @@ -0,0 +1,20 @@ +//----------------------------------------------------------------------- +// <copyright file="OpenIdUtilitiesTests.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.Test.OpenId { + using System; + using System.Collections.Generic; + using System.Linq; + using System.Text; + using DotNetOpenAuth.OpenId; + using DotNetOpenAuth.OpenId.Extensions.SimpleRegistration; + using DotNetOpenAuth.OpenId.Messages; + using NUnit.Framework; + + [TestFixture] + public class OpenIdUtilitiesTests : OpenIdTestBase { + } +} diff --git a/src/DotNetOpenAuth.Test/OpenId/Provider/AnonymousRequestTests.cs b/src/DotNetOpenAuth.Test/OpenId/Provider/AnonymousRequestTests.cs index 14fef91..1df4c9e 100644 --- a/src/DotNetOpenAuth.Test/OpenId/Provider/AnonymousRequestTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/Provider/AnonymousRequestTests.cs @@ -9,14 +9,14 @@ namespace DotNetOpenAuth.Test.OpenId.Provider { using DotNetOpenAuth.OpenId.Messages; using DotNetOpenAuth.OpenId.Provider; using DotNetOpenAuth.OpenId.RelyingParty; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; - [TestClass] + [TestFixture] public class AnonymousRequestTests : OpenIdTestBase { /// <summary> /// Verifies that IsApproved controls which response message is returned. /// </summary> - [TestMethod] + [TestCase] public void IsApprovedDeterminesReturnedMessage() { var op = CreateProvider(); Protocol protocol = Protocol.V20; @@ -27,11 +27,11 @@ namespace DotNetOpenAuth.Test.OpenId.Provider { Assert.IsFalse(anonReq.IsApproved.HasValue); anonReq.IsApproved = false; - Assert.IsInstanceOfType(anonReq.Response, typeof(NegativeAssertionResponse)); + Assert.IsInstanceOf<NegativeAssertionResponse>(anonReq.Response); anonReq.IsApproved = true; - Assert.IsInstanceOfType(anonReq.Response, typeof(IndirectSignedResponse)); - Assert.IsNotInstanceOfType(anonReq.Response, typeof(PositiveAssertionResponse)); + Assert.IsInstanceOf<IndirectSignedResponse>(anonReq.Response); + Assert.IsNotInstanceOf<PositiveAssertionResponse>(anonReq.Response); } } } diff --git a/src/DotNetOpenAuth.Test/OpenId/Provider/AuthenticationRequestTest.cs b/src/DotNetOpenAuth.Test/OpenId/Provider/AuthenticationRequestTest.cs index accbd97..dc5b3e3 100644 --- a/src/DotNetOpenAuth.Test/OpenId/Provider/AuthenticationRequestTest.cs +++ b/src/DotNetOpenAuth.Test/OpenId/Provider/AuthenticationRequestTest.cs @@ -10,14 +10,14 @@ namespace DotNetOpenAuth.Test.OpenId.Provider { using DotNetOpenAuth.OpenId; using DotNetOpenAuth.OpenId.Messages; using DotNetOpenAuth.OpenId.Provider; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; - [TestClass] + [TestFixture] public class AuthenticationRequestTest : OpenIdTestBase { /// <summary> /// Verifies the user_setup_url is set properly for immediate negative responses. /// </summary> - [TestMethod] + [TestCase] public void UserSetupUrl() { // Construct a V1 immediate request Protocol protocol = Protocol.V11; diff --git a/src/DotNetOpenAuth.Test/OpenId/Provider/HostProcessedRequestTests.cs b/src/DotNetOpenAuth.Test/OpenId/Provider/HostProcessedRequestTests.cs index d308271..9bb8095 100644 --- a/src/DotNetOpenAuth.Test/OpenId/Provider/HostProcessedRequestTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/Provider/HostProcessedRequestTests.cs @@ -9,16 +9,16 @@ namespace DotNetOpenAuth.Test.OpenId.Provider { using DotNetOpenAuth.OpenId; using DotNetOpenAuth.OpenId.Messages; using DotNetOpenAuth.OpenId.Provider; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; - [TestClass] + [TestFixture] public class HostProcessedRequestTests : OpenIdTestBase { private Protocol protocol; private OpenIdProvider provider; private CheckIdRequest checkIdRequest; private AuthenticationRequest request; - [TestInitialize] + [SetUp] public override void SetUp() { base.SetUp(); @@ -30,12 +30,12 @@ namespace DotNetOpenAuth.Test.OpenId.Provider { this.request = new AuthenticationRequest(this.provider, this.checkIdRequest); } - [TestMethod] + [TestCase] public void IsReturnUrlDiscoverableNoResponse() { Assert.AreEqual(RelyingPartyDiscoveryResult.NoServiceDocument, this.request.IsReturnUrlDiscoverable(this.provider)); } - [TestMethod] + [TestCase] public void IsReturnUrlDiscoverableValidResponse() { this.MockResponder.RegisterMockRPDiscovery(); this.request = new AuthenticationRequest(this.provider, this.checkIdRequest); @@ -46,7 +46,7 @@ namespace DotNetOpenAuth.Test.OpenId.Provider { /// Verifies that when discovery would be performed over standard HTTP and RequireSsl /// is set, that discovery fails. /// </summary> - [TestMethod] + [TestCase] public void IsReturnUrlDiscoverableNotSsl() { this.provider.SecuritySettings.RequireSsl = true; this.MockResponder.RegisterMockRPDiscovery(); @@ -56,7 +56,7 @@ namespace DotNetOpenAuth.Test.OpenId.Provider { /// <summary> /// Verifies that when discovery would be performed over HTTPS that discovery succeeds. /// </summary> - [TestMethod] + [TestCase] public void IsReturnUrlDiscoverableRequireSsl() { this.MockResponder.RegisterMockRPDiscovery(); this.checkIdRequest.Realm = RPRealmUriSsl; @@ -73,7 +73,7 @@ namespace DotNetOpenAuth.Test.OpenId.Provider { Assert.AreEqual(RelyingPartyDiscoveryResult.Success, this.request.IsReturnUrlDiscoverable(this.provider)); } - [TestMethod] + [TestCase] public void IsReturnUrlDiscoverableValidButNoMatch() { this.MockResponder.RegisterMockRPDiscovery(); this.provider.SecuritySettings.RequireSsl = false; // reset for another failure test case diff --git a/src/DotNetOpenAuth.Test/OpenId/Provider/OpenIdProviderTests.cs b/src/DotNetOpenAuth.Test/OpenId/Provider/OpenIdProviderTests.cs index 8528aa7..75d871c 100644 --- a/src/DotNetOpenAuth.Test/OpenId/Provider/OpenIdProviderTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/Provider/OpenIdProviderTests.cs @@ -15,13 +15,13 @@ namespace DotNetOpenAuth.Test.OpenId.Provider { using DotNetOpenAuth.OpenId.Provider; using DotNetOpenAuth.OpenId.RelyingParty; using DotNetOpenAuth.Test.Hosting; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; - [TestClass] + [TestFixture] public class OpenIdProviderTests : OpenIdTestBase { private OpenIdProvider provider; - [TestInitialize] + [SetUp] public override void SetUp() { base.SetUp(); @@ -31,7 +31,7 @@ namespace DotNetOpenAuth.Test.OpenId.Provider { /// <summary> /// Verifies that the constructor throws an exception if the app store is null. /// </summary> - [TestMethod, ExpectedException(typeof(ArgumentNullException))] + [TestCase, ExpectedException(typeof(ArgumentNullException))] public void CtorNull() { new OpenIdProvider(null); } @@ -39,7 +39,7 @@ namespace DotNetOpenAuth.Test.OpenId.Provider { /// <summary> /// Verifies that the SecuritySettings property throws when set to null. /// </summary> - [TestMethod, ExpectedException(typeof(ArgumentNullException))] + [TestCase, ExpectedException(typeof(ArgumentNullException))] public void SecuritySettingsSetNull() { this.provider.SecuritySettings = null; } @@ -47,25 +47,25 @@ namespace DotNetOpenAuth.Test.OpenId.Provider { /// <summary> /// Verifies the SecuritySettings property can be set to a new instance. /// </summary> - [TestMethod] + [TestCase] public void SecuritySettings() { var newSettings = new ProviderSecuritySettings(); this.provider.SecuritySettings = newSettings; Assert.AreSame(newSettings, this.provider.SecuritySettings); } - [TestMethod] + [TestCase] public void ExtensionFactories() { var factories = this.provider.ExtensionFactories; Assert.IsNotNull(factories); Assert.AreEqual(1, factories.Count); - Assert.IsInstanceOfType(factories[0], typeof(StandardOpenIdExtensionFactory)); + Assert.IsInstanceOf<StandardOpenIdExtensionFactory>(factories[0]); } /// <summary> /// Verifies the Channel property. /// </summary> - [TestMethod] + [TestCase] public void ChannelGetter() { Assert.IsNotNull(this.provider.Channel); } @@ -73,7 +73,7 @@ namespace DotNetOpenAuth.Test.OpenId.Provider { /// <summary> /// Verifies the GetRequest method throws outside an HttpContext. /// </summary> - [TestMethod, ExpectedException(typeof(InvalidOperationException))] + [TestCase, ExpectedException(typeof(InvalidOperationException))] public void GetRequestNoContext() { HttpContext.Current = null; this.provider.GetRequest(); @@ -82,7 +82,7 @@ namespace DotNetOpenAuth.Test.OpenId.Provider { /// <summary> /// Verifies GetRequest throws on null input. /// </summary> - [TestMethod, ExpectedException(typeof(ArgumentNullException))] + [TestCase, ExpectedException(typeof(ArgumentNullException))] public void GetRequestNull() { this.provider.GetRequest(null); } @@ -90,7 +90,7 @@ namespace DotNetOpenAuth.Test.OpenId.Provider { /// <summary> /// Verifies that GetRequest correctly returns the right messages. /// </summary> - [TestMethod] + [TestCase] public void GetRequest() { HttpRequestInfo httpInfo = new HttpRequestInfo(); httpInfo.UrlBeforeRewriting = new Uri("http://someUri"); @@ -104,13 +104,13 @@ namespace DotNetOpenAuth.Test.OpenId.Provider { }, op => { IRequest request = op.GetRequest(); - Assert.IsInstanceOfType(request, typeof(AutoResponsiveRequest)); + Assert.IsInstanceOf<AutoResponsiveRequest>(request); op.SendResponse(request); }); coordinator.Run(); } - [TestMethod] + [TestCase] public void BadRequestsGenerateValidErrorResponses() { var coordinator = new OpenIdCoordinator( rp => { @@ -127,7 +127,7 @@ namespace DotNetOpenAuth.Test.OpenId.Provider { coordinator.Run(); } - [TestMethod] + [TestCase, Category("HostASPNET")] public void BadRequestsGenerateValidErrorResponsesHosted() { try { using (AspNetHost host = AspNetHost.CreateHost(TestWebDirectory)) { diff --git a/src/DotNetOpenAuth.Test/OpenId/Provider/PerformanceTests.cs b/src/DotNetOpenAuth.Test/OpenId/Provider/PerformanceTests.cs index 9f4727d..7984b58 100644 --- a/src/DotNetOpenAuth.Test/OpenId/Provider/PerformanceTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/Provider/PerformanceTests.cs @@ -18,28 +18,28 @@ namespace DotNetOpenAuth.Test.OpenId.Provider { using DotNetOpenAuth.OpenId.ChannelElements; using DotNetOpenAuth.OpenId.Messages; using DotNetOpenAuth.OpenId.Provider; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; - [TestClass] + [TestFixture, Category("Performance")] public class PerformanceTests : OpenIdTestBase { private const string SharedAssociationHandle = "handle"; private static readonly TimeSpan TestRunTime = TimeSpan.FromSeconds(3); private OpenIdProvider provider; - [TestInitialize] + [SetUp] public override void SetUp() { base.SetUp(); SuspendLogging(); this.provider = CreateProvider(); } - [TestCleanup] + [TearDown] public override void Cleanup() { ResumeLogging(); base.Cleanup(); } - [TestMethod] + [TestCase] public void AssociateDH() { var associateRequest = this.CreateAssociateRequest(OPUri); Stopwatch timer = new Stopwatch(); @@ -48,15 +48,15 @@ namespace DotNetOpenAuth.Test.OpenId.Provider { for (iterations = 0; timer.ElapsedMilliseconds < TestRunTime.TotalMilliseconds; iterations++) { IRequest request = this.provider.GetRequest(associateRequest); var response = this.provider.PrepareResponse(request); - Assert.IsInstanceOfType(response.OriginalMessage, typeof(AssociateSuccessfulResponse)); + Assert.IsInstanceOf<AssociateSuccessfulResponse>(response.OriginalMessage); } timer.Stop(); double executionsPerSecond = GetExecutionsPerSecond(iterations, timer); - TestContext.WriteLine("Created {0} associations in {1}, or {2} per second.", iterations, timer.Elapsed, executionsPerSecond); + TestUtilities.TestLogger.InfoFormat("Created {0} associations in {1}, or {2} per second.", iterations, timer.Elapsed, executionsPerSecond); Assert.IsTrue(executionsPerSecond >= 2, "Too slow ({0} >= 2 executions per second required.)", executionsPerSecond); } - [TestMethod] + [TestCase] public void AssociateClearText() { var associateRequest = this.CreateAssociateRequest(OPUriSsl); // SSL will cause a plaintext association Stopwatch timer = new Stopwatch(); @@ -65,29 +65,29 @@ namespace DotNetOpenAuth.Test.OpenId.Provider { for (iterations = 0; timer.ElapsedMilliseconds < TestRunTime.TotalMilliseconds; iterations++) { IRequest request = this.provider.GetRequest(associateRequest); var response = this.provider.PrepareResponse(request); - Assert.IsInstanceOfType(response.OriginalMessage, typeof(AssociateSuccessfulResponse)); + Assert.IsInstanceOf<AssociateSuccessfulResponse>(response.OriginalMessage); } timer.Stop(); double executionsPerSecond = GetExecutionsPerSecond(iterations, timer); - TestContext.WriteLine("Created {0} associations in {1}, or {2} per second.", iterations, timer.Elapsed, executionsPerSecond); + TestUtilities.TestLogger.InfoFormat("Created {0} associations in {1}, or {2} per second.", iterations, timer.Elapsed, executionsPerSecond); Assert.IsTrue(executionsPerSecond > 1000, "Too slow ({0} > 1000 executions per second required.)", executionsPerSecond); } - [TestMethod] + [TestCase] public void CheckIdSharedHmacSha1Association() { Protocol protocol = Protocol.Default; string assocType = protocol.Args.SignatureAlgorithm.HMAC_SHA1; double executionsPerSecond = this.ParameterizedCheckIdTest(protocol, assocType); - TestContext.WriteLine("{0} executions per second.", executionsPerSecond); + TestUtilities.TestLogger.InfoFormat("{0} executions per second.", executionsPerSecond); Assert.IsTrue(executionsPerSecond > 500, "Too slow ({0} > 500 executions per second required.)", executionsPerSecond); } - [TestMethod] + [TestCase] public void CheckIdSharedHmacSha256Association() { Protocol protocol = Protocol.Default; string assocType = protocol.Args.SignatureAlgorithm.HMAC_SHA256; double executionsPerSecond = this.ParameterizedCheckIdTest(protocol, assocType); - TestContext.WriteLine("{0} executions per second.", executionsPerSecond); + TestUtilities.TestLogger.InfoFormat("{0} executions per second.", executionsPerSecond); Assert.IsTrue(executionsPerSecond > 400, "Too slow ({0} > 400 executions per second required.)", executionsPerSecond); } @@ -110,11 +110,11 @@ namespace DotNetOpenAuth.Test.OpenId.Provider { var request = (IAuthenticationRequest)this.provider.GetRequest(checkidRequest); request.IsAuthenticated = true; var response = this.provider.PrepareResponse(request); - Assert.IsInstanceOfType(response.OriginalMessage, typeof(PositiveAssertionResponse)); + Assert.IsInstanceOf<PositiveAssertionResponse>(response.OriginalMessage); } timer.Stop(); double executionsPerSecond = GetExecutionsPerSecond(iterations, timer); - TestContext.WriteLine("Responded to {0} checkid messages in {1}; or {2} authentications per second.", iterations, timer.Elapsed, executionsPerSecond); + TestUtilities.TestLogger.InfoFormat("Responded to {0} checkid messages in {1}; or {2} authentications per second.", iterations, timer.Elapsed, executionsPerSecond); return executionsPerSecond; } diff --git a/src/DotNetOpenAuth.Test/OpenId/ProviderEndpointDescriptionTests.cs b/src/DotNetOpenAuth.Test/OpenId/ProviderEndpointDescriptionTests.cs index 089265f..65185fc 100644 --- a/src/DotNetOpenAuth.Test/OpenId/ProviderEndpointDescriptionTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/ProviderEndpointDescriptionTests.cs @@ -6,57 +6,23 @@ namespace DotNetOpenAuth.Test.OpenId { using System; + using DotNetOpenAuth.Messaging; using DotNetOpenAuth.OpenId; using DotNetOpenAuth.OpenId.Extensions.SimpleRegistration; using DotNetOpenAuth.OpenId.Messages; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; - [TestClass] + [TestFixture] public class ProviderEndpointDescriptionTests : OpenIdTestBase { - private ProviderEndpointDescription se; - - private string[] v20TypeUris = { Protocol.V20.ClaimedIdentifierServiceTypeURI }; - - [TestInitialize] - public override void SetUp() { - base.SetUp(); - - this.se = new ProviderEndpointDescription(OPUri, Protocol.V20.Version); - } - - [TestMethod, ExpectedException(typeof(ArgumentNullException))] - public void IsExtensionSupportedNullType() { - this.se.IsExtensionSupported((Type)null); - } - - [TestMethod, ExpectedException(typeof(ArgumentException))] - public void IsExtensionSupportedNullString() { - this.se.IsExtensionSupported((string)null); - } - - [TestMethod, ExpectedException(typeof(ArgumentException))] - public void IsExtensionSupportedEmptyString() { - this.se.IsExtensionSupported(string.Empty); + [TestCase] + public void NonNullCapabilities() { + var epd = new ProviderEndpointDescription(OPUri, Protocol.Default.Version); + Assert.IsNotNull(epd.Capabilities); } - [TestMethod, ExpectedException(typeof(ArgumentNullException))] - public void IsExtensionSupportedNullExtension() { - this.se.IsExtensionSupported((IOpenIdMessageExtension)null); - } - - [TestMethod] - public void IsExtensionSupported() { - this.se = new ProviderEndpointDescription(OPUri, this.v20TypeUris); - Assert.IsFalse(this.se.IsExtensionSupported<ClaimsRequest>()); - Assert.IsFalse(this.se.IsExtensionSupported(new ClaimsRequest())); - Assert.IsFalse(this.se.IsExtensionSupported("http://someextension/typeuri")); - - this.se = new ProviderEndpointDescription( - OPUri, - new[] { Protocol.V20.ClaimedIdentifierServiceTypeURI, "http://someextension", Constants.sreg_ns }); - Assert.IsTrue(this.se.IsExtensionSupported<ClaimsRequest>()); - Assert.IsTrue(this.se.IsExtensionSupported(new ClaimsRequest())); - Assert.IsTrue(this.se.IsExtensionSupported("http://someextension")); + [TestCase, ExpectedException(typeof(ProtocolException))] + public void ProtocolDetectionWithoutClues() { + new ProviderEndpointDescription(OPUri, new[] { Protocol.V20.HtmlDiscoveryLocalIdKey }); // random type URI irrelevant to detection } } } diff --git a/src/DotNetOpenAuth.Test/OpenId/RealmTests.cs b/src/DotNetOpenAuth.Test/OpenId/RealmTests.cs index e062e12..fceb15a 100644 --- a/src/DotNetOpenAuth.Test/OpenId/RealmTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/RealmTests.cs @@ -7,11 +7,11 @@ namespace DotNetOpenAuth.Test { using System; using DotNetOpenAuth.OpenId; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; - [TestClass] + [TestFixture] public class RealmTests { - [TestMethod] + [TestCase] public void ValidRealmsTest() { // Just create these. If any are determined to be invalid, // an exception should be thrown that would fail this test. @@ -26,67 +26,67 @@ namespace DotNetOpenAuth.Test { new Realm("http://*.guest.myopenid.com/"); } - [TestMethod] + [TestCase] [ExpectedException(typeof(ArgumentNullException))] public void InvalidRealmNullString() { new Realm((string)null); } - [TestMethod] + [TestCase] [ExpectedException(typeof(ArgumentNullException))] public void InvalidRealmNullUri() { new Realm((Uri)null); } - [TestMethod] + [TestCase] [ExpectedException(typeof(UriFormatException))] public void InvalidRealmEmpty() { new Realm(string.Empty); } - [TestMethod] + [TestCase] [ExpectedException(typeof(UriFormatException))] public void InvalidRealmBadProtocol() { new Realm("asdf://www.microsoft.com/"); } - [TestMethod] + [TestCase] [ExpectedException(typeof(UriFormatException))] public void InvalidRealmNoScheme() { new Realm("www.guy.com"); } - [TestMethod] + [TestCase] [ExpectedException(typeof(UriFormatException))] public void InvalidRealmBadWildcard1() { new Realm("http://*www.my.com"); } - [TestMethod] + [TestCase] [ExpectedException(typeof(UriFormatException))] public void InvalidRealmBadWildcard2() { new Realm("http://www.*.com"); } - [TestMethod] + [TestCase] [ExpectedException(typeof(UriFormatException))] public void InvalidRealmBadWildcard3() { new Realm("http://www.my.*/"); } - [TestMethod] + [TestCase] [ExpectedException(typeof(UriFormatException))] public void InvalidRealmTwoWildcards1() { new Realm("http://**.my.com"); } - [TestMethod] + [TestCase] [ExpectedException(typeof(UriFormatException))] public void InvalidRealmTwoWildcards2() { new Realm("http://*.*.my.com"); } - [TestMethod] + [TestCase] public void IsSaneTest() { Assert.IsTrue(new Realm("http://www.myopenid.com").IsSane); Assert.IsTrue(new Realm("http://myopenid.com").IsSane); @@ -98,7 +98,7 @@ namespace DotNetOpenAuth.Test { Assert.IsFalse(new Realm("http://*.co.uk").IsSane); } - [TestMethod] + [TestCase] public void IsUrlWithinRealmTests() { /* * The openid.return_to URL MUST descend from the openid.trust_root, or the @@ -166,7 +166,7 @@ namespace DotNetOpenAuth.Test { Assert.IsFalse(new Realm("http://www.my.com/abc").Contains("http://www.my.com/ABC")); } - [TestMethod] + [TestCase] public void ImplicitConversionFromStringTests() { Realm realm = "http://host"; Assert.AreEqual("host", realm.Host); @@ -174,7 +174,7 @@ namespace DotNetOpenAuth.Test { Assert.IsNull(realm); } - [TestMethod] + [TestCase] public void ImplicitConversionToStringTests() { Realm realm = new Realm("http://host/"); string realmString = realm; @@ -184,7 +184,7 @@ namespace DotNetOpenAuth.Test { Assert.IsNull(realmString); } - [TestMethod] + [TestCase] public void ImplicitConverstionFromUriTests() { Uri uri = new Uri("http://host"); Realm realm = uri; @@ -194,7 +194,7 @@ namespace DotNetOpenAuth.Test { Assert.IsNull(realm); } - [TestMethod] + [TestCase] public void EqualsTest() { Realm testRealm1a = new Realm("http://www.yahoo.com"); Realm testRealm1b = new Realm("http://www.yahoo.com"); diff --git a/src/DotNetOpenAuth.Test/OpenId/RelyingParty/AuthenticationRequestTests.cs b/src/DotNetOpenAuth.Test/OpenId/RelyingParty/AuthenticationRequestTests.cs index 0ddc76b..001f3fa 100644 --- a/src/DotNetOpenAuth.Test/OpenId/RelyingParty/AuthenticationRequestTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/RelyingParty/AuthenticationRequestTests.cs @@ -16,9 +16,10 @@ namespace DotNetOpenAuth.Test.OpenId.RelyingParty { using DotNetOpenAuth.OpenId.Extensions.SimpleRegistration; using DotNetOpenAuth.OpenId.Messages; using DotNetOpenAuth.OpenId.RelyingParty; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using DotNetOpenAuth.Test.Mocks; + using NUnit.Framework; - [TestClass] + [TestFixture] public class AuthenticationRequestTests : OpenIdTestBase { private readonly Realm realm = new Realm("http://localhost/rp.aspx"); private readonly Identifier claimedId = "http://claimedId"; @@ -26,7 +27,7 @@ namespace DotNetOpenAuth.Test.OpenId.RelyingParty { private readonly Protocol protocol = Protocol.Default; private Uri returnTo; - [TestInitialize] + [SetUp] public override void SetUp() { base.SetUp(); this.returnTo = new Uri("http://localhost/rp.aspx"); @@ -35,9 +36,9 @@ namespace DotNetOpenAuth.Test.OpenId.RelyingParty { /// <summary> /// Verifies IsDirectedIdentity returns true when appropriate. /// </summary> - [TestMethod] + [TestCase] public void IsDirectedIdentity() { - IAuthenticationRequest_Accessor iauthRequest = this.CreateAuthenticationRequest(this.claimedId, this.claimedId); + var iauthRequest = this.CreateAuthenticationRequest(this.claimedId, this.claimedId); Assert.IsFalse(iauthRequest.IsDirectedIdentity); iauthRequest = this.CreateAuthenticationRequest(IdentifierSelect, IdentifierSelect); @@ -47,9 +48,9 @@ namespace DotNetOpenAuth.Test.OpenId.RelyingParty { /// <summary> /// Verifies ClaimedIdentifier behavior. /// </summary> - [TestMethod] + [TestCase] public void ClaimedIdentifier() { - IAuthenticationRequest_Accessor iauthRequest = this.CreateAuthenticationRequest(this.claimedId, this.delegatedLocalId); + var iauthRequest = this.CreateAuthenticationRequest(this.claimedId, this.delegatedLocalId); Assert.AreEqual(this.claimedId, iauthRequest.ClaimedIdentifier); iauthRequest = this.CreateAuthenticationRequest(IdentifierSelect, IdentifierSelect); @@ -59,16 +60,16 @@ namespace DotNetOpenAuth.Test.OpenId.RelyingParty { /// <summary> /// Verifies ProviderVersion behavior. /// </summary> - [TestMethod] + [TestCase] public void ProviderVersion() { var authRequest = this.CreateAuthenticationRequest(this.claimedId, this.claimedId); - Assert.AreEqual(this.protocol.Version, authRequest.endpoint.Protocol.Version); + Assert.AreEqual(this.protocol.Version, authRequest.DiscoveryResult.Version); } /// <summary> /// Verifies RedirectingResponse. /// </summary> - [TestMethod] + [TestCase] public void CreateRequestMessage() { OpenIdCoordinator coordinator = new OpenIdCoordinator( rp => { @@ -106,7 +107,7 @@ namespace DotNetOpenAuth.Test.OpenId.RelyingParty { /// <summary> /// Verifies that delegating authentication requests are filtered out when configured to do so. /// </summary> - [TestMethod] + [TestCase] public void CreateFiltersDelegatingIdentifiers() { Identifier id = GetMockIdentifier(ProtocolVersion.V20, false, true); var rp = CreateRelyingParty(); @@ -122,9 +123,9 @@ namespace DotNetOpenAuth.Test.OpenId.RelyingParty { /// <summary> /// Verifies the Provider property returns non-null. /// </summary> - [TestMethod] + [TestCase] public void Provider() { - IAuthenticationRequest_Accessor authRequest = this.CreateAuthenticationRequest(this.claimedId, this.claimedId); + var authRequest = this.CreateAuthenticationRequest(this.claimedId, this.claimedId); Assert.IsNotNull(authRequest.Provider); Assert.AreEqual(OPUri, authRequest.Provider.Uri); Assert.AreEqual(this.protocol.Version, authRequest.Provider.Version); @@ -133,9 +134,9 @@ namespace DotNetOpenAuth.Test.OpenId.RelyingParty { /// <summary> /// Verifies that AddCallbackArguments adds query arguments to the return_to URL of the message. /// </summary> - [TestMethod] + [TestCase] public void AddCallbackArgument() { - IAuthenticationRequest_Accessor authRequest = this.CreateAuthenticationRequest(this.claimedId, this.claimedId); + var authRequest = this.CreateAuthenticationRequest(this.claimedId, this.claimedId); Assert.AreEqual(this.returnTo, authRequest.ReturnToUrl); authRequest.AddCallbackArguments("p1", "v1"); var req = (SignedResponseRequest)authRequest.RedirectingResponse.OriginalMessage; @@ -147,12 +148,12 @@ namespace DotNetOpenAuth.Test.OpenId.RelyingParty { /// Verifies that AddCallbackArguments replaces pre-existing parameter values /// rather than appending them. /// </summary> - [TestMethod] + [TestCase] public void AddCallbackArgumentClearsPreviousArgument() { UriBuilder returnToWithArgs = new UriBuilder(this.returnTo); returnToWithArgs.AppendQueryArgs(new Dictionary<string, string> { { "p1", "v1" } }); this.returnTo = returnToWithArgs.Uri; - IAuthenticationRequest_Accessor authRequest = this.CreateAuthenticationRequest(this.claimedId, this.claimedId); + var authRequest = this.CreateAuthenticationRequest(this.claimedId, this.claimedId); authRequest.AddCallbackArguments("p1", "v2"); var req = (SignedResponseRequest)authRequest.RedirectingResponse.OriginalMessage; NameValueCollection query = HttpUtility.ParseQueryString(req.ReturnTo.Query); @@ -162,32 +163,48 @@ namespace DotNetOpenAuth.Test.OpenId.RelyingParty { /// <summary> /// Verifies identity-less checkid_* request behavior. /// </summary> - [TestMethod] + [TestCase] public void NonIdentityRequest() { - IAuthenticationRequest_Accessor authRequest = this.CreateAuthenticationRequest(this.claimedId, this.claimedId); + var authRequest = this.CreateAuthenticationRequest(this.claimedId, this.claimedId); authRequest.IsExtensionOnly = true; Assert.IsTrue(authRequest.IsExtensionOnly); var req = (SignedResponseRequest)authRequest.RedirectingResponse.OriginalMessage; - Assert.IsNotInstanceOfType(req, typeof(CheckIdRequest), "An unexpected SignedResponseRequest derived type was generated."); + Assert.IsNotInstanceOf<CheckIdRequest>(req, "An unexpected SignedResponseRequest derived type was generated."); + } + + /// <summary> + /// Verifies that discovery on identifiers that serve as OP identifiers and claimed identifiers + /// only generate OP Identifier auth requests. + /// </summary> + [TestCase] + public void DualIdentifierUsedOnlyAsOPIdentifierForAuthRequest() { + var rp = this.CreateRelyingParty(true); + var results = AuthenticationRequest.Create(GetMockDualIdentifier(), rp, this.realm, this.returnTo, false).ToList(); + Assert.AreEqual(1, results.Count); + Assert.IsTrue(results[0].IsDirectedIdentity); + + // Also test when dual identiifer support is turned on. + rp.SecuritySettings.AllowDualPurposeIdentifiers = true; + results = AuthenticationRequest.Create(GetMockDualIdentifier(), rp, this.realm, this.returnTo, false).ToList(); + Assert.AreEqual(1, results.Count); + Assert.IsTrue(results[0].IsDirectedIdentity); } /// <summary> /// Verifies that authentication requests are generated first for OPs that respond /// to authentication requests. /// </summary> - [TestMethod, Ignore] + [TestCase, Ignore("Not yet implemented")] public void UnresponsiveProvidersComeLast() { // TODO: code here Assert.Inconclusive("Not yet implemented."); } - private AuthenticationRequest_Accessor CreateAuthenticationRequest(Identifier claimedIdentifier, Identifier providerLocalIdentifier) { + private AuthenticationRequest CreateAuthenticationRequest(Identifier claimedIdentifier, Identifier providerLocalIdentifier) { ProviderEndpointDescription providerEndpoint = new ProviderEndpointDescription(OPUri, this.protocol.Version); - ServiceEndpoint endpoint = ServiceEndpoint.CreateForClaimedIdentifier(claimedIdentifier, providerLocalIdentifier, providerEndpoint, 10, 5); - ServiceEndpoint_Accessor endpointAccessor = ServiceEndpoint_Accessor.AttachShadow(endpoint); + IdentifierDiscoveryResult endpoint = IdentifierDiscoveryResult.CreateForClaimedIdentifier(claimedIdentifier, providerLocalIdentifier, providerEndpoint, 10, 5); OpenIdRelyingParty rp = this.CreateRelyingParty(); - AuthenticationRequest_Accessor authRequest = new AuthenticationRequest_Accessor(endpointAccessor, this.realm, this.returnTo, rp); - return authRequest; + return AuthenticationRequest.CreateForTest(endpoint, this.realm, this.returnTo, rp); } } } diff --git a/src/DotNetOpenAuth.Test/OpenId/RelyingParty/FailedAuthenticationResponseTests.cs b/src/DotNetOpenAuth.Test/OpenId/RelyingParty/FailedAuthenticationResponseTests.cs index a82634a..43d056f 100644 --- a/src/DotNetOpenAuth.Test/OpenId/RelyingParty/FailedAuthenticationResponseTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/RelyingParty/FailedAuthenticationResponseTests.cs @@ -12,14 +12,14 @@ namespace DotNetOpenAuth.Test.OpenId.RelyingParty { using DotNetOpenAuth.Messaging; using DotNetOpenAuth.OpenId.Extensions.SimpleRegistration; using DotNetOpenAuth.OpenId.RelyingParty; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; - [TestClass] + [TestFixture] public class FailedAuthenticationResponseTests : OpenIdTestBase { private FailedAuthenticationResponse response; private ProtocolException exception; - [TestInitialize] + [SetUp] public override void SetUp() { base.SetUp(); @@ -27,12 +27,12 @@ namespace DotNetOpenAuth.Test.OpenId.RelyingParty { this.response = new FailedAuthenticationResponse(this.exception); } - [TestMethod, ExpectedException(typeof(ArgumentNullException))] + [TestCase, ExpectedException(typeof(ArgumentNullException))] public void CtorNull() { new FailedAuthenticationResponse(null); } - [TestMethod] + [TestCase] public void CommonProperties() { Assert.AreEqual(AuthenticationStatus.Failed, this.response.Status); Assert.AreSame(this.exception, this.response.Exception); @@ -40,7 +40,7 @@ namespace DotNetOpenAuth.Test.OpenId.RelyingParty { Assert.IsNull(this.response.FriendlyIdentifierForDisplay); } - [TestMethod] + [TestCase] public void CommonMethods() { Assert.IsNull(this.response.GetExtension<ClaimsRequest>()); Assert.IsNull(this.response.GetExtension(typeof(ClaimsRequest))); diff --git a/src/DotNetOpenAuth.Test/OpenId/RelyingParty/IdentifierDiscoveryResultTests.cs b/src/DotNetOpenAuth.Test/OpenId/RelyingParty/IdentifierDiscoveryResultTests.cs new file mode 100644 index 0000000..896cf57 --- /dev/null +++ b/src/DotNetOpenAuth.Test/OpenId/RelyingParty/IdentifierDiscoveryResultTests.cs @@ -0,0 +1,199 @@ +//----------------------------------------------------------------------- +// <copyright file="IdentifierDiscoveryResultTests.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.Extensions.SimpleRegistration; + using DotNetOpenAuth.OpenId.Messages; + using DotNetOpenAuth.OpenId.RelyingParty; + using DotNetOpenAuth.Test.Messaging; + using NUnit.Framework; + + [TestFixture] + public class IdentifierDiscoveryResultTests : 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; + + [SetUp] + public override void SetUp() { + base.SetUp(); + } + + [TestCase] + public void Ctor() { + IdentifierDiscoveryResult se = IdentifierDiscoveryResult.CreateForClaimedIdentifier(this.claimedId, this.localId, new ProviderEndpointDescription(this.providerEndpoint, this.v20TypeUris), this.servicePriority, this.uriPriority); + Assert.AreEqual(this.claimedId, se.ClaimedIdentifier); + Assert.AreSame(this.providerEndpoint, se.ProviderEndpoint); + Assert.AreSame(this.localId, se.ProviderLocalIdentifier); + CollectionAssert<string>.AreEquivalent(this.v20TypeUris, se.Capabilities); + Assert.AreEqual(this.servicePriority, se.ServicePriority); + } + + [TestCase] + public void CtorImpliedLocalIdentifier() { + IdentifierDiscoveryResult se = IdentifierDiscoveryResult.CreateForClaimedIdentifier(this.claimedId, null, new ProviderEndpointDescription(this.providerEndpoint, this.v20TypeUris), this.servicePriority, this.uriPriority); + Assert.AreEqual(this.claimedId, se.ClaimedIdentifier); + Assert.AreSame(this.providerEndpoint, se.ProviderEndpoint); + Assert.AreSame(this.claimedId, se.ProviderLocalIdentifier); + CollectionAssert<string>.AreEquivalent(this.v20TypeUris, se.Capabilities); + } + + [TestCase] + public void ProtocolDetection() { + IdentifierDiscoveryResult se = IdentifierDiscoveryResult.CreateForClaimedIdentifier(this.claimedId, this.localId, new ProviderEndpointDescription(this.providerEndpoint, this.v20TypeUris), this.servicePriority, this.uriPriority); + Assert.AreSame(Protocol.V20, se.Protocol); + se = IdentifierDiscoveryResult.CreateForClaimedIdentifier( + this.claimedId, + this.localId, + new ProviderEndpointDescription(this.providerEndpoint, new[] { Protocol.V20.OPIdentifierServiceTypeURI }), + this.servicePriority, + this.uriPriority); + Assert.AreSame(Protocol.V20, se.Protocol); + se = IdentifierDiscoveryResult.CreateForClaimedIdentifier(this.claimedId, this.localId, new ProviderEndpointDescription(this.providerEndpoint, this.v11TypeUris), this.servicePriority, this.uriPriority); + Assert.AreSame(Protocol.V11, se.Protocol); + } + + [TestCase] + public void EqualsTests() { + IdentifierDiscoveryResult se = IdentifierDiscoveryResult.CreateForClaimedIdentifier(this.claimedId, this.localId, new ProviderEndpointDescription(this.providerEndpoint, this.v20TypeUris), this.servicePriority, this.uriPriority); + IdentifierDiscoveryResult se2 = IdentifierDiscoveryResult.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); + + IdentifierDiscoveryResult se3 = IdentifierDiscoveryResult.CreateForClaimedIdentifier(new UriIdentifier(this.claimedId + "a"), this.localId, new ProviderEndpointDescription(this.providerEndpoint, this.v20TypeUris), this.servicePriority, this.uriPriority); + Assert.AreNotEqual(se, se3); + se3 = IdentifierDiscoveryResult.CreateForClaimedIdentifier(this.claimedId, this.localId, new ProviderEndpointDescription(new Uri(this.providerEndpoint.AbsoluteUri + "a"), this.v20TypeUris), this.servicePriority, this.uriPriority); + Assert.AreNotEqual(se, se3); + se3 = IdentifierDiscoveryResult.CreateForClaimedIdentifier(this.claimedId, this.localId + "a", new ProviderEndpointDescription(this.providerEndpoint, this.v20TypeUris), this.servicePriority, this.uriPriority); + Assert.AreNotEqual(se, se3); + se3 = IdentifierDiscoveryResult.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. + var list = new List<IdentifierDiscoveryResult>(); + list.Add(se); + Assert.IsTrue(list.Contains(se2)); + } + + [TestCase] + public void GetFriendlyIdentifierForDisplay() { + Uri providerEndpoint = new Uri("http://someprovider"); + Identifier localId = "someuser"; + string[] serviceTypeUris = new string[] { + Protocol.V20.ClaimedIdentifierServiceTypeURI, + }; + IdentifierDiscoveryResult se; + + // strip of protocol, port, query and fragment + se = IdentifierDiscoveryResult.CreateForClaimedIdentifier( + "http://someprovider.somedomain.com:79/someuser?query#frag", + localId, + new ProviderEndpointDescription(providerEndpoint, serviceTypeUris), + null, + null); + Assert.AreEqual("someprovider.somedomain.com/someuser", se.FriendlyIdentifierForDisplay); + + // unescape characters + Uri foreignUri = new Uri("http://server崎/村"); + se = IdentifierDiscoveryResult.CreateForClaimedIdentifier(foreignUri, localId, new ProviderEndpointDescription(providerEndpoint, serviceTypeUris), null, null); + Assert.AreEqual("server崎/村", se.FriendlyIdentifierForDisplay); + + // restore user supplied identifier to XRIs + se = IdentifierDiscoveryResult.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 = IdentifierDiscoveryResult.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); + } + + [TestCase] + public void IsTypeUriPresent() { + IdentifierDiscoveryResult se = IdentifierDiscoveryResult.CreateForClaimedIdentifier(this.claimedXri, this.userSuppliedXri, this.localId, new ProviderEndpointDescription(this.providerEndpoint, this.v20TypeUris), this.servicePriority, this.uriPriority); + Assert.IsTrue(se.IsTypeUriPresent(Protocol.Default.ClaimedIdentifierServiceTypeURI)); + Assert.IsFalse(se.IsTypeUriPresent("http://someother")); + } + + [TestCase, ExpectedException(typeof(ArgumentException))] + public void IsTypeUriPresentNull() { + IdentifierDiscoveryResult se = IdentifierDiscoveryResult.CreateForClaimedIdentifier(this.claimedXri, this.userSuppliedXri, this.localId, new ProviderEndpointDescription(this.providerEndpoint, this.v20TypeUris), this.servicePriority, this.uriPriority); + se.IsTypeUriPresent(null); + } + + [TestCase, ExpectedException(typeof(ArgumentException))] + public void IsTypeUriPresentEmpty() { + IdentifierDiscoveryResult se = IdentifierDiscoveryResult.CreateForClaimedIdentifier(this.claimedXri, this.userSuppliedXri, this.localId, new ProviderEndpointDescription(this.providerEndpoint, this.v20TypeUris), this.servicePriority, this.uriPriority); + se.IsTypeUriPresent(string.Empty); + } + + [TestCase, ExpectedException(typeof(ArgumentNullException))] + public void IsExtensionSupportedNullType() { + var se = IdentifierDiscoveryResult.CreateForProviderIdentifier(OPUri, new ProviderEndpointDescription(OPUri, this.v20TypeUris), null, null); + se.IsExtensionSupported((Type)null); + } + + [TestCase, ExpectedException(typeof(ArgumentException))] + public void IsTypeUriPresentNullString() { + var se = IdentifierDiscoveryResult.CreateForProviderIdentifier(OPUri, new ProviderEndpointDescription(OPUri, this.v20TypeUris), null, null); + se.IsTypeUriPresent((string)null); + } + + [TestCase, ExpectedException(typeof(ArgumentException))] + public void IsTypeUriPresentEmptyString() { + var se = IdentifierDiscoveryResult.CreateForProviderIdentifier(OPUri, new ProviderEndpointDescription(OPUri, this.v20TypeUris), null, null); + se.IsTypeUriPresent(string.Empty); + } + + [TestCase, ExpectedException(typeof(ArgumentNullException))] + public void IsExtensionSupportedNullExtension() { + var se = IdentifierDiscoveryResult.CreateForProviderIdentifier(OPUri, new ProviderEndpointDescription(OPUri, this.v20TypeUris), null, null); + se.IsExtensionSupported((IOpenIdMessageExtension)null); + } + + [TestCase] + public void IsExtensionSupported() { + var se = IdentifierDiscoveryResult.CreateForProviderIdentifier(OPUri, new ProviderEndpointDescription(OPUri, this.v20TypeUris), null, null); + Assert.IsFalse(se.IsExtensionSupported<ClaimsRequest>()); + Assert.IsFalse(se.IsExtensionSupported(new ClaimsRequest())); + Assert.IsFalse(se.IsTypeUriPresent("http://someextension/typeuri")); + + se = IdentifierDiscoveryResult.CreateForProviderIdentifier( + OPUri, + new ProviderEndpointDescription(OPUri, new[] { Protocol.V20.ClaimedIdentifierServiceTypeURI, "http://someextension", Constants.sreg_ns }), + null, + null); + Assert.IsTrue(se.IsExtensionSupported<ClaimsRequest>()); + Assert.IsTrue(se.IsExtensionSupported(new ClaimsRequest())); + Assert.IsTrue(se.IsTypeUriPresent("http://someextension")); + } + } +} diff --git a/src/DotNetOpenAuth.Test/OpenId/RelyingParty/NegativeAuthenticationResponseTests.cs b/src/DotNetOpenAuth.Test/OpenId/RelyingParty/NegativeAuthenticationResponseTests.cs index acf537e..dbb4a42 100644 --- a/src/DotNetOpenAuth.Test/OpenId/RelyingParty/NegativeAuthenticationResponseTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/RelyingParty/NegativeAuthenticationResponseTests.cs @@ -13,16 +13,16 @@ namespace DotNetOpenAuth.Test.OpenId.RelyingParty { using DotNetOpenAuth.OpenId.Extensions.SimpleRegistration; using DotNetOpenAuth.OpenId.Messages; using DotNetOpenAuth.OpenId.RelyingParty; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; - [TestClass] + [TestFixture] public class NegativeAuthenticationResponseTests : OpenIdTestBase { private const string UserSuppliedIdentifier = "=arnott"; private Protocol protocol; private NegativeAssertionResponse responseMessage; private NegativeAuthenticationResponse response; - [TestInitialize] + [SetUp] public override void SetUp() { base.SetUp(); @@ -32,7 +32,7 @@ namespace DotNetOpenAuth.Test.OpenId.RelyingParty { this.response = new NegativeAuthenticationResponse(this.responseMessage); } - [TestMethod, ExpectedException(typeof(ArgumentNullException))] + [TestCase, ExpectedException(typeof(ArgumentNullException))] public void CtorNull() { new NegativeAuthenticationResponse(null); } @@ -40,7 +40,7 @@ namespace DotNetOpenAuth.Test.OpenId.RelyingParty { /// <summary> /// Verifies that immediate/setup modes are correctly detected. /// </summary> - [TestMethod] + [TestCase] public void ImmediateVsSetupModes() { this.responseMessage = new NegativeAssertionResponse(this.protocol.Version, RPUri, this.protocol.Args.Mode.cancel); this.response = new NegativeAuthenticationResponse(this.responseMessage); @@ -55,17 +55,17 @@ namespace DotNetOpenAuth.Test.OpenId.RelyingParty { this.responseMessage.ExtraData[AuthenticationRequest.UserSuppliedIdentifierParameterName] = UserSuppliedIdentifier; this.response = new NegativeAuthenticationResponse(this.responseMessage); Assert.AreEqual(AuthenticationStatus.SetupRequired, this.response.Status); - Assert.AreEqual<string>(UserSuppliedIdentifier, this.response.UserSuppliedIdentifier); + Assert.AreEqual(UserSuppliedIdentifier, (string)this.response.UserSuppliedIdentifier); } - [TestMethod] + [TestCase] public void CommonProperties() { Assert.IsNull(this.response.Exception); Assert.IsNull(this.response.ClaimedIdentifier); Assert.IsNull(this.response.FriendlyIdentifierForDisplay); } - [TestMethod] + [TestCase] public void CommonMethods() { Assert.IsNull(this.response.GetExtension<ClaimsRequest>()); Assert.IsNull(this.response.GetExtension(typeof(ClaimsRequest))); diff --git a/src/DotNetOpenAuth.Test/OpenId/RelyingParty/OpenIdRelyingPartyTests.cs b/src/DotNetOpenAuth.Test/OpenId/RelyingParty/OpenIdRelyingPartyTests.cs index f6a57e7..b0ec395 100644 --- a/src/DotNetOpenAuth.Test/OpenId/RelyingParty/OpenIdRelyingPartyTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/RelyingParty/OpenIdRelyingPartyTests.cs @@ -12,40 +12,40 @@ namespace DotNetOpenAuth.Test.OpenId.RelyingParty { using DotNetOpenAuth.OpenId.Extensions; using DotNetOpenAuth.OpenId.Messages; using DotNetOpenAuth.OpenId.RelyingParty; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; - [TestClass] + [TestFixture] public class OpenIdRelyingPartyTests : OpenIdTestBase { - [TestInitialize] + [SetUp] public override void SetUp() { base.SetUp(); } - [TestMethod] + [TestCase] public void CreateRequestDumbMode() { - var rp = new OpenIdRelyingParty(null); + var rp = this.CreateRelyingParty(true); Identifier id = this.GetMockIdentifier(ProtocolVersion.V20); var authReq = rp.CreateRequest(id, RPRealmUri, RPUri); CheckIdRequest requestMessage = (CheckIdRequest)authReq.RedirectingResponse.OriginalMessage; Assert.IsNull(requestMessage.AssociationHandle); } - [TestMethod, ExpectedException(typeof(ArgumentNullException))] + [TestCase, ExpectedException(typeof(ArgumentNullException))] public void SecuritySettingsSetNull() { var rp = new OpenIdRelyingParty(new StandardRelyingPartyApplicationStore()); rp.SecuritySettings = null; } - [TestMethod] + [TestCase] public void ExtensionFactories() { var rp = new OpenIdRelyingParty(null); var factories = rp.ExtensionFactories; Assert.IsNotNull(factories); Assert.AreEqual(1, factories.Count); - Assert.IsInstanceOfType(factories[0], typeof(StandardOpenIdExtensionFactory)); + Assert.IsInstanceOf<StandardOpenIdExtensionFactory>(factories[0]); } - [TestMethod] + [TestCase] public void CreateRequest() { var rp = this.CreateRelyingParty(); StoreAssociation(rp, OPUri, HmacShaAssociation.Create("somehandle", new byte[20], TimeSpan.FromDays(1))); @@ -54,7 +54,7 @@ namespace DotNetOpenAuth.Test.OpenId.RelyingParty { Assert.IsNotNull(req); } - [TestMethod] + [TestCase] public void CreateRequests() { var rp = this.CreateRelyingParty(); StoreAssociation(rp, OPUri, HmacShaAssociation.Create("somehandle", new byte[20], TimeSpan.FromDays(1))); @@ -63,7 +63,7 @@ namespace DotNetOpenAuth.Test.OpenId.RelyingParty { Assert.AreEqual(1, requests.Count()); } - [TestMethod] + [TestCase] public void CreateRequestsWithEndpointFilter() { var rp = this.CreateRelyingParty(); StoreAssociation(rp, OPUri, HmacShaAssociation.Create("somehandle", new byte[20], TimeSpan.FromDays(1))); @@ -78,7 +78,7 @@ namespace DotNetOpenAuth.Test.OpenId.RelyingParty { Assert.AreEqual(0, requests.Count()); } - [TestMethod, ExpectedException(typeof(ProtocolException))] + [TestCase, ExpectedException(typeof(ProtocolException))] public void CreateRequestOnNonOpenID() { Uri nonOpenId = new Uri("http://www.microsoft.com/"); var rp = this.CreateRelyingParty(); @@ -86,7 +86,7 @@ namespace DotNetOpenAuth.Test.OpenId.RelyingParty { rp.CreateRequest(nonOpenId, RPRealmUri, RPUri); } - [TestMethod] + [TestCase] public void CreateRequestsOnNonOpenID() { Uri nonOpenId = new Uri("http://www.microsoft.com/"); var rp = this.CreateRelyingParty(); @@ -99,7 +99,7 @@ namespace DotNetOpenAuth.Test.OpenId.RelyingParty { /// Verifies that incoming positive assertions throw errors if they come from /// OPs that are not approved by <see cref="OpenIdRelyingParty.EndpointFilter"/>. /// </summary> - [TestMethod] + [TestCase] public void AssertionWithEndpointFilter() { var coordinator = new OpenIdCoordinator( rp => { diff --git a/src/DotNetOpenAuth.Test/OpenId/RelyingParty/OpenIdTextBoxTests.cs b/src/DotNetOpenAuth.Test/OpenId/RelyingParty/OpenIdTextBoxTests.cs index 67255e3..2c70e0f 100644 --- a/src/DotNetOpenAuth.Test/OpenId/RelyingParty/OpenIdTextBoxTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/RelyingParty/OpenIdTextBoxTests.cs @@ -6,14 +6,14 @@ namespace DotNetOpenAuth.Test.OpenId.RelyingParty { using DotNetOpenAuth.OpenId.RelyingParty; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; - [TestClass] + [TestFixture] public class OpenIdTextBoxTests : OpenIdTestBase { /// <summary> /// Verifies that the Text and Identifier properties interact correctly. /// </summary> - [TestMethod] + [TestCase] public void IdentifierTextInteraction() { var box = new OpenIdTextBox(); Assert.AreEqual(string.Empty, box.Text); diff --git a/src/DotNetOpenAuth.Test/OpenId/RelyingParty/PositiveAnonymousResponseTests.cs b/src/DotNetOpenAuth.Test/OpenId/RelyingParty/PositiveAnonymousResponseTests.cs index 1418513..b0586a6 100644 --- a/src/DotNetOpenAuth.Test/OpenId/RelyingParty/PositiveAnonymousResponseTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/RelyingParty/PositiveAnonymousResponseTests.cs @@ -10,14 +10,14 @@ namespace DotNetOpenAuth.Test.OpenId.RelyingParty { using DotNetOpenAuth.OpenId.Extensions.SimpleRegistration; using DotNetOpenAuth.OpenId.Messages; using DotNetOpenAuth.OpenId.RelyingParty; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; - [TestClass] + [TestFixture] public class PositiveAnonymousResponseTests : OpenIdTestBase { private readonly Realm realm = new Realm("http://localhost/rp.aspx"); private readonly Uri returnTo = new Uri("http://localhost/rp.aspx"); - [TestInitialize] + [SetUp] public override void SetUp() { base.SetUp(); } @@ -25,7 +25,7 @@ namespace DotNetOpenAuth.Test.OpenId.RelyingParty { /// <summary> /// Verifies that the Status property returns the correct value. /// </summary> - [TestMethod] + [TestCase] public void CtorAndProperties() { var responseMessage = new IndirectSignedResponse(Protocol.V20.Version, this.returnTo); var ext = new ClaimsResponse(); @@ -43,7 +43,7 @@ namespace DotNetOpenAuth.Test.OpenId.RelyingParty { /// <summary> /// Verifies the Provider property. /// </summary> - [TestMethod] + [TestCase] public void ProviderTest() { var responseMessage = new IndirectSignedResponse(Protocol.V20.Version, this.returnTo); responseMessage.ProviderEndpoint = OPUri; diff --git a/src/DotNetOpenAuth.Test/OpenId/RelyingParty/PositiveAuthenticationResponseSnapshotTests.cs b/src/DotNetOpenAuth.Test/OpenId/RelyingParty/PositiveAuthenticationResponseSnapshotTests.cs new file mode 100644 index 0000000..e069c44 --- /dev/null +++ b/src/DotNetOpenAuth.Test/OpenId/RelyingParty/PositiveAuthenticationResponseSnapshotTests.cs @@ -0,0 +1,39 @@ +//----------------------------------------------------------------------- +// <copyright file="PositiveAuthenticationResponseSnapshotTests.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.Test.OpenId.RelyingParty { + using System.Collections.Generic; + using System.IO; + using System.Runtime.Serialization; + using System.Runtime.Serialization.Formatters.Binary; + using DotNetOpenAuth.OpenId; + using DotNetOpenAuth.OpenId.Messages; + using DotNetOpenAuth.OpenId.RelyingParty; + using Microsoft.VisualStudio.TestTools.UnitTesting; + using Moq; + + [TestClass] + public class PositiveAuthenticationResponseSnapshotTests : OpenIdTestBase { + /// <summary> + /// Verifies that the PositiveAuthenticationResponseSnapshot is serializable, + /// as required by the <see cref="OpenIdRelyingPartyAjaxControlBase"/> class. + /// </summary> + [TestMethod] + public void Serializable() { + var response = new Mock<IAuthenticationResponse>(MockBehavior.Strict); + response.Setup(o => o.ClaimedIdentifier).Returns(VanityUri); + response.Setup(o => o.FriendlyIdentifierForDisplay).Returns(VanityUri.AbsoluteUri); + response.Setup(o => o.Status).Returns(AuthenticationStatus.Authenticated); + response.Setup(o => o.Provider).Returns(new ProviderEndpointDescription(OPUri, Protocol.Default.Version)); + response.Setup(o => o.GetUntrustedCallbackArguments()).Returns(new Dictionary<string, string>()); + response.Setup(o => o.GetCallbackArguments()).Returns(new Dictionary<string, string>()); + var snapshot = new PositiveAuthenticationResponseSnapshot(response.Object); + MemoryStream ms = new MemoryStream(); + IFormatter formatter = new BinaryFormatter(); + formatter.Serialize(ms, snapshot); + } + } +} diff --git a/src/DotNetOpenAuth.Test/OpenId/RelyingParty/PositiveAuthenticationResponseTests.cs b/src/DotNetOpenAuth.Test/OpenId/RelyingParty/PositiveAuthenticationResponseTests.cs index 701bcae..25b0607 100644 --- a/src/DotNetOpenAuth.Test/OpenId/RelyingParty/PositiveAuthenticationResponseTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/RelyingParty/PositiveAuthenticationResponseTests.cs @@ -12,14 +12,15 @@ namespace DotNetOpenAuth.Test.OpenId.RelyingParty { using DotNetOpenAuth.OpenId.Extensions.SimpleRegistration; using DotNetOpenAuth.OpenId.Messages; using DotNetOpenAuth.OpenId.RelyingParty; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using DotNetOpenAuth.Test.Mocks; + using NUnit.Framework; - [TestClass] + [TestFixture] public class PositiveAuthenticationResponseTests : OpenIdTestBase { private readonly Realm realm = new Realm("http://localhost/rp.aspx"); private readonly Uri returnTo = new Uri("http://localhost/rp.aspx"); - [TestInitialize] + [SetUp] public override void SetUp() { base.SetUp(); } @@ -27,7 +28,7 @@ namespace DotNetOpenAuth.Test.OpenId.RelyingParty { /// <summary> /// Verifies good, positive assertions are accepted. /// </summary> - [TestMethod] + [TestCase] public void Valid() { PositiveAssertionResponse assertion = this.GetPositiveAssertion(); ClaimsResponse extension = new ClaimsResponse(); @@ -37,8 +38,8 @@ namespace DotNetOpenAuth.Test.OpenId.RelyingParty { var authResponseAccessor = PositiveAuthenticationResponse_Accessor.AttachShadow(authResponse); Assert.AreEqual(AuthenticationStatus.Authenticated, authResponse.Status); Assert.IsNull(authResponse.Exception); - Assert.AreEqual<string>(assertion.ClaimedIdentifier, authResponse.ClaimedIdentifier); - Assert.AreEqual<string>(authResponse.Endpoint.FriendlyIdentifierForDisplay, authResponse.FriendlyIdentifierForDisplay); + Assert.AreEqual((string)assertion.ClaimedIdentifier, (string)authResponse.ClaimedIdentifier); + Assert.AreEqual(authResponse.Endpoint.FriendlyIdentifierForDisplay, authResponse.FriendlyIdentifierForDisplay); Assert.AreSame(extension, authResponse.GetUntrustedExtension(typeof(ClaimsResponse))); Assert.AreSame(extension, authResponse.GetUntrustedExtension<ClaimsResponse>()); Assert.IsNull(authResponse.GetCallbackArgument("a")); @@ -46,11 +47,37 @@ namespace DotNetOpenAuth.Test.OpenId.RelyingParty { } /// <summary> + /// Verifies that discovery verification of a positive assertion can match a dual identifier. + /// </summary> + [TestCase] + public void DualIdentifierMatchesInAssertionVerification() { + PositiveAssertionResponse assertion = this.GetPositiveAssertion(true); + ClaimsResponse extension = new ClaimsResponse(); + assertion.Extensions.Add(extension); + var rp = CreateRelyingParty(); + rp.SecuritySettings.AllowDualPurposeIdentifiers = true; + new PositiveAuthenticationResponse(assertion, rp); // this will throw if it fails to find a match + } + + /// <summary> + /// Verifies that discovery verification of a positive assertion cannot match a dual identifier + /// if the default settings are in place. + /// </summary> + [TestCase, ExpectedException(typeof(ProtocolException))] + public void DualIdentifierNoMatchInAssertionVerificationByDefault() { + PositiveAssertionResponse assertion = this.GetPositiveAssertion(true); + ClaimsResponse extension = new ClaimsResponse(); + assertion.Extensions.Add(extension); + var rp = CreateRelyingParty(); + new PositiveAuthenticationResponse(assertion, rp); // this will throw if it fails to find a match + } + + /// <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))] + [TestCase, ExpectedException(typeof(ProtocolException))] public void SpoofedClaimedIdDetectionSolicited() { PositiveAssertionResponse assertion = this.GetPositiveAssertion(); assertion.ProviderEndpoint = new Uri("http://rogueOP"); @@ -63,7 +90,7 @@ namespace DotNetOpenAuth.Test.OpenId.RelyingParty { /// Verifies that the RP rejects positive assertions with HTTP Claimed /// Cdentifiers when RequireSsl is set to true. /// </summary> - [TestMethod, ExpectedException(typeof(ProtocolException))] + [TestCase, ExpectedException(typeof(ProtocolException))] public void InsecureIdentifiersRejectedWithRequireSsl() { PositiveAssertionResponse assertion = this.GetPositiveAssertion(); var rp = CreateRelyingParty(); @@ -71,7 +98,7 @@ namespace DotNetOpenAuth.Test.OpenId.RelyingParty { var authResponse = new PositiveAuthenticationResponse(assertion, rp); } - [TestMethod] + [TestCase] public void GetCallbackArguments() { PositiveAssertionResponse assertion = this.GetPositiveAssertion(); var rp = CreateRelyingParty(); @@ -94,10 +121,34 @@ namespace DotNetOpenAuth.Test.OpenId.RelyingParty { Assert.IsNull(authResponse.GetCallbackArgument("a")); } + /// <summary> + /// Verifies that certain problematic claimed identifiers pass through to the RP response correctly. + /// </summary> + [TestCase] + public void ProblematicClaimedId() { + var providerEndpoint = new ProviderEndpointDescription(OpenIdTestBase.OPUri, Protocol.Default.Version); + string claimed_id = BaseMockUri + "a./b."; + var se = IdentifierDiscoveryResult.CreateForClaimedIdentifier(claimed_id, claimed_id, providerEndpoint, null, null); + UriIdentifier identityUri = (UriIdentifier)se.ClaimedIdentifier; + var mockId = new MockIdentifier(identityUri, this.MockResponder, new IdentifierDiscoveryResult[] { se }); + + var positiveAssertion = this.GetPositiveAssertion(); + positiveAssertion.ClaimedIdentifier = mockId; + positiveAssertion.LocalIdentifier = mockId; + var rp = CreateRelyingParty(); + var authResponse = new PositiveAuthenticationResponse(positiveAssertion, rp); + Assert.AreEqual(AuthenticationStatus.Authenticated, authResponse.Status); + Assert.AreEqual(claimed_id, authResponse.ClaimedIdentifier.ToString()); + } + private PositiveAssertionResponse GetPositiveAssertion() { + return this.GetPositiveAssertion(false); + } + + private PositiveAssertionResponse GetPositiveAssertion(bool dualIdentifier) { Protocol protocol = Protocol.Default; PositiveAssertionResponse assertion = new PositiveAssertionResponse(protocol.Version, this.returnTo); - assertion.ClaimedIdentifier = this.GetMockIdentifier(protocol.ProtocolVersion, false); + assertion.ClaimedIdentifier = dualIdentifier ? this.GetMockDualIdentifier() : this.GetMockIdentifier(protocol.ProtocolVersion, false); assertion.LocalIdentifier = OPLocalIdentifiers[0]; assertion.ReturnTo = this.returnTo; assertion.ProviderEndpoint = OPUri; diff --git a/src/DotNetOpenAuth.Test/OpenId/RelyingParty/RelyingPartySecuritySettingsTests.cs b/src/DotNetOpenAuth.Test/OpenId/RelyingParty/RelyingPartySecuritySettingsTests.cs index 851939e..2f6d218 100644 --- a/src/DotNetOpenAuth.Test/OpenId/RelyingParty/RelyingPartySecuritySettingsTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/RelyingParty/RelyingPartySecuritySettingsTests.cs @@ -10,20 +10,20 @@ namespace DotNetOpenAuth.Test.OpenId.RelyingParty { using System.Linq; using System.Text; using DotNetOpenAuth.OpenId.RelyingParty; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; - [TestClass] + [TestFixture] public class RelyingPartySecuritySettingsTests : OpenIdTestBase { private RelyingPartySecuritySettings settings; - [TestInitialize] + [SetUp] public override void SetUp() { base.SetUp(); this.settings = new RelyingPartySecuritySettings(); } - [TestMethod] + [TestCase] public void Defaults() { Assert.IsFalse(this.settings.RejectUnsolicitedAssertions); Assert.IsFalse(this.settings.RequireSsl, "Default should be to not require SSL."); @@ -33,7 +33,7 @@ namespace DotNetOpenAuth.Test.OpenId.RelyingParty { /// Verifies that the <see cref="RelyingPartySecuritySettings.RequireSsl"/> property /// getter/setter are implemented correctly. /// </summary> - [TestMethod] + [TestCase] public void RequireSsl() { this.settings.RequireSsl = true; Assert.IsTrue(this.settings.RequireSsl); @@ -45,7 +45,7 @@ namespace DotNetOpenAuth.Test.OpenId.RelyingParty { /// Verifies that the <see cref="RelyingPartySecuritySettings.RequireDirectedIdentity"/> /// property getter/setter are implemented correctly. /// </summary> - [TestMethod] + [TestCase] public void RequireDirectedIdentity() { this.settings.RequireDirectedIdentity = true; Assert.IsTrue(this.settings.RequireDirectedIdentity); @@ -57,7 +57,7 @@ namespace DotNetOpenAuth.Test.OpenId.RelyingParty { /// Verifies that the <see cref="RelyingPartySecuritySettings.RequireAssociation"/> /// property getter/setter are implemented correctly. /// </summary> - [TestMethod] + [TestCase] public void RequireAssociation() { this.settings.RequireAssociation = true; Assert.IsTrue(this.settings.RequireAssociation); diff --git a/src/DotNetOpenAuth.Test/OpenId/RelyingParty/ServiceEndpointTests.cs b/src/DotNetOpenAuth.Test/OpenId/RelyingParty/ServiceEndpointTests.cs deleted file mode 100644 index ff15aa3..0000000 --- a/src/DotNetOpenAuth.Test/OpenId/RelyingParty/ServiceEndpointTests.cs +++ /dev/null @@ -1,195 +0,0 @@ -//----------------------------------------------------------------------- -// <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.Extensions.SimpleRegistration; - using DotNetOpenAuth.OpenId.Messages; - 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.AreEqual(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.AreEqual(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, port, query and fragment - se = ServiceEndpoint.CreateForClaimedIdentifier( - "http://someprovider.somedomain.com:79/someuser?query#frag", - localId, - new ProviderEndpointDescription(providerEndpoint, serviceTypeUris), - null, - null); - Assert.AreEqual("someprovider.somedomain.com/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); - } - - [TestMethod] - public void IsTypeUriPresent() { - ServiceEndpoint se = ServiceEndpoint.CreateForClaimedIdentifier(this.claimedXri, this.userSuppliedXri, this.localId, new ProviderEndpointDescription(this.providerEndpoint, this.v20TypeUris), this.servicePriority, this.uriPriority); - Assert.IsTrue(se.IsTypeUriPresent(Protocol.Default.ClaimedIdentifierServiceTypeURI)); - Assert.IsFalse(se.IsTypeUriPresent("http://someother")); - } - - [TestMethod, ExpectedException(typeof(ArgumentException))] - public void IsTypeUriPresentNull() { - ServiceEndpoint se = ServiceEndpoint.CreateForClaimedIdentifier(this.claimedXri, this.userSuppliedXri, this.localId, new ProviderEndpointDescription(this.providerEndpoint, this.v20TypeUris), this.servicePriority, this.uriPriority); - se.IsTypeUriPresent(null); - } - - [TestMethod, ExpectedException(typeof(ArgumentException))] - public void IsTypeUriPresentEmpty() { - ServiceEndpoint se = ServiceEndpoint.CreateForClaimedIdentifier(this.claimedXri, this.userSuppliedXri, this.localId, new ProviderEndpointDescription(this.providerEndpoint, this.v20TypeUris), this.servicePriority, this.uriPriority); - se.IsTypeUriPresent(string.Empty); - } - } -} diff --git a/src/DotNetOpenAuth.Test/OpenId/UriIdentifierTests.cs b/src/DotNetOpenAuth.Test/OpenId/UriIdentifierTests.cs index 5a5182f..5b015ff 100644 --- a/src/DotNetOpenAuth.Test/OpenId/UriIdentifierTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/UriIdentifierTests.cs @@ -13,40 +13,40 @@ namespace DotNetOpenAuth.Test.OpenId { using DotNetOpenAuth.OpenId; using DotNetOpenAuth.OpenId.Extensions.SimpleRegistration; using DotNetOpenAuth.OpenId.RelyingParty; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; - [TestClass] + [TestFixture] public class UriIdentifierTests : OpenIdTestBase { private string goodUri = "http://blog.nerdbank.net/"; private string relativeUri = "host/path"; private string badUri = "som%-)830w8vf/?.<>,ewackedURI"; - [TestInitialize] + [SetUp] public override void SetUp() { base.SetUp(); } - [TestMethod, ExpectedException(typeof(ArgumentNullException))] + [TestCase, ExpectedException(typeof(ArgumentNullException))] public void CtorNullUri() { new UriIdentifier((Uri)null); } - [TestMethod, ExpectedException(typeof(ArgumentException))] + [TestCase, ExpectedException(typeof(ArgumentException))] public void CtorNullString() { new UriIdentifier((string)null); } - [TestMethod, ExpectedException(typeof(ArgumentException))] + [TestCase, ExpectedException(typeof(ArgumentException))] public void CtorBlank() { new UriIdentifier(string.Empty); } - [TestMethod, ExpectedException(typeof(UriFormatException))] + [TestCase, ExpectedException(typeof(UriFormatException))] public void CtorBadUri() { new UriIdentifier(this.badUri); } - [TestMethod] + [TestCase] public void CtorGoodUri() { var uri = new UriIdentifier(this.goodUri); Assert.AreEqual(new Uri(this.goodUri), uri.Uri); @@ -54,33 +54,33 @@ namespace DotNetOpenAuth.Test.OpenId { Assert.IsFalse(uri.IsDiscoverySecureEndToEnd); } - [TestMethod] + [TestCase] public void CtorStringNoSchemeSecure() { var uri = new UriIdentifier("host/path", true); Assert.AreEqual("https://host/path", uri.Uri.AbsoluteUri); Assert.IsTrue(uri.IsDiscoverySecureEndToEnd); } - [TestMethod] + [TestCase] public void CtorStringHttpsSchemeSecure() { var uri = new UriIdentifier("https://host/path", true); Assert.AreEqual("https://host/path", uri.Uri.AbsoluteUri); Assert.IsTrue(uri.IsDiscoverySecureEndToEnd); } - [TestMethod, ExpectedException(typeof(ArgumentException))] + [TestCase, ExpectedException(typeof(ArgumentException))] public void CtorStringHttpSchemeSecure() { new UriIdentifier("http://host/path", true); } - [TestMethod] + [TestCase] public void CtorUriHttpsSchemeSecure() { var uri = new UriIdentifier(new Uri("https://host/path"), true); Assert.AreEqual("https://host/path", uri.Uri.AbsoluteUri); Assert.IsTrue(uri.IsDiscoverySecureEndToEnd); } - [TestMethod, ExpectedException(typeof(ArgumentException))] + [TestCase, ExpectedException(typeof(ArgumentException))] public void CtorUriHttpSchemeSecure() { new UriIdentifier(new Uri("http://host/path"), true); } @@ -93,44 +93,73 @@ namespace DotNetOpenAuth.Test.OpenId { /// they should NOT be stripped from claimed identifiers. So the UriIdentifier /// class, which serves both identifier types, must not do the stripping. /// </remarks> - [TestMethod] + [TestCase] public void DoesNotStripFragment() { Uri original = new Uri("http://a/b#c"); UriIdentifier identifier = new UriIdentifier(original); Assert.AreEqual(original.Fragment, identifier.Uri.Fragment); } - [TestMethod] + [TestCase] public void IsValid() { Assert.IsTrue(UriIdentifier.IsValidUri(this.goodUri)); Assert.IsFalse(UriIdentifier.IsValidUri(this.badUri)); Assert.IsTrue(UriIdentifier.IsValidUri(this.relativeUri), "URL lacking http:// prefix should have worked anyway."); } - [TestMethod] + [TestCase] public void TrimFragment() { Identifier noFragment = UriIdentifier.Parse("http://a/b"); Identifier fragment = UriIdentifier.Parse("http://a/b#c"); Assert.AreSame(noFragment, noFragment.TrimFragment()); - Assert.AreEqual(noFragment, fragment.TrimFragment()); + Assert.AreEqual(noFragment.ToString(), fragment.TrimFragment().ToString()); + + // Try the problematic ones + TestAsFullAndPartialTrust(fullTrust => { + Identifier noFrag = UriIdentifier.Parse("http://a/b./c"); + Identifier frag = UriIdentifier.Parse("http://a/b./c#d"); + Assert.AreSame(noFrag, noFrag.TrimFragment()); + Assert.AreEqual(noFrag.ToString(), frag.TrimFragment().ToString()); + }); } - [TestMethod] + [TestCase] public void ToStringTest() { Assert.AreEqual(this.goodUri, new UriIdentifier(this.goodUri).ToString()); + TestAsFullAndPartialTrust(fullTrust => { + Assert.AreEqual("http://abc/D./e.?Qq#Ff", new UriIdentifier("HTTP://ABC/D./e.?Qq#Ff").ToString()); + Assert.AreEqual("http://abc/D./e.?Qq", new UriIdentifier("HTTP://ABC/D./e.?Qq").ToString()); + Assert.AreEqual("http://abc/D./e.#Ff", new UriIdentifier("HTTP://ABC/D./e.#Ff").ToString()); + Assert.AreEqual("http://abc/", new UriIdentifier("HTTP://ABC").ToString()); + Assert.AreEqual("http://abc/?q", new UriIdentifier("HTTP://ABC?q").ToString()); + Assert.AreEqual("http://abc/#f", new UriIdentifier("HTTP://ABC#f").ToString()); + }); } - [TestMethod] + [TestCase] public void EqualsTest() { - Assert.AreEqual(new UriIdentifier(this.goodUri), new UriIdentifier(this.goodUri)); - // This next test is an interesting side-effect of passing off to Uri.Equals. But it's probably ok. - Assert.AreEqual(new UriIdentifier(this.goodUri), new UriIdentifier(this.goodUri + "#frag")); - Assert.AreNotEqual(new UriIdentifier(this.goodUri), new UriIdentifier(this.goodUri + "a")); - Assert.AreNotEqual(null, new UriIdentifier(this.goodUri)); - Assert.AreEqual(this.goodUri, new UriIdentifier(this.goodUri)); - } - - [TestMethod] + TestAsFullAndPartialTrust(fulltrust => { + Assert.AreEqual(new UriIdentifier(this.goodUri), new UriIdentifier(this.goodUri)); + // This next test is an interesting side-effect of passing off to Uri.Equals. But it's probably ok. + Assert.AreEqual(new UriIdentifier(this.goodUri), new UriIdentifier(this.goodUri + "#frag")); + Assert.AreEqual(new UriIdentifier("http://a/b./c."), new UriIdentifier("http://a/b./c.#frag")); + Assert.AreNotEqual(new UriIdentifier(this.goodUri), new UriIdentifier(this.goodUri + "a")); + Assert.AreNotEqual(null, new UriIdentifier(this.goodUri)); + Assert.IsTrue(new UriIdentifier(this.goodUri).Equals(this.goodUri)); + + Assert.AreEqual(Identifier.Parse("HTTP://WWW.FOO.COM/abc", true), Identifier.Parse("http://www.foo.com/abc", true)); + Assert.AreEqual(Identifier.Parse("HTTP://WWW.FOO.COM/abc", true), Identifier.Parse("http://www.foo.com/abc", false)); + Assert.AreEqual(Identifier.Parse("HTTP://WWW.FOO.COM/abc", false), Identifier.Parse("http://www.foo.com/abc", false)); + Assert.AreNotEqual(Identifier.Parse("http://www.foo.com/abc", true), Identifier.Parse("http://www.foo.com/ABC", true)); + Assert.AreNotEqual(Identifier.Parse("http://www.foo.com/abc", true), Identifier.Parse("http://www.foo.com/ABC", false)); + Assert.AreNotEqual(Identifier.Parse("http://www.foo.com/abc", false), Identifier.Parse("http://www.foo.com/ABC", false)); + + Assert.AreNotEqual(Identifier.Parse("http://a/b./c."), Identifier.Parse("http://a/b/c.")); + Assert.AreEqual(Identifier.Parse("http://a/b./c."), Identifier.Parse("http://a/b./c.")); + }); + } + + [TestCase] public void UnicodeTest() { string unicodeUrl = "http://nerdbank.org/opaffirmative/崎村.aspx"; Assert.IsTrue(UriIdentifier.IsValidUri(unicodeUrl)); @@ -140,63 +169,7 @@ namespace DotNetOpenAuth.Test.OpenId { Assert.AreEqual(Uri.EscapeUriString(unicodeUrl), id.ToString()); } - [TestMethod] - public void HtmlDiscover_11() { - this.DiscoverHtml("html10prov", ProtocolVersion.V11, null, "http://a/b"); - this.DiscoverHtml("html10both", ProtocolVersion.V11, "http://c/d", "http://a/b"); - this.FailDiscoverHtml("html10del"); - - // Verify that HTML discovery generates the 1.x endpoints when appropriate - this.DiscoverHtml("html2010", ProtocolVersion.V11, "http://g/h", "http://e/f"); - this.DiscoverHtml("html1020", ProtocolVersion.V11, "http://g/h", "http://e/f"); - this.DiscoverHtml("html2010combinedA", ProtocolVersion.V11, "http://c/d", "http://a/b"); - this.DiscoverHtml("html2010combinedB", ProtocolVersion.V11, "http://c/d", "http://a/b"); - this.DiscoverHtml("html2010combinedC", ProtocolVersion.V11, "http://c/d", "http://a/b"); - } - - [TestMethod] - public void HtmlDiscover_20() { - this.DiscoverHtml("html20prov", ProtocolVersion.V20, null, "http://a/b"); - this.DiscoverHtml("html20both", ProtocolVersion.V20, "http://c/d", "http://a/b"); - this.FailDiscoverHtml("html20del"); - this.DiscoverHtml("html2010", ProtocolVersion.V20, "http://c/d", "http://a/b"); - this.DiscoverHtml("html1020", ProtocolVersion.V20, "http://c/d", "http://a/b"); - this.DiscoverHtml("html2010combinedA", ProtocolVersion.V20, "http://c/d", "http://a/b"); - this.DiscoverHtml("html2010combinedB", ProtocolVersion.V20, "http://c/d", "http://a/b"); - this.DiscoverHtml("html2010combinedC", ProtocolVersion.V20, "http://c/d", "http://a/b"); - this.FailDiscoverHtml("html20relative"); - } - - [TestMethod] - public void XrdsDiscoveryFromHead() { - this.MockResponder.RegisterMockResponse(new Uri("http://localhost/xrds1020.xml"), "application/xrds+xml", LoadEmbeddedFile("/Discovery/xrdsdiscovery/xrds1020.xml")); - this.DiscoverXrds("XrdsReferencedInHead.html", ProtocolVersion.V10, null, "http://a/b"); - } - - [TestMethod] - public void XrdsDiscoveryFromHttpHeader() { - WebHeaderCollection headers = new WebHeaderCollection(); - headers.Add("X-XRDS-Location", new Uri("http://localhost/xrds1020.xml").AbsoluteUri); - this.MockResponder.RegisterMockResponse(new Uri("http://localhost/xrds1020.xml"), "application/xrds+xml", LoadEmbeddedFile("/Discovery/xrdsdiscovery/xrds1020.xml")); - this.DiscoverXrds("XrdsReferencedInHttpHeader.html", ProtocolVersion.V10, null, "http://a/b", headers); - } - - [TestMethod] - public void XrdsDirectDiscovery_10() { - this.FailDiscoverXrds("xrds-irrelevant"); - this.DiscoverXrds("xrds10", ProtocolVersion.V10, null, "http://a/b"); - this.DiscoverXrds("xrds11", ProtocolVersion.V11, null, "http://a/b"); - this.DiscoverXrds("xrds1020", ProtocolVersion.V10, null, "http://a/b"); - } - - [TestMethod] - public void XrdsDirectDiscovery_20() { - this.DiscoverXrds("xrds20", ProtocolVersion.V20, null, "http://a/b"); - this.DiscoverXrds("xrds2010a", ProtocolVersion.V20, null, "http://a/b"); - this.DiscoverXrds("xrds2010b", ProtocolVersion.V20, null, "http://a/b"); - } - - [TestMethod] + [TestCase] public void NormalizeCase() { // only the host name can be normalized in casing safely. Identifier id = "http://HOST:80/PaTH?KeY=VaLUE#fRag"; @@ -206,36 +179,66 @@ namespace DotNetOpenAuth.Test.OpenId { Assert.AreEqual("https://host:80/PaTH?KeY=VaLUE#fRag", id.ToString()); } - [TestMethod] + /// <summary> + /// Verifies that URIs that contain base64 encoded path segments (such as Yahoo) are properly preserved. + /// </summary> + /// <remarks> + /// Yahoo includes a base64 encoded part as their last path segment, + /// which may end with a period. The default .NET Uri parser trims off + /// trailing periods, which breaks OpenID unless special precautions are taken. + /// </remarks> + [TestCase] + public void TrailingPeriodsNotTrimmed() { + TestAsFullAndPartialTrust(fullTrust => { + string claimedIdentifier = "https://me.yahoo.com/a/AsDf.#asdf"; + Identifier id = claimedIdentifier; + Assert.AreEqual(claimedIdentifier, id.OriginalString); + Assert.AreEqual(claimedIdentifier, id.ToString()); + + UriIdentifier idUri = new UriIdentifier(claimedIdentifier); + Assert.AreEqual(claimedIdentifier, idUri.OriginalString); + Assert.AreEqual(claimedIdentifier, idUri.ToString()); + if (fullTrust) { + Assert.AreEqual(claimedIdentifier, idUri.Uri.AbsoluteUri); + } + Assert.AreEqual(Uri.UriSchemeHttps, idUri.Uri.Scheme); // in case custom scheme tricks are played, this must still match + Assert.AreEqual("https://me.yahoo.com/a/AsDf.", idUri.TrimFragment().ToString()); + Assert.AreEqual("https://me.yahoo.com/a/AsDf.", idUri.TrimFragment().OriginalString); + Assert.AreEqual(id.ToString(), new UriIdentifier((Uri)idUri).ToString(), "Round tripping UriIdentifier->Uri->UriIdentifier failed."); + + idUri = new UriIdentifier(new Uri(claimedIdentifier)); + Assert.AreEqual(claimedIdentifier, idUri.OriginalString); + Assert.AreEqual(claimedIdentifier, idUri.ToString()); + if (fullTrust) { + Assert.AreEqual(claimedIdentifier, idUri.Uri.AbsoluteUri); + } + Assert.AreEqual(Uri.UriSchemeHttps, idUri.Uri.Scheme); // in case custom scheme tricks are played, this must still match + Assert.AreEqual("https://me.yahoo.com/a/AsDf.", idUri.TrimFragment().ToString()); + Assert.AreEqual("https://me.yahoo.com/a/AsDf.", idUri.TrimFragment().OriginalString); + Assert.AreEqual(id.ToString(), new UriIdentifier((Uri)idUri).ToString(), "Round tripping UriIdentifier->Uri->UriIdentifier failed."); + + claimedIdentifier = "https://me.yahoo.com:443/a/AsDf.#asdf"; + id = claimedIdentifier; + Assert.AreEqual(claimedIdentifier, id.OriginalString); + Assert.AreEqual("https://me.yahoo.com/a/AsDf.#asdf", id.ToString()); + }); + } + + [TestCase] public void HttpSchemePrepended() { UriIdentifier id = new UriIdentifier("www.yahoo.com"); Assert.AreEqual("http://www.yahoo.com/", id.ToString()); Assert.IsTrue(id.SchemeImplicitlyPrepended); } - ////[TestMethod, Ignore("The spec says http:// must be prepended in this case, but that just creates an invalid URI. Our UntrustedWebRequest will stop disallowed schemes.")] + ////[TestCase, Ignore("The spec says http:// must be prepended in this case, but that just creates an invalid URI. Our UntrustedWebRequest will stop disallowed schemes.")] public void CtorDisallowedScheme() { UriIdentifier id = new UriIdentifier(new Uri("ftp://host/path")); Assert.AreEqual("http://ftp://host/path", id.ToString()); Assert.IsTrue(id.SchemeImplicitlyPrepended); } - [TestMethod] - public void DiscoveryWithRedirects() { - Identifier claimedId = this.GetMockIdentifier(ProtocolVersion.V20, false); - - // Add a couple of chained redirect pages that lead to the claimedId. - Uri userSuppliedUri = new Uri("https://localhost/someSecurePage"); - Uri insecureMidpointUri = new Uri("http://localhost/insecureStop"); - this.MockResponder.RegisterMockRedirect(userSuppliedUri, insecureMidpointUri); - this.MockResponder.RegisterMockRedirect(insecureMidpointUri, new Uri(claimedId.ToString())); - - // don't require secure SSL discovery for this test. - Identifier userSuppliedIdentifier = new UriIdentifier(userSuppliedUri, false); - Assert.AreEqual(1, userSuppliedIdentifier.Discover(this.RequestHandler).Count()); - } - - [TestMethod] + [TestCase] public void TryRequireSslAdjustsIdentifier() { Identifier secureId; // Try Parse and ctor without explicit scheme @@ -256,180 +259,53 @@ namespace DotNetOpenAuth.Test.OpenId { Assert.IsFalse(id.TryRequireSsl(out secureId)); Assert.IsTrue(secureId.IsDiscoverySecureEndToEnd, "Although the TryRequireSsl failed, the created identifier should retain the Ssl status."); Assert.AreEqual("http://www.yahoo.com/", secureId.ToString()); - Assert.AreEqual(0, secureId.Discover(this.RequestHandler).Count(), "Since TryRequireSsl failed, the created Identifier should never discover anything."); + Assert.AreEqual(0, Discover(secureId).Count(), "Since TryRequireSsl failed, the created Identifier should never discover anything."); id = new UriIdentifier("http://www.yahoo.com"); Assert.IsFalse(id.TryRequireSsl(out secureId)); Assert.IsTrue(secureId.IsDiscoverySecureEndToEnd); Assert.AreEqual("http://www.yahoo.com/", secureId.ToString()); - Assert.AreEqual(0, secureId.Discover(this.RequestHandler).Count()); - } - - [TestMethod] - public void DiscoverRequireSslWithSecureRedirects() { - Identifier claimedId = this.GetMockIdentifier(ProtocolVersion.V20, true); - - // Add a couple of chained redirect pages that lead to the claimedId. - // All redirects should be secure. - Uri userSuppliedUri = new Uri("https://localhost/someSecurePage"); - Uri secureMidpointUri = new Uri("https://localhost/secureStop"); - this.MockResponder.RegisterMockRedirect(userSuppliedUri, secureMidpointUri); - this.MockResponder.RegisterMockRedirect(secureMidpointUri, new Uri(claimedId.ToString())); - - Identifier userSuppliedIdentifier = new UriIdentifier(userSuppliedUri, true); - Assert.AreEqual(1, userSuppliedIdentifier.Discover(this.RequestHandler).Count()); - } - - [TestMethod, ExpectedException(typeof(ProtocolException))] - public void DiscoverRequireSslWithInsecureRedirect() { - Identifier claimedId = this.GetMockIdentifier(ProtocolVersion.V20, true); - - // Add a couple of chained redirect pages that lead to the claimedId. - // Include an insecure HTTP jump in those redirects to verify that - // the ultimate endpoint is never found as a result of high security profile. - Uri userSuppliedUri = new Uri("https://localhost/someSecurePage"); - Uri insecureMidpointUri = new Uri("http://localhost/insecureStop"); - this.MockResponder.RegisterMockRedirect(userSuppliedUri, insecureMidpointUri); - this.MockResponder.RegisterMockRedirect(insecureMidpointUri, new Uri(claimedId.ToString())); - - Identifier userSuppliedIdentifier = new UriIdentifier(userSuppliedUri, true); - userSuppliedIdentifier.Discover(this.RequestHandler); + Assert.AreEqual(0, Discover(secureId).Count()); } - [TestMethod] - public void DiscoveryRequireSslWithInsecureXrdsInSecureHtmlHead() { - var insecureXrdsSource = this.GetMockIdentifier(ProtocolVersion.V20, false); - Uri secureClaimedUri = new Uri("https://localhost/secureId"); - - string html = string.Format("<html><head><meta http-equiv='X-XRDS-Location' content='{0}'/></head><body></body></html>", insecureXrdsSource); - this.MockResponder.RegisterMockResponse(secureClaimedUri, "text/html", html); - - Identifier userSuppliedIdentifier = new UriIdentifier(secureClaimedUri, true); - Assert.AreEqual(0, userSuppliedIdentifier.Discover(this.RequestHandler).Count()); - } - - [TestMethod] - public void DiscoveryRequireSslWithInsecureXrdsInSecureHttpHeader() { - var insecureXrdsSource = this.GetMockIdentifier(ProtocolVersion.V20, false); - - string html = "<html><head></head><body></body></html>"; - WebHeaderCollection headers = new WebHeaderCollection { - { "X-XRDS-Location", insecureXrdsSource } - }; - this.MockResponder.RegisterMockResponse(VanityUriSsl, VanityUriSsl, "text/html", headers, html); - - Identifier userSuppliedIdentifier = new UriIdentifier(VanityUriSsl, true); - Assert.AreEqual(0, userSuppliedIdentifier.Discover(this.RequestHandler).Count()); - } - - [TestMethod] - public void DiscoveryRequireSslWithInsecureXrdsButSecureLinkTags() { - var insecureXrdsSource = this.GetMockIdentifier(ProtocolVersion.V20, false); - string html = string.Format( - @" - <html><head> - <meta http-equiv='X-XRDS-Location' content='{0}'/> <!-- this one will be insecure and ignored --> - <link rel='openid2.provider' href='{1}' /> - <link rel='openid2.local_id' href='{2}' /> - </head><body></body></html>", - HttpUtility.HtmlEncode(insecureXrdsSource), - HttpUtility.HtmlEncode(OPUriSsl.AbsoluteUri), - HttpUtility.HtmlEncode(OPLocalIdentifiersSsl[1].AbsoluteUri)); - this.MockResponder.RegisterMockResponse(VanityUriSsl, "text/html", html); - - Identifier userSuppliedIdentifier = new UriIdentifier(VanityUriSsl, true); - - // We verify that the XRDS was ignored and the LINK tags were used - // because the XRDS OP-LocalIdentifier uses different local identifiers. - Assert.AreEqual(OPLocalIdentifiersSsl[1], userSuppliedIdentifier.Discover(this.RequestHandler).Single().ProviderLocalIdentifier); - } - - [TestMethod] - public void DiscoveryRequiresSslIgnoresInsecureEndpointsInXrds() { - var insecureEndpoint = GetServiceEndpoint(0, ProtocolVersion.V20, 10, false); - var secureEndpoint = GetServiceEndpoint(1, ProtocolVersion.V20, 20, true); - UriIdentifier secureClaimedId = new UriIdentifier(VanityUriSsl, true); - this.MockResponder.RegisterMockXrdsResponse(secureClaimedId, new ServiceEndpoint[] { insecureEndpoint, secureEndpoint }); - Assert.AreEqual(secureEndpoint.ProviderLocalIdentifier, secureClaimedId.Discover(this.RequestHandler).Single().ProviderLocalIdentifier); - } - - private void Discover(string url, ProtocolVersion version, Identifier expectedLocalId, string providerEndpoint, bool expectSreg, bool useRedirect) { - this.Discover(url, version, expectedLocalId, providerEndpoint, expectSreg, useRedirect, null); - } - - private void Discover(string url, ProtocolVersion version, Identifier expectedLocalId, string providerEndpoint, bool expectSreg, bool useRedirect, WebHeaderCollection headers) { - Protocol protocol = Protocol.Lookup(version); - Uri baseUrl = new Uri("http://localhost/"); - UriIdentifier claimedId = new Uri(baseUrl, url); - UriIdentifier userSuppliedIdentifier = new Uri(baseUrl, "Discovery/htmldiscovery/redirect.aspx?target=" + url); - if (expectedLocalId == null) { - expectedLocalId = claimedId; - } - Identifier idToDiscover = useRedirect ? userSuppliedIdentifier : claimedId; - - string contentType; - if (url.EndsWith("html")) { - contentType = "text/html"; - } else if (url.EndsWith("xml")) { - contentType = "application/xrds+xml"; - } else { - throw new InvalidOperationException(); - } - this.MockResponder.RegisterMockResponse(new Uri(idToDiscover), claimedId, contentType, headers ?? new WebHeaderCollection(), LoadEmbeddedFile(url)); - - ServiceEndpoint expected = ServiceEndpoint.CreateForClaimedIdentifier( - claimedId, - expectedLocalId, - new ProviderEndpointDescription(new Uri(providerEndpoint), new string[] { protocol.ClaimedIdentifierServiceTypeURI }), // services aren't checked by Equals - null, - null); - - ServiceEndpoint se = idToDiscover.Discover(this.RequestHandler).FirstOrDefault(ep => ep.Equals(expected)); - Assert.IsNotNull(se, url + " failed to be discovered."); - - // Do extra checking of service type URIs, which aren't included in - // the ServiceEndpoint.Equals method. - Assert.AreEqual(expectSreg ? 2 : 1, se.ProviderSupportedServiceTypeUris.Count); - Assert.IsTrue(se.ProviderSupportedServiceTypeUris.Contains(protocol.ClaimedIdentifierServiceTypeURI)); - Assert.AreEqual(expectSreg, se.IsExtensionSupported<ClaimsRequest>()); - } - - private void DiscoverXrds(string page, ProtocolVersion version, Identifier expectedLocalId, string providerEndpoint) { - this.DiscoverXrds(page, version, expectedLocalId, providerEndpoint, null); + /// <summary> + /// Verifies that unicode hostnames are handled. + /// </summary> + [TestCase] + public void UnicodeHostSupport() { + var id = new UriIdentifier("http://server崎/村"); + Assert.AreEqual("server崎", id.Uri.Host); } - private void DiscoverXrds(string page, ProtocolVersion version, Identifier expectedLocalId, string providerEndpoint, WebHeaderCollection headers) { - if (!page.Contains(".")) { - page += ".xml"; + /// <summary> + /// Verifies SimpleUri behavior + /// </summary> + [TestCase] + public void SimpleUri() { + Assert.AreEqual("http://abc/D./e.?Qq#Ff", new UriIdentifier.SimpleUri("HTTP://ABC/D./e.?Qq#Ff").ToString()); + Assert.AreEqual("http://abc/D./e.?Qq", new UriIdentifier.SimpleUri("HTTP://ABC/D./e.?Qq").ToString()); + Assert.AreEqual("http://abc/D./e.#Ff", new UriIdentifier.SimpleUri("HTTP://ABC/D./e.#Ff").ToString()); + Assert.AreEqual("http://abc/", new UriIdentifier.SimpleUri("HTTP://ABC/").ToString()); + Assert.AreEqual("http://abc/", new UriIdentifier.SimpleUri("HTTP://ABC").ToString()); + Assert.AreEqual("http://abc/?q", new UriIdentifier.SimpleUri("HTTP://ABC?q").ToString()); + Assert.AreEqual("http://abc/#f", new UriIdentifier.SimpleUri("HTTP://ABC#f").ToString()); + + Assert.AreEqual("http://abc/a//b", new UriIdentifier.SimpleUri("http://abc/a//b").ToString()); + Assert.AreEqual("http://abc/a%2Fb/c", new UriIdentifier.SimpleUri("http://abc/a%2fb/c").ToString()); + Assert.AreEqual("http://abc/A/c", new UriIdentifier.SimpleUri("http://abc/%41/c").ToString()); + } + + private static void TestAsFullAndPartialTrust(Action<bool> action) { + // Test a bunch of interesting URLs both with scheme substitution on and off. + Assert.IsTrue(UriIdentifier_Accessor.schemeSubstitution, "Expected scheme substitution to be working."); + action(true); + + UriIdentifier_Accessor.schemeSubstitution = false; + try { + action(false); + } finally { + UriIdentifier_Accessor.schemeSubstitution = true; } - this.Discover("/Discovery/xrdsdiscovery/" + page, version, expectedLocalId, providerEndpoint, true, false, headers); - this.Discover("/Discovery/xrdsdiscovery/" + page, version, expectedLocalId, providerEndpoint, true, true, headers); - } - - private void DiscoverHtml(string page, ProtocolVersion version, Identifier expectedLocalId, string providerEndpoint, bool useRedirect) { - this.Discover("/Discovery/htmldiscovery/" + page, version, expectedLocalId, providerEndpoint, false, useRedirect); - } - - private void DiscoverHtml(string scenario, ProtocolVersion version, Identifier expectedLocalId, string providerEndpoint) { - string page = scenario + ".html"; - this.DiscoverHtml(page, version, expectedLocalId, providerEndpoint, false); - this.DiscoverHtml(page, version, expectedLocalId, providerEndpoint, true); - } - - private void FailDiscover(string url) { - UriIdentifier userSuppliedId = new Uri(new Uri("http://localhost"), url); - - this.MockResponder.RegisterMockResponse(new Uri(userSuppliedId), userSuppliedId, "text/html", LoadEmbeddedFile(url)); - - Assert.AreEqual(0, userSuppliedId.Discover(this.RequestHandler).Count()); // ... but that no endpoint info is discoverable - } - - private void FailDiscoverHtml(string scenario) { - this.FailDiscover("/Discovery/htmldiscovery/" + scenario + ".html"); - } - - private void FailDiscoverXrds(string scenario) { - this.FailDiscover("/Discovery/xrdsdiscovery/" + scenario + ".xml"); } } } diff --git a/src/DotNetOpenAuth.Test/OpenId/XriIdentifierTests.cs b/src/DotNetOpenAuth.Test/OpenId/XriIdentifierTests.cs index 46427bb..0c80821 100644 --- a/src/DotNetOpenAuth.Test/OpenId/XriIdentifierTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/XriIdentifierTests.cs @@ -10,34 +10,34 @@ namespace DotNetOpenAuth.Test.OpenId { using System.Linq; using DotNetOpenAuth.OpenId; using DotNetOpenAuth.OpenId.RelyingParty; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; - [TestClass] + [TestFixture] public class XriIdentifierTests : OpenIdTestBase { private string goodXri = "=Andrew*Arnott"; private string badXri = "some\\wacky%^&*()non-XRI"; - [TestInitialize] + [SetUp] public override void SetUp() { base.SetUp(); } - [TestMethod, ExpectedException(typeof(ArgumentException))] + [TestCase, ExpectedException(typeof(ArgumentException))] public void CtorNull() { new XriIdentifier(null); } - [TestMethod, ExpectedException(typeof(ArgumentException))] + [TestCase, ExpectedException(typeof(ArgumentException))] public void CtorBlank() { new XriIdentifier(string.Empty); } - [TestMethod, ExpectedException(typeof(FormatException))] + [TestCase, ExpectedException(typeof(FormatException))] public void CtorBadXri() { new XriIdentifier(this.badXri); } - [TestMethod] + [TestCase] public void CtorGoodXri() { var xri = new XriIdentifier(this.goodXri); Assert.AreEqual(this.goodXri, xri.OriginalXri); @@ -45,7 +45,7 @@ namespace DotNetOpenAuth.Test.OpenId { Assert.IsFalse(xri.IsDiscoverySecureEndToEnd); } - [TestMethod] + [TestCase] public void CtorGoodXriSecure() { var xri = new XriIdentifier(this.goodXri, true); Assert.AreEqual(this.goodXri, xri.OriginalXri); @@ -53,7 +53,7 @@ namespace DotNetOpenAuth.Test.OpenId { Assert.IsTrue(xri.IsDiscoverySecureEndToEnd); } - [TestMethod] + [TestCase] public void IsValid() { Assert.IsTrue(XriIdentifier.IsValidXri(this.goodXri)); Assert.IsFalse(XriIdentifier.IsValidXri(this.badXri)); @@ -62,412 +62,36 @@ namespace DotNetOpenAuth.Test.OpenId { /// <summary> /// Verifies 2.0 spec section 7.2#1 /// </summary> - [TestMethod] + [TestCase] public void StripXriScheme() { var xri = new XriIdentifier("xri://" + this.goodXri); Assert.AreEqual("xri://" + this.goodXri, xri.OriginalXri); Assert.AreEqual(this.goodXri, xri.CanonicalXri); } - [TestMethod] + [TestCase] public void TrimFragment() { Identifier xri = new XriIdentifier(this.goodXri); Assert.AreSame(xri, xri.TrimFragment()); } - [TestMethod] + [TestCase] public void ToStringTest() { Assert.AreEqual(this.goodXri, new XriIdentifier(this.goodXri).ToString()); } - [TestMethod] + [TestCase] public void EqualsTest() { Assert.AreEqual(new XriIdentifier(this.goodXri), new XriIdentifier(this.goodXri)); Assert.AreNotEqual(new XriIdentifier(this.goodXri), new XriIdentifier(this.goodXri + "a")); Assert.AreNotEqual(null, new XriIdentifier(this.goodXri)); - Assert.AreEqual(this.goodXri, new XriIdentifier(this.goodXri)); + Assert.IsTrue(new XriIdentifier(this.goodXri).Equals(this.goodXri)); } - [TestMethod] - public void Discover() { - string xrds = @"<?xml version='1.0' encoding='UTF-8'?> -<XRD version='2.0' xmlns='xri://$xrd*($v*2.0)'> - <Query>*Arnott</Query> - <Status ceid='off' cid='verified' code='100'/> - <Expires>2008-07-14T02:03:24.000Z</Expires> - <ProviderID>xri://=</ProviderID> - <LocalID>!9b72.7dd1.50a9.5ccd</LocalID> - <CanonicalID>=!9B72.7DD1.50A9.5CCD</CanonicalID> - - <Service priority='10'> - <ProviderID>xri://!!1008</ProviderID> - <Type select='true'>xri://+i-service*(+contact)*($v*1.0)</Type> - <Type match='default' select='false'/> - <Path select='true'>(+contact)</Path> - <Path match='null' select='false'/> - <URI append='qxri' priority='1'>http://1id.com/contact/</URI> - - </Service> - <Service priority='10'> - <ProviderID>xri://!!1008</ProviderID> - <Type select='true'>xri://+i-service*(+forwarding)*($v*1.0)</Type> - <Type match='null' select='false'/> - <URI append='qxri' priority='1'>http://1id.com/</URI> - </Service> - - <Service priority='10'> - <ProviderID>xri://!!1008</ProviderID> - <Type select='true'>http://openid.net/signon/1.0</Type> - <URI append='none' priority='10'>http://1id.com/sso</URI> - </Service> -</XRD>"; - Dictionary<string, string> mocks = new Dictionary<string, string> { - { "https://xri.net/=Arnott?_xrd_r=application/xrd%2Bxml;sep=false", xrds }, - { "https://xri.net/=!9B72.7DD1.50A9.5CCD?_xrd_r=application/xrd%2Bxml;sep=false", xrds }, - }; - this.MockResponder.RegisterMockXrdsResponses(mocks); - - string expectedCanonicalId = "=!9B72.7DD1.50A9.5CCD"; - ServiceEndpoint se = this.VerifyCanonicalId("=Arnott", expectedCanonicalId); - Assert.AreEqual(Protocol.V10, se.Protocol); - Assert.AreEqual("http://1id.com/sso", se.ProviderEndpoint.ToString()); - Assert.AreEqual(se.ClaimedIdentifier, se.ProviderLocalIdentifier); - Assert.AreEqual("=Arnott", se.FriendlyIdentifierForDisplay); - } - - [TestMethod] - public void DiscoverCommunityInameCanonicalIDs() { - string llliResponse = @"<?xml version='1.0' encoding='UTF-8'?> -<XRD version='2.0' xmlns='xri://$xrd*($v*2.0)'> - <Query>*llli</Query> - <Status ceid='off' cid='verified' code='100'/> - <Expires>2008-07-14T02:21:06.000Z</Expires> - <ProviderID>xri://@</ProviderID> - <LocalID>!72cd.a072.157e.a9c6</LocalID> - <CanonicalID>@!72CD.A072.157E.A9C6</CanonicalID> - <Service priority='10'> - <ProviderID>xri://!!1003!103</ProviderID> - <Type select='true'>http://openid.net/signon/1.0</Type> - <URI append='none' priority='1'>https://login.llli.org/server/</URI> - </Service> - <Service priority='1'> - <ProviderID>xri://!!1003!103</ProviderID> - <Type match='null' select='false'/> - <Type select='true'>xri://+i-service*(+forwarding)*($v*1.0)</Type> - <Path match='default'/> - <Path>(+index)</Path> - <URI append='qxri' priority='1'>http://linksafe-forward.ezibroker.net/forwarding/</URI> - </Service> - <Service priority='10'> - <ProviderID>xri://!!1003!103</ProviderID> - <Type select='true'>xri://$res*auth*($v*2.0)</Type> - <MediaType>application/xrds+xml;trust=none</MediaType> - <URI priority='10'>http://resolve.ezibroker.net/resolve/@llli/</URI> - </Service> - <Service priority='10'> - <ProviderID>xri://!!1003!103</ProviderID> - <Type select='true'>xri://+i-service*(+contact)*($v*1.0)</Type> - <Type match='null'/> - <Path select='true'>(+contact)</Path> - <Path match='null'/> - <URI append='authority' priority='1'>http://linksafe-contact.ezibroker.net/contact/</URI> - </Service> -</XRD> -"; - string llliAreaResponse = @"<?xml version='1.0' encoding='UTF-8'?> -<XRD xmlns='xri://$xrd*($v*2.0)'> - <Query>*area</Query> - <Status cid='verified' code='100'>SUCCESS</Status> - <ServerStatus code='100'>SUCCESS</ServerStatus> - <Expires>2008-07-15T01:21:07.000Z</Expires> - <ProviderID>xri://!!1003</ProviderID> - <LocalID>0000.0000.3B9A.CA0C</LocalID> - <CanonicalID>@!72CD.A072.157E.A9C6!0000.0000.3B9A.CA0C</CanonicalID> - <Service> - <ProviderID>xri://!!1003!103</ProviderID> - <Type select='true'>http://openid.net/signon/1.0</Type> - <URI append='none' priority='1'>https://login.llli.org/server/</URI> - </Service> - <Service> - <ProviderID>xri://!!1003!103</ProviderID> - <Type select='true'>xri://+i-service*(+contact)*($v*1.0)</Type> - <Type match='null'/> - <Path select='true'>(+contact)</Path> - <Path match='null'/> - <URI append='authority' priority='1'>http://linksafe-contact.ezibroker.net/contact/</URI> - </Service> - <Service priority='1'> - <ProviderID>xri://!!1003!103</ProviderID> - <Type select='true'>xri://+i-service*(+forwarding)*($v*1.0)</Type> - <Type match='null' select='false'/> - <Path>(+index)</Path> - <Path match='default'/> - <URI append='qxri' priority='1'>http://linksafe-forward.ezibroker.net/forwarding/</URI> - </Service> - <Service> - <ProviderID>xri://!!1003!103</ProviderID> - <Type select='true'>xri://$res*auth*($v*2.0)</Type> - <MediaType>application/xrds+xml;trust=none</MediaType> - <URI>http://resolve.ezibroker.net/resolve/@llli*area/</URI> - </Service> -</XRD>"; - string llliAreaCanadaUnattachedResponse = @"<?xml version='1.0' encoding='UTF-8'?> -<XRD xmlns='xri://$xrd*($v*2.0)'> - <Query>*canada.unattached</Query> - <Status cid='verified' code='100'>SUCCESS</Status> - <ServerStatus code='100'>SUCCESS</ServerStatus> - <Expires>2008-07-15T01:21:08.000Z</Expires> - <ProviderID>xri://!!1003</ProviderID> - <LocalID>0000.0000.3B9A.CA41</LocalID> - <CanonicalID>@!72CD.A072.157E.A9C6!0000.0000.3B9A.CA0C!0000.0000.3B9A.CA41</CanonicalID> - <Service> - <ProviderID>xri://!!1003!103</ProviderID> - <Type select='true'>http://openid.net/signon/1.0</Type> - <URI append='none' priority='1'>https://login.llli.org/server/</URI> - </Service> - <Service> - <ProviderID>xri://!!1003!103</ProviderID> - <Type select='true'>xri://+i-service*(+contact)*($v*1.0)</Type> - <Type match='null'/> - <Path select='true'>(+contact)</Path> - <Path match='null'/> - <URI append='authority' priority='1'>http://linksafe-contact.ezibroker.net/contact/</URI> - </Service> - <Service priority='1'> - <ProviderID>xri://!!1003!103</ProviderID> - <Type select='true'>xri://+i-service*(+forwarding)*($v*1.0)</Type> - <Type match='null' select='false'/> - <Path>(+index)</Path> - <Path match='default'/> - <URI append='qxri' priority='1'>http://linksafe-forward.ezibroker.net/forwarding/</URI> - </Service> - <Service> - <ProviderID>xri://!!1003!103</ProviderID> - <Type select='true'>xri://$res*auth*($v*2.0)</Type> - <MediaType>application/xrds+xml;trust=none</MediaType> - <URI>http://resolve.ezibroker.net/resolve/@llli*area*canada.unattached/</URI> - </Service> -</XRD>"; - string llliAreaCanadaUnattachedAdaResponse = @"<?xml version='1.0' encoding='UTF-8'?> -<XRD xmlns='xri://$xrd*($v*2.0)'> - <Query>*ada</Query> - <Status cid='verified' code='100'>SUCCESS</Status> - <ServerStatus code='100'>SUCCESS</ServerStatus> - <Expires>2008-07-15T01:21:10.000Z</Expires> - <ProviderID>xri://!!1003</ProviderID> - <LocalID>0000.0000.3B9A.CA01</LocalID> - <CanonicalID>@!72CD.A072.157E.A9C6!0000.0000.3B9A.CA0C!0000.0000.3B9A.CA41!0000.0000.3B9A.CA01</CanonicalID> - <Service> - <ProviderID>xri://!!1003!103</ProviderID> - <Type select='true'>http://openid.net/signon/1.0</Type> - <URI append='none' priority='1'>https://login.llli.org/server/</URI> - </Service> - <Service> - <ProviderID>xri://!!1003!103</ProviderID> - <Type select='true'>xri://+i-service*(+contact)*($v*1.0)</Type> - <Type match='null'/> - <Path select='true'>(+contact)</Path> - <Path match='null'/> - <URI append='authority' priority='1'>http://linksafe-contact.ezibroker.net/contact/</URI> - </Service> - <Service priority='1'> - <ProviderID>xri://!!1003!103</ProviderID> - <Type select='true'>xri://+i-service*(+forwarding)*($v*1.0)</Type> - <Type match='null' select='false'/> - <Path>(+index)</Path> - <Path match='default'/> - <URI append='qxri' priority='1'>http://linksafe-forward.ezibroker.net/forwarding/</URI> - </Service> -</XRD>"; - string webResponse = @"<?xml version='1.0' encoding='UTF-8'?> -<XRD version='2.0' xmlns='xri://$xrd*($v*2.0)'> - <Query>*Web</Query> - <Status ceid='off' cid='verified' code='100'/> - <Expires>2008-07-14T02:21:12.000Z</Expires> - <ProviderID>xri://=</ProviderID> - <LocalID>!91f2.8153.f600.ae24</LocalID> - <CanonicalID>=!91F2.8153.F600.AE24</CanonicalID> - <Service priority='10'> - <Type select='true'>xri://+i-service*(+locator)*($v*1.0)</Type> - <Path select='true'>(+locator)</Path> - <MediaType match='default' select='false'/> - <URI append='qxri'>http://locator.fullxri.com/locator/</URI> - </Service> - <Service priority='10'> - <ProviderID>xri://=web</ProviderID> - <Type select='true'>xri://$res*auth*($v*2.0)</Type> - <Type select='true'>xri://$res*auth*($v*2.0)</Type> - <MediaType select='true'>application/xrds+xml</MediaType> - <URI append='qxri' priority='1'>https://resolve.freexri.com/ns/=web/</URI> - <URI append='qxri' priority='2'>http://resolve.freexri.com/ns/=web/</URI> - </Service> - <Service priority='10'> - <Type select='true'>http://openid.net/signon/1.0</Type> - <Type select='true'>http://specs.openid.net/auth/2.0/signon</Type> - <Path select='true'>(+login)</Path> - <Path match='default' select='false'/> - <MediaType match='default' select='false'/> - <URI append='none' priority='2'>http://authn.fullxri.com/authentication/</URI> - <URI append='none' priority='1'>https://authn.fullxri.com/authentication/</URI> - </Service> - <Service priority='10'> - <Type select='true'>xri://+i-service*(+contact)*($v*1.0)</Type> - <Type match='null' select='false'/> - <Path select='true'>(+contact)</Path> - <Path match='null' select='false'/> - <MediaType match='default' select='false'/> - <URI append='qxri'>http://contact.fullxri.com/contact/</URI> - </Service> - <KeyInfo xmlns='http://www.w3.org/2000/09/xmldsig#'> - <X509Data> - <X509Certificate> -MIIExzCCA6+gAwIBAgIJAM+MlFr0Sth6MA0GCSqGSIb3DQEBBQUAMIGdMR8wHQYD -VQQDExZTdXBlcnZpbGxhaW46IFRoZSBSb290MQswCQYDVQQGEwJVUzERMA8GA1UE -CBMITmV3IFlvcmsxDzANBgNVBAcTBkdvdGhhbTEgMB4GA1UEChMXU3VwZXJ2aWxs -YWluIFVuaXZlcnNpdHkxJzAlBgkqhkiG9w0BCQEWGHBlbmd1aW5Ac3VwZXJ2aWxs -YWluLmVkdTAeFw0wNjA4MTcxOTU5NTNaFw0xMTA4MTYxOTU5NTNaMIGdMR8wHQYD -VQQDExZTdXBlcnZpbGxhaW46IFRoZSBSb290MQswCQYDVQQGEwJVUzERMA8GA1UE -CBMITmV3IFlvcmsxDzANBgNVBAcTBkdvdGhhbTEgMB4GA1UEChMXU3VwZXJ2aWxs -YWluIFVuaXZlcnNpdHkxJzAlBgkqhkiG9w0BCQEWGHBlbmd1aW5Ac3VwZXJ2aWxs -YWluLmVkdTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAL6uFqas4dK6 -A2wTZL0viRQNJrPyFnFBDSZGib/2ijhgzed/vvmZIBM9sFpwahcuR5hvyKUe37/c -/RSZXoNDi/eiNOx4qb0l9UB6bd8qvc4V1PnLE7L+ZYcmwrvTKm4x8qXMgEv1wca2 -FPsreHNPdLiTUZ8v0tDTWi3Mgi7y47VTzJaTkcfmO1nL6xAtln5sLdH0PbMM3LAp -T1d3nwI3VdbhqqZ+6+OKEuC8gk5iH4lfrbr6C9bYS6vzIKrotHpZ3N2aIC3NMjJD -PMw/mfCuADfRNlHXgZW+0zyUkwGTMDea8qgsoAMWJGdeTIw8I1I3RhnbgLzdsNQl -b/1ZXx1uJRUCAwEAAaOCAQYwggECMB0GA1UdDgQWBBQe+xSjYTrlfraJARjMxscb -j36jvDCB0gYDVR0jBIHKMIHHgBQe+xSjYTrlfraJARjMxscbj36jvKGBo6SBoDCB -nTEfMB0GA1UEAxMWU3VwZXJ2aWxsYWluOiBUaGUgUm9vdDELMAkGA1UEBhMCVVMx -ETAPBgNVBAgTCE5ldyBZb3JrMQ8wDQYDVQQHEwZHb3RoYW0xIDAeBgNVBAoTF1N1 -cGVydmlsbGFpbiBVbml2ZXJzaXR5MScwJQYJKoZIhvcNAQkBFhhwZW5ndWluQHN1 -cGVydmlsbGFpbi5lZHWCCQDPjJRa9ErYejAMBgNVHRMEBTADAQH/MA0GCSqGSIb3 -DQEBBQUAA4IBAQC4SPBDGYAxfbXd8N5OvG0drM7a5hjXfcCZpiILlPSRpxp79yh7 -I5vVWxBxUfolwbei7PTBVy7CE27SUbSICeqWjcDCfjNjiZk6mLS80rm/TdLrHSyM -+Ujlw9MGcBGaLI+sdziDUMtTQDpeAyQTaGVbh1mx5874Hlo1VXqGYNo0RwR+iLfs -x48VuO6GbWVyxtktkE2ypz1KLWiyI056YynydRvuBCBHeRqGUixPlH9CrmeSCP2S -sfbiKnMOGXjIYbvbsTAMdW2iqg6IWa/fgxhvZoAXChM9bkhisJQc0qD0J5TJQwgr -uEyb50RJ7DWmXctSC0b3eymZ2lSXxAWNOsNy - </X509Certificate> - </X509Data> - </KeyInfo> -</XRD>"; - this.MockResponder.RegisterMockXrdsResponses(new Dictionary<string, string> { - { "https://xri.net/@llli?_xrd_r=application/xrd%2Bxml;sep=false", llliResponse }, - { "https://xri.net/@llli*area?_xrd_r=application/xrd%2Bxml;sep=false", llliAreaResponse }, - { "https://xri.net/@llli*area*canada.unattached?_xrd_r=application/xrd%2Bxml;sep=false", llliAreaCanadaUnattachedResponse }, - { "https://xri.net/@llli*area*canada.unattached*ada?_xrd_r=application/xrd%2Bxml;sep=false", llliAreaCanadaUnattachedAdaResponse }, - { "https://xri.net/=Web?_xrd_r=application/xrd%2Bxml;sep=false", webResponse }, - }); - this.VerifyCanonicalId("@llli", "@!72CD.A072.157E.A9C6"); - this.VerifyCanonicalId("@llli*area", "@!72CD.A072.157E.A9C6!0000.0000.3B9A.CA0C"); - this.VerifyCanonicalId("@llli*area*canada.unattached", "@!72CD.A072.157E.A9C6!0000.0000.3B9A.CA0C!0000.0000.3B9A.CA41"); - this.VerifyCanonicalId("@llli*area*canada.unattached*ada", "@!72CD.A072.157E.A9C6!0000.0000.3B9A.CA0C!0000.0000.3B9A.CA41!0000.0000.3B9A.CA01"); - this.VerifyCanonicalId("=Web", "=!91F2.8153.F600.AE24"); - } - - [TestMethod] - public void DiscoveryCommunityInameDelegateWithoutCanonicalID() { - this.MockResponder.RegisterMockXrdsResponses(new Dictionary<string, string> { - { "https://xri.net/=Web*andrew.arnott?_xrd_r=application/xrd%2Bxml;sep=false", @"<?xml version='1.0' encoding='UTF-8'?> -<XRD xmlns='xri://$xrd*($v*2.0)'> - <Query>*andrew.arnott</Query> - <Status cid='absent' code='100'>Success</Status> - <ServerStatus code='100'>Success</ServerStatus> - <Expires>2008-07-14T03:30:59.722Z</Expires> - <ProviderID>=!91F2.8153.F600.AE24</ProviderID> - <Service> - <Type select='true'>http://openid.net/signon/1.0</Type> - <Path select='true'>(+login)</Path> - <Path match='default'/> - <MediaType match='default'/> - <URI append='none' priority='2'>http://www.myopenid.com/server</URI> - <openid:Delegate xmlns:openid='http://openid.net/xmlns/1.0'>http://blog.nerdbank.net</openid:Delegate> - </Service> - <Service> - <ProviderID>@!7F6F.F50.A4E4.1133</ProviderID> - <Type select='true'>xri://+i-service*(+contact)*($v*1.0)</Type> - <Type match='null'/> - <Path select='true'>(+contact)</Path> - <Path match='null'/> - <MediaType match='default'/> - <URI append='qxri'>http://contact.freexri.com/contact/</URI> - </Service> - <Service> - <ProviderID>@!7F6F.F50.A4E4.1133</ProviderID> - <Type select='true'>xri://+i-service*(+forwarding)*($v*1.0)</Type> - <Path select='true'>(+index)</Path> - <Path match='default'/> - <MediaType match='default'/> - <URI append='qxri'>http://forwarding.freexri.com/forwarding/</URI> - </Service> - <Service> - <ProviderID>@!7F6F.F50.A4E4.1133</ProviderID> - <Type select='true'>http://openid.net/signon/1.0</Type> - <Path select='true'>(+login)</Path> - <Path match='default'/> - <MediaType match='default'/> - <URI append='none' priority='2'>http://authn.freexri.com/authentication/</URI> - <URI append='none' priority='1'>https://authn.freexri.com/authentication/</URI> - </Service> - <ServedBy>OpenXRI</ServedBy> -</XRD>" }, - { "https://xri.net/@id*andrewarnott?_xrd_r=application/xrd%2Bxml;sep=false", @"<?xml version='1.0' encoding='UTF-8'?> -<XRD xmlns='xri://$xrd*($v*2.0)'> - <Query>*andrewarnott</Query> - <Status cid='absent' code='100'>Success</Status> - <ServerStatus code='100'>Success</ServerStatus> - <Expires>2008-07-14T03:31:00.466Z</Expires> - <ProviderID>@!B1E8.C27B.E41C.25C3</ProviderID> - <Service> - <Type select='true'>http://openid.net/signon/1.0</Type> - <Path select='true'>(+login)</Path> - <Path match='default'/> - <MediaType match='default'/> - <URI append='none' priority='2'>http://www.myopenid.com/server</URI> - <openid:Delegate xmlns:openid='http://openid.net/xmlns/1.0'>http://blog.nerdbank.net</openid:Delegate> - </Service> - <Service> - <ProviderID>@!7F6F.F50.A4E4.1133</ProviderID> - <Type select='true'>xri://+i-service*(+contact)*($v*1.0)</Type> - <Type match='null'/> - <Path select='true'>(+contact)</Path> - <Path match='null'/> - <MediaType match='default'/> - <URI append='qxri'>http://contact.freexri.com/contact/</URI> - </Service> - <Service> - <ProviderID>@!7F6F.F50.A4E4.1133</ProviderID> - <Type select='true'>xri://+i-service*(+forwarding)*($v*1.0)</Type> - <Path select='true'>(+index)</Path> - <Path match='default'/> - <MediaType match='default'/> - <URI append='qxri'>http://forwarding.freexri.com/forwarding/</URI> - </Service> - <ServedBy>OpenXRI</ServedBy> -</XRD>" }, - }); - // Consistent with spec section 7.3.2.3, we do not permit - // delegation on XRI discovery when there is no CanonicalID present. - this.VerifyCanonicalId("=Web*andrew.arnott", null); - this.VerifyCanonicalId("@id*andrewarnott", null); - } - - [TestMethod, Ignore] // XRI parsing and normalization is not implemented (yet). + [TestCase, Ignore("XRI parsing and normalization is not implemented (yet).")] public void NormalizeCase() { Identifier id = "=!9B72.7dd1.50a9.5ccd"; Assert.AreEqual("=!9B72.7DD1.50A9.5CCD", id.ToString()); } - - private ServiceEndpoint VerifyCanonicalId(Identifier iname, string expectedClaimedIdentifier) { - ServiceEndpoint se = iname.Discover(this.RequestHandler).FirstOrDefault(); - if (expectedClaimedIdentifier != null) { - Assert.IsNotNull(se); - Assert.AreEqual(expectedClaimedIdentifier, se.ClaimedIdentifier.ToString(), "i-name {0} discovery resulted in unexpected CanonicalId", iname); - Assert.IsTrue(se.ProviderSupportedServiceTypeUris.Count > 0); - } else { - Assert.IsNull(se); - } - return se; - } } } |