diff options
Diffstat (limited to 'src/DotNetOpenAuth.Test')
26 files changed, 1178 insertions, 91 deletions
diff --git a/src/DotNetOpenAuth.Test/DotNetOpenAuth.Test.csproj b/src/DotNetOpenAuth.Test/DotNetOpenAuth.Test.csproj index 03f6285..7212008 100644 --- a/src/DotNetOpenAuth.Test/DotNetOpenAuth.Test.csproj +++ b/src/DotNetOpenAuth.Test/DotNetOpenAuth.Test.csproj @@ -98,6 +98,10 @@ <HintPath>..\..\lib\Microsoft.Contracts.dll</HintPath> </Reference> <Reference Include="Microsoft.VisualStudio.QualityTools.UnitTestFramework, Version=9.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL" /> + <Reference Include="Moq, Version=3.1.416.3, Culture=neutral, PublicKeyToken=69f491c39445e920, processorArchitecture=MSIL"> + <SpecificVersion>False</SpecificVersion> + <HintPath>..\..\lib\Moq.dll</HintPath> + </Reference> <Reference Include="System" /> <Reference Include="System.configuration" /> <Reference Include="System.Core"> @@ -128,6 +132,7 @@ <Compile Include="Hosting\HttpHost.cs" /> <Compile Include="Hosting\TestingWorkerRequest.cs" /> <Compile Include="Messaging\CollectionAssert.cs" /> + <Compile Include="Messaging\EnumerableCacheTests.cs" /> <Compile Include="Messaging\ErrorUtilitiesTests.cs" /> <Compile Include="Messaging\MessageSerializerTests.cs" /> <Compile Include="Messaging\OutgoingWebResponseTests.cs" /> @@ -189,13 +194,17 @@ <Compile Include="OpenId\Extensions\AttributeExchange\AttributeValuesTests.cs" /> <Compile Include="OpenId\Extensions\AttributeExchange\StoreRequestTests.cs" /> <Compile Include="OpenId\Extensions\AttributeExchange\StoreResponseTests.cs" /> + <Compile Include="OpenId\Extensions\ExtensionsInteropHelperOPTests.cs" /> + <Compile Include="OpenId\Extensions\ExtensionsInteropHelperRPResponseTests.cs" /> <Compile Include="OpenId\Extensions\ProviderAuthenticationPolicy\PapeRoundTripTests.cs" /> <Compile Include="OpenId\Extensions\ProviderAuthenticationPolicy\PolicyRequestTests.cs" /> <Compile Include="OpenId\Extensions\ProviderAuthenticationPolicy\PolicyResponseTests.cs" /> <Compile Include="OpenId\Extensions\SimpleRegistration\ClaimsResponseTests.cs" /> <Compile Include="OpenId\Extensions\ExtensionTestUtilities.cs" /> <Compile Include="OpenId\Extensions\SimpleRegistration\ClaimsRequestTests.cs" /> + <Compile Include="OpenId\Extensions\UI\UIRequestTests.cs" /> <Compile Include="OpenId\IdentifierTests.cs" /> + <Compile Include="OpenId\Extensions\ExtensionsInteropHelperRPRequestTests.cs" /> <Compile Include="OpenId\Messages\AssociateDiffieHellmanRequestTests.cs" /> <Compile Include="OpenId\Messages\AssociateRequestTests.cs" /> <Compile Include="OpenId\Messages\AssociateUnsuccessfulResponseTests.cs" /> @@ -210,15 +219,21 @@ <Compile Include="OpenId\Messages\IndirectErrorResponseTests.cs" /> <Compile Include="OpenId\Messages\PositiveAssertionResponseTests.cs" /> <Compile Include="OpenId\Messages\SignedResponseRequestTests.cs" /> + <Compile Include="OpenId\NonIdentityTests.cs" /> <Compile Include="OpenId\OpenIdCoordinator.cs" /> <Compile Include="OpenId\AssociationHandshakeTests.cs" /> <Compile Include="OpenId\OpenIdTestBase.cs" /> + <Compile Include="OpenId\Provider\PerformanceTests.cs" /> + <Compile Include="OpenId\ProviderEndpointDescriptionTests.cs" /> + <Compile Include="OpenId\Provider\AnonymousRequestTests.cs" /> <Compile Include="OpenId\Provider\AuthenticationRequestTest.cs" /> + <Compile Include="OpenId\Provider\HostProcessedRequestTests.cs" /> <Compile Include="OpenId\Provider\OpenIdProviderTests.cs" /> <Compile Include="OpenId\RealmTests.cs" /> <Compile Include="OpenId\RelyingParty\AuthenticationRequestTests.cs" /> <Compile Include="OpenId\RelyingParty\FailedAuthenticationResponseTests.cs" /> <Compile Include="OpenId\RelyingParty\NegativeAuthenticationResponseTests.cs" /> + <Compile Include="OpenId\RelyingParty\PositiveAnonymousResponseTests.cs" /> <Compile Include="OpenId\RelyingParty\PositiveAuthenticationResponseTests.cs" /> <Compile Include="OpenId\RelyingParty\OpenIdRelyingPartyTests.cs" /> <Compile Include="OpenId\RelyingParty\RelyingPartySecuritySettingsTests.cs" /> diff --git a/src/DotNetOpenAuth.Test/Messaging/EnumerableCacheTests.cs b/src/DotNetOpenAuth.Test/Messaging/EnumerableCacheTests.cs new file mode 100644 index 0000000..55f4394 --- /dev/null +++ b/src/DotNetOpenAuth.Test/Messaging/EnumerableCacheTests.cs @@ -0,0 +1,130 @@ +//----------------------------------------------------------------------- +// <copyright file="EnumerableCacheTests.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// This code is released under the Microsoft Public License (Ms-PL). +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.Test.Messaging { + using System; + using System.Collections.Generic; + using System.Collections.ObjectModel; + using System.Linq; + using DotNetOpenAuth.Messaging; + using Microsoft.VisualStudio.TestTools.UnitTesting; + + /// <summary> + /// Tests for cached enumeration. + /// </summary> + [TestClass] + public class EnumerableCacheTests { + /// <summary> + /// The number of times the generator method's implementation is started. + /// </summary> + private int generatorInvocations; + + /// <summary> + /// The number of times the end of the generator method's implementation is reached. + /// </summary> + private int generatorCompleted; + + /// <summary> + /// Gets or sets the test context. + /// </summary> + public TestContext TestContext { get; set; } + + /// <summary> + /// Sets up a test. + /// </summary> + [TestInitialize] + public void Setup() { + this.generatorInvocations = 0; + this.generatorCompleted = 0; + } + + [TestMethod] + public void EnumerableCache() { + // Baseline + var generator = this.NumberGenerator(); + var list1 = generator.ToList(); + var list2 = generator.ToList(); + Assert.AreEqual(2, this.generatorInvocations); + CollectionAssert.AreEqual(list1, list2); + + // Cache behavior + this.generatorInvocations = 0; + this.generatorCompleted = 0; + generator = this.NumberGenerator().CacheGeneratedResults(); + var list3 = generator.ToList(); + var list4 = generator.ToList(); + Assert.AreEqual(1, this.generatorInvocations); + Assert.AreEqual(1, this.generatorCompleted); + CollectionAssert.AreEqual(list1, list3); + CollectionAssert.AreEqual(list1, list4); + } + + [TestMethod] + public void GeneratesOnlyRequiredElements() { + var generator = this.NumberGenerator().CacheGeneratedResults(); + Assert.AreEqual(0, this.generatorInvocations); + generator.Take(2).ToList(); + Assert.AreEqual(1, this.generatorInvocations); + Assert.AreEqual(0, this.generatorCompleted, "Only taking part of the list should not have completed the generator."); + } + + [TestMethod] + public void PassThruDoubleCache() { + var cache1 = this.NumberGenerator().CacheGeneratedResults(); + var cache2 = cache1.CacheGeneratedResults(); + Assert.AreSame(cache1, cache2, "Two caches were set up rather than just sharing the first one."); + } + + [TestMethod] + public void PassThruList() { + var list = this.NumberGenerator().ToList(); + var cache = list.CacheGeneratedResults(); + Assert.AreSame(list, cache); + } + + [TestMethod] + public void PassThruArray() { + var array = this.NumberGenerator().ToArray(); + var cache = array.CacheGeneratedResults(); + Assert.AreSame(array, cache); + } + + [TestMethod] + public void PassThruCollection() { + var collection = new Collection<int>(); + var cache = collection.CacheGeneratedResults(); + Assert.AreSame(collection, cache); + } + + /// <summary> + /// Tests calling IEnumerator.Current before first call to MoveNext. + /// </summary> + [TestMethod, ExpectedException(typeof(InvalidOperationException))] + public void EnumerableCacheCurrentThrowsBefore() { + var foo = this.NumberGenerator().CacheGeneratedResults().GetEnumerator().Current; + } + + /// <summary> + /// Tests calling IEnumerator.Current after MoveNext returns false. + /// </summary> + [TestMethod, ExpectedException(typeof(InvalidOperationException))] + public void EnumerableCacheCurrentThrowsAfter() { + var enumerator = this.NumberGenerator().CacheGeneratedResults().GetEnumerator(); + while (enumerator.MoveNext()) { + } + var foo = enumerator.Current; + } + + private IEnumerable<int> NumberGenerator() { + this.generatorInvocations++; + for (int i = 10; i < 15; i++) { + yield return i; + } + this.generatorCompleted++; + } + } +} diff --git a/src/DotNetOpenAuth.Test/Mocks/InMemoryTokenManager.cs b/src/DotNetOpenAuth.Test/Mocks/InMemoryTokenManager.cs index 6980761..48547b7 100644 --- a/src/DotNetOpenAuth.Test/Mocks/InMemoryTokenManager.cs +++ b/src/DotNetOpenAuth.Test/Mocks/InMemoryTokenManager.cs @@ -102,6 +102,10 @@ namespace DotNetOpenAuth.Test.Mocks { return this.tokens[token]; } + public IServiceProviderAccessToken GetAccessToken(string token) { + return this.tokens[token]; + } + #endregion /// <summary> @@ -125,7 +129,7 @@ namespace DotNetOpenAuth.Test.Mocks { this.requestTokens[requestToken] = true; } - private class TokenInfo : IServiceProviderRequestToken { + private class TokenInfo : IServiceProviderRequestToken, IServiceProviderAccessToken { internal TokenInfo() { this.CreatedOn = DateTime.Now; } @@ -142,6 +146,12 @@ namespace DotNetOpenAuth.Test.Mocks { public Version ConsumerVersion { get; set; } + public string Username { get; set; } + + public string[] Roles { get; set; } + + public DateTime? ExpirationDate { get; set; } + internal string Secret { get; set; } } diff --git a/src/DotNetOpenAuth.Test/Mocks/MockHttpRequest.cs b/src/DotNetOpenAuth.Test/Mocks/MockHttpRequest.cs index d2e1f0b..66f258d 100644 --- a/src/DotNetOpenAuth.Test/Mocks/MockHttpRequest.cs +++ b/src/DotNetOpenAuth.Test/Mocks/MockHttpRequest.cs @@ -152,6 +152,7 @@ namespace DotNetOpenAuth.Test.Mocks { <Service priority='10'> <Type>{0}</Type> <URI>{1}</URI> + <URI>{2}</URI> </Service> </XRD> </xrds:XRDS>"; @@ -159,9 +160,11 @@ namespace DotNetOpenAuth.Test.Mocks { CultureInfo.InvariantCulture, template, HttpUtility.HtmlEncode(Protocol.V20.RPReturnToTypeURI), - HttpUtility.HtmlEncode(OpenIdTestBase.RPRealmUri.AbsoluteUri)); + HttpUtility.HtmlEncode(OpenIdTestBase.RPRealmUri.AbsoluteUri), + HttpUtility.HtmlEncode(OpenIdTestBase.RPRealmUriSsl.AbsoluteUri)); this.RegisterMockResponse(OpenIdTestBase.RPRealmUri, ContentTypes.Xrds, xrds); + this.RegisterMockResponse(OpenIdTestBase.RPRealmUriSsl, ContentTypes.Xrds, xrds); } internal void DeleteResponse(Uri requestUri) { diff --git a/src/DotNetOpenAuth.Test/Mocks/MockRealm.cs b/src/DotNetOpenAuth.Test/Mocks/MockRealm.cs index 4e29bba..ae39ebb 100644 --- a/src/DotNetOpenAuth.Test/Mocks/MockRealm.cs +++ b/src/DotNetOpenAuth.Test/Mocks/MockRealm.cs @@ -35,7 +35,7 @@ namespace DotNetOpenAuth.Test.Mocks { /// <returns> /// The details of the endpoints if found, otherwise null. /// </returns> - internal override IEnumerable<RelyingPartyEndpointDescription> Discover(IDirectWebRequestHandler requestHandler, bool allowRedirects) { + internal override IEnumerable<RelyingPartyEndpointDescription> DiscoverReturnToEndpoints(IDirectWebRequestHandler requestHandler, bool allowRedirects) { return this.relyingPartyDescriptions; } } diff --git a/src/DotNetOpenAuth.Test/OpenId/AssociationHandshakeTests.cs b/src/DotNetOpenAuth.Test/OpenId/AssociationHandshakeTests.cs index f88af0d..af3b1b1 100644 --- a/src/DotNetOpenAuth.Test/OpenId/AssociationHandshakeTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/AssociationHandshakeTests.cs @@ -375,8 +375,8 @@ namespace DotNetOpenAuth.Test.OpenId { var unencryptedResponse = (AssociateUnencryptedResponse)associateSuccessfulResponse; } } else { - Assert.IsNull(associationManagerAccessor.associationStore.GetAssociation(opDescription.Endpoint, new SecuritySettings(false))); - Assert.IsNull(coordinator.Provider.AssociationStore.GetAssociation(AssociationRelyingPartyType.Smart, new SecuritySettings(true))); + Assert.IsNull(associationManagerAccessor.associationStore.GetAssociation(opDescription.Endpoint, new RelyingPartySecuritySettings())); + Assert.IsNull(coordinator.Provider.AssociationStore.GetAssociation(AssociationRelyingPartyType.Smart, new ProviderSecuritySettings())); } } } diff --git a/src/DotNetOpenAuth.Test/OpenId/AuthenticationTests.cs b/src/DotNetOpenAuth.Test/OpenId/AuthenticationTests.cs index 807beae..4ebdf74 100644 --- a/src/DotNetOpenAuth.Test/OpenId/AuthenticationTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/AuthenticationTests.cs @@ -58,24 +58,62 @@ namespace DotNetOpenAuth.Test.OpenId { this.ParameterizedAuthenticationTest(false, false, false); } - /// <summary> - /// Verifies that unsolicited assertions can be sent and received. - /// </summary> [TestMethod] public void UnsolicitedAssertion() { - var coordinator = new OpenIdCoordinator( + this.MockResponder.RegisterMockRPDiscovery(); + OpenIdCoordinator coordinator = new OpenIdCoordinator( rp => { - // register with RP so that id discovery passes rp.Channel.WebRequestHandler = this.MockResponder.MockWebRequestHandler; - - // Receive the unsolicited assertion - var response = rp.GetResponse(); + IAuthenticationResponse response = rp.GetResponse(); Assert.AreEqual(AuthenticationStatus.Authenticated, response.Status); }, op => { + op.Channel.WebRequestHandler = this.MockResponder.MockWebRequestHandler; Identifier id = GetMockIdentifier(ProtocolVersion.V20); - op.SendUnsolicitedAssertion(OPUri, GetMockRealm(false), id, id); - AutoProvider(op); + op.SendUnsolicitedAssertion(OPUri, RPRealmUri, id, OPLocalIdentifiers[0]); + AutoProvider(op); // handle check_auth + }); + coordinator.Run(); + } + + [TestMethod] + public void UnsolicitedAssertionRejected() { + this.MockResponder.RegisterMockRPDiscovery(); + OpenIdCoordinator coordinator = new OpenIdCoordinator( + rp => { + rp.Channel.WebRequestHandler = this.MockResponder.MockWebRequestHandler; + rp.SecuritySettings.RejectUnsolicitedAssertions = true; + IAuthenticationResponse response = rp.GetResponse(); + Assert.AreEqual(AuthenticationStatus.Failed, response.Status); + }, + op => { + op.Channel.WebRequestHandler = this.MockResponder.MockWebRequestHandler; + Identifier id = GetMockIdentifier(ProtocolVersion.V20); + op.SendUnsolicitedAssertion(OPUri, RPRealmUri, id, OPLocalIdentifiers[0]); + AutoProvider(op); // handle check_auth + }); + coordinator.Run(); + } + + /// <summary> + /// Verifies that delegating identifiers are rejected in unsolicited assertions + /// when the appropriate security setting is set. + /// </summary> + [TestMethod] + public void UnsolicitedDelegatingIdentifierRejection() { + this.MockResponder.RegisterMockRPDiscovery(); + OpenIdCoordinator coordinator = new OpenIdCoordinator( + rp => { + rp.Channel.WebRequestHandler = this.MockResponder.MockWebRequestHandler; + rp.SecuritySettings.RejectDelegatingIdentifiers = true; + IAuthenticationResponse response = rp.GetResponse(); + Assert.AreEqual(AuthenticationStatus.Failed, response.Status); + }, + op => { + op.Channel.WebRequestHandler = this.MockResponder.MockWebRequestHandler; + Identifier id = GetMockIdentifier(ProtocolVersion.V20, false, true); + op.SendUnsolicitedAssertion(OPUri, RPRealmUri, id, OPLocalIdentifiers[0]); + AutoProvider(op); // handle check_auth }); coordinator.Run(); } diff --git a/src/DotNetOpenAuth.Test/OpenId/ChannelElements/ExtensionsBindingElementTests.cs b/src/DotNetOpenAuth.Test/OpenId/ChannelElements/ExtensionsBindingElementTests.cs index 12f6e7a..5af1caf 100644 --- a/src/DotNetOpenAuth.Test/OpenId/ChannelElements/ExtensionsBindingElementTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/ChannelElements/ExtensionsBindingElementTests.cs @@ -31,7 +31,7 @@ namespace DotNetOpenAuth.Test.OpenId.ChannelElements { this.factory = new StandardOpenIdExtensionFactory(); this.factory.RegisterExtension(MockOpenIdExtension.Factory); - this.rpElement = new ExtensionsBindingElement(this.factory); + this.rpElement = new ExtensionsBindingElement(this.factory, new RelyingPartySecuritySettings()); this.rpElement.Channel = new TestChannel(this.MessageDescriptions); this.request = new SignedResponseRequest(Protocol.Default.Version, OpenIdTestBase.OPUri, AuthenticationRequestMode.Immediate); } diff --git a/src/DotNetOpenAuth.Test/OpenId/Extensions/AttributeExchange/FetchResponseTests.cs b/src/DotNetOpenAuth.Test/OpenId/Extensions/AttributeExchange/FetchResponseTests.cs index 9d209a9..d7082c3 100644 --- a/src/DotNetOpenAuth.Test/OpenId/Extensions/AttributeExchange/FetchResponseTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/Extensions/AttributeExchange/FetchResponseTests.cs @@ -40,6 +40,22 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions { } [TestMethod] + public void GetAttributeValue() { + var response = new FetchResponse(); + + // Verify that null is returned if the attribute is absent. + Assert.IsNull(response.GetAttributeValue("http://someattribute")); + + // Now add an attribute with no values. + response.Attributes.Add(new AttributeValues("http://someattribute2")); + Assert.IsNull(response.GetAttributeValue("http://someattribute2")); + + // Now add an attribute with many values. + response.Attributes.Add(new AttributeValues("http://someattribute3", "a", "b", "c")); + Assert.AreEqual("a", response.GetAttributeValue("http://someattribute3")); + } + + [TestMethod] public void EqualityTests() { var response1 = new FetchResponse(); var response2 = new FetchResponse(); diff --git a/src/DotNetOpenAuth.Test/OpenId/Extensions/ExtensionsInteropHelperOPTests.cs b/src/DotNetOpenAuth.Test/OpenId/Extensions/ExtensionsInteropHelperOPTests.cs new file mode 100644 index 0000000..9f849ea --- /dev/null +++ b/src/DotNetOpenAuth.Test/OpenId/Extensions/ExtensionsInteropHelperOPTests.cs @@ -0,0 +1,147 @@ +//----------------------------------------------------------------------- +// <copyright file="ExtensionsInteropHelperOPTests.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.Test.OpenId.Extensions { + using System.Collections.Generic; + using System.Linq; + using DotNetOpenAuth.Messaging; + using DotNetOpenAuth.OpenId; + using DotNetOpenAuth.OpenId.Extensions; + using DotNetOpenAuth.OpenId.Extensions.AttributeExchange; + using DotNetOpenAuth.OpenId.Extensions.SimpleRegistration; + using DotNetOpenAuth.OpenId.Messages; + using DotNetOpenAuth.OpenId.Provider; + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class ExtensionsInteropHelperOPTests : OpenIdTestBase { + private AuthenticationRequest request; + private IList<IExtensionMessage> extensions; + + [TestInitialize] + public override void SetUp() { + base.SetUp(); + + var op = this.CreateProvider(); + var rpRequest = new CheckIdRequest(Protocol.Default.Version, OPUri, DotNetOpenAuth.OpenId.RelyingParty.AuthenticationRequestMode.Setup); + rpRequest.ReturnTo = RPUri; + this.extensions = rpRequest.Extensions; + this.request = new AuthenticationRequest(op, rpRequest); + this.request.IsAuthenticated = true; + } + + /// <summary> + /// Verifies no extensions appear as no extensions + /// </summary> + [TestMethod] + public void NoRequestedExtensions() { + var sreg = ExtensionsInteropHelper.UnifyExtensionsAsSreg(this.request); + Assert.IsNull(sreg); + + // Make sure we're still able to send an sreg response. + var sregResponse = new ClaimsResponse(); + this.request.AddResponseExtension(sregResponse); + ExtensionsInteropHelper.ConvertSregToMatchRequest(this.request); + var extensions = this.GetResponseExtensions(); + Assert.AreSame(sregResponse, extensions.Single()); + } + + /// <summary> + /// Verifies sreg coming in is seen as sreg. + /// </summary> + [TestMethod] + public void UnifyExtensionsAsSregWithSreg() { + var sregInjected = new ClaimsRequest { + Nickname = DemandLevel.Request, + }; + this.extensions.Add(sregInjected); + var sreg = ExtensionsInteropHelper.UnifyExtensionsAsSreg(this.request); + Assert.AreSame(sregInjected, sreg); + Assert.AreEqual(DemandLevel.Request, sreg.Nickname); + Assert.AreEqual(DemandLevel.NoRequest, sreg.FullName); + + var sregResponse = new ClaimsResponse(); + this.request.AddResponseExtension(sregResponse); + ExtensionsInteropHelper.ConvertSregToMatchRequest(this.request); + var extensions = this.GetResponseExtensions(); + Assert.AreSame(sregResponse, extensions.Single()); + } + + /// <summary> + /// Verifies AX coming in looks like sreg. + /// </summary> + [TestMethod] + public void UnifyExtensionsAsSregWithAX() { + this.ParameterizedAXTest(AXAttributeFormats.AXSchemaOrg); + } + + /// <summary> + /// Verifies AX coming in looks like sreg. + /// </summary> + [TestMethod] + public void UnifyExtensionsAsSregWithAXSchemaOpenIdNet() { + this.ParameterizedAXTest(AXAttributeFormats.SchemaOpenIdNet); + } + + /// <summary> + /// Verifies sreg and AX in one request has a preserved sreg request. + /// </summary> + [TestMethod] + public void UnifyExtensionsAsSregWithBothSregAndAX() { + var sregInjected = new ClaimsRequest { + Nickname = DemandLevel.Request, + }; + this.extensions.Add(sregInjected); + var axInjected = new FetchRequest(); + axInjected.Attributes.AddOptional(WellKnownAttributes.Contact.Email); + this.extensions.Add(axInjected); + var sreg = ExtensionsInteropHelper.UnifyExtensionsAsSreg(this.request); + Assert.AreSame(sregInjected, sreg); + Assert.AreEqual(DemandLevel.Request, sreg.Nickname); + Assert.AreEqual(DemandLevel.NoRequest, sreg.Email); + + var sregResponseInjected = new ClaimsResponse { + Nickname = "andy", + }; + this.request.AddResponseExtension(sregResponseInjected); + var axResponseInjected = new FetchResponse(); + axResponseInjected.Attributes.Add(WellKnownAttributes.Contact.Email, "a@b.com"); + this.request.AddResponseExtension(axResponseInjected); + ExtensionsInteropHelper.ConvertSregToMatchRequest(this.request); + var extensions = this.GetResponseExtensions(); + var sregResponse = extensions.OfType<ClaimsResponse>().Single(); + Assert.AreEqual("andy", sregResponse.Nickname); + var axResponse = extensions.OfType<FetchResponse>().Single(); + Assert.AreEqual("a@b.com", axResponse.GetAttributeValue(WellKnownAttributes.Contact.Email)); + } + + private IList<IExtensionMessage> GetResponseExtensions() { + IProtocolMessageWithExtensions response = (IProtocolMessageWithExtensions)this.request.Response; + return response.Extensions; + } + + private void ParameterizedAXTest(AXAttributeFormats format) { + var axInjected = new FetchRequest(); + axInjected.Attributes.AddOptional(ExtensionsInteropHelper_Accessor.TransformAXFormat(WellKnownAttributes.Name.Alias, format)); + axInjected.Attributes.AddRequired(ExtensionsInteropHelper_Accessor.TransformAXFormat(WellKnownAttributes.Name.FullName, format)); + this.extensions.Add(axInjected); + var sreg = ExtensionsInteropHelper.UnifyExtensionsAsSreg(this.request); + Assert.AreSame(sreg, this.request.GetExtension<ClaimsRequest>()); + Assert.AreEqual(DemandLevel.Request, sreg.Nickname); + Assert.AreEqual(DemandLevel.Require, sreg.FullName); + Assert.AreEqual(DemandLevel.NoRequest, sreg.Language); + + var sregResponse = new ClaimsResponse { + Nickname = "andy", + }; + this.request.AddResponseExtension(sregResponse); + ExtensionsInteropHelper.ConvertSregToMatchRequest(this.request); + var extensions = this.GetResponseExtensions(); + var axResponse = extensions.OfType<FetchResponse>().Single(); + Assert.AreEqual("andy", axResponse.GetAttributeValue(ExtensionsInteropHelper_Accessor.TransformAXFormat(WellKnownAttributes.Name.Alias, format))); + } + } +} diff --git a/src/DotNetOpenAuth.Test/OpenId/Extensions/ExtensionsInteropHelperRPRequestTests.cs b/src/DotNetOpenAuth.Test/OpenId/Extensions/ExtensionsInteropHelperRPRequestTests.cs new file mode 100644 index 0000000..ba5e335 --- /dev/null +++ b/src/DotNetOpenAuth.Test/OpenId/Extensions/ExtensionsInteropHelperRPRequestTests.cs @@ -0,0 +1,128 @@ +//----------------------------------------------------------------------- +// <copyright file="ExtensionsInteropHelperRPRequestTests.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.Test.OpenId { + 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; + + [TestClass] + public class ExtensionsInteropHelperRPRequestTests : OpenIdTestBase { + private AuthenticationRequest authReq; + private ClaimsRequest sreg; + + [TestInitialize] + public override void SetUp() { + base.SetUp(); + + var rp = CreateRelyingParty(true); + Identifier identifier = this.GetMockIdentifier(ProtocolVersion.V20); + this.authReq = (AuthenticationRequest)rp.CreateRequest(identifier, RPRealmUri, RPUri); + this.sreg = new ClaimsRequest { + Nickname = DemandLevel.Request, + FullName = DemandLevel.Request, + BirthDate = DemandLevel.Request, + Email = DemandLevel.Require, + Country = DemandLevel.Request, + PostalCode = DemandLevel.Request, + Gender = DemandLevel.Request, + Language = DemandLevel.Request, + TimeZone = DemandLevel.Request, + }; + } + + /// <summary> + /// Verifies that without an Sreg extension to copy from, no AX extension request is added. + /// </summary> + [TestMethod] + public void SpreadSregToAXNoExtensions() { + ExtensionsInteropHelper.SpreadSregToAX(this.authReq, AXAttributeFormats.AXSchemaOrg); + Assert.AreEqual(0, this.authReq.AppliedExtensions.Count()); + } + + /// <summary> + /// Verifies that Sreg requests are correctly copied to axschema.org AX requests. + /// </summary> + [TestMethod] + public void SpreadSregToAXBasic() { + this.authReq.AddExtension(this.sreg); + ExtensionsInteropHelper.SpreadSregToAX(this.authReq, AXAttributeFormats.AXSchemaOrg); + var ax = this.authReq.AppliedExtensions.OfType<FetchRequest>().Single(); + Assert.IsFalse(ax.Attributes[WellKnownAttributes.Name.Alias].IsRequired); + Assert.IsFalse(ax.Attributes[WellKnownAttributes.Name.FullName].IsRequired); + Assert.IsFalse(ax.Attributes[WellKnownAttributes.BirthDate.WholeBirthDate].IsRequired); + Assert.IsTrue(ax.Attributes[WellKnownAttributes.Contact.Email].IsRequired); + Assert.IsFalse(ax.Attributes[WellKnownAttributes.Contact.HomeAddress.Country].IsRequired); + Assert.IsFalse(ax.Attributes[WellKnownAttributes.Contact.HomeAddress.PostalCode].IsRequired); + Assert.IsFalse(ax.Attributes[WellKnownAttributes.Person.Gender].IsRequired); + Assert.IsFalse(ax.Attributes[WellKnownAttributes.Preferences.Language].IsRequired); + Assert.IsFalse(ax.Attributes[WellKnownAttributes.Preferences.TimeZone].IsRequired); + } + + /// <summary> + /// Verifies that sreg can spread to multiple AX schemas. + /// </summary> + [TestMethod] + public void SpreadSregToAxMultipleSchemas() { + this.authReq.AddExtension(this.sreg); + ExtensionsInteropHelper.SpreadSregToAX(this.authReq, AXAttributeFormats.AXSchemaOrg | AXAttributeFormats.SchemaOpenIdNet); + var ax = this.authReq.AppliedExtensions.OfType<FetchRequest>().Single(); + Assert.IsTrue(ax.Attributes.Contains(WellKnownAttributes.Name.Alias)); + Assert.IsTrue(ax.Attributes.Contains(ExtensionsInteropHelper_Accessor.TransformAXFormat(WellKnownAttributes.Name.Alias, AXAttributeFormats.SchemaOpenIdNet))); + Assert.IsFalse(ax.Attributes.Contains(ExtensionsInteropHelper_Accessor.TransformAXFormat(WellKnownAttributes.Name.Alias, AXAttributeFormats.OpenIdNetSchema))); + } + + /// <summary> + /// Verifies no spread if the OP advertises sreg support. + /// </summary> + [TestMethod] + public void SpreadSregToAxNoOpIfOPSupportsSreg() { + this.authReq.AddExtension(this.sreg); + this.InjectAdvertisedTypeUri(DotNetOpenAuth.OpenId.Extensions.SimpleRegistration.Constants.sreg_ns); + ExtensionsInteropHelper.SpreadSregToAX(this.authReq, AXAttributeFormats.All); + Assert.IsFalse(this.authReq.AppliedExtensions.OfType<FetchRequest>().Any()); + } + + /// <summary> + /// Verifies a targeted AX request if the OP advertises a recognized type URI format. + /// </summary> + [TestMethod] + public void SpreadSregToAxTargetedAtOPFormat() { + this.authReq.AddExtension(this.sreg); + this.InjectAdvertisedTypeUri(WellKnownAttributes.Name.FullName); + ExtensionsInteropHelper.SpreadSregToAX(this.authReq, AXAttributeFormats.OpenIdNetSchema); + var ax = this.authReq.AppliedExtensions.OfType<FetchRequest>().Single(); + Assert.IsFalse(ax.Attributes.Contains(ExtensionsInteropHelper_Accessor.TransformAXFormat(WellKnownAttributes.Contact.Email, AXAttributeFormats.OpenIdNetSchema))); + Assert.IsTrue(ax.Attributes.Contains(WellKnownAttributes.Contact.Email)); + } + + /// <summary> + /// Verifies that TransformAXFormat correctly translates AX schema Type URIs. + /// </summary> + [TestMethod] + 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)); + Assert.AreEqual("http://openid.net/schema/namePerson/friendly", ExtensionsInteropHelper_Accessor.TransformAXFormat(WellKnownAttributes.Name.Alias, AXAttributeFormats.OpenIdNetSchema)); + } + + /// <summary> + /// Injects the advertised type URI into the list of advertised services for the authentication request. + /// </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 }))); + } + } +} diff --git a/src/DotNetOpenAuth.Test/OpenId/Extensions/ExtensionsInteropHelperRPResponseTests.cs b/src/DotNetOpenAuth.Test/OpenId/Extensions/ExtensionsInteropHelperRPResponseTests.cs new file mode 100644 index 0000000..5fe05c1 --- /dev/null +++ b/src/DotNetOpenAuth.Test/OpenId/Extensions/ExtensionsInteropHelperRPResponseTests.cs @@ -0,0 +1,83 @@ +//----------------------------------------------------------------------- +// <copyright file="ExtensionsInteropHelperRPResponseTests.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.Test.OpenId { + using System.Collections.Generic; + using DotNetOpenAuth.Messaging; + using DotNetOpenAuth.OpenId; + using DotNetOpenAuth.OpenId.Extensions; + using DotNetOpenAuth.OpenId.Extensions.AttributeExchange; + using DotNetOpenAuth.OpenId.Extensions.SimpleRegistration; + using DotNetOpenAuth.OpenId.Messages; + using DotNetOpenAuth.OpenId.RelyingParty; + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class ExtensionsInteropHelperRPResponseTests : OpenIdTestBase { + private IAuthenticationResponse response; + private IList<IExtensionMessage> extensions; + + [TestInitialize] + public override void SetUp() { + base.SetUp(); + + IndirectSignedResponse responseMessage = new IndirectSignedResponse(Protocol.Default.Version, RPUri); + this.extensions = responseMessage.Extensions; + this.response = new DotNetOpenAuth.OpenId.RelyingParty.PositiveAnonymousResponse(responseMessage); + } + + /// <summary> + /// Verifies that with no extensions present, UnifyExtensionsAsSreg returns an empty ClaimsResponse. + /// </summary> + [TestMethod] + public void UnifyExtensionsAsSregNoExtensions() { + var sreg = ExtensionsInteropHelper.UnifyExtensionsAsSreg(this.response, true); + Assert.IsNotNull(sreg); + Assert.IsNull(sreg.Nickname); + } + + /// <summary> + /// Verifies that with sreg and AX extensions present, the sreg extension is returned. + /// </summary> + [TestMethod] + public void UnifyExtensionsAsSregWithSreg() { + var sregInjected = new ClaimsResponse { + Nickname = "andy", + }; + var axInjected = new FetchResponse(); + axInjected.Attributes.Add(WellKnownAttributes.Name.Alias, "nate"); + this.extensions.Add(sregInjected); + this.extensions.Add(axInjected); + var sreg = ExtensionsInteropHelper.UnifyExtensionsAsSreg(this.response, true); + Assert.AreSame(sregInjected, sreg); + Assert.AreEqual("andy", sreg.Nickname); + } + + /// <summary> + /// Verifies UnifyExtensionsAsSreg correctly converts AX to sreg. + /// </summary> + [TestMethod] + public void UnifyExtensionsAsSregFromAXSchemaOrg() { + var axInjected = new FetchResponse(); + axInjected.Attributes.Add(WellKnownAttributes.Name.Alias, "nate"); + this.extensions.Add(axInjected); + var sreg = ExtensionsInteropHelper.UnifyExtensionsAsSreg(this.response, true); + Assert.AreEqual("nate", sreg.Nickname); + } + + /// <summary> + /// Verifies UnifyExtensionsAsSreg correctly converts AX in a non-standard format to sreg. + /// </summary> + [TestMethod] + public void UnifyExtensionsasSregFromSchemaOpenIdNet() { + var axInjected = new FetchResponse(); + axInjected.Attributes.Add(ExtensionsInteropHelper_Accessor.TransformAXFormat(WellKnownAttributes.Name.Alias, AXAttributeFormats.SchemaOpenIdNet), "nate"); + this.extensions.Add(axInjected); + var sreg = ExtensionsInteropHelper.UnifyExtensionsAsSreg(this.response, true); + Assert.AreEqual("nate", sreg.Nickname); + } + } +} diff --git a/src/DotNetOpenAuth.Test/OpenId/Extensions/UI/UIRequestTests.cs b/src/DotNetOpenAuth.Test/OpenId/Extensions/UI/UIRequestTests.cs new file mode 100644 index 0000000..7a60a32 --- /dev/null +++ b/src/DotNetOpenAuth.Test/OpenId/Extensions/UI/UIRequestTests.cs @@ -0,0 +1,52 @@ +//----------------------------------------------------------------------- +// <copyright file="UIRequestTests.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.Test.OpenId.Extensions.UI { + using System.Globalization; + using DotNetOpenAuth.Messaging.Reflection; + using DotNetOpenAuth.OpenId.Extensions.UI; + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class UIRequestTests : OpenIdTestBase { + [TestMethod] + public void Defaults() { + UIRequest request = new UIRequest(); + Assert.AreEqual("popup", request.Mode); + Assert.AreEqual(1, request.LanguagePreference.Length); + Assert.AreEqual(CultureInfo.CurrentUICulture, request.LanguagePreference[0]); + } + + [TestMethod] + public void LanguagePreferenceEncodingDecoding() { + var request = new UIRequest(); + MessageDictionary dictionary = this.MessageDescriptions.GetAccessor(request); + + request.LanguagePreference = new[] { new CultureInfo("en-US") }; + Assert.AreEqual("en-US", dictionary["lang"]); + + request.LanguagePreference = new[] { new CultureInfo("en-US"), new CultureInfo("es-ES") }; + Assert.AreEqual("en-US,es-ES", dictionary["lang"]); + + // Now test decoding + dictionary["lang"] = "en-US"; + Assert.AreEqual(1, request.LanguagePreference.Length); + Assert.AreEqual(new CultureInfo("en-US"), request.LanguagePreference[0]); + + dictionary["lang"] = "en-US,es-ES"; + Assert.AreEqual(2, request.LanguagePreference.Length); + Assert.AreEqual(new CultureInfo("en-US"), request.LanguagePreference[0]); + Assert.AreEqual(new CultureInfo("es-ES"), request.LanguagePreference[1]); + } + + [TestMethod] + public void ModeEncoding() { + var request = new UIRequest(); + MessageDictionary dictionary = this.MessageDescriptions.GetAccessor(request); + Assert.AreEqual("popup", dictionary["mode"]); + } + } +} diff --git a/src/DotNetOpenAuth.Test/OpenId/NonIdentityTests.cs b/src/DotNetOpenAuth.Test/OpenId/NonIdentityTests.cs new file mode 100644 index 0000000..49bb32c --- /dev/null +++ b/src/DotNetOpenAuth.Test/OpenId/NonIdentityTests.cs @@ -0,0 +1,57 @@ +//----------------------------------------------------------------------- +// <copyright file="NonIdentityTests.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.Test.OpenId { + using DotNetOpenAuth.OpenId; + using DotNetOpenAuth.OpenId.Messages; + using DotNetOpenAuth.OpenId.Provider; + using DotNetOpenAuth.OpenId.RelyingParty; + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class NonIdentityTests : OpenIdTestBase { + [TestMethod] + public void ExtensionOnlyChannelLevel() { + Protocol protocol = Protocol.V20; + AuthenticationRequestMode mode = AuthenticationRequestMode.Setup; + + var coordinator = new OpenIdCoordinator( + rp => { + var request = new SignedResponseRequest(protocol.Version, OPUri, mode); + rp.Channel.Send(request); + }, + op => { + var request = op.Channel.ReadFromRequest<SignedResponseRequest>(); + Assert.IsNotInstanceOfType(request, typeof(CheckIdRequest)); + }); + coordinator.Run(); + } + + [TestMethod] + public void ExtensionOnlyFacadeLevel() { + Protocol protocol = Protocol.V20; + var coordinator = new OpenIdCoordinator( + rp => { + var request = rp.CreateRequest(GetMockIdentifier(protocol.ProtocolVersion), RPRealmUri, RPUri); + + request.IsExtensionOnly = true; + rp.Channel.Send(request.RedirectingResponse.OriginalMessage); + IAuthenticationResponse response = rp.GetResponse(); + Assert.AreEqual(AuthenticationStatus.ExtensionsOnly, response.Status); + }, + op => { + var assocRequest = op.GetRequest(); + op.SendResponse(assocRequest); + + var request = (IAnonymousRequest)op.GetRequest(); + request.IsApproved = true; + Assert.IsNotInstanceOfType(request, typeof(CheckIdRequest)); + op.SendResponse(request); + }); + coordinator.Run(); + } + } +} diff --git a/src/DotNetOpenAuth.Test/OpenId/OpenIdTestBase.cs b/src/DotNetOpenAuth.Test/OpenId/OpenIdTestBase.cs index 6099b86..5034b7e 100644 --- a/src/DotNetOpenAuth.Test/OpenId/OpenIdTestBase.cs +++ b/src/DotNetOpenAuth.Test/OpenId/OpenIdTestBase.cs @@ -117,13 +117,19 @@ namespace DotNetOpenAuth.Test.OpenId { } internal static ServiceEndpoint 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) { 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( - useSsl ? OPLocalIdentifiersSsl[user] : OPLocalIdentifiers[user], - useSsl ? OPLocalIdentifiersSsl[user] : OPLocalIdentifiers[user], - useSsl ? OPLocalIdentifiersSsl[user] : OPLocalIdentifiers[user], + claimed_id, + claimed_id, + local_id, providerEndpoint, servicePriority, 10); @@ -180,8 +186,12 @@ namespace DotNetOpenAuth.Test.OpenId { } protected Identifier GetMockIdentifier(ProtocolVersion providerVersion, bool useSsl) { - ServiceEndpoint se = GetServiceEndpoint(0, providerVersion, 10, useSsl); - UriIdentifier identityUri = useSsl ? OpenIdTestBase.OPLocalIdentifiersSsl[0] : OpenIdTestBase.OPLocalIdentifiers[0]; + return this.GetMockIdentifier(providerVersion, useSsl, false); + } + + protected Identifier GetMockIdentifier(ProtocolVersion providerVersion, bool useSsl, bool delegating) { + ServiceEndpoint se = GetServiceEndpoint(0, providerVersion, 10, useSsl, delegating); + UriIdentifier identityUri = (UriIdentifier)se.ClaimedIdentifier; return new MockIdentifier(identityUri, this.MockResponder, new ServiceEndpoint[] { se }); } @@ -190,7 +200,16 @@ namespace DotNetOpenAuth.Test.OpenId { /// </summary> /// <returns>The new instance.</returns> protected OpenIdRelyingParty CreateRelyingParty() { - var rp = new OpenIdRelyingParty(new StandardRelyingPartyApplicationStore()); + return this.CreateRelyingParty(false); + } + + /// <summary> + /// Creates a standard <see cref="OpenIdRelyingParty"/> instance for general testing. + /// </summary> + /// <param name="stateless">if set to <c>true</c> a stateless RP is created.</param> + /// <returns>The new instance.</returns> + protected OpenIdRelyingParty CreateRelyingParty(bool stateless) { + var rp = new OpenIdRelyingParty(stateless ? null : new StandardRelyingPartyApplicationStore()); rp.Channel.WebRequestHandler = this.MockResponder.MockWebRequestHandler; return rp; } diff --git a/src/DotNetOpenAuth.Test/OpenId/Provider/AnonymousRequestTests.cs b/src/DotNetOpenAuth.Test/OpenId/Provider/AnonymousRequestTests.cs new file mode 100644 index 0000000..14fef91 --- /dev/null +++ b/src/DotNetOpenAuth.Test/OpenId/Provider/AnonymousRequestTests.cs @@ -0,0 +1,37 @@ +//----------------------------------------------------------------------- +// <copyright file="AnonymousRequestTests.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.Test.OpenId.Provider { + using DotNetOpenAuth.OpenId; + using DotNetOpenAuth.OpenId.Messages; + using DotNetOpenAuth.OpenId.Provider; + using DotNetOpenAuth.OpenId.RelyingParty; + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class AnonymousRequestTests : OpenIdTestBase { + /// <summary> + /// Verifies that IsApproved controls which response message is returned. + /// </summary> + [TestMethod] + public void IsApprovedDeterminesReturnedMessage() { + var op = CreateProvider(); + Protocol protocol = Protocol.V20; + var req = new SignedResponseRequest(protocol.Version, OPUri, AuthenticationRequestMode.Setup); + req.ReturnTo = RPUri; + var anonReq = new AnonymousRequest(op, req); + + Assert.IsFalse(anonReq.IsApproved.HasValue); + + anonReq.IsApproved = false; + Assert.IsInstanceOfType(anonReq.Response, typeof(NegativeAssertionResponse)); + + anonReq.IsApproved = true; + Assert.IsInstanceOfType(anonReq.Response, typeof(IndirectSignedResponse)); + Assert.IsNotInstanceOfType(anonReq.Response, typeof(PositiveAssertionResponse)); + } + } +} diff --git a/src/DotNetOpenAuth.Test/OpenId/Provider/AuthenticationRequestTest.cs b/src/DotNetOpenAuth.Test/OpenId/Provider/AuthenticationRequestTest.cs index 9803095..accbd97 100644 --- a/src/DotNetOpenAuth.Test/OpenId/Provider/AuthenticationRequestTest.cs +++ b/src/DotNetOpenAuth.Test/OpenId/Provider/AuthenticationRequestTest.cs @@ -45,20 +45,5 @@ namespace DotNetOpenAuth.Test.OpenId.Provider { Assert.AreEqual(immediateRequest.LocalIdentifier, setupRequestMessage.LocalIdentifier); Assert.AreEqual(immediateRequest.Version, setupRequestMessage.Version); } - - [TestMethod] - public void IsReturnUrlDiscoverable() { - Protocol protocol = Protocol.Default; - OpenIdProvider provider = this.CreateProvider(); - CheckIdRequest checkIdRequest = new CheckIdRequest(protocol.Version, OPUri, DotNetOpenAuth.OpenId.RelyingParty.AuthenticationRequestMode.Setup); - checkIdRequest.Realm = RPRealmUri; - checkIdRequest.ReturnTo = RPUri; - AuthenticationRequest request = new AuthenticationRequest(provider, checkIdRequest); - Assert.IsFalse(request.IsReturnUrlDiscoverable(this.MockResponder.MockWebRequestHandler)); - - this.MockResponder.RegisterMockRPDiscovery(); - request = new AuthenticationRequest(provider, checkIdRequest); - Assert.IsTrue(request.IsReturnUrlDiscoverable(this.MockResponder.MockWebRequestHandler)); - } } } diff --git a/src/DotNetOpenAuth.Test/OpenId/Provider/HostProcessedRequestTests.cs b/src/DotNetOpenAuth.Test/OpenId/Provider/HostProcessedRequestTests.cs new file mode 100644 index 0000000..d308271 --- /dev/null +++ b/src/DotNetOpenAuth.Test/OpenId/Provider/HostProcessedRequestTests.cs @@ -0,0 +1,85 @@ +//----------------------------------------------------------------------- +// <copyright file="HostProcessedRequestTests.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.Test.OpenId.Provider { + using System; + using DotNetOpenAuth.OpenId; + using DotNetOpenAuth.OpenId.Messages; + using DotNetOpenAuth.OpenId.Provider; + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class HostProcessedRequestTests : OpenIdTestBase { + private Protocol protocol; + private OpenIdProvider provider; + private CheckIdRequest checkIdRequest; + private AuthenticationRequest request; + + [TestInitialize] + public override void SetUp() { + base.SetUp(); + + this.protocol = Protocol.Default; + this.provider = this.CreateProvider(); + this.checkIdRequest = new CheckIdRequest(this.protocol.Version, OPUri, DotNetOpenAuth.OpenId.RelyingParty.AuthenticationRequestMode.Setup); + this.checkIdRequest.Realm = RPRealmUri; + this.checkIdRequest.ReturnTo = RPUri; + this.request = new AuthenticationRequest(this.provider, this.checkIdRequest); + } + + [TestMethod] + public void IsReturnUrlDiscoverableNoResponse() { + Assert.AreEqual(RelyingPartyDiscoveryResult.NoServiceDocument, this.request.IsReturnUrlDiscoverable(this.provider)); + } + + [TestMethod] + public void IsReturnUrlDiscoverableValidResponse() { + this.MockResponder.RegisterMockRPDiscovery(); + this.request = new AuthenticationRequest(this.provider, this.checkIdRequest); + Assert.AreEqual(RelyingPartyDiscoveryResult.Success, this.request.IsReturnUrlDiscoverable(this.provider)); + } + + /// <summary> + /// Verifies that when discovery would be performed over standard HTTP and RequireSsl + /// is set, that discovery fails. + /// </summary> + [TestMethod] + public void IsReturnUrlDiscoverableNotSsl() { + this.provider.SecuritySettings.RequireSsl = true; + this.MockResponder.RegisterMockRPDiscovery(); + Assert.AreEqual(RelyingPartyDiscoveryResult.NoServiceDocument, this.request.IsReturnUrlDiscoverable(this.provider)); + } + + /// <summary> + /// Verifies that when discovery would be performed over HTTPS that discovery succeeds. + /// </summary> + [TestMethod] + public void IsReturnUrlDiscoverableRequireSsl() { + this.MockResponder.RegisterMockRPDiscovery(); + this.checkIdRequest.Realm = RPRealmUriSsl; + this.checkIdRequest.ReturnTo = RPUriSsl; + + // Try once with RequireSsl + this.provider.SecuritySettings.RequireSsl = true; + this.request = new AuthenticationRequest(this.provider, this.checkIdRequest); + Assert.AreEqual(RelyingPartyDiscoveryResult.Success, this.request.IsReturnUrlDiscoverable(this.provider)); + + // And again without RequireSsl + this.provider.SecuritySettings.RequireSsl = false; + this.request = new AuthenticationRequest(this.provider, this.checkIdRequest); + Assert.AreEqual(RelyingPartyDiscoveryResult.Success, this.request.IsReturnUrlDiscoverable(this.provider)); + } + + [TestMethod] + public void IsReturnUrlDiscoverableValidButNoMatch() { + this.MockResponder.RegisterMockRPDiscovery(); + this.provider.SecuritySettings.RequireSsl = false; // reset for another failure test case + this.checkIdRequest.ReturnTo = new Uri("http://somerandom/host"); + this.request = new AuthenticationRequest(this.provider, this.checkIdRequest); + Assert.AreEqual(RelyingPartyDiscoveryResult.NoMatchingReturnTo, this.request.IsReturnUrlDiscoverable(this.provider)); + } + } +} diff --git a/src/DotNetOpenAuth.Test/OpenId/Provider/PerformanceTests.cs b/src/DotNetOpenAuth.Test/OpenId/Provider/PerformanceTests.cs new file mode 100644 index 0000000..9f4727d --- /dev/null +++ b/src/DotNetOpenAuth.Test/OpenId/Provider/PerformanceTests.cs @@ -0,0 +1,157 @@ +//----------------------------------------------------------------------- +// <copyright file="PerformanceTests.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.Test.OpenId.Provider { + using System; + using System.Collections.Generic; + using System.Diagnostics; + using System.IO; + using System.Linq; + using System.Net; + using System.Text; + using DotNetOpenAuth.Messaging; + using DotNetOpenAuth.Messaging.Reflection; + using DotNetOpenAuth.OpenId; + using DotNetOpenAuth.OpenId.ChannelElements; + using DotNetOpenAuth.OpenId.Messages; + using DotNetOpenAuth.OpenId.Provider; + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class PerformanceTests : OpenIdTestBase { + private const string SharedAssociationHandle = "handle"; + private static readonly TimeSpan TestRunTime = TimeSpan.FromSeconds(3); + private OpenIdProvider provider; + + [TestInitialize] + public override void SetUp() { + base.SetUp(); + SuspendLogging(); + this.provider = CreateProvider(); + } + + [TestCleanup] + public override void Cleanup() { + ResumeLogging(); + base.Cleanup(); + } + + [TestMethod] + public void AssociateDH() { + var associateRequest = this.CreateAssociateRequest(OPUri); + Stopwatch timer = new Stopwatch(); + timer.Start(); + int iterations; + 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)); + } + timer.Stop(); + double executionsPerSecond = GetExecutionsPerSecond(iterations, timer); + TestContext.WriteLine("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] + public void AssociateClearText() { + var associateRequest = this.CreateAssociateRequest(OPUriSsl); // SSL will cause a plaintext association + Stopwatch timer = new Stopwatch(); + timer.Start(); + int iterations; + 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)); + } + timer.Stop(); + double executionsPerSecond = GetExecutionsPerSecond(iterations, timer); + TestContext.WriteLine("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] + 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); + Assert.IsTrue(executionsPerSecond > 500, "Too slow ({0} > 500 executions per second required.)", executionsPerSecond); + } + + [TestMethod] + 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); + Assert.IsTrue(executionsPerSecond > 400, "Too slow ({0} > 400 executions per second required.)", executionsPerSecond); + } + + private static double GetExecutionsPerSecond(int iterations, Stopwatch timer) { + return (double)iterations / (timer.ElapsedMilliseconds / 1000); + } + + private double ParameterizedCheckIdTest(Protocol protocol, string assocType) { + Association assoc = HmacShaAssociation.Create( + protocol, + assocType, + AssociationRelyingPartyType.Smart, + this.provider.SecuritySettings); + this.provider.AssociationStore.StoreAssociation(AssociationRelyingPartyType.Smart, assoc); + var checkidRequest = this.CreateCheckIdRequest(true); + Stopwatch timer = new Stopwatch(); + timer.Start(); + int iterations; + for (iterations = 0; timer.ElapsedMilliseconds < TestRunTime.TotalMilliseconds; iterations++) { + var request = (IAuthenticationRequest)this.provider.GetRequest(checkidRequest); + request.IsAuthenticated = true; + var response = this.provider.PrepareResponse(request); + Assert.IsInstanceOfType(response.OriginalMessage, typeof(PositiveAssertionResponse)); + } + 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); + return executionsPerSecond; + } + + private HttpRequestInfo CreateAssociateRequest(Uri opEndpoint) { + var rp = CreateRelyingParty(true); + AssociateRequest associateMessage = AssociateRequest.Create(rp.SecuritySettings, new ProviderEndpointDescription(opEndpoint, Protocol.Default.Version)); + Channel rpChannel = rp.Channel; + MemoryStream ms = new MemoryStream(); + StreamWriter mswriter = new StreamWriter(ms); + mswriter.Write(MessagingUtilities.CreateQueryString(rpChannel.MessageDescriptions.GetAccessor(associateMessage))); + mswriter.Flush(); + ms.Position = 0; + var headers = new WebHeaderCollection(); + headers.Add(HttpRequestHeader.ContentType, Channel.HttpFormUrlEncoded); + var httpRequest = new HttpRequestInfo("POST", opEndpoint, opEndpoint.PathAndQuery, headers, ms); + return httpRequest; + } + + private HttpRequestInfo CreateCheckIdRequest(bool sharedAssociation) { + var rp = CreateRelyingParty(true); + CheckIdRequest checkidMessage = new CheckIdRequest( + Protocol.Default.Version, + OPUri, + DotNetOpenAuth.OpenId.RelyingParty.AuthenticationRequestMode.Setup); + if (sharedAssociation) { + checkidMessage.AssociationHandle = SharedAssociationHandle; + } + checkidMessage.ClaimedIdentifier = OPLocalIdentifiers[0]; + checkidMessage.LocalIdentifier = OPLocalIdentifiers[0]; + checkidMessage.Realm = RPRealmUri; + checkidMessage.ReturnTo = RPUri; + Channel rpChannel = rp.Channel; + UriBuilder receiver = new UriBuilder(OPUri); + receiver.Query = MessagingUtilities.CreateQueryString(rpChannel.MessageDescriptions.GetAccessor(checkidMessage)); + var headers = new WebHeaderCollection(); + var httpRequest = new HttpRequestInfo("GET", receiver.Uri, receiver.Uri.PathAndQuery, headers, null); + return httpRequest; + } + } +} diff --git a/src/DotNetOpenAuth.Test/OpenId/ProviderEndpointDescriptionTests.cs b/src/DotNetOpenAuth.Test/OpenId/ProviderEndpointDescriptionTests.cs new file mode 100644 index 0000000..005b8a0 --- /dev/null +++ b/src/DotNetOpenAuth.Test/OpenId/ProviderEndpointDescriptionTests.cs @@ -0,0 +1,62 @@ +//----------------------------------------------------------------------- +// <copyright file="ProviderEndpointDescriptionTests.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.Test.OpenId { + using System; + using DotNetOpenAuth.OpenId; + using DotNetOpenAuth.OpenId.Extensions.SimpleRegistration; + using DotNetOpenAuth.OpenId.Messages; + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + 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(ArgumentNullException))] + public void IsExtensionSupportedNullString() { + this.se.IsExtensionSupported((string)null); + } + + [TestMethod, ExpectedException(typeof(ArgumentException))] + public void IsExtensionSupportedEmptyString() { + this.se.IsExtensionSupported(string.Empty); + } + + [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")); + } + } +} diff --git a/src/DotNetOpenAuth.Test/OpenId/RelyingParty/AuthenticationRequestTests.cs b/src/DotNetOpenAuth.Test/OpenId/RelyingParty/AuthenticationRequestTests.cs index 2c7e74c..10497b2 100644 --- a/src/DotNetOpenAuth.Test/OpenId/RelyingParty/AuthenticationRequestTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/RelyingParty/AuthenticationRequestTests.cs @@ -104,6 +104,22 @@ namespace DotNetOpenAuth.Test.OpenId.RelyingParty { } /// <summary> + /// Verifies that delegating authentication requests are filtered out when configured to do so. + /// </summary> + [TestMethod] + public void CreateFiltersDelegatingIdentifiers() { + Identifier id = GetMockIdentifier(ProtocolVersion.V20, false, true); + var rp = CreateRelyingParty(); + + // First verify that delegating identifiers work + Assert.IsTrue(AuthenticationRequest.Create(id, rp, realm, returnTo, false).Any(), "The delegating identifier should have not generated any results."); + + // Now disable them and try again. + rp.SecuritySettings.RejectDelegatingIdentifiers = true; + Assert.IsFalse(AuthenticationRequest.Create(id, rp, realm, returnTo, false).Any(), "The delegating identifier should have not generated any results."); + } + + /// <summary> /// Verifies the Provider property returns non-null. /// </summary> [TestMethod] @@ -144,6 +160,18 @@ namespace DotNetOpenAuth.Test.OpenId.RelyingParty { } /// <summary> + /// Verifies identity-less checkid_* request behavior. + /// </summary> + [TestMethod] + public void NonIdentityRequest() { + IAuthenticationRequest_Accessor 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."); + } + + /// <summary> /// Verifies that authentication requests are generated first for OPs that respond /// to authentication requests. /// </summary> diff --git a/src/DotNetOpenAuth.Test/OpenId/RelyingParty/PositiveAnonymousResponseTests.cs b/src/DotNetOpenAuth.Test/OpenId/RelyingParty/PositiveAnonymousResponseTests.cs new file mode 100644 index 0000000..1418513 --- /dev/null +++ b/src/DotNetOpenAuth.Test/OpenId/RelyingParty/PositiveAnonymousResponseTests.cs @@ -0,0 +1,56 @@ +//----------------------------------------------------------------------- +// <copyright file="PositiveAnonymousResponseTests.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.Test.OpenId.RelyingParty { + using System; + using DotNetOpenAuth.OpenId; + using DotNetOpenAuth.OpenId.Extensions.SimpleRegistration; + using DotNetOpenAuth.OpenId.Messages; + using DotNetOpenAuth.OpenId.RelyingParty; + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + 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] + public override void SetUp() { + base.SetUp(); + } + + /// <summary> + /// Verifies that the Status property returns the correct value. + /// </summary> + [TestMethod] + public void CtorAndProperties() { + var responseMessage = new IndirectSignedResponse(Protocol.V20.Version, this.returnTo); + var ext = new ClaimsResponse(); + responseMessage.Extensions.Add(ext); + var response = new PositiveAnonymousResponse(responseMessage); + Assert.AreEqual(AuthenticationStatus.ExtensionsOnly, response.Status); + Assert.AreSame(responseMessage, response.Response); + Assert.IsNull(response.ClaimedIdentifier); + Assert.IsNull(response.FriendlyIdentifierForDisplay); + Assert.IsNull(response.Exception); + Assert.IsNull(response.Provider); + Assert.AreSame(ext, response.GetUntrustedExtension<ClaimsResponse>()); + } + + /// <summary> + /// Verifies the Provider property. + /// </summary> + [TestMethod] + public void ProviderTest() { + var responseMessage = new IndirectSignedResponse(Protocol.V20.Version, this.returnTo); + responseMessage.ProviderEndpoint = OPUri; + var response = new PositiveAnonymousResponse(responseMessage); + Assert.IsNotNull(response.Provider); + Assert.AreEqual(OPUri, response.Provider.Uri); + Assert.AreEqual(responseMessage.Version, response.Provider.Version); + } + } +} diff --git a/src/DotNetOpenAuth.Test/OpenId/RelyingParty/RelyingPartySecuritySettingsTests.cs b/src/DotNetOpenAuth.Test/OpenId/RelyingParty/RelyingPartySecuritySettingsTests.cs index cb5fbb5..851939e 100644 --- a/src/DotNetOpenAuth.Test/OpenId/RelyingParty/RelyingPartySecuritySettingsTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/RelyingParty/RelyingPartySecuritySettingsTests.cs @@ -23,13 +23,18 @@ namespace DotNetOpenAuth.Test.OpenId.RelyingParty { this.settings = new RelyingPartySecuritySettings(); } + [TestMethod] + public void Defaults() { + Assert.IsFalse(this.settings.RejectUnsolicitedAssertions); + Assert.IsFalse(this.settings.RequireSsl, "Default should be to not require SSL."); + } + /// <summary> /// Verifies that the <see cref="RelyingPartySecuritySettings.RequireSsl"/> property /// getter/setter are implemented correctly. /// </summary> [TestMethod] public void RequireSsl() { - Assert.IsFalse(this.settings.RequireSsl, "Default should be to not require SSL."); this.settings.RequireSsl = true; Assert.IsTrue(this.settings.RequireSsl); this.settings.RequireSsl = false; @@ -37,21 +42,27 @@ namespace DotNetOpenAuth.Test.OpenId.RelyingParty { } /// <summary> - /// Verifies that changing the <see cref="RelyingPartySecuritySettings.RequireSsl"/> property - /// fires the <see cref="RelyingPartySecuritySettings.RequireSslChanged"/> event. + /// Verifies that the <see cref="RelyingPartySecuritySettings.RequireDirectedIdentity"/> + /// property getter/setter are implemented correctly. /// </summary> [TestMethod] - public void RequireSslFiresEvent() { - bool requireSslChanged = false; - this.settings.RequireSslChanged += (sender, e) => { requireSslChanged = true; }; - - // Setting the property to its current value should not fire event. - this.settings.RequireSsl = this.settings.RequireSsl; - Assert.IsFalse(requireSslChanged); + public void RequireDirectedIdentity() { + this.settings.RequireDirectedIdentity = true; + Assert.IsTrue(this.settings.RequireDirectedIdentity); + this.settings.RequireDirectedIdentity = false; + Assert.IsFalse(this.settings.RequireDirectedIdentity); + } - // Changing the property's value should fire the event. - this.settings.RequireSsl = !this.settings.RequireSsl; - Assert.IsTrue(requireSslChanged); + /// <summary> + /// Verifies that the <see cref="RelyingPartySecuritySettings.RequireAssociation"/> + /// property getter/setter are implemented correctly. + /// </summary> + [TestMethod] + public void RequireAssociation() { + this.settings.RequireAssociation = true; + Assert.IsTrue(this.settings.RequireAssociation); + this.settings.RequireAssociation = false; + Assert.IsFalse(this.settings.RequireAssociation); } } } diff --git a/src/DotNetOpenAuth.Test/OpenId/RelyingParty/ServiceEndpointTests.cs b/src/DotNetOpenAuth.Test/OpenId/RelyingParty/ServiceEndpointTests.cs index 7b71eef..bd09bc9 100644 --- a/src/DotNetOpenAuth.Test/OpenId/RelyingParty/ServiceEndpointTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/RelyingParty/ServiceEndpointTests.cs @@ -173,46 +173,6 @@ namespace DotNetOpenAuth.Test.OpenId.RelyingParty { Assert.AreEqual("=!9B72.7DD1.50A9.5CCD", se.FriendlyIdentifierForDisplay); } - [TestMethod, ExpectedException(typeof(ArgumentNullException))] - public void IsExtensionSupportedNullType() { - ServiceEndpoint se = ServiceEndpoint.CreateForClaimedIdentifier(this.claimedXri, this.userSuppliedXri, this.localId, new ProviderEndpointDescription(this.providerEndpoint, this.v20TypeUris), this.servicePriority, this.uriPriority); - se.IsExtensionSupported((Type)null); - } - - [TestMethod, ExpectedException(typeof(ArgumentNullException))] - public void IsExtensionSupportedNullString() { - ServiceEndpoint se = ServiceEndpoint.CreateForClaimedIdentifier(this.claimedXri, this.userSuppliedXri, this.localId, new ProviderEndpointDescription(this.providerEndpoint, this.v20TypeUris), this.servicePriority, this.uriPriority); - se.IsExtensionSupported((string)null); - } - - [TestMethod, ExpectedException(typeof(ArgumentException))] - public void IsExtensionSupportedEmptyString() { - ServiceEndpoint se = ServiceEndpoint.CreateForClaimedIdentifier(this.claimedXri, this.userSuppliedXri, this.localId, new ProviderEndpointDescription(this.providerEndpoint, this.v20TypeUris), this.servicePriority, this.uriPriority); - se.IsExtensionSupported(string.Empty); - } - - [TestMethod, ExpectedException(typeof(ArgumentNullException))] - public void IsExtensionSupportedNullExtension() { - ServiceEndpoint se = ServiceEndpoint.CreateForClaimedIdentifier(this.claimedXri, this.userSuppliedXri, this.localId, new ProviderEndpointDescription(this.providerEndpoint, this.v20TypeUris), this.servicePriority, this.uriPriority); - se.IsExtensionSupported((IOpenIdMessageExtension)null); - } - - [TestMethod] - public void IsExtensionSupported() { - ServiceEndpoint se = ServiceEndpoint.CreateForClaimedIdentifier(this.claimedXri, this.userSuppliedXri, this.localId, new ProviderEndpointDescription(this.providerEndpoint, this.v20TypeUris), this.servicePriority, this.uriPriority); - Assert.IsFalse(se.IsExtensionSupported<ClaimsRequest>()); - Assert.IsFalse(se.IsExtensionSupported(new ClaimsRequest())); - Assert.IsFalse(se.IsExtensionSupported("http://someextension/typeuri")); - - ProviderEndpointDescription ped = new ProviderEndpointDescription( - OPUri, - new[] { Protocol.V20.ClaimedIdentifierServiceTypeURI, "http://someextension", Constants.sreg_ns }); - se = ServiceEndpoint.CreateForClaimedIdentifier(this.claimedXri, this.userSuppliedXri, this.localId, ped, this.servicePriority, this.uriPriority); - Assert.IsTrue(se.IsExtensionSupported<ClaimsRequest>()); - Assert.IsTrue(se.IsExtensionSupported(new ClaimsRequest())); - Assert.IsTrue(se.IsExtensionSupported("http://someextension")); - } - [TestMethod] public void IsTypeUriPresent() { ServiceEndpoint se = ServiceEndpoint.CreateForClaimedIdentifier(this.claimedXri, this.userSuppliedXri, this.localId, new ProviderEndpointDescription(this.providerEndpoint, this.v20TypeUris), this.servicePriority, this.uriPriority); diff --git a/src/DotNetOpenAuth.Test/OpenId/UriIdentifierTests.cs b/src/DotNetOpenAuth.Test/OpenId/UriIdentifierTests.cs index 3b3f985..f1823e6 100644 --- a/src/DotNetOpenAuth.Test/OpenId/UriIdentifierTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/UriIdentifierTests.cs @@ -391,7 +391,7 @@ namespace DotNetOpenAuth.Test.OpenId { // the ServiceEndpoint.Equals method. Assert.AreEqual(expectSreg ? 2 : 1, se.ProviderSupportedServiceTypeUris.Count); Assert.IsTrue(se.ProviderSupportedServiceTypeUris.Contains(protocol.ClaimedIdentifierServiceTypeURI)); - Assert.AreEqual(expectSreg, se.IsExtensionSupported(new ClaimsRequest())); + Assert.AreEqual(expectSreg, se.IsExtensionSupported<ClaimsRequest>()); } private void DiscoverXrds(string page, ProtocolVersion version, Identifier expectedLocalId, string providerEndpoint) { diff --git a/src/DotNetOpenAuth.Test/TestBase.cs b/src/DotNetOpenAuth.Test/TestBase.cs index d21691b..f9db40c 100644 --- a/src/DotNetOpenAuth.Test/TestBase.cs +++ b/src/DotNetOpenAuth.Test/TestBase.cs @@ -57,5 +57,13 @@ namespace DotNetOpenAuth.Test { public virtual void Cleanup() { log4net.LogManager.Shutdown(); } + + protected internal static void SuspendLogging() { + LogManager.GetLoggerRepository().Threshold = LogManager.GetLoggerRepository().LevelMap["OFF"]; + } + + protected internal static void ResumeLogging() { + LogManager.GetLoggerRepository().Threshold = LogManager.GetLoggerRepository().LevelMap["ALL"]; + } } } |