diff options
Diffstat (limited to 'src')
17 files changed, 157 insertions, 167 deletions
diff --git a/src/DotNetOpenAuth.Test/CoordinatorBase.cs b/src/DotNetOpenAuth.Test/CoordinatorBase.cs index 4f712d0..be56de6 100644 --- a/src/DotNetOpenAuth.Test/CoordinatorBase.cs +++ b/src/DotNetOpenAuth.Test/CoordinatorBase.cs @@ -42,7 +42,7 @@ namespace DotNetOpenAuth.Test { } protected internal virtual async Task RunAsync(CancellationToken cancellationToken = default(CancellationToken)) { - IHostFactories hostFactories = new MyHostFactories(this.handlers); + IHostFactories hostFactories = new MockingHostFactories(this.handlers); await this.driver(hostFactories, cancellationToken); } @@ -104,45 +104,5 @@ namespace DotNetOpenAuth.Test { }); } } - - private class MyHostFactories : IHostFactories { - private readonly Handler[] handlers; - - public MyHostFactories(Handler[] handlers) { - this.handlers = handlers; - } - - public HttpMessageHandler CreateHttpMessageHandler() { - return new ForwardingMessageHandler(this.handlers, this); - } - - public HttpClient CreateHttpClient(HttpMessageHandler handler = null) { - return new HttpClient(handler ?? this.CreateHttpMessageHandler()); - } - } - - private class ForwardingMessageHandler : HttpMessageHandler { - private readonly Handler[] handlers; - - private readonly IHostFactories hostFactories; - - public ForwardingMessageHandler(Handler[] handlers, IHostFactories hostFactories) { - this.handlers = handlers; - this.hostFactories = hostFactories; - } - - protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { - foreach (var handler in this.handlers) { - if (handler.Uri.IsBaseOf(request.RequestUri) && handler.Uri.AbsolutePath == request.RequestUri.AbsolutePath) { - var response = await handler.MessageHandler(this.hostFactories, request, cancellationToken); - if (response != null) { - return response; - } - } - } - - return new HttpResponseMessage(HttpStatusCode.NotFound); - } - } } } diff --git a/src/DotNetOpenAuth.Test/DotNetOpenAuth.Test.csproj b/src/DotNetOpenAuth.Test/DotNetOpenAuth.Test.csproj index e40d663..d777f50 100644 --- a/src/DotNetOpenAuth.Test/DotNetOpenAuth.Test.csproj +++ b/src/DotNetOpenAuth.Test/DotNetOpenAuth.Test.csproj @@ -125,6 +125,7 @@ <Compile Include="Messaging\Reflection\MessagePartTests.cs" /> <Compile Include="Messaging\Reflection\ValueMappingTests.cs" /> <Compile Include="Messaging\StandardMessageFactoryTests.cs" /> + <Compile Include="MockingHostFactories.cs" /> <Compile Include="Mocks\AssociateUnencryptedRequestNoSslCheck.cs" /> <Compile Include="Mocks\IBaseMessageExplicitMembers.cs" /> <Compile Include="Mocks\InMemoryTokenManager.cs" /> diff --git a/src/DotNetOpenAuth.Test/Mocks/MockHttpRequest.cs b/src/DotNetOpenAuth.Test/Mocks/MockHttpRequest.cs index 469a412..1979cf4 100644 --- a/src/DotNetOpenAuth.Test/Mocks/MockHttpRequest.cs +++ b/src/DotNetOpenAuth.Test/Mocks/MockHttpRequest.cs @@ -84,7 +84,7 @@ namespace DotNetOpenAuth.Test.Mocks { internal static CoordinatorBase.Handler RegisterMockXrdsResponse(string embeddedResourcePath, out Identifier id) { id = new Uri(new Uri("http://localhost/"), embeddedResourcePath); return CoordinatorBase.Handle(new Uri(id)) - .By(OpenIdTestBase.LoadEmbeddedFile(embeddedResourcePath), "application/xrds+xml"); + .By(OpenIdTestBase.LoadEmbeddedFile(embeddedResourcePath), "application/xrds+xml"); } internal static CoordinatorBase.Handler RegisterMockRPDiscovery(bool ssl) { @@ -113,5 +113,17 @@ namespace DotNetOpenAuth.Test.Mocks { response.Headers.Location = redirectLocation; return new CoordinatorBase.Handler(origin).By(req => response); } + + internal static CoordinatorBase.Handler[] RegisterMockXrdsResponses( + IEnumerable<KeyValuePair<string, string>> urlXrdsPairs) { + Requires.NotNull(urlXrdsPairs, "urlXrdsPairs"); + + var results = new List<CoordinatorBase.Handler>(); + foreach (var keyValuePair in urlXrdsPairs) { + results.Add(CoordinatorBase.Handle(new Uri(keyValuePair.Key)).By(keyValuePair.Value, ContentTypes.Xrds)); + } + + return results.ToArray(); + } } } diff --git a/src/DotNetOpenAuth.Test/OpenId/AssociationHandshakeTests.cs b/src/DotNetOpenAuth.Test/OpenId/AssociationHandshakeTests.cs index e293011..2262878 100644 --- a/src/DotNetOpenAuth.Test/OpenId/AssociationHandshakeTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/AssociationHandshakeTests.cs @@ -245,7 +245,7 @@ namespace DotNetOpenAuth.Test.OpenId { public async Task RPOnlyRenegotiatesOnce() { Protocol protocol = Protocol.V20; int opStep = 0; - var coordinator = new CoordinatorBase( + await CoordinatorBase.RunAsync( CoordinatorBase.RelyingPartyDriver(async (rp, ct) => { var association = await rp.AssociationManager.GetOrCreateAssociationAsync(new ProviderEndpointDescription(OPUri, protocol.Version), ct); Assert.IsNull(association, "The RP should quietly give up when the OP misbehaves."); @@ -271,9 +271,11 @@ namespace DotNetOpenAuth.Test.OpenId { renegotiateResponse.AssociationType = protocol.Args.SignatureAlgorithm.HMAC_SHA256; renegotiateResponse.SessionType = protocol.Args.SessionType.DH_SHA256; return await op.Channel.PrepareResponseAsync(renegotiateResponse, ct); + + default: + throw Assumes.NotReachable(); } })); - await coordinator.RunAsync(); } /// <summary> @@ -301,9 +303,9 @@ namespace DotNetOpenAuth.Test.OpenId { /// </summary> [Test] public async Task AssociateQuietlyFailsAfterHttpError() { - this.MockResponder.RegisterMockNotFound(OPUri); + // Without wiring up a mock HTTP handler, the RP will get a 404 Not Found error. var rp = this.CreateRelyingParty(); - var association = await rp.AssociationManager.GetOrCreateAssociationAsync(new ProviderEndpointDescription(OPUri, Protocol.V20.Version)); + var association = await rp.AssociationManager.GetOrCreateAssociationAsync(new ProviderEndpointDescription(OPUri, Protocol.V20.Version), CancellationToken.None); Assert.IsNull(association); } diff --git a/src/DotNetOpenAuth.Test/OpenId/ChannelElements/ExtensionsBindingElementTests.cs b/src/DotNetOpenAuth.Test/OpenId/ChannelElements/ExtensionsBindingElementTests.cs index e60ac3c..ca9b0a7 100644 --- a/src/DotNetOpenAuth.Test/OpenId/ChannelElements/ExtensionsBindingElementTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/ChannelElements/ExtensionsBindingElementTests.cs @@ -43,10 +43,10 @@ namespace DotNetOpenAuth.Test.OpenId.ChannelElements { } [Test] - public void RoundTripFullStackTest() { + public async Task RoundTripFullStackTest() { IOpenIdMessageExtension request = new MockOpenIdExtension("requestPart", "requestData"); IOpenIdMessageExtension response = new MockOpenIdExtension("responsePart", "responseData"); - ExtensionTestUtilities.Roundtrip( + await ExtensionTestUtilities.RoundtripAsync( Protocol.Default, new IOpenIdMessageExtension[] { request }, new IOpenIdMessageExtension[] { response }); @@ -179,11 +179,11 @@ namespace DotNetOpenAuth.Test.OpenId.ChannelElements { /// "A namespace MUST NOT be assigned more than one alias in the same message". /// </remarks> [Test] - public void TwoExtensionsSameTypeUri() { + public async Task TwoExtensionsSameTypeUri() { IOpenIdMessageExtension request1 = new MockOpenIdExtension("requestPart1", "requestData1"); IOpenIdMessageExtension request2 = new MockOpenIdExtension("requestPart2", "requestData2"); try { - ExtensionTestUtilities.Roundtrip( + await ExtensionTestUtilities.RoundtripAsync( Protocol.Default, new IOpenIdMessageExtension[] { request1, request2 }, new IOpenIdMessageExtension[0]); diff --git a/src/DotNetOpenAuth.Test/OpenId/ChannelElements/OpenIdChannelTests.cs b/src/DotNetOpenAuth.Test/OpenId/ChannelElements/OpenIdChannelTests.cs index f50137d..c9cd52c 100644 --- a/src/DotNetOpenAuth.Test/OpenId/ChannelElements/OpenIdChannelTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/ChannelElements/OpenIdChannelTests.cs @@ -10,7 +10,10 @@ namespace DotNetOpenAuth.Test.OpenId.ChannelElements { using System.IO; using System.Linq; using System.Net; + using System.Net.Http; using System.Text; + using System.Threading; + using System.Threading.Tasks; using DotNetOpenAuth.Messaging; using DotNetOpenAuth.Messaging.Bindings; using DotNetOpenAuth.Messaging.Reflection; @@ -21,16 +24,13 @@ namespace DotNetOpenAuth.Test.OpenId.ChannelElements { using NUnit.Framework; [TestFixture] - public class OpenIdChannelTests : TestBase { + public class OpenIdChannelTests : OpenIdTestBase { private static readonly TimeSpan maximumMessageAge = TimeSpan.FromHours(3); // good for tests, too long for production private OpenIdChannel channel; - private Mocks.TestWebRequestHandler webHandler; [SetUp] public void Setup() { - this.webHandler = new Mocks.TestWebRequestHandler(); - this.channel = new OpenIdRelyingPartyChannel(new MemoryCryptoKeyStore(), new NonceMemoryStore(maximumMessageAge), new RelyingPartySecuritySettings()); - this.channel.WebRequestHandler = this.webHandler; + this.channel = new OpenIdRelyingPartyChannel(new MemoryCryptoKeyStore(), new NonceMemoryStore(maximumMessageAge), new RelyingPartySecuritySettings(), this.HostFactories); } [Test] @@ -52,14 +52,14 @@ namespace DotNetOpenAuth.Test.OpenId.ChannelElements { /// Verifies that the channel sends direct message requests as HTTP POST requests. /// </summary> [Test] - public void DirectRequestsUsePost() { + public async Task DirectRequestsUsePost() { IDirectedProtocolMessage requestMessage = new Mocks.TestDirectedMessage(MessageTransport.Direct) { Recipient = new Uri("http://host"), Name = "Andrew", }; - HttpWebRequest httpRequest = this.channel.CreateHttpRequestTestHook(requestMessage); - Assert.AreEqual("POST", httpRequest.Method); - StringAssert.Contains("Name=Andrew", this.webHandler.RequestEntityAsString); + var httpRequest = this.channel.CreateHttpRequestTestHook(requestMessage); + Assert.AreEqual(HttpMethod.Post, httpRequest.Method); + StringAssert.Contains("Name=Andrew", await httpRequest.Content.ReadAsStringAsync()); } /// <summary> @@ -72,16 +72,15 @@ namespace DotNetOpenAuth.Test.OpenId.ChannelElements { /// <see cref="OpenIdChannel.SendDirectMessageResponse"/> method. /// </remarks> [Test] - public void DirectResponsesSentUsingKeyValueForm() { + public async Task DirectResponsesSentUsingKeyValueForm() { IProtocolMessage message = MessagingTestBase.GetStandardTestMessage(MessagingTestBase.FieldFill.AllRequired); MessageDictionary messageFields = this.MessageDescriptions.GetAccessor(message); byte[] expectedBytes = KeyValueFormEncoding.GetBytes(messageFields); string expectedContentType = OpenIdChannel.KeyValueFormContentType; - OutgoingWebResponse directResponse = this.channel.PrepareDirectResponseTestHook(message); - Assert.AreEqual(expectedContentType, directResponse.Headers[HttpResponseHeader.ContentType]); - byte[] actualBytes = new byte[directResponse.ResponseStream.Length]; - directResponse.ResponseStream.Read(actualBytes, 0, actualBytes.Length); + var directResponse = this.channel.PrepareDirectResponseTestHook(message); + Assert.AreEqual(expectedContentType, directResponse.Content.Headers.ContentType.MediaType); + byte[] actualBytes = await directResponse.Content.ReadAsByteArrayAsync(); Assert.IsTrue(MessagingUtilities.AreEquivalent(expectedBytes, actualBytes)); } @@ -89,15 +88,15 @@ namespace DotNetOpenAuth.Test.OpenId.ChannelElements { /// Verifies that direct message responses are read in using the Key Value Form decoder. /// </summary> [Test] - public void DirectResponsesReceivedAsKeyValueForm() { + public async Task DirectResponsesReceivedAsKeyValueForm() { var fields = new Dictionary<string, string> { { "var1", "value1" }, { "var2", "value2" }, }; - var response = new CachedDirectWebResponse { - CachedResponseStream = new MemoryStream(KeyValueFormEncoding.GetBytes(fields)), + var response = new HttpResponseMessage { + Content = new StreamContent(new MemoryStream(KeyValueFormEncoding.GetBytes(fields))), }; - Assert.IsTrue(MessagingUtilities.AreEquivalent(fields, this.channel.ReadFromResponseCoreTestHook(response))); + Assert.IsTrue(MessagingUtilities.AreEquivalent(fields, await this.channel.ReadFromResponseCoreAsyncTestHook(response, CancellationToken.None))); } /// <summary> @@ -106,14 +105,14 @@ namespace DotNetOpenAuth.Test.OpenId.ChannelElements { [Test] public void SendDirectMessageResponseHonorsHttpStatusCodes() { IProtocolMessage message = MessagingTestBase.GetStandardTestMessage(MessagingTestBase.FieldFill.AllRequired); - OutgoingWebResponse directResponse = this.channel.PrepareDirectResponseTestHook(message); - Assert.AreEqual(HttpStatusCode.OK, directResponse.Status); + var directResponse = this.channel.PrepareDirectResponseTestHook(message); + Assert.AreEqual(HttpStatusCode.OK, directResponse.StatusCode); var httpMessage = new TestDirectResponseMessageWithHttpStatus(); MessagingTestBase.GetStandardTestMessage(MessagingTestBase.FieldFill.AllRequired, httpMessage); httpMessage.HttpStatusCode = HttpStatusCode.NotAcceptable; directResponse = this.channel.PrepareDirectResponseTestHook(httpMessage); - Assert.AreEqual(HttpStatusCode.NotAcceptable, directResponse.Status); + Assert.AreEqual(HttpStatusCode.NotAcceptable, directResponse.StatusCode); } } } diff --git a/src/DotNetOpenAuth.Test/OpenId/ChannelElements/SigningBindingElementTests.cs b/src/DotNetOpenAuth.Test/OpenId/ChannelElements/SigningBindingElementTests.cs index f7722e3..42b447e 100644 --- a/src/DotNetOpenAuth.Test/OpenId/ChannelElements/SigningBindingElementTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/ChannelElements/SigningBindingElementTests.cs @@ -8,6 +8,9 @@ namespace DotNetOpenAuth.Test.OpenId.ChannelElements { using System; using System.Collections.Generic; using System.Linq; + using System.Threading; + using System.Threading.Tasks; + using DotNetOpenAuth.Messaging; using DotNetOpenAuth.Messaging.Bindings; using DotNetOpenAuth.OpenId; @@ -24,7 +27,7 @@ namespace DotNetOpenAuth.Test.OpenId.ChannelElements { /// Verifies that the signatures generated match Known Good signatures. /// </summary> [Test] - public void SignaturesMatchKnownGood() { + public async Task SignaturesMatchKnownGood() { Protocol protocol = Protocol.V20; var settings = new ProviderSecuritySettings(); var cryptoStore = new MemoryCryptoKeyStore(); @@ -41,7 +44,7 @@ namespace DotNetOpenAuth.Test.OpenId.ChannelElements { message.ProviderEndpoint = new Uri("http://provider"); signedMessage.UtcCreationDate = DateTime.Parse("1/1/2009"); signedMessage.AssociationHandle = handle; - Assert.IsNotNull(signer.ProcessOutgoingMessage(message)); + Assert.IsNotNull(await signer.ProcessOutgoingMessageAsync(message, CancellationToken.None)); Assert.AreEqual("o9+uN7qTaUS9v0otbHTuNAtbkpBm14+es9QnNo6IHD4=", signedMessage.Signature); } @@ -49,7 +52,7 @@ namespace DotNetOpenAuth.Test.OpenId.ChannelElements { /// Verifies that all parameters in ExtraData in signed responses are signed. /// </summary> [Test] - public void SignedResponsesIncludeExtraDataInSignature() { + public async Task SignedResponsesIncludeExtraDataInSignature() { Protocol protocol = Protocol.Default; SigningBindingElement sbe = new ProviderSigningBindingElement(new ProviderAssociationHandleEncoder(new MemoryCryptoKeyStore()), new ProviderSecuritySettings()); sbe.Channel = new TestChannel(this.MessageDescriptions); @@ -60,7 +63,7 @@ namespace DotNetOpenAuth.Test.OpenId.ChannelElements { response.ExtraData["someunsigned"] = "value"; response.ExtraData["openid.somesigned"] = "value"; - Assert.IsNotNull(sbe.ProcessOutgoingMessage(response)); + Assert.IsNotNull(await sbe.ProcessOutgoingMessageAsync(response, CancellationToken.None)); ITamperResistantOpenIdMessage signedResponse = (ITamperResistantOpenIdMessage)response; // Make sure that the extra parameters are signed. @@ -76,14 +79,14 @@ namespace DotNetOpenAuth.Test.OpenId.ChannelElements { /// Regression test for bug #45 (https://github.com/AArnott/dotnetopenid/issues/45) /// </summary> [Test, ExpectedException(typeof(ProtocolException))] - public void MissingSignedParameter() { + public async Task MissingSignedParameter() { var cryptoStore = new MemoryCryptoKeyStore(); byte[] associationSecret = Convert.FromBase64String("rsSwv1zPWfjPRQU80hciu8FPDC+GONAMJQ/AvSo1a2M="); string handle = "{634477555066085461}{TTYcIg==}{32}"; cryptoStore.StoreKey(ProviderAssociationKeyStorage.PrivateAssociationBucket, handle, new CryptoKey(associationSecret, DateTime.UtcNow.AddDays(1))); var signer = new ProviderSigningBindingElement(new ProviderAssociationKeyStorage(cryptoStore), new ProviderSecuritySettings()); - var testChannel = new TestChannel(new OpenIdProviderMessageFactory()); + var testChannel = new TestChannel(new OpenIdProviderMessageFactory(), new IChannelBindingElement[0], this.HostFactories); signer.Channel = testChannel; var buggyRPMessage = new Dictionary<string, string>() { @@ -101,7 +104,7 @@ namespace DotNetOpenAuth.Test.OpenId.ChannelElements { }; var message = (CheckAuthenticationRequest)testChannel.Receive(buggyRPMessage, new MessageReceivingEndpoint(OPUri, HttpDeliveryMethods.PostRequest)); var originalResponse = new IndirectSignedResponse(message, signer.Channel); - signer.ProcessIncomingMessage(originalResponse); + await signer.ProcessIncomingMessageAsync(originalResponse, CancellationToken.None); } } } diff --git a/src/DotNetOpenAuth.Test/OpenId/DiscoveryServices/XriDiscoveryProxyServiceTests.cs b/src/DotNetOpenAuth.Test/OpenId/DiscoveryServices/XriDiscoveryProxyServiceTests.cs index fe767ea..03f9349 100644 --- a/src/DotNetOpenAuth.Test/OpenId/DiscoveryServices/XriDiscoveryProxyServiceTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/DiscoveryServices/XriDiscoveryProxyServiceTests.cs @@ -9,14 +9,16 @@ namespace DotNetOpenAuth.Test.OpenId.DiscoveryServices { using System.Collections.Generic; using System.Linq; using System.Text; + using System.Threading.Tasks; using DotNetOpenAuth.OpenId; using DotNetOpenAuth.OpenId.RelyingParty; + using DotNetOpenAuth.Test.Mocks; using NUnit.Framework; [TestFixture] public class XriDiscoveryProxyServiceTests : OpenIdTestBase { [Test] - public void Discover() { + public async Task Discover() { string xrds = @"<?xml version='1.0' encoding='UTF-8'?> <XRD version='2.0' xmlns='xri://$xrd*($v*2.0)'> <Query>*Arnott</Query> @@ -48,14 +50,14 @@ namespace DotNetOpenAuth.Test.OpenId.DiscoveryServices { <URI append='none' priority='10'>http://1id.com/sso</URI> </Service> </XRD>"; - Dictionary<string, string> mocks = new Dictionary<string, string> { + var 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); + this.HostFactories.Handlers.AddRange(MockHttpRequest.RegisterMockXrdsResponses(mocks)); string expectedCanonicalId = "=!9B72.7DD1.50A9.5CCD"; - IdentifierDiscoveryResult se = this.VerifyCanonicalId("=Arnott", expectedCanonicalId); + IdentifierDiscoveryResult se = await this.VerifyCanonicalIdAsync("=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); @@ -63,7 +65,7 @@ namespace DotNetOpenAuth.Test.OpenId.DiscoveryServices { } [Test] - public void DiscoverCommunityInameCanonicalIDs() { + public async Task DiscoverCommunityInameCanonicalIDs() { string llliResponse = @"<?xml version='1.0' encoding='UTF-8'?> <XRD version='2.0' xmlns='xri://$xrd*($v*2.0)'> <Query>*llli</Query> @@ -278,23 +280,25 @@ uEyb50RJ7DWmXctSC0b3eymZ2lSXxAWNOsNy </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"); + this.HostFactories.Handlers.AddRange( + MockHttpRequest.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 }, + })); + await this.VerifyCanonicalIdAsync("@llli", "@!72CD.A072.157E.A9C6"); + await this.VerifyCanonicalIdAsync("@llli*area", "@!72CD.A072.157E.A9C6!0000.0000.3B9A.CA0C"); + await this.VerifyCanonicalIdAsync("@llli*area*canada.unattached", "@!72CD.A072.157E.A9C6!0000.0000.3B9A.CA0C!0000.0000.3B9A.CA41"); + await this.VerifyCanonicalIdAsync("@llli*area*canada.unattached*ada", "@!72CD.A072.157E.A9C6!0000.0000.3B9A.CA0C!0000.0000.3B9A.CA41!0000.0000.3B9A.CA01"); + await this.VerifyCanonicalIdAsync("=Web", "=!91F2.8153.F600.AE24"); } [Test] - public void DiscoveryCommunityInameDelegateWithoutCanonicalID() { - this.MockResponder.RegisterMockXrdsResponses(new Dictionary<string, string> { + public async Task DiscoveryCommunityInameDelegateWithoutCanonicalID() { + this.HostFactories.Handlers.AddRange( + MockHttpRequest.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> @@ -372,15 +376,15 @@ uEyb50RJ7DWmXctSC0b3eymZ2lSXxAWNOsNy </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); + await this.VerifyCanonicalIdAsync("=Web*andrew.arnott", null); + await this.VerifyCanonicalIdAsync("@id*andrewarnott", null); } - private IdentifierDiscoveryResult VerifyCanonicalId(Identifier iname, string expectedClaimedIdentifier) { - var se = this.Discover(iname).FirstOrDefault(); + private async Task<IdentifierDiscoveryResult> VerifyCanonicalIdAsync(Identifier iname, string expectedClaimedIdentifier) { + var se = (await this.DiscoverAsync(iname)).FirstOrDefault(); if (expectedClaimedIdentifier != null) { Assert.IsNotNull(se); Assert.AreEqual(expectedClaimedIdentifier, se.ClaimedIdentifier.ToString(), "i-name {0} discovery resulted in unexpected CanonicalId", iname); diff --git a/src/DotNetOpenAuth.Test/OpenId/Extensions/AttributeExchange/AttributeExchangeRoundtripTests.cs b/src/DotNetOpenAuth.Test/OpenId/Extensions/AttributeExchange/AttributeExchangeRoundtripTests.cs index ab0a10b..6f46daa 100644 --- a/src/DotNetOpenAuth.Test/OpenId/Extensions/AttributeExchange/AttributeExchangeRoundtripTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/Extensions/AttributeExchange/AttributeExchangeRoundtripTests.cs @@ -5,6 +5,8 @@ //----------------------------------------------------------------------- namespace DotNetOpenAuth.Test.OpenId.Extensions { + using System.Threading.Tasks; + using DotNetOpenAuth.OpenId; using DotNetOpenAuth.OpenId.Extensions.AttributeExchange; using NUnit.Framework; @@ -17,7 +19,7 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions { private int incrementingAttributeValue = 1; [Test] - public void Fetch() { + public async Task Fetch() { var request = new FetchRequest(); request.Attributes.Add(new AttributeRequest(NicknameTypeUri)); request.Attributes.Add(new AttributeRequest(EmailTypeUri, false, int.MaxValue)); @@ -26,11 +28,11 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions { response.Attributes.Add(new AttributeValues(NicknameTypeUri, "Andrew")); response.Attributes.Add(new AttributeValues(EmailTypeUri, "a@a.com", "b@b.com")); - ExtensionTestUtilities.Roundtrip(Protocol.Default, new[] { request }, new[] { response }); + await ExtensionTestUtilities.RoundtripAsync(Protocol.Default, new[] { request }, new[] { response }); } [Test] - public void Store() { + public async Task Store() { var request = new StoreRequest(); var newAttribute = new AttributeValues( IncrementingAttribute, @@ -41,13 +43,13 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions { var successResponse = new StoreResponse(); successResponse.Succeeded = true; - ExtensionTestUtilities.Roundtrip(Protocol.Default, new[] { request }, new[] { successResponse }); + await ExtensionTestUtilities.RoundtripAsync(Protocol.Default, new[] { request }, new[] { successResponse }); var failureResponse = new StoreResponse(); failureResponse.Succeeded = false; failureResponse.FailureReason = "Some error"; - ExtensionTestUtilities.Roundtrip(Protocol.Default, new[] { request }, new[] { failureResponse }); + await ExtensionTestUtilities.RoundtripAsync(Protocol.Default, new[] { request }, new[] { failureResponse }); } } } diff --git a/src/DotNetOpenAuth.Test/OpenId/Extensions/ExtensionTestUtilities.cs b/src/DotNetOpenAuth.Test/OpenId/Extensions/ExtensionTestUtilities.cs index 8d0e6ff..f2928f3 100644 --- a/src/DotNetOpenAuth.Test/OpenId/Extensions/ExtensionTestUtilities.cs +++ b/src/DotNetOpenAuth.Test/OpenId/Extensions/ExtensionTestUtilities.cs @@ -8,6 +8,9 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions { using System; using System.Collections.Generic; using System.Linq; + using System.Net.Http; + using System.Threading.Tasks; + using DotNetOpenAuth.Messaging; using DotNetOpenAuth.Messaging.Bindings; using DotNetOpenAuth.OpenId; @@ -30,7 +33,7 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions { /// This method relies on the extension objects' Equals methods to verify /// accurate transport. The Equals methods should be verified by separate tests. /// </remarks> - internal static void Roundtrip( + internal static async Task RoundtripAsync( Protocol protocol, IEnumerable<IOpenIdMessageExtension> requests, IEnumerable<IOpenIdMessageExtension> responses) { @@ -38,8 +41,8 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions { var cryptoKeyStore = new MemoryCryptoKeyStore(); var associationStore = new ProviderAssociationHandleEncoder(cryptoKeyStore); Association association = HmacShaAssociationProvider.Create(protocol, protocol.Args.SignatureAlgorithm.Best, AssociationRelyingPartyType.Smart, associationStore, securitySettings); - var coordinator = new OpenIdCoordinator( - rp => { + await CoordinatorBase.RunAsync( + CoordinatorBase.RelyingPartyDriver(async (rp, ct) => { RegisterExtension(rp.Channel, Mocks.MockOpenIdExtension.Factory); var requestBase = new CheckIdRequest(protocol.Version, OpenIdTestBase.OPUri, AuthenticationRequestMode.Immediate); OpenIdTestBase.StoreAssociation(rp, OpenIdTestBase.OPUri, association); @@ -52,17 +55,24 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions { requestBase.Extensions.Add(extension); } - rp.Channel.Respond(requestBase); - var response = rp.Channel.ReadFromRequest<PositiveAssertionResponse>(); + var redirectingRequest = await rp.Channel.PrepareResponseAsync(requestBase); + Uri redirectingResponseUri; + using (var httpClient = rp.Channel.HostFactories.CreateHttpClient()) { + using (var redirectingResponse = await httpClient.GetAsync(redirectingRequest.Headers.Location, ct)) { + redirectingResponse.EnsureSuccessStatusCode(); + redirectingResponseUri = redirectingResponse.Headers.Location; + } + } + var response = await rp.Channel.ReadFromRequestAsync<PositiveAssertionResponse>(new HttpRequestMessage(HttpMethod.Get, redirectingResponseUri), ct); var receivedResponses = response.Extensions.Cast<IOpenIdMessageExtension>(); CollectionAssert<IOpenIdMessageExtension>.AreEquivalentByEquality(responses.ToArray(), receivedResponses.ToArray()); - }, - op => { + }), + CoordinatorBase.HandleProvider(async (op, req, ct) => { RegisterExtension(op.Channel, Mocks.MockOpenIdExtension.Factory); var key = cryptoKeyStore.GetCurrentKey(ProviderAssociationHandleEncoder.AssociationHandleEncodingSecretBucket, TimeSpan.FromSeconds(1)); op.CryptoKeyStore.StoreKey(ProviderAssociationHandleEncoder.AssociationHandleEncodingSecretBucket, key.Key, key.Value); - var request = op.Channel.ReadFromRequest<CheckIdRequest>(); + var request = await op.Channel.ReadFromRequestAsync<CheckIdRequest>(req, ct); var response = new PositiveAssertionResponse(request); var receivedRequests = request.Extensions.Cast<IOpenIdMessageExtension>(); CollectionAssert<IOpenIdMessageExtension>.AreEquivalentByEquality(requests.ToArray(), receivedRequests.ToArray()); @@ -71,9 +81,8 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions { response.Extensions.Add(extensionResponse); } - op.Channel.Respond(response); - }); - coordinator.Run(); + return await op.Channel.PrepareResponseAsync(response, ct); + })); } internal static void RegisterExtension(Channel channel, StandardOpenIdExtensionFactory.CreateDelegate extensionFactory) { diff --git a/src/DotNetOpenAuth.Test/OpenId/Extensions/ExtensionsInteropHelperOPTests.cs b/src/DotNetOpenAuth.Test/OpenId/Extensions/ExtensionsInteropHelperOPTests.cs index e9ff7a4..60075f3 100644 --- a/src/DotNetOpenAuth.Test/OpenId/Extensions/ExtensionsInteropHelperOPTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/Extensions/ExtensionsInteropHelperOPTests.cs @@ -7,6 +7,8 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions { using System.Collections.Generic; using System.Linq; + using System.Threading; + using System.Threading.Tasks; using DotNetOpenAuth.Messaging; using DotNetOpenAuth.OpenId; using DotNetOpenAuth.OpenId.Extensions; @@ -38,7 +40,7 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions { /// Verifies no extensions appear as no extensions /// </summary> [Test] - public void NoRequestedExtensions() { + public async Task NoRequestedExtensions() { var sreg = ExtensionsInteropHelper.UnifyExtensionsAsSreg(this.request); Assert.IsNull(sreg); @@ -47,22 +49,22 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions { // to directly create a response without a request. var sregResponse = new ClaimsResponse(); this.request.AddResponseExtension(sregResponse); - ExtensionsInteropHelper.ConvertSregToMatchRequest(this.request); - var extensions = this.GetResponseExtensions(); + await ExtensionsInteropHelper.ConvertSregToMatchRequestAsync(this.request, CancellationToken.None); + var extensions = await this.GetResponseExtensionsAsync(); Assert.AreSame(sregResponse, extensions.Single()); } [Test] - public void NegativeResponse() { + public async Task NegativeResponse() { this.request.IsAuthenticated = false; - ExtensionsInteropHelper.ConvertSregToMatchRequest(this.request); + await ExtensionsInteropHelper.ConvertSregToMatchRequestAsync(this.request, CancellationToken.None); } /// <summary> /// Verifies sreg coming in is seen as sreg. /// </summary> [Test] - public void UnifyExtensionsAsSregWithSreg() { + public async Task UnifyExtensionsAsSregWithSreg() { var sregInjected = new ClaimsRequest(DotNetOpenAuth.OpenId.Extensions.SimpleRegistration.Constants.TypeUris.Standard) { Nickname = DemandLevel.Request, }; @@ -74,8 +76,8 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions { var sregResponse = sreg.CreateResponse(); this.request.AddResponseExtension(sregResponse); - ExtensionsInteropHelper.ConvertSregToMatchRequest(this.request); - var extensions = this.GetResponseExtensions(); + await ExtensionsInteropHelper.ConvertSregToMatchRequestAsync(this.request, CancellationToken.None); + var extensions = await this.GetResponseExtensionsAsync(); Assert.AreSame(sregResponse, extensions.Single()); } @@ -83,23 +85,23 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions { /// Verifies AX coming in looks like sreg. /// </summary> [Test] - public void UnifyExtensionsAsSregWithAX() { - this.ParameterizedAXTest(AXAttributeFormats.AXSchemaOrg); + public async Task UnifyExtensionsAsSregWithAX() { + await this.ParameterizedAXTestAsync(AXAttributeFormats.AXSchemaOrg); } /// <summary> /// Verifies AX coming in looks like sreg. /// </summary> [Test] - public void UnifyExtensionsAsSregWithAXSchemaOpenIdNet() { - this.ParameterizedAXTest(AXAttributeFormats.SchemaOpenIdNet); + public async Task UnifyExtensionsAsSregWithAXSchemaOpenIdNet() { + await this.ParameterizedAXTestAsync(AXAttributeFormats.SchemaOpenIdNet); } /// <summary> /// Verifies sreg and AX in one request has a preserved sreg request. /// </summary> [Test] - public void UnifyExtensionsAsSregWithBothSregAndAX() { + public async Task UnifyExtensionsAsSregWithBothSregAndAX() { var sregInjected = new ClaimsRequest(DotNetOpenAuth.OpenId.Extensions.SimpleRegistration.Constants.TypeUris.Standard) { Nickname = DemandLevel.Request, }; @@ -118,20 +120,20 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions { 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(); + await ExtensionsInteropHelper.ConvertSregToMatchRequestAsync(this.request, CancellationToken.None); + var extensions = await this.GetResponseExtensionsAsync(); 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; + private async Task<IList<IExtensionMessage>> GetResponseExtensionsAsync() { + var response = (IProtocolMessageWithExtensions)await this.request.GetResponseAsync(CancellationToken.None); return response.Extensions; } - private void ParameterizedAXTest(AXAttributeFormats format) { + private async Task ParameterizedAXTestAsync(AXAttributeFormats format) { var axInjected = new FetchRequest(); axInjected.Attributes.AddOptional(ExtensionsInteropHelper.TransformAXFormatTestHook(WellKnownAttributes.Name.Alias, format)); axInjected.Attributes.AddRequired(ExtensionsInteropHelper.TransformAXFormatTestHook(WellKnownAttributes.Name.FullName, format)); @@ -145,8 +147,8 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions { var sregResponse = sreg.CreateResponse(); sregResponse.Nickname = "andy"; this.request.AddResponseExtension(sregResponse); - ExtensionsInteropHelper.ConvertSregToMatchRequest(this.request); - var extensions = this.GetResponseExtensions(); + await ExtensionsInteropHelper.ConvertSregToMatchRequestAsync(this.request, CancellationToken.None); + var extensions = await this.GetResponseExtensionsAsync(); var axResponse = extensions.OfType<FetchResponse>().Single(); Assert.AreEqual("andy", axResponse.GetAttributeValue(ExtensionsInteropHelper.TransformAXFormatTestHook(WellKnownAttributes.Name.Alias, format))); } diff --git a/src/DotNetOpenAuth.Test/OpenId/Extensions/ExtensionsInteropHelperRPRequestTests.cs b/src/DotNetOpenAuth.Test/OpenId/Extensions/ExtensionsInteropHelperRPRequestTests.cs index 05ba3ad..055cf8c 100644 --- a/src/DotNetOpenAuth.Test/OpenId/Extensions/ExtensionsInteropHelperRPRequestTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/Extensions/ExtensionsInteropHelperRPRequestTests.cs @@ -27,7 +27,7 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions { var rp = CreateRelyingParty(true); Identifier identifier = this.GetMockIdentifier(ProtocolVersion.V20); - this.authReq = (AuthenticationRequest)rp.CreateRequest(identifier, RPRealmUri, RPUri); + this.authReq = (AuthenticationRequest)rp.CreateRequestAsync(identifier, RPRealmUri, RPUri).Result; this.sreg = new ClaimsRequest { Nickname = DemandLevel.Request, FullName = DemandLevel.Request, diff --git a/src/DotNetOpenAuth.Test/OpenId/Extensions/ProviderAuthenticationPolicy/PapeRoundTripTests.cs b/src/DotNetOpenAuth.Test/OpenId/Extensions/ProviderAuthenticationPolicy/PapeRoundTripTests.cs index cba54bf..2969511 100644 --- a/src/DotNetOpenAuth.Test/OpenId/Extensions/ProviderAuthenticationPolicy/PapeRoundTripTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/Extensions/ProviderAuthenticationPolicy/PapeRoundTripTests.cs @@ -6,6 +6,8 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions.ProviderAuthenticationPolicy { using System; + using System.Threading.Tasks; + using DotNetOpenAuth.OpenId; using DotNetOpenAuth.OpenId.Extensions.ProviderAuthenticationPolicy; using DotNetOpenAuth.Test.OpenId.Extensions; @@ -14,14 +16,14 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions.ProviderAuthenticationPolicy { [TestFixture] public class PapeRoundTripTests : OpenIdTestBase { [Test] - public void Trivial() { + public async Task Trivial() { var request = new PolicyRequest(); var response = new PolicyResponse(); - ExtensionTestUtilities.Roundtrip(Protocol.Default, new[] { request }, new[] { response }); + await ExtensionTestUtilities.RoundtripAsync(Protocol.Default, new[] { request }, new[] { response }); } [Test] - public void Full() { + public async Task Full() { var request = new PolicyRequest(); request.MaximumAuthenticationAge = TimeSpan.FromMinutes(10); request.PreferredAuthLevelTypes.Add(Constants.AssuranceLevels.NistTypeUri); @@ -37,7 +39,7 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions.ProviderAuthenticationPolicy { response.AssuranceLevels["customlevel"] = "ABC"; response.NistAssuranceLevel = NistAssuranceLevel.Level2; - ExtensionTestUtilities.Roundtrip(Protocol.Default, new[] { request }, new[] { response }); + await ExtensionTestUtilities.RoundtripAsync(Protocol.Default, new[] { request }, new[] { response }); } } } diff --git a/src/DotNetOpenAuth.Test/OpenId/Extensions/SimpleRegistration/ClaimsResponseTests.cs b/src/DotNetOpenAuth.Test/OpenId/Extensions/SimpleRegistration/ClaimsResponseTests.cs index f898511..40f9d76 100644 --- a/src/DotNetOpenAuth.Test/OpenId/Extensions/SimpleRegistration/ClaimsResponseTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/Extensions/SimpleRegistration/ClaimsResponseTests.cs @@ -10,6 +10,7 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions { using System.IO; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; + using System.Threading.Tasks; using System.Xml.Serialization; using DotNetOpenAuth.OpenId; using DotNetOpenAuth.OpenId.Extensions.SimpleRegistration; @@ -132,14 +133,14 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions { } [Test] - public void ResponseAlternateTypeUriTests() { + public async Task ResponseAlternateTypeUriTests() { var request = new ClaimsRequest(Constants.TypeUris.Variant10); request.Email = DemandLevel.Require; var response = new ClaimsResponse(Constants.TypeUris.Variant10); response.Email = "a@b.com"; - ExtensionTestUtilities.Roundtrip(Protocol.Default, new[] { request }, new[] { response }); + await ExtensionTestUtilities.RoundtripAsync(Protocol.Default, new[] { request }, new[] { response }); } private ClaimsResponse GetFilledData() { diff --git a/src/DotNetOpenAuth.Test/OpenId/OpenIdTestBase.cs b/src/DotNetOpenAuth.Test/OpenId/OpenIdTestBase.cs index c23f042..05dd8dd 100644 --- a/src/DotNetOpenAuth.Test/OpenId/OpenIdTestBase.cs +++ b/src/DotNetOpenAuth.Test/OpenId/OpenIdTestBase.cs @@ -23,9 +23,7 @@ namespace DotNetOpenAuth.Test.OpenId { using NUnit.Framework; public class OpenIdTestBase : TestBase { - internal IDirectWebRequestHandler RequestHandler; - - internal MockHttpRequest MockResponder; + internal MockingHostFactories HostFactories; protected internal const string IdentifierSelect = "http://specs.openid.net/auth/2.0/identifier_select"; @@ -73,8 +71,7 @@ namespace DotNetOpenAuth.Test.OpenId { this.RelyingPartySecuritySettings = OpenIdElement.Configuration.RelyingParty.SecuritySettings.CreateSecuritySettings(); this.ProviderSecuritySettings = OpenIdElement.Configuration.Provider.SecuritySettings.CreateSecuritySettings(); - this.MockResponder = MockHttpRequest.CreateUntrustedMockHttpHandler(); - this.RequestHandler = this.MockResponder.MockWebRequestHandler; + this.HostFactories = new MockingHostFactories(); this.AutoProviderScenario = Scenarios.AutoApproval; Identifier.EqualityOnStrings = true; } @@ -191,10 +188,9 @@ namespace DotNetOpenAuth.Test.OpenId { return await provider.PrepareResponseAsync(request, ct); } - internal IEnumerable<IdentifierDiscoveryResult> Discover(Identifier identifier) { + internal Task<IEnumerable<IdentifierDiscoveryResult>> DiscoverAsync(Identifier identifier, CancellationToken cancellationToken = default(CancellationToken)) { var rp = this.CreateRelyingParty(true); - rp.Channel.WebRequestHandler = this.RequestHandler; - return rp.Discover(identifier); + return rp.DiscoverAsync(identifier, cancellationToken); } protected Realm GetMockRealm(bool useSsl) { @@ -212,8 +208,8 @@ namespace DotNetOpenAuth.Test.OpenId { protected Identifier GetMockIdentifier(ProtocolVersion providerVersion, bool useSsl, bool delegating) { var se = GetServiceEndpoint(0, providerVersion, 10, useSsl, delegating); - UriIdentifier identityUri = (UriIdentifier)se.ClaimedIdentifier; - return new MockIdentifier(identityUri, this.MockResponder, new IdentifierDiscoveryResult[] { se }); + this.HostFactories.Handlers.Add(MockHttpRequest.RegisterMockXrdsResponse(se)); + return se.ClaimedIdentifier; } protected Identifier GetMockDualIdentifier() { @@ -224,8 +220,8 @@ namespace DotNetOpenAuth.Test.OpenId { IdentifierDiscoveryResult.CreateForProviderIdentifier(protocol.ClaimedIdentifierForOPIdentifier, opDesc, 20, 20), }; - Identifier dualId = new MockIdentifier(VanityUri, this.MockResponder, dualResults); - return dualId; + this.HostFactories.Handlers.Add(MockHttpRequest.RegisterMockXrdsResponse(VanityUri, dualResults)); + return VanityUri; } /// <summary> @@ -242,9 +238,7 @@ namespace DotNetOpenAuth.Test.OpenId { /// <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; - rp.DiscoveryServices.Add(new MockIdentifierDiscoveryService()); + var rp = new OpenIdRelyingParty(stateless ? null : new StandardRelyingPartyApplicationStore(), this.HostFactories); return rp; } @@ -253,9 +247,7 @@ namespace DotNetOpenAuth.Test.OpenId { /// </summary> /// <returns>The new instance.</returns> protected OpenIdProvider CreateProvider() { - var op = new OpenIdProvider(new StandardProviderApplicationStore()); - op.Channel.WebRequestHandler = this.MockResponder.MockWebRequestHandler; - op.DiscoveryServices.Add(new MockIdentifierDiscoveryService()); + var op = new OpenIdProvider(new StandardProviderApplicationStore(), this.HostFactories); return op; } } diff --git a/src/DotNetOpenAuth.Test/OpenId/UriIdentifierTests.cs b/src/DotNetOpenAuth.Test/OpenId/UriIdentifierTests.cs index b6a52a7..465fd23 100644 --- a/src/DotNetOpenAuth.Test/OpenId/UriIdentifierTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/UriIdentifierTests.cs @@ -8,6 +8,7 @@ namespace DotNetOpenAuth.Test.OpenId { using System; using System.Linq; using System.Net; + using System.Threading.Tasks; using System.Web; using DotNetOpenAuth.Messaging; using DotNetOpenAuth.OpenId; @@ -243,7 +244,7 @@ namespace DotNetOpenAuth.Test.OpenId { } [Test] - public void TryRequireSslAdjustsIdentifier() { + public async Task TryRequireSslAdjustsIdentifier() { Identifier secureId; // Try Parse and ctor without explicit scheme var id = Identifier.Parse("www.yahoo.com"); @@ -263,13 +264,13 @@ 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, Discover(secureId).Count(), "Since TryRequireSsl failed, the created Identifier should never discover anything."); + Assert.AreEqual(0, (await DiscoverAsync(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, Discover(secureId).Count()); + Assert.AreEqual(0, (await DiscoverAsync(secureId)).Count()); } /// <summary> diff --git a/src/DotNetOpenAuth.Test/TestBase.cs b/src/DotNetOpenAuth.Test/TestBase.cs index 612d871..28f5ccd 100644 --- a/src/DotNetOpenAuth.Test/TestBase.cs +++ b/src/DotNetOpenAuth.Test/TestBase.cs @@ -76,7 +76,7 @@ namespace DotNetOpenAuth.Test { var timer = new MultiSampleCodeTimer(samples, iterations); Stats stats; using (new HighPerformance()) { - stats = timer.Measure(name ?? TestContext.CurrentContext.Test.FullName, action().Wait()); + stats = timer.Measure(name ?? TestContext.CurrentContext.Test.FullName, () => action().Wait()); } stats.AdjustForScale(PerformanceTestUtilities.Baseline.Median); |