summaryrefslogtreecommitdiffstats
path: root/src/DotNetOpenAuth.Test
diff options
context:
space:
mode:
Diffstat (limited to 'src/DotNetOpenAuth.Test')
-rw-r--r--src/DotNetOpenAuth.Test/App.config6
-rw-r--r--src/DotNetOpenAuth.Test/AssemblyTesting.cs7
-rw-r--r--src/DotNetOpenAuth.Test/CoordinatorBase.cs6
-rw-r--r--src/DotNetOpenAuth.Test/DotNetOpenAuth.Test.csproj65
-rw-r--r--src/DotNetOpenAuth.Test/LocalizationTests.cs28
-rw-r--r--src/DotNetOpenAuth.Test/Messaging/Bindings/StandardExpirationBindingElementTests.cs2
-rw-r--r--src/DotNetOpenAuth.Test/Messaging/Bindings/StandardReplayProtectionBindingElementTests.cs1
-rw-r--r--src/DotNetOpenAuth.Test/Messaging/ChannelTests.cs4
-rw-r--r--src/DotNetOpenAuth.Test/Messaging/CollectionAssert.cs12
-rw-r--r--src/DotNetOpenAuth.Test/Messaging/MessagingUtilitiesTests.cs77
-rw-r--r--src/DotNetOpenAuth.Test/Messaging/MultipartPostPartTests.cs108
-rw-r--r--src/DotNetOpenAuth.Test/Messaging/OutgoingWebResponseTests.cs4
-rw-r--r--src/DotNetOpenAuth.Test/Messaging/ResponseTests.cs1
-rw-r--r--src/DotNetOpenAuth.Test/Mocks/CoordinatingChannel.cs16
-rw-r--r--src/DotNetOpenAuth.Test/Mocks/CoordinatingOAuthChannel.cs7
-rw-r--r--src/DotNetOpenAuth.Test/Mocks/CoordinatingOutgoingWebResponse.cs5
-rw-r--r--src/DotNetOpenAuth.Test/Mocks/InMemoryTokenManager.cs4
-rw-r--r--src/DotNetOpenAuth.Test/Mocks/MockHttpRequest.cs15
-rw-r--r--src/DotNetOpenAuth.Test/Mocks/MockIdentifier.cs9
-rw-r--r--src/DotNetOpenAuth.Test/Mocks/MockRealm.cs4
-rw-r--r--src/DotNetOpenAuth.Test/Mocks/TestDirectedMessage.cs4
-rw-r--r--src/DotNetOpenAuth.Test/Mocks/TestMessageFactory.cs3
-rw-r--r--src/DotNetOpenAuth.Test/Mocks/TestWebRequestHandler.cs2
-rw-r--r--src/DotNetOpenAuth.Test/OAuth/ChannelElements/HmacSha1SigningBindingElementTests.cs4
-rw-r--r--src/DotNetOpenAuth.Test/OAuth/ChannelElements/OAuthChannelTests.cs23
-rw-r--r--src/DotNetOpenAuth.Test/OAuth/ChannelElements/PlaintextSigningBindingElementTest.cs6
-rw-r--r--src/DotNetOpenAuth.Test/OAuth/ChannelElements/SigningBindingElementBaseTests.cs10
-rw-r--r--src/DotNetOpenAuth.Test/OAuth/OAuthCoordinator.cs5
-rw-r--r--src/DotNetOpenAuth.Test/OpenId/AssociationHandshakeTests.cs18
-rw-r--r--src/DotNetOpenAuth.Test/OpenId/AuthenticationTests.cs5
-rw-r--r--src/DotNetOpenAuth.Test/OpenId/ChannelElements/ExtensionsBindingElementTests.cs5
-rw-r--r--src/DotNetOpenAuth.Test/OpenId/ChannelElements/OpenIdChannelTests.cs14
-rw-r--r--src/DotNetOpenAuth.Test/OpenId/Extensions/AttributeExchange/AttributeRequestTests.cs2
-rw-r--r--src/DotNetOpenAuth.Test/OpenId/Extensions/ExtensionTestUtilities.cs4
-rw-r--r--src/DotNetOpenAuth.Test/OpenId/Extensions/ExtensionsInteropHelperOPTests.cs6
-rw-r--r--src/DotNetOpenAuth.Test/OpenId/Extensions/ExtensionsInteropHelperRPRequestTests.cs19
-rw-r--r--src/DotNetOpenAuth.Test/OpenId/Extensions/ExtensionsInteropHelperRPResponseTests.cs2
-rw-r--r--src/DotNetOpenAuth.Test/OpenId/IdentifierTests.cs2
-rw-r--r--src/DotNetOpenAuth.Test/OpenId/Messages/IndirectSignedResponseTests.cs12
-rw-r--r--src/DotNetOpenAuth.Test/OpenId/OpenIdCoordinator.cs5
-rw-r--r--src/DotNetOpenAuth.Test/OpenId/OpenIdTestBase.cs6
-rw-r--r--src/DotNetOpenAuth.Test/OpenId/Provider/AuthenticationRequestTest.cs4
-rw-r--r--src/DotNetOpenAuth.Test/OpenId/Provider/OpenIdProviderTests.cs2
-rw-r--r--src/DotNetOpenAuth.Test/OpenId/ProviderEndpointDescriptionTests.cs2
-rw-r--r--src/DotNetOpenAuth.Test/OpenId/RelyingParty/AuthenticationRequestTests.cs23
-rw-r--r--src/DotNetOpenAuth.Test/OpenId/RelyingParty/OpenIdTextBoxTests.cs49
-rw-r--r--src/DotNetOpenAuth.Test/OpenId/RelyingParty/PositiveAuthenticationResponseTests.cs3
-rw-r--r--src/DotNetOpenAuth.Test/OpenId/RelyingParty/ServiceEndpointTests.cs8
-rw-r--r--src/DotNetOpenAuth.Test/OpenId/UriIdentifierTests.cs2
-rw-r--r--src/DotNetOpenAuth.Test/OpenId/XriIdentifierTests.cs2
-rw-r--r--src/DotNetOpenAuth.Test/Properties/AssemblyInfo.cs2
-rw-r--r--src/DotNetOpenAuth.Test/TestBase.cs13
52 files changed, 497 insertions, 151 deletions
diff --git a/src/DotNetOpenAuth.Test/App.config b/src/DotNetOpenAuth.Test/App.config
index 359e25f..b3da723 100644
--- a/src/DotNetOpenAuth.Test/App.config
+++ b/src/DotNetOpenAuth.Test/App.config
@@ -49,5 +49,11 @@
</security>
</provider>
</openid>
+ <!-- We definitely do NOT want to report on events that happen while running tests. -->
+ <reporting enabled="false" />
</dotNetOpenAuth>
+
+ <system.diagnostics>
+ <assert assertuienabled="false"/>
+ </system.diagnostics>
</configuration> \ No newline at end of file
diff --git a/src/DotNetOpenAuth.Test/AssemblyTesting.cs b/src/DotNetOpenAuth.Test/AssemblyTesting.cs
index d0868d2..7659a82 100644
--- a/src/DotNetOpenAuth.Test/AssemblyTesting.cs
+++ b/src/DotNetOpenAuth.Test/AssemblyTesting.cs
@@ -14,10 +14,9 @@ namespace DotNetOpenAuth.Test {
public static void AssemblyInitialize(TestContext tc) {
// Make contract failures become test failures.
Contract.ContractFailed += (sender, e) => {
- if (e.FailureKind == ContractFailureKind.Precondition) {
- // Currently we ignore these so that the regular ErrorUtilities can kick in.
- e.SetHandled();
- } else {
+ // For now, we have tests that verify that preconditions throw exceptions.
+ // So we don't want to fail a test just because a precondition check failed.
+ if (e.FailureKind != ContractFailureKind.Precondition) {
e.SetHandled();
Assert.Fail(e.FailureKind.ToString() + ": " + e.Message);
}
diff --git a/src/DotNetOpenAuth.Test/CoordinatorBase.cs b/src/DotNetOpenAuth.Test/CoordinatorBase.cs
index d1bf27c..df331f3 100644
--- a/src/DotNetOpenAuth.Test/CoordinatorBase.cs
+++ b/src/DotNetOpenAuth.Test/CoordinatorBase.cs
@@ -6,6 +6,7 @@
namespace DotNetOpenAuth.Test {
using System;
+ using System.Diagnostics.Contracts;
using System.Threading;
using DotNetOpenAuth.Messaging;
using DotNetOpenAuth.OpenId.RelyingParty;
@@ -17,8 +18,8 @@ namespace DotNetOpenAuth.Test {
private Action<T2> party2Action;
protected CoordinatorBase(Action<T1> party1Action, Action<T2> party2Action) {
- ErrorUtilities.VerifyArgumentNotNull(party1Action, "party1Action");
- ErrorUtilities.VerifyArgumentNotNull(party2Action, "party2Action");
+ Contract.Requires<ArgumentNullException>(party1Action != null);
+ Contract.Requires<ArgumentNullException>(party2Action != null);
this.party1Action = party1Action;
this.party2Action = party2Action;
@@ -38,6 +39,7 @@ namespace DotNetOpenAuth.Test {
// terminate the other thread and inform the test host that the test failed.
Action<Action> safeWrapper = (action) => {
try {
+ TestBase.SetMockHttpContext();
action();
} catch (Exception ex) {
// We may be the second thread in an ThreadAbortException, so check the "flag"
diff --git a/src/DotNetOpenAuth.Test/DotNetOpenAuth.Test.csproj b/src/DotNetOpenAuth.Test/DotNetOpenAuth.Test.csproj
index 7212008..17f33ff 100644
--- a/src/DotNetOpenAuth.Test/DotNetOpenAuth.Test.csproj
+++ b/src/DotNetOpenAuth.Test/DotNetOpenAuth.Test.csproj
@@ -12,6 +12,7 @@
<TargetFrameworkVersion>v3.5</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<ProjectTypeGuids>{3AC096D0-A1C2-E12C-1390-A8335801FDAB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
+ <CodeContractsAssemblyMode>1</CodeContractsAssemblyMode>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
@@ -21,12 +22,12 @@
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
- <CodeContractsEnableRuntimeChecking>False</CodeContractsEnableRuntimeChecking>
+ <CodeContractsEnableRuntimeChecking>True</CodeContractsEnableRuntimeChecking>
<CodeContractsCustomRewriterAssembly>
</CodeContractsCustomRewriterAssembly>
<CodeContractsCustomRewriterClass>
</CodeContractsCustomRewriterClass>
- <CodeContractsRuntimeCheckingLevel>Full</CodeContractsRuntimeCheckingLevel>
+ <CodeContractsRuntimeCheckingLevel>None</CodeContractsRuntimeCheckingLevel>
<CodeContractsRunCodeAnalysis>False</CodeContractsRunCodeAnalysis>
<CodeContractsBuildReferenceAssembly>False</CodeContractsBuildReferenceAssembly>
<CodeContractsNonNullObligations>False</CodeContractsNonNullObligations>
@@ -44,6 +45,14 @@
<CodeContractsRunInBackground>True</CodeContractsRunInBackground>
<CodeContractsShowSquigglies>False</CodeContractsShowSquigglies>
<CodeContractsRuntimeOnlyPublicSurface>False</CodeContractsRuntimeOnlyPublicSurface>
+ <CodeContractsRuntimeThrowOnFailure>True</CodeContractsRuntimeThrowOnFailure>
+ <CodeContractsRuntimeCallSiteRequires>False</CodeContractsRuntimeCallSiteRequires>
+ <CodeContractsContainerAnalysis>False</CodeContractsContainerAnalysis>
+ <CodeContractsRedundantAssumptions>False</CodeContractsRedundantAssumptions>
+ <CodeContractsEmitXMLDocs>False</CodeContractsEmitXMLDocs>
+ <CodeContractsExtraRewriteOptions>
+ </CodeContractsExtraRewriteOptions>
+ <CodeContractsReferenceAssembly>%28none%29</CodeContractsReferenceAssembly>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
@@ -52,10 +61,40 @@
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
+ <CodeContractsEnableRuntimeChecking>True</CodeContractsEnableRuntimeChecking>
+ <CodeContractsCustomRewriterAssembly>
+ </CodeContractsCustomRewriterAssembly>
+ <CodeContractsCustomRewriterClass>
+ </CodeContractsCustomRewriterClass>
+ <CodeContractsRuntimeCheckingLevel>None</CodeContractsRuntimeCheckingLevel>
+ <CodeContractsRuntimeOnlyPublicSurface>False</CodeContractsRuntimeOnlyPublicSurface>
+ <CodeContractsRuntimeThrowOnFailure>True</CodeContractsRuntimeThrowOnFailure>
+ <CodeContractsRuntimeCallSiteRequires>False</CodeContractsRuntimeCallSiteRequires>
+ <CodeContractsRunCodeAnalysis>False</CodeContractsRunCodeAnalysis>
+ <CodeContractsBuildReferenceAssembly>False</CodeContractsBuildReferenceAssembly>
+ <CodeContractsNonNullObligations>False</CodeContractsNonNullObligations>
+ <CodeContractsBoundsObligations>False</CodeContractsBoundsObligations>
+ <CodeContractsArithmeticObligations>False</CodeContractsArithmeticObligations>
+ <CodeContractsLibPaths>
+ </CodeContractsLibPaths>
+ <CodeContractsPlatformPath>
+ </CodeContractsPlatformPath>
+ <CodeContractsExtraAnalysisOptions>
+ </CodeContractsExtraAnalysisOptions>
+ <CodeContractsBaseLineFile>
+ </CodeContractsBaseLineFile>
+ <CodeContractsUseBaseLine>False</CodeContractsUseBaseLine>
+ <CodeContractsRunInBackground>True</CodeContractsRunInBackground>
+ <CodeContractsShowSquigglies>False</CodeContractsShowSquigglies>
+ <CodeContractsContainerAnalysis>False</CodeContractsContainerAnalysis>
+ <CodeContractsRedundantAssumptions>False</CodeContractsRedundantAssumptions>
+ <CodeContractsEmitXMLDocs>False</CodeContractsEmitXMLDocs>
+ <CodeContractsExtraRewriteOptions>
+ </CodeContractsExtraRewriteOptions>
+ <CodeContractsReferenceAssembly>%28none%29</CodeContractsReferenceAssembly>
</PropertyGroup>
- <PropertyGroup Condition=" '$(Sign)' == 'true' ">
+ <PropertyGroup>
<SignAssembly>true</SignAssembly>
- <AssemblyOriginatorKeyFile>..\official-build-key.pfx</AssemblyOriginatorKeyFile>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'CodeAnalysis|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
@@ -71,7 +110,7 @@
</CodeContractsCustomRewriterAssembly>
<CodeContractsCustomRewriterClass>
</CodeContractsCustomRewriterClass>
- <CodeContractsRuntimeCheckingLevel>Full</CodeContractsRuntimeCheckingLevel>
+ <CodeContractsRuntimeCheckingLevel>None</CodeContractsRuntimeCheckingLevel>
<CodeContractsRunCodeAnalysis>True</CodeContractsRunCodeAnalysis>
<CodeContractsBuildReferenceAssembly>False</CodeContractsBuildReferenceAssembly>
<CodeContractsNonNullObligations>False</CodeContractsNonNullObligations>
@@ -87,6 +126,16 @@
<CodeContractsUseBaseLine>False</CodeContractsUseBaseLine>
<CodeContractsRunInBackground>True</CodeContractsRunInBackground>
<CodeContractsShowSquigglies>True</CodeContractsShowSquigglies>
+ <CodeContractsRuntimeOnlyPublicSurface>False</CodeContractsRuntimeOnlyPublicSurface>
+ <CodeContractsRuntimeThrowOnFailure>True</CodeContractsRuntimeThrowOnFailure>
+ <CodeContractsRuntimeCallSiteRequires>False</CodeContractsRuntimeCallSiteRequires>
+ <CodeContractsArithmeticObligations>False</CodeContractsArithmeticObligations>
+ <CodeContractsContainerAnalysis>False</CodeContractsContainerAnalysis>
+ <CodeContractsRedundantAssumptions>False</CodeContractsRedundantAssumptions>
+ <CodeContractsEmitXMLDocs>False</CodeContractsEmitXMLDocs>
+ <CodeContractsExtraRewriteOptions>
+ </CodeContractsExtraRewriteOptions>
+ <CodeContractsReferenceAssembly>%28none%29</CodeContractsReferenceAssembly>
</PropertyGroup>
<ItemGroup>
<Reference Include="log4net, Version=1.2.10.0, Culture=neutral, PublicKeyToken=1b44e1d426115821, processorArchitecture=MSIL">
@@ -131,10 +180,12 @@
<Compile Include="Hosting\HostingTests.cs" />
<Compile Include="Hosting\HttpHost.cs" />
<Compile Include="Hosting\TestingWorkerRequest.cs" />
+ <Compile Include="LocalizationTests.cs" />
<Compile Include="Messaging\CollectionAssert.cs" />
<Compile Include="Messaging\EnumerableCacheTests.cs" />
<Compile Include="Messaging\ErrorUtilitiesTests.cs" />
<Compile Include="Messaging\MessageSerializerTests.cs" />
+ <Compile Include="Messaging\MultipartPostPartTests.cs" />
<Compile Include="Messaging\OutgoingWebResponseTests.cs" />
<Compile Include="Messaging\Reflection\MessageDescriptionTests.cs" />
<Compile Include="Messaging\Reflection\MessageDictionaryTests.cs" />
@@ -233,6 +284,7 @@
<Compile Include="OpenId\RelyingParty\AuthenticationRequestTests.cs" />
<Compile Include="OpenId\RelyingParty\FailedAuthenticationResponseTests.cs" />
<Compile Include="OpenId\RelyingParty\NegativeAuthenticationResponseTests.cs" />
+ <Compile Include="OpenId\RelyingParty\OpenIdTextBoxTests.cs" />
<Compile Include="OpenId\RelyingParty\PositiveAnonymousResponseTests.cs" />
<Compile Include="OpenId\RelyingParty\PositiveAuthenticationResponseTests.cs" />
<Compile Include="OpenId\RelyingParty\OpenIdRelyingPartyTests.cs" />
@@ -260,9 +312,6 @@
<EmbeddedResource Include="Logging.config" />
</ItemGroup>
<ItemGroup>
- <Shadow Include="Test References\DotNetOpenAuth.accessor" />
- </ItemGroup>
- <ItemGroup>
<EmbeddedResource Include="OpenId\Discovery\htmldiscovery\html1020.html" />
<EmbeddedResource Include="OpenId\Discovery\htmldiscovery\html10both.html" />
<EmbeddedResource Include="OpenId\Discovery\htmldiscovery\html10del.html" />
diff --git a/src/DotNetOpenAuth.Test/LocalizationTests.cs b/src/DotNetOpenAuth.Test/LocalizationTests.cs
new file mode 100644
index 0000000..50e9a34
--- /dev/null
+++ b/src/DotNetOpenAuth.Test/LocalizationTests.cs
@@ -0,0 +1,28 @@
+//-----------------------------------------------------------------------
+// <copyright file="LocalizationTests.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.Test {
+ using System;
+ using System.Globalization;
+ using System.Threading;
+ using DotNetOpenAuth.Messaging;
+ using Microsoft.VisualStudio.TestTools.UnitTesting;
+
+ /// <summary>
+ /// Tests various localized resources work as expected.
+ /// </summary>
+ [TestClass]
+ public class LocalizationTests {
+ /// <summary>
+ /// Tests that Serbian localized strings are correctly installed.
+ /// </summary>
+ [TestMethod, ExpectedException(typeof(InvalidOperationException), "Ovaj metod zahteva tekući HttpContext. Kao alternativa, koristite preklopljeni metod koji dozvoljava da se prosledi informacija bez HttpContext-a.")]
+ public void Serbian() {
+ Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("sr");
+ ErrorUtilities.VerifyHttpContext();
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth.Test/Messaging/Bindings/StandardExpirationBindingElementTests.cs b/src/DotNetOpenAuth.Test/Messaging/Bindings/StandardExpirationBindingElementTests.cs
index cbaded1..3cc792b 100644
--- a/src/DotNetOpenAuth.Test/Messaging/Bindings/StandardExpirationBindingElementTests.cs
+++ b/src/DotNetOpenAuth.Test/Messaging/Bindings/StandardExpirationBindingElementTests.cs
@@ -33,7 +33,7 @@ namespace DotNetOpenAuth.Test.Messaging.Bindings {
[TestMethod, ExpectedException(typeof(ExpiredMessageException))]
public void VerifyBadTimestampIsRejected() {
this.Channel = CreateChannel(MessageProtections.Expiration);
- this.ParameterizedReceiveProtectedTest(DateTime.UtcNow - StandardExpirationBindingElement.DefaultMaximumMessageAge - TimeSpan.FromSeconds(1), false);
+ this.ParameterizedReceiveProtectedTest(DateTime.UtcNow - StandardExpirationBindingElement.MaximumMessageAge - TimeSpan.FromSeconds(1), false);
}
}
}
diff --git a/src/DotNetOpenAuth.Test/Messaging/Bindings/StandardReplayProtectionBindingElementTests.cs b/src/DotNetOpenAuth.Test/Messaging/Bindings/StandardReplayProtectionBindingElementTests.cs
index 26ce01c..14651bc 100644
--- a/src/DotNetOpenAuth.Test/Messaging/Bindings/StandardReplayProtectionBindingElementTests.cs
+++ b/src/DotNetOpenAuth.Test/Messaging/Bindings/StandardReplayProtectionBindingElementTests.cs
@@ -31,6 +31,7 @@ namespace DotNetOpenAuth.Test.Messaging.Bindings {
this.protocol = Protocol.Default;
this.nonceStore = new NonceMemoryStore(TimeSpan.FromHours(3));
this.nonceElement = new StandardReplayProtectionBindingElement(this.nonceStore);
+ this.nonceElement.Channel = new Mocks.TestChannel();
this.message = new TestReplayProtectedMessage();
this.message.UtcCreationDate = DateTime.UtcNow;
}
diff --git a/src/DotNetOpenAuth.Test/Messaging/ChannelTests.cs b/src/DotNetOpenAuth.Test/Messaging/ChannelTests.cs
index 669abbc..f625edb 100644
--- a/src/DotNetOpenAuth.Test/Messaging/ChannelTests.cs
+++ b/src/DotNetOpenAuth.Test/Messaging/ChannelTests.cs
@@ -201,6 +201,7 @@ namespace DotNetOpenAuth.Test.Messaging {
[TestMethod, ExpectedException(typeof(InvalidOperationException))]
public void ReadFromRequestNoContext() {
+ HttpContext.Current = null;
TestBadChannel badChannel = new TestBadChannel(false);
badChannel.ReadFromRequest();
}
@@ -253,8 +254,7 @@ namespace DotNetOpenAuth.Test.Messaging {
new TestMessageFactory(),
new MockSigningBindingElement(),
new MockSigningBindingElement());
- Channel_Accessor accessor = Channel_Accessor.AttachShadow(channel);
- accessor.ProcessOutgoingMessage(new TestSignedDirectedMessage());
+ channel.ProcessOutgoingMessageTestHook(new TestSignedDirectedMessage());
}
[TestMethod]
diff --git a/src/DotNetOpenAuth.Test/Messaging/CollectionAssert.cs b/src/DotNetOpenAuth.Test/Messaging/CollectionAssert.cs
index f9e569a..db136f5 100644
--- a/src/DotNetOpenAuth.Test/Messaging/CollectionAssert.cs
+++ b/src/DotNetOpenAuth.Test/Messaging/CollectionAssert.cs
@@ -5,16 +5,18 @@
//-----------------------------------------------------------------------
namespace DotNetOpenAuth.Test.Messaging {
+ using System;
using System.Collections;
using System.Collections.Generic;
+ using System.Diagnostics.Contracts;
using System.Linq;
using DotNetOpenAuth.Messaging;
using Microsoft.VisualStudio.TestTools.UnitTesting;
internal class CollectionAssert<T> {
internal static void AreEquivalent(ICollection<T> expected, ICollection<T> actual) {
- ErrorUtilities.VerifyArgumentNotNull(expected, "expected");
- ErrorUtilities.VerifyArgumentNotNull(actual, "actual");
+ Contract.Requires<ArgumentNullException>(expected != null);
+ Contract.Requires<ArgumentNullException>(actual != null);
ICollection expectedNonGeneric = new List<T>(expected);
ICollection actualNonGeneric = new List<T>(actual);
@@ -22,8 +24,8 @@ namespace DotNetOpenAuth.Test.Messaging {
}
internal static void AreEquivalentByEquality(ICollection<T> expected, ICollection<T> actual) {
- ErrorUtilities.VerifyArgumentNotNull(expected, "expected");
- ErrorUtilities.VerifyArgumentNotNull(actual, "actual");
+ Contract.Requires<ArgumentNullException>(expected != null);
+ Contract.Requires<ArgumentNullException>(actual != null);
Assert.AreEqual(expected.Count, actual.Count);
foreach (T value in expected) {
@@ -32,7 +34,7 @@ namespace DotNetOpenAuth.Test.Messaging {
}
internal static void Contains(IEnumerable<T> sequence, T element) {
- ErrorUtilities.VerifyArgumentNotNull(sequence, "sequence");
+ Contract.Requires<ArgumentNullException>(sequence != null);
if (!sequence.Contains(element)) {
Assert.Fail("Sequence did not include expected element '{0}'.", element);
diff --git a/src/DotNetOpenAuth.Test/Messaging/MessagingUtilitiesTests.cs b/src/DotNetOpenAuth.Test/Messaging/MessagingUtilitiesTests.cs
index 26ce4cd..4fc89a7 100644
--- a/src/DotNetOpenAuth.Test/Messaging/MessagingUtilitiesTests.cs
+++ b/src/DotNetOpenAuth.Test/Messaging/MessagingUtilitiesTests.cs
@@ -11,8 +11,10 @@ namespace DotNetOpenAuth.Test.Messaging
using System.Collections.Specialized;
using System.IO;
using System.Net;
+ using System.Text.RegularExpressions;
using System.Web;
using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.Test.Mocks;
using Microsoft.VisualStudio.TestTools.UnitTesting;
[TestClass]
@@ -139,5 +141,80 @@ namespace DotNetOpenAuth.Test.Messaging
Assert.AreEqual("%C2%80", MessagingUtilities.EscapeUriDataStringRfc3986("\u0080"));
Assert.AreEqual("%E3%80%81", MessagingUtilities.EscapeUriDataStringRfc3986("\u3001"));
}
+
+ /// <summary>
+ /// Verifies the overall format of the multipart POST is correct.
+ /// </summary>
+ [TestMethod]
+ public void PostMultipart() {
+ var httpHandler = new TestWebRequestHandler();
+ bool callbackTriggered = false;
+ httpHandler.Callback = req => {
+ Match m = Regex.Match(req.ContentType, "multipart/form-data; boundary=(.+)");
+ Assert.IsTrue(m.Success, "Content-Type HTTP header not set correctly.");
+ string boundary = m.Groups[1].Value;
+ boundary = boundary.Substring(0, boundary.IndexOf(';')); // trim off charset
+ string expectedEntity = "--{0}\r\nContent-Disposition: form-data; name=\"a\"\r\n\r\nb\r\n--{0}--\r\n";
+ expectedEntity = string.Format(expectedEntity, boundary);
+ string actualEntity = httpHandler.RequestEntityAsString;
+ Assert.AreEqual(expectedEntity, actualEntity);
+ callbackTriggered = true;
+ Assert.AreEqual(req.ContentLength, actualEntity.Length);
+ IncomingWebResponse resp = new CachedDirectWebResponse();
+ return resp;
+ };
+ var request = (HttpWebRequest)WebRequest.Create("http://someserver");
+ var parts = new[] {
+ MultipartPostPart.CreateFormPart("a", "b"),
+ };
+ request.PostMultipart(httpHandler, parts);
+ Assert.IsTrue(callbackTriggered);
+ }
+
+ /// <summary>
+ /// Verifies proper behavior of GetHttpVerb
+ /// </summary>
+ [TestMethod]
+ public void GetHttpVerbTest() {
+ Assert.AreEqual("GET", MessagingUtilities.GetHttpVerb(HttpDeliveryMethods.GetRequest));
+ Assert.AreEqual("POST", MessagingUtilities.GetHttpVerb(HttpDeliveryMethods.PostRequest));
+ Assert.AreEqual("HEAD", MessagingUtilities.GetHttpVerb(HttpDeliveryMethods.HeadRequest));
+ Assert.AreEqual("DELETE", MessagingUtilities.GetHttpVerb(HttpDeliveryMethods.DeleteRequest));
+ Assert.AreEqual("PUT", MessagingUtilities.GetHttpVerb(HttpDeliveryMethods.PutRequest));
+
+ Assert.AreEqual("GET", MessagingUtilities.GetHttpVerb(HttpDeliveryMethods.GetRequest | HttpDeliveryMethods.AuthorizationHeaderRequest));
+ Assert.AreEqual("POST", MessagingUtilities.GetHttpVerb(HttpDeliveryMethods.PostRequest | HttpDeliveryMethods.AuthorizationHeaderRequest));
+ Assert.AreEqual("HEAD", MessagingUtilities.GetHttpVerb(HttpDeliveryMethods.HeadRequest | HttpDeliveryMethods.AuthorizationHeaderRequest));
+ Assert.AreEqual("DELETE", MessagingUtilities.GetHttpVerb(HttpDeliveryMethods.DeleteRequest | HttpDeliveryMethods.AuthorizationHeaderRequest));
+ Assert.AreEqual("PUT", MessagingUtilities.GetHttpVerb(HttpDeliveryMethods.PutRequest | HttpDeliveryMethods.AuthorizationHeaderRequest));
+ }
+
+ /// <summary>
+ /// Verifies proper behavior of GetHttpVerb on invalid input.
+ /// </summary>
+ [TestMethod, ExpectedException(typeof(ArgumentException))]
+ public void GetHttpVerbOutOfRangeTest() {
+ MessagingUtilities.GetHttpVerb(HttpDeliveryMethods.PutRequest | HttpDeliveryMethods.PostRequest);
+ }
+
+ /// <summary>
+ /// Verifies proper behavior of GetHttpDeliveryMethod
+ /// </summary>
+ [TestMethod]
+ public void GetHttpDeliveryMethodTest() {
+ Assert.AreEqual(HttpDeliveryMethods.GetRequest, MessagingUtilities.GetHttpDeliveryMethod("GET"));
+ Assert.AreEqual(HttpDeliveryMethods.PostRequest, MessagingUtilities.GetHttpDeliveryMethod("POST"));
+ Assert.AreEqual(HttpDeliveryMethods.HeadRequest, MessagingUtilities.GetHttpDeliveryMethod("HEAD"));
+ Assert.AreEqual(HttpDeliveryMethods.PutRequest, MessagingUtilities.GetHttpDeliveryMethod("PUT"));
+ Assert.AreEqual(HttpDeliveryMethods.DeleteRequest, MessagingUtilities.GetHttpDeliveryMethod("DELETE"));
+ }
+
+ /// <summary>
+ /// Verifies proper behavior of GetHttpDeliveryMethod for an unexpected input
+ /// </summary>
+ [TestMethod, ExpectedException(typeof(ArgumentException))]
+ public void GetHttpDeliveryMethodOutOfRangeTest() {
+ MessagingUtilities.GetHttpDeliveryMethod("UNRECOGNIZED");
+ }
}
}
diff --git a/src/DotNetOpenAuth.Test/Messaging/MultipartPostPartTests.cs b/src/DotNetOpenAuth.Test/Messaging/MultipartPostPartTests.cs
new file mode 100644
index 0000000..57614ba
--- /dev/null
+++ b/src/DotNetOpenAuth.Test/Messaging/MultipartPostPartTests.cs
@@ -0,0 +1,108 @@
+//-----------------------------------------------------------------------
+// <copyright file="MultipartPostPartTests.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.Test.Messaging {
+ using System.CodeDom.Compiler;
+ using System.Collections.Generic;
+ using System.Diagnostics.Contracts;
+ using System.IO;
+ using System.Net;
+ using DotNetOpenAuth.Messaging;
+ using Microsoft.VisualStudio.TestTools.UnitTesting;
+
+ [TestClass]
+ public class MultipartPostPartTests : TestBase {
+ /// <summary>
+ /// Verifies that the Length property matches the length actually serialized.
+ /// </summary>
+ [TestMethod]
+ public void FormDataSerializeMatchesLength() {
+ var part = MultipartPostPart.CreateFormPart("a", "b");
+ VerifyLength(part);
+ }
+
+ /// <summary>
+ /// Verifies that the length property matches the length actually serialized.
+ /// </summary>
+ [TestMethod]
+ public void FileSerializeMatchesLength() {
+ using (TempFileCollection tfc = new TempFileCollection()) {
+ string file = tfc.AddExtension(".txt");
+ File.WriteAllText(file, "sometext");
+ var part = MultipartPostPart.CreateFormFilePart("someformname", file, "text/plain");
+ VerifyLength(part);
+ }
+ }
+
+ /// <summary>
+ /// Verifies file multiparts identify themselves as files and not merely form-data.
+ /// </summary>
+ [TestMethod]
+ public void FilePartAsFile() {
+ var part = MultipartPostPart.CreateFormFilePart("somename", "somefile", "plain/text", new MemoryStream());
+ Assert.AreEqual("file", part.ContentDisposition);
+ }
+
+ /// <summary>
+ /// Verifies MultiPartPost sends the right number of bytes.
+ /// </summary>
+ [TestMethod]
+ public void MultiPartPostAscii() {
+ using (TempFileCollection tfc = new TempFileCollection()) {
+ string file = tfc.AddExtension("txt");
+ File.WriteAllText(file, "sometext");
+ this.VerifyFullPost(new List<MultipartPostPart> {
+ MultipartPostPart.CreateFormPart("a", "b"),
+ MultipartPostPart.CreateFormFilePart("SomeFormField", file, "text/plain"),
+ });
+ }
+ }
+
+ /// <summary>
+ /// Verifies MultiPartPost sends the right number of bytes.
+ /// </summary>
+ [TestMethod]
+ public void MultiPartPostMultiByteCharacters() {
+ using (TempFileCollection tfc = new TempFileCollection()) {
+ string file = tfc.AddExtension("txt");
+ File.WriteAllText(file, "\x1020\x818");
+ this.VerifyFullPost(new List<MultipartPostPart> {
+ MultipartPostPart.CreateFormPart("a", "\x987"),
+ MultipartPostPart.CreateFormFilePart("SomeFormField", file, "text/plain"),
+ });
+ }
+ }
+
+ private static void VerifyLength(MultipartPostPart part) {
+ Contract.Requires(part != null);
+
+ var expectedLength = part.Length;
+ var ms = new MemoryStream();
+ var sw = new StreamWriter(ms);
+ part.Serialize(sw);
+ sw.Flush();
+ var actualLength = ms.Length;
+ Assert.AreEqual(expectedLength, actualLength);
+ }
+
+ private void VerifyFullPost(List<MultipartPostPart> parts) {
+ var request = (HttpWebRequest)WebRequest.Create("http://localhost");
+ var handler = new Mocks.TestWebRequestHandler();
+ bool posted = false;
+ handler.Callback = req => {
+ foreach (string header in req.Headers) {
+ TestContext.WriteLine("{0}: {1}", header, req.Headers[header]);
+ }
+ TestContext.WriteLine(handler.RequestEntityAsString);
+ Assert.AreEqual(req.ContentLength, handler.RequestEntityStream.Length);
+ posted = true;
+ return null;
+ };
+ request.PostMultipart(handler, parts);
+ Assert.IsTrue(posted, "HTTP POST never sent.");
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth.Test/Messaging/OutgoingWebResponseTests.cs b/src/DotNetOpenAuth.Test/Messaging/OutgoingWebResponseTests.cs
index 35f9259..2923af4 100644
--- a/src/DotNetOpenAuth.Test/Messaging/OutgoingWebResponseTests.cs
+++ b/src/DotNetOpenAuth.Test/Messaging/OutgoingWebResponseTests.cs
@@ -6,6 +6,7 @@
namespace DotNetOpenAuth.Test.Messaging {
using System.Net;
+ using System.Net.Mime;
using System.Text;
using DotNetOpenAuth.Messaging;
using Microsoft.VisualStudio.TestTools.UnitTesting;
@@ -30,7 +31,8 @@ namespace DotNetOpenAuth.Test.Messaging {
CollectionAssert.AreEqual(expectedBuffer, actualBuffer);
// Verify that the header was set correctly.
- Assert.AreEqual(encoding.HeaderName, response.Headers[HttpResponseHeader.ContentEncoding]);
+ Assert.IsNull(response.Headers[HttpResponseHeader.ContentEncoding]);
+ Assert.AreEqual(encoding.HeaderName, new ContentType(response.Headers[HttpResponseHeader.ContentType]).CharSet);
}
}
}
diff --git a/src/DotNetOpenAuth.Test/Messaging/ResponseTests.cs b/src/DotNetOpenAuth.Test/Messaging/ResponseTests.cs
index a0e7c3f..89d165a 100644
--- a/src/DotNetOpenAuth.Test/Messaging/ResponseTests.cs
+++ b/src/DotNetOpenAuth.Test/Messaging/ResponseTests.cs
@@ -15,6 +15,7 @@ namespace DotNetOpenAuth.Test.Messaging {
public class ResponseTests : TestBase {
[TestMethod, ExpectedException(typeof(InvalidOperationException))]
public void SendWithoutAspNetContext() {
+ HttpContext.Current = null;
new OutgoingWebResponse().Send();
}
diff --git a/src/DotNetOpenAuth.Test/Mocks/CoordinatingChannel.cs b/src/DotNetOpenAuth.Test/Mocks/CoordinatingChannel.cs
index 3bbe6e3..2f7c03c 100644
--- a/src/DotNetOpenAuth.Test/Mocks/CoordinatingChannel.cs
+++ b/src/DotNetOpenAuth.Test/Mocks/CoordinatingChannel.cs
@@ -7,6 +7,7 @@
namespace DotNetOpenAuth.Test.Mocks {
using System;
using System.Collections.Generic;
+ using System.Diagnostics.Contracts;
using System.Linq;
using System.Text;
using System.Threading;
@@ -84,7 +85,7 @@ namespace DotNetOpenAuth.Test.Mocks {
/// <param name="outgoingMessageFilter">The outgoing message filter. May be null.</param>
internal CoordinatingChannel(Channel wrappedChannel, Action<IProtocolMessage> incomingMessageFilter, Action<IProtocolMessage> outgoingMessageFilter)
: base(GetMessageFactory(wrappedChannel), wrappedChannel.BindingElements.ToArray()) {
- ErrorUtilities.VerifyArgumentNotNull(wrappedChannel, "wrappedChannel");
+ Contract.Requires<ArgumentNullException>(wrappedChannel != null);
this.wrappedChannel = wrappedChannel;
this.incomingMessageFilter = incomingMessageFilter;
@@ -199,13 +200,11 @@ namespace DotNetOpenAuth.Test.Mocks {
}
protected override IDictionary<string, string> ReadFromResponseCore(IncomingWebResponse response) {
- Channel_Accessor accessor = Channel_Accessor.AttachShadow(this.wrappedChannel);
- return accessor.ReadFromResponseCore(response);
+ return this.wrappedChannel.ReadFromResponseCoreTestHook(response);
}
protected override void ProcessIncomingMessage(IProtocolMessage message) {
- Channel_Accessor accessor = Channel_Accessor.AttachShadow(this.wrappedChannel);
- accessor.ProcessIncomingMessage(message);
+ this.wrappedChannel.ProcessIncomingMessageTestHook(message);
}
/// <summary>
@@ -220,7 +219,7 @@ namespace DotNetOpenAuth.Test.Mocks {
/// channel since their message factory is not used.
/// </remarks>
protected virtual T CloneSerializedParts<T>(T message) where T : class, IProtocolMessage {
- ErrorUtilities.VerifyArgumentNotNull(message, "message");
+ Contract.Requires<ArgumentNullException>(message != null);
IProtocolMessage clonedMessage;
var messageAccessor = this.MessageDescriptions.GetAccessor(message);
@@ -251,10 +250,9 @@ namespace DotNetOpenAuth.Test.Mocks {
}
private static IMessageFactory GetMessageFactory(Channel channel) {
- ErrorUtilities.VerifyArgumentNotNull(channel, "channel");
+ Contract.Requires<ArgumentNullException>(channel != null);
- Channel_Accessor accessor = Channel_Accessor.AttachShadow(channel);
- return accessor.MessageFactory;
+ return channel.MessageFactoryTestHook;
}
private IDictionary<string, string> AwaitIncomingMessage(out MessageReceivingEndpoint recipient) {
diff --git a/src/DotNetOpenAuth.Test/Mocks/CoordinatingOAuthChannel.cs b/src/DotNetOpenAuth.Test/Mocks/CoordinatingOAuthChannel.cs
index 10b0261..e862ca6 100644
--- a/src/DotNetOpenAuth.Test/Mocks/CoordinatingOAuthChannel.cs
+++ b/src/DotNetOpenAuth.Test/Mocks/CoordinatingOAuthChannel.cs
@@ -6,6 +6,7 @@
namespace DotNetOpenAuth.Test.Mocks {
using System;
+ using System.Diagnostics.Contracts;
using System.Threading;
using DotNetOpenAuth.Messaging;
using DotNetOpenAuth.Messaging.Bindings;
@@ -30,7 +31,7 @@ namespace DotNetOpenAuth.Test.Mocks {
internal CoordinatingOAuthChannel(ITamperProtectionChannelBindingElement signingBindingElement, IConsumerTokenManager tokenManager)
: base(
signingBindingElement,
- new NonceMemoryStore(StandardExpirationBindingElement.DefaultMaximumMessageAge),
+ new NonceMemoryStore(StandardExpirationBindingElement.MaximumMessageAge),
tokenManager) {
}
@@ -44,7 +45,7 @@ namespace DotNetOpenAuth.Test.Mocks {
internal CoordinatingOAuthChannel(ITamperProtectionChannelBindingElement signingBindingElement, IServiceProviderTokenManager tokenManager)
: base(
signingBindingElement,
- new NonceMemoryStore(StandardExpirationBindingElement.DefaultMaximumMessageAge),
+ new NonceMemoryStore(StandardExpirationBindingElement.MaximumMessageAge),
tokenManager) {
}
@@ -134,7 +135,7 @@ namespace DotNetOpenAuth.Test.Mocks {
}
private T CloneSerializedParts<T>(T message, HttpRequestInfo requestInfo) where T : class, IProtocolMessage {
- ErrorUtilities.VerifyArgumentNotNull(message, "message");
+ Contract.Requires<ArgumentNullException>(message != null);
IProtocolMessage clonedMessage;
var messageAccessor = this.MessageDescriptions.GetAccessor(message);
diff --git a/src/DotNetOpenAuth.Test/Mocks/CoordinatingOutgoingWebResponse.cs b/src/DotNetOpenAuth.Test/Mocks/CoordinatingOutgoingWebResponse.cs
index 07f9bc9..62ea871 100644
--- a/src/DotNetOpenAuth.Test/Mocks/CoordinatingOutgoingWebResponse.cs
+++ b/src/DotNetOpenAuth.Test/Mocks/CoordinatingOutgoingWebResponse.cs
@@ -7,6 +7,7 @@
namespace DotNetOpenAuth.Test.Mocks {
using System;
using System.Collections.Generic;
+ using System.Diagnostics.Contracts;
using System.Linq;
using System.Text;
using DotNetOpenAuth.Messaging;
@@ -20,8 +21,8 @@ namespace DotNetOpenAuth.Test.Mocks {
/// <param name="message">The direct response message to send to the remote channel. This message will be cloned.</param>
/// <param name="receivingChannel">The receiving channel.</param>
internal CoordinatingOutgoingWebResponse(IProtocolMessage message, CoordinatingChannel receivingChannel) {
- ErrorUtilities.VerifyArgumentNotNull(message, "message");
- ErrorUtilities.VerifyArgumentNotNull(receivingChannel, "receivingChannel");
+ Contract.Requires<ArgumentNullException>(message != null);
+ Contract.Requires<ArgumentNullException>(receivingChannel != null);
this.receivingChannel = receivingChannel;
this.OriginalMessage = message;
diff --git a/src/DotNetOpenAuth.Test/Mocks/InMemoryTokenManager.cs b/src/DotNetOpenAuth.Test/Mocks/InMemoryTokenManager.cs
index aae119d..e11854e 100644
--- a/src/DotNetOpenAuth.Test/Mocks/InMemoryTokenManager.cs
+++ b/src/DotNetOpenAuth.Test/Mocks/InMemoryTokenManager.cs
@@ -107,6 +107,10 @@ namespace DotNetOpenAuth.Test.Mocks {
return this.tokens[token];
}
+ public void UpdateToken(IServiceProviderRequestToken token) {
+ // Nothing to do here, since we're using Linq To SQL.
+ }
+
#endregion
/// <summary>
diff --git a/src/DotNetOpenAuth.Test/Mocks/MockHttpRequest.cs b/src/DotNetOpenAuth.Test/Mocks/MockHttpRequest.cs
index 66f258d..2dcbfec 100644
--- a/src/DotNetOpenAuth.Test/Mocks/MockHttpRequest.cs
+++ b/src/DotNetOpenAuth.Test/Mocks/MockHttpRequest.cs
@@ -7,6 +7,7 @@
namespace DotNetOpenAuth.Test.Mocks {
using System;
using System.Collections.Generic;
+ using System.Diagnostics.Contracts;
using System.Globalization;
using System.IO;
using System.Net;
@@ -22,7 +23,7 @@ namespace DotNetOpenAuth.Test.Mocks {
private readonly Dictionary<Uri, IncomingWebResponse> registeredMockResponses = new Dictionary<Uri, IncomingWebResponse>();
private MockHttpRequest(IDirectWebRequestHandler mockHandler) {
- ErrorUtilities.VerifyArgumentNotNull(mockHandler, "mockHandler");
+ Contract.Requires<ArgumentNullException>(mockHandler != null);
this.MockWebRequestHandler = mockHandler;
}
@@ -41,7 +42,7 @@ namespace DotNetOpenAuth.Test.Mocks {
}
internal void RegisterMockResponse(IncomingWebResponse response) {
- ErrorUtilities.VerifyArgumentNotNull(response, "response");
+ Contract.Requires<ArgumentNullException>(response != null);
if (this.registeredMockResponses.ContainsKey(response.RequestUri)) {
Logger.Http.WarnFormat("Mock HTTP response already registered for {0}.", response.RequestUri);
} else {
@@ -58,9 +59,9 @@ namespace DotNetOpenAuth.Test.Mocks {
}
internal void RegisterMockResponse(Uri requestUri, Uri responseUri, string contentType, WebHeaderCollection headers, string responseBody) {
- ErrorUtilities.VerifyArgumentNotNull(requestUri, "requestUri");
- ErrorUtilities.VerifyArgumentNotNull(responseUri, "responseUri");
- ErrorUtilities.VerifyNonZeroLength(contentType, "contentType");
+ Contract.Requires<ArgumentNullException>(requestUri != null);
+ Contract.Requires<ArgumentNullException>(responseUri != null);
+ Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(contentType));
// Set up the redirect if appropriate
if (requestUri != responseUri) {
@@ -83,7 +84,7 @@ namespace DotNetOpenAuth.Test.Mocks {
}
internal void RegisterMockXrdsResponse(ServiceEndpoint endpoint) {
- ErrorUtilities.VerifyArgumentNotNull(endpoint, "endpoint");
+ ErrorUtilities.VerifyArgumentNotNull(endpoint != null, "endpoint"); // CCBUG: Contract.Requires<ArgumentNullException>(endpoints != null);
string identityUri;
if (endpoint.ClaimedIdentifier == endpoint.Protocol.ClaimedIdentifierForOPIdentifier) {
@@ -95,7 +96,7 @@ namespace DotNetOpenAuth.Test.Mocks {
}
internal void RegisterMockXrdsResponse(Uri respondingUri, IEnumerable<ServiceEndpoint> endpoints) {
- ErrorUtilities.VerifyArgumentNotNull(endpoints, "endpoints");
+ Contract.Requires<ArgumentNullException>(endpoints != null);
StringBuilder xrds = new StringBuilder();
xrds.AppendLine(@"<xrds:XRDS xmlns:xrds='xri://$xrds' xmlns:openid='http://openid.net/xmlns/1.0' xmlns='xri://$xrd*($v*2.0)'>
diff --git a/src/DotNetOpenAuth.Test/Mocks/MockIdentifier.cs b/src/DotNetOpenAuth.Test/Mocks/MockIdentifier.cs
index 669e4d3..346dde9 100644
--- a/src/DotNetOpenAuth.Test/Mocks/MockIdentifier.cs
+++ b/src/DotNetOpenAuth.Test/Mocks/MockIdentifier.cs
@@ -7,6 +7,7 @@
namespace DotNetOpenAuth.Test.Mocks {
using System;
using System.Collections.Generic;
+ using System.Diagnostics.Contracts;
using DotNetOpenAuth.Messaging;
using DotNetOpenAuth.OpenId;
using DotNetOpenAuth.OpenId.RelyingParty;
@@ -24,10 +25,10 @@ namespace DotNetOpenAuth.Test.Mocks {
private Identifier wrappedIdentifier;
public MockIdentifier(Identifier wrappedIdentifier, MockHttpRequest mockHttpRequest, IEnumerable<ServiceEndpoint> endpoints)
- : base(false) {
- ErrorUtilities.VerifyArgumentNotNull(wrappedIdentifier, "wrappedIdentifier");
- ErrorUtilities.VerifyArgumentNotNull(mockHttpRequest, "mockHttpRequest");
- ErrorUtilities.VerifyArgumentNotNull(endpoints, "endpoints");
+ : base(wrappedIdentifier.OriginalString, false) {
+ Contract.Requires<ArgumentNullException>(wrappedIdentifier != null);
+ Contract.Requires<ArgumentNullException>(mockHttpRequest != null);
+ Contract.Requires<ArgumentNullException>(endpoints != null);
this.wrappedIdentifier = wrappedIdentifier;
this.endpoints = endpoints;
diff --git a/src/DotNetOpenAuth.Test/Mocks/MockRealm.cs b/src/DotNetOpenAuth.Test/Mocks/MockRealm.cs
index ae39ebb..dd17735 100644
--- a/src/DotNetOpenAuth.Test/Mocks/MockRealm.cs
+++ b/src/DotNetOpenAuth.Test/Mocks/MockRealm.cs
@@ -5,7 +5,9 @@
//-----------------------------------------------------------------------
namespace DotNetOpenAuth.Test.Mocks {
+ using System;
using System.Collections.Generic;
+ using System.Diagnostics.Contracts;
using DotNetOpenAuth.Messaging;
using DotNetOpenAuth.OpenId;
@@ -19,7 +21,7 @@ namespace DotNetOpenAuth.Test.Mocks {
/// <param name="relyingPartyDescriptions">The relying party descriptions.</param>
internal MockRealm(Realm wrappedRealm, params RelyingPartyEndpointDescription[] relyingPartyDescriptions)
: base(wrappedRealm) {
- ErrorUtilities.VerifyArgumentNotNull(relyingPartyDescriptions, "relyingPartyDescriptions");
+ Contract.Requires<ArgumentNullException>(relyingPartyDescriptions != null);
this.relyingPartyDescriptions = relyingPartyDescriptions;
}
diff --git a/src/DotNetOpenAuth.Test/Mocks/TestDirectedMessage.cs b/src/DotNetOpenAuth.Test/Mocks/TestDirectedMessage.cs
index 342a303..1b3c2b2 100644
--- a/src/DotNetOpenAuth.Test/Mocks/TestDirectedMessage.cs
+++ b/src/DotNetOpenAuth.Test/Mocks/TestDirectedMessage.cs
@@ -11,11 +11,11 @@ namespace DotNetOpenAuth.Test.Mocks {
internal class TestDirectedMessage : TestMessage, IDirectedProtocolMessage {
internal TestDirectedMessage() {
- this.HttpMethods = HttpDeliveryMethods.GetRequest | HttpDeliveryMethods.PostRequest;
+ this.HttpMethods = HttpDeliveryMethods.GetRequest | HttpDeliveryMethods.PostRequest | HttpDeliveryMethods.HeadRequest;
}
internal TestDirectedMessage(MessageTransport transport) : base(transport) {
- this.HttpMethods = HttpDeliveryMethods.GetRequest | HttpDeliveryMethods.PostRequest;
+ this.HttpMethods = HttpDeliveryMethods.GetRequest | HttpDeliveryMethods.PostRequest | HttpDeliveryMethods.HeadRequest;
}
#region IDirectedProtocolMessage Members
diff --git a/src/DotNetOpenAuth.Test/Mocks/TestMessageFactory.cs b/src/DotNetOpenAuth.Test/Mocks/TestMessageFactory.cs
index ffb117c..7b13175 100644
--- a/src/DotNetOpenAuth.Test/Mocks/TestMessageFactory.cs
+++ b/src/DotNetOpenAuth.Test/Mocks/TestMessageFactory.cs
@@ -7,6 +7,7 @@
namespace DotNetOpenAuth.Test.Mocks {
using System;
using System.Collections.Generic;
+ using System.Diagnostics.Contracts;
using System.Linq;
using System.Text;
using DotNetOpenAuth.Messaging;
@@ -32,8 +33,6 @@ namespace DotNetOpenAuth.Test.Mocks {
#region IMessageFactory Members
public IDirectedProtocolMessage GetNewRequestMessage(MessageReceivingEndpoint recipient, IDictionary<string, string> fields) {
- ErrorUtilities.VerifyArgumentNotNull(fields, "fields");
-
if (fields.ContainsKey("age")) {
if (this.signedMessages) {
if (this.expiringMessages) {
diff --git a/src/DotNetOpenAuth.Test/Mocks/TestWebRequestHandler.cs b/src/DotNetOpenAuth.Test/Mocks/TestWebRequestHandler.cs
index b74c0f0..03dbd6b 100644
--- a/src/DotNetOpenAuth.Test/Mocks/TestWebRequestHandler.cs
+++ b/src/DotNetOpenAuth.Test/Mocks/TestWebRequestHandler.cs
@@ -56,7 +56,7 @@ namespace DotNetOpenAuth.Test.Mocks {
#region IWebRequestHandler Members
public bool CanSupport(DirectWebRequestOptions options) {
- return options == DirectWebRequestOptions.None;
+ return true;
}
/// <summary>
diff --git a/src/DotNetOpenAuth.Test/OAuth/ChannelElements/HmacSha1SigningBindingElementTests.cs b/src/DotNetOpenAuth.Test/OAuth/ChannelElements/HmacSha1SigningBindingElementTests.cs
index 6477510..7191709 100644
--- a/src/DotNetOpenAuth.Test/OAuth/ChannelElements/HmacSha1SigningBindingElementTests.cs
+++ b/src/DotNetOpenAuth.Test/OAuth/ChannelElements/HmacSha1SigningBindingElementTests.cs
@@ -16,9 +16,9 @@ namespace DotNetOpenAuth.Test.OAuth.ChannelElements {
public void SignatureTest() {
UnauthorizedTokenRequest message = SigningBindingElementBaseTests.CreateTestRequestTokenMessage(this.MessageDescriptions, null);
- HmacSha1SigningBindingElement_Accessor hmac = new HmacSha1SigningBindingElement_Accessor();
+ var hmac = new HmacSha1SigningBindingElement();
hmac.Channel = new TestChannel(this.MessageDescriptions);
- Assert.AreEqual("kR0LhH8UqylaLfR/esXVVlP4sQI=", hmac.GetSignature(message));
+ Assert.AreEqual("kR0LhH8UqylaLfR/esXVVlP4sQI=", hmac.GetSignatureTestHook(message));
}
}
}
diff --git a/src/DotNetOpenAuth.Test/OAuth/ChannelElements/OAuthChannelTests.cs b/src/DotNetOpenAuth.Test/OAuth/ChannelElements/OAuthChannelTests.cs
index e215bc1..532091b 100644
--- a/src/DotNetOpenAuth.Test/OAuth/ChannelElements/OAuthChannelTests.cs
+++ b/src/DotNetOpenAuth.Test/OAuth/ChannelElements/OAuthChannelTests.cs
@@ -8,6 +8,7 @@ namespace DotNetOpenAuth.Test.OAuth.ChannelElements {
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
+ using System.Diagnostics.Contracts;
using System.IO;
using System.Net;
using System.Text;
@@ -23,7 +24,6 @@ namespace DotNetOpenAuth.Test.OAuth.ChannelElements {
[TestClass]
public class OAuthChannelTests : TestBase {
private OAuthChannel channel;
- private OAuthChannel_Accessor accessor;
private TestWebRequestHandler webRequestHandler;
private SigningBindingElementBase signingElement;
private INonceStore nonceStore;
@@ -34,13 +34,12 @@ namespace DotNetOpenAuth.Test.OAuth.ChannelElements {
this.webRequestHandler = new TestWebRequestHandler();
this.signingElement = new RsaSha1SigningBindingElement(new InMemoryTokenManager());
- this.nonceStore = new NonceMemoryStore(StandardExpirationBindingElement.DefaultMaximumMessageAge);
+ this.nonceStore = new NonceMemoryStore(StandardExpirationBindingElement.MaximumMessageAge);
this.channel = new OAuthChannel(this.signingElement, this.nonceStore, new InMemoryTokenManager(), new TestMessageFactory());
- this.accessor = OAuthChannel_Accessor.AttachShadow(this.channel);
this.channel.WebRequestHandler = this.webRequestHandler;
}
- [TestMethod, ExpectedException(typeof(ArgumentException))]
+ [TestMethod, ExpectedException(typeof(ArgumentNullException))]
public void CtorNullSigner() {
new OAuthChannel(null, this.nonceStore, new InMemoryTokenManager(), new TestMessageFactory());
}
@@ -148,8 +147,7 @@ namespace DotNetOpenAuth.Test.OAuth.ChannelElements {
writer.Write(MessagingUtilities.CreateQueryString(fields));
writer.Flush();
ms.Seek(0, SeekOrigin.Begin);
- Channel_Accessor channelAccessor = Channel_Accessor.AttachShadow(this.channel);
- IDictionary<string, string> deserializedFields = channelAccessor.ReadFromResponseCore(new CachedDirectWebResponse { CachedResponseStream = ms });
+ IDictionary<string, string> deserializedFields = this.channel.ReadFromResponseCoreTestHook(new CachedDirectWebResponse { CachedResponseStream = ms });
Assert.AreEqual(fields.Count, deserializedFields.Count);
foreach (string key in fields.Keys) {
Assert.AreEqual(fields[key], deserializedFields[key]);
@@ -226,24 +224,29 @@ namespace DotNetOpenAuth.Test.OAuth.ChannelElements {
this.ParameterizedRequestTest(HttpDeliveryMethods.PostRequest);
}
+ [TestMethod]
+ public void RequestUsingHead() {
+ this.ParameterizedRequestTest(HttpDeliveryMethods.HeadRequest);
+ }
+
/// <summary>
/// Verifies that messages asking for special HTTP status codes get them.
/// </summary>
[TestMethod]
public void SendDirectMessageResponseHonorsHttpStatusCodes() {
IProtocolMessage message = MessagingTestBase.GetStandardTestMessage(MessagingTestBase.FieldFill.AllRequired);
- OutgoingWebResponse directResponse = this.accessor.PrepareDirectResponse(message);
+ OutgoingWebResponse directResponse = this.channel.PrepareDirectResponseTestHook(message);
Assert.AreEqual(HttpStatusCode.OK, directResponse.Status);
var httpMessage = new TestDirectResponseMessageWithHttpStatus();
MessagingTestBase.GetStandardTestMessage(MessagingTestBase.FieldFill.AllRequired, httpMessage);
httpMessage.HttpStatusCode = HttpStatusCode.NotAcceptable;
- directResponse = this.accessor.PrepareDirectResponse(httpMessage);
+ directResponse = this.channel.PrepareDirectResponseTestHook(httpMessage);
Assert.AreEqual(HttpStatusCode.NotAcceptable, directResponse.Status);
}
private static string CreateAuthorizationHeader(IDictionary<string, string> fields) {
- ErrorUtilities.VerifyArgumentNotNull(fields, "fields");
+ Contract.Requires<ArgumentNullException>(fields != null);
StringBuilder authorization = new StringBuilder();
authorization.Append("OAuth ");
@@ -322,7 +325,7 @@ namespace DotNetOpenAuth.Test.OAuth.ChannelElements {
this.webRequestHandler.Callback = (req) => {
Assert.IsNotNull(req);
HttpRequestInfo reqInfo = ConvertToRequestInfo(req, this.webRequestHandler.RequestEntityStream);
- Assert.AreEqual(scheme == HttpDeliveryMethods.PostRequest ? "POST" : "GET", reqInfo.HttpMethod);
+ Assert.AreEqual(MessagingUtilities.GetHttpVerb(scheme), reqInfo.HttpMethod);
var incomingMessage = this.channel.ReadFromRequest(reqInfo) as TestMessage;
Assert.IsNotNull(incomingMessage);
Assert.AreEqual(request.Age, incomingMessage.Age);
diff --git a/src/DotNetOpenAuth.Test/OAuth/ChannelElements/PlaintextSigningBindingElementTest.cs b/src/DotNetOpenAuth.Test/OAuth/ChannelElements/PlaintextSigningBindingElementTest.cs
index 80a1c01..b69e11c 100644
--- a/src/DotNetOpenAuth.Test/OAuth/ChannelElements/PlaintextSigningBindingElementTest.cs
+++ b/src/DotNetOpenAuth.Test/OAuth/ChannelElements/PlaintextSigningBindingElementTest.cs
@@ -9,6 +9,7 @@ namespace DotNetOpenAuth.Test.OAuth.ChannelElements {
using DotNetOpenAuth.OAuth;
using DotNetOpenAuth.OAuth.ChannelElements;
using DotNetOpenAuth.OAuth.Messages;
+ using DotNetOpenAuth.Test.Mocks;
using Microsoft.VisualStudio.TestTools.UnitTesting;
[TestClass]
@@ -16,6 +17,7 @@ namespace DotNetOpenAuth.Test.OAuth.ChannelElements {
[TestMethod]
public void HttpsSignatureGeneration() {
SigningBindingElementBase target = new PlaintextSigningBindingElement();
+ target.Channel = new TestChannel();
MessageReceivingEndpoint endpoint = new MessageReceivingEndpoint("https://localtest", HttpDeliveryMethods.GetRequest);
ITamperResistantOAuthMessage message = new UnauthorizedTokenRequest(endpoint, Protocol.Default.Version);
message.ConsumerSecret = "cs";
@@ -29,6 +31,7 @@ namespace DotNetOpenAuth.Test.OAuth.ChannelElements {
public void HttpsSignatureVerification() {
MessageReceivingEndpoint endpoint = new MessageReceivingEndpoint("https://localtest", HttpDeliveryMethods.GetRequest);
ITamperProtectionChannelBindingElement target = new PlaintextSigningBindingElement();
+ target.Channel = new TestChannel();
ITamperResistantOAuthMessage message = new UnauthorizedTokenRequest(endpoint, Protocol.Default.Version);
message.ConsumerSecret = "cs";
message.TokenSecret = "ts";
@@ -40,6 +43,7 @@ namespace DotNetOpenAuth.Test.OAuth.ChannelElements {
[TestMethod]
public void HttpsSignatureVerificationNotApplicable() {
SigningBindingElementBase target = new PlaintextSigningBindingElement();
+ target.Channel = new TestChannel();
MessageReceivingEndpoint endpoint = new MessageReceivingEndpoint("https://localtest", HttpDeliveryMethods.GetRequest);
ITamperResistantOAuthMessage message = new UnauthorizedTokenRequest(endpoint, Protocol.Default.Version);
message.ConsumerSecret = "cs";
@@ -52,6 +56,7 @@ namespace DotNetOpenAuth.Test.OAuth.ChannelElements {
[TestMethod]
public void HttpSignatureGeneration() {
SigningBindingElementBase target = new PlaintextSigningBindingElement();
+ target.Channel = new TestChannel();
MessageReceivingEndpoint endpoint = new MessageReceivingEndpoint("http://localtest", HttpDeliveryMethods.GetRequest);
ITamperResistantOAuthMessage message = new UnauthorizedTokenRequest(endpoint, Protocol.Default.Version);
message.ConsumerSecret = "cs";
@@ -66,6 +71,7 @@ namespace DotNetOpenAuth.Test.OAuth.ChannelElements {
[TestMethod]
public void HttpSignatureVerification() {
SigningBindingElementBase target = new PlaintextSigningBindingElement();
+ target.Channel = new TestChannel();
MessageReceivingEndpoint endpoint = new MessageReceivingEndpoint("http://localtest", HttpDeliveryMethods.GetRequest);
ITamperResistantOAuthMessage message = new UnauthorizedTokenRequest(endpoint, Protocol.Default.Version);
message.ConsumerSecret = "cs";
diff --git a/src/DotNetOpenAuth.Test/OAuth/ChannelElements/SigningBindingElementBaseTests.cs b/src/DotNetOpenAuth.Test/OAuth/ChannelElements/SigningBindingElementBaseTests.cs
index 49549f5..f4063c2 100644
--- a/src/DotNetOpenAuth.Test/OAuth/ChannelElements/SigningBindingElementBaseTests.cs
+++ b/src/DotNetOpenAuth.Test/OAuth/ChannelElements/SigningBindingElementBaseTests.cs
@@ -22,7 +22,7 @@ namespace DotNetOpenAuth.Test.OAuth.ChannelElements {
new MessageReceivingEndpoint("https://www.google.com/accounts/OAuthGetRequestToken", HttpDeliveryMethods.AuthorizationHeaderRequest | HttpDeliveryMethods.GetRequest));
Assert.AreEqual(
"GET&https%3A%2F%2Fwww.google.com%2Faccounts%2FOAuthGetRequestToken&oauth_consumer_key%3Dnerdbank.org%26oauth_nonce%3Dfe4045a3f0efdd1e019fa8f8ae3f5c38%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1222665749%26oauth_version%3D1.0%26scope%3Dhttp%253A%252F%252Fwww.google.com%252Fm8%252Ffeeds%252F",
- SigningBindingElementBase_Accessor.ConstructSignatureBaseString(message, MessageDictionary_Accessor.AttachShadow(this.MessageDescriptions.GetAccessor(message))));
+ SigningBindingElementBase.ConstructSignatureBaseString(message, this.MessageDescriptions.GetAccessor(message)));
// Test HTTP GET with an attached query string. We're elevating the scope parameter to the query string
// and removing it from the extradata dictionary. This should NOT affect the base signature string.
@@ -32,7 +32,7 @@ namespace DotNetOpenAuth.Test.OAuth.ChannelElements {
message.ExtraData.Remove("scope"); // remove it from ExtraData since we put it in the URL
Assert.AreEqual(
"GET&https%3A%2F%2Fwww.google.com%2Faccounts%2FOAuthGetRequestToken&oauth_consumer_key%3Dnerdbank.org%26oauth_nonce%3Dfe4045a3f0efdd1e019fa8f8ae3f5c38%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1222665749%26oauth_version%3D1.0%26scope%3Dhttp%253A%252F%252Fwww.google.com%252Fm8%252Ffeeds%252F",
- SigningBindingElementBase_Accessor.ConstructSignatureBaseString(message, MessageDictionary_Accessor.AttachShadow(this.MessageDescriptions.GetAccessor(message))));
+ SigningBindingElementBase.ConstructSignatureBaseString(message, this.MessageDescriptions.GetAccessor(message)));
// Test HTTP POST, with query string as well
message = CreateTestRequestTokenMessage(
@@ -41,7 +41,7 @@ namespace DotNetOpenAuth.Test.OAuth.ChannelElements {
message.ExtraData.Remove("scope"); // remove it from ExtraData since we put it in the URL
Assert.AreEqual(
"GET&https%3A%2F%2Fwww.google.com%2Faccounts%2FOAuthGetRequestToken&oauth_consumer_key%3Dnerdbank.org%26oauth_nonce%3Dfe4045a3f0efdd1e019fa8f8ae3f5c38%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1222665749%26oauth_version%3D1.0%26scope%3Dhttp%253A%252F%252Fwww.google.com%252Fm8%252Ffeeds%252F",
- SigningBindingElementBase_Accessor.ConstructSignatureBaseString(message, MessageDictionary_Accessor.AttachShadow(this.MessageDescriptions.GetAccessor(message))));
+ SigningBindingElementBase.ConstructSignatureBaseString(message, this.MessageDescriptions.GetAccessor(message)));
// Test HTTP POST, with query string, but not using the Authorization header
message = CreateTestRequestTokenMessage(
@@ -50,7 +50,7 @@ namespace DotNetOpenAuth.Test.OAuth.ChannelElements {
message.ExtraData.Remove("scope"); // remove it from ExtraData since we put it in the URL
Assert.AreEqual(
"GET&https%3A%2F%2Fwww.google.com%2Faccounts%2FOAuthGetRequestToken&oauth_consumer_key%3Dnerdbank.org%26oauth_nonce%3Dfe4045a3f0efdd1e019fa8f8ae3f5c38%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1222665749%26oauth_version%3D1.0%26scope%3Dhttp%253A%252F%252Fwww.google.com%252Fm8%252Ffeeds%252F",
- SigningBindingElementBase_Accessor.ConstructSignatureBaseString(message, MessageDictionary_Accessor.AttachShadow(this.MessageDescriptions.GetAccessor(message))));
+ SigningBindingElementBase.ConstructSignatureBaseString(message, this.MessageDescriptions.GetAccessor(message)));
// This is a simulation of receiving the message, where the query string is still in the URL,
// but has been read into ExtraData, so parameters in the query string appear twice.
@@ -59,7 +59,7 @@ namespace DotNetOpenAuth.Test.OAuth.ChannelElements {
new MessageReceivingEndpoint("https://www.google.com/accounts/OAuthGetRequestToken?scope=http://www.google.com/m8/feeds/", HttpDeliveryMethods.AuthorizationHeaderRequest | HttpDeliveryMethods.PostRequest));
Assert.AreEqual(
"GET&https%3A%2F%2Fwww.google.com%2Faccounts%2FOAuthGetRequestToken&oauth_consumer_key%3Dnerdbank.org%26oauth_nonce%3Dfe4045a3f0efdd1e019fa8f8ae3f5c38%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1222665749%26oauth_version%3D1.0%26scope%3Dhttp%253A%252F%252Fwww.google.com%252Fm8%252Ffeeds%252F",
- SigningBindingElementBase_Accessor.ConstructSignatureBaseString(message, MessageDictionary_Accessor.AttachShadow(this.MessageDescriptions.GetAccessor(message))));
+ SigningBindingElementBase.ConstructSignatureBaseString(message, this.MessageDescriptions.GetAccessor(message)));
}
internal static UnauthorizedTokenRequest CreateTestRequestTokenMessage(MessageDescriptionCollection messageDescriptions, MessageReceivingEndpoint endpoint) {
diff --git a/src/DotNetOpenAuth.Test/OAuth/OAuthCoordinator.cs b/src/DotNetOpenAuth.Test/OAuth/OAuthCoordinator.cs
index c3ef6c2..972dd2a 100644
--- a/src/DotNetOpenAuth.Test/OAuth/OAuthCoordinator.cs
+++ b/src/DotNetOpenAuth.Test/OAuth/OAuthCoordinator.cs
@@ -6,6 +6,7 @@
namespace DotNetOpenAuth.Test.OAuth {
using System;
+ using System.Diagnostics.Contracts;
using DotNetOpenAuth.Messaging;
using DotNetOpenAuth.Messaging.Bindings;
using DotNetOpenAuth.OAuth;
@@ -26,8 +27,8 @@ namespace DotNetOpenAuth.Test.OAuth {
/// <param name="serviceProviderAction">The code path of the Service Provider.</param>
internal OAuthCoordinator(ConsumerDescription consumerDescription, ServiceProviderDescription serviceDescription, Action<WebConsumer> consumerAction, Action<ServiceProvider> serviceProviderAction)
: base(consumerAction, serviceProviderAction) {
- ErrorUtilities.VerifyArgumentNotNull(consumerDescription, "consumerDescription");
- ErrorUtilities.VerifyArgumentNotNull(serviceDescription, "serviceDescription");
+ Contract.Requires<ArgumentNullException>(consumerDescription != null);
+ Contract.Requires<ArgumentNullException>(serviceDescription != null);
this.consumerDescription = consumerDescription;
this.serviceDescription = serviceDescription;
diff --git a/src/DotNetOpenAuth.Test/OpenId/AssociationHandshakeTests.cs b/src/DotNetOpenAuth.Test/OpenId/AssociationHandshakeTests.cs
index af3b1b1..4e7b922 100644
--- a/src/DotNetOpenAuth.Test/OpenId/AssociationHandshakeTests.cs
+++ b/src/DotNetOpenAuth.Test/OpenId/AssociationHandshakeTests.cs
@@ -80,24 +80,22 @@ namespace DotNetOpenAuth.Test.OpenId {
op.SecuritySettings.MaximumHashBitLength = 160; // Force OP to reject HMAC-SHA256
// Receive initial request for an HMAC-SHA256 association.
- AutoResponsiveRequest req = (AutoResponsiveRequest) op.GetRequest();
- AutoResponsiveRequest_Accessor reqAccessor = AutoResponsiveRequest_Accessor.AttachShadow(req);
- AssociateRequest associateRequest = (AssociateRequest)reqAccessor.RequestMessage;
+ AutoResponsiveRequest req = (AutoResponsiveRequest)op.GetRequest();
+ AssociateRequest associateRequest = (AssociateRequest)req.RequestMessage;
Assert.AreEqual(protocol.Args.SignatureAlgorithm.HMAC_SHA256, associateRequest.AssociationType);
// Ensure that the response is a suggestion that the RP try again with HMAC-SHA1
- AssociateUnsuccessfulResponse renegotiateResponse = (AssociateUnsuccessfulResponse)reqAccessor.ResponseMessage;
+ AssociateUnsuccessfulResponse renegotiateResponse = (AssociateUnsuccessfulResponse)req.ResponseMessageTestHook;
Assert.AreEqual(protocol.Args.SignatureAlgorithm.HMAC_SHA1, renegotiateResponse.AssociationType);
op.SendResponse(req);
// Receive second attempt request for an HMAC-SHA1 association.
req = (AutoResponsiveRequest)op.GetRequest();
- reqAccessor = AutoResponsiveRequest_Accessor.AttachShadow(req);
- associateRequest = (AssociateRequest)reqAccessor.RequestMessage;
+ associateRequest = (AssociateRequest)req.RequestMessage;
Assert.AreEqual(protocol.Args.SignatureAlgorithm.HMAC_SHA1, associateRequest.AssociationType);
// Ensure that the response is a success response.
- AssociateSuccessfulResponse successResponse = (AssociateSuccessfulResponse)reqAccessor.ResponseMessage;
+ AssociateSuccessfulResponse successResponse = (AssociateSuccessfulResponse)req.ResponseMessageTestHook;
Assert.AreEqual(protocol.Args.SignatureAlgorithm.HMAC_SHA1, successResponse.AssociationType);
op.SendResponse(req);
});
@@ -352,11 +350,9 @@ namespace DotNetOpenAuth.Test.OpenId {
};
coordinator.Run();
- var associationManagerAccessor = AssociationManager_Accessor.AttachShadow(coordinator.RelyingParty.AssociationManager);
-
if (expectSuccess) {
Assert.IsNotNull(rpAssociation);
- Assert.AreSame(rpAssociation, associationManagerAccessor.associationStore.GetAssociation(opDescription.Endpoint, rpAssociation.Handle));
+ Assert.AreSame(rpAssociation, coordinator.RelyingParty.AssociationManager.AssociationStoreTestHook.GetAssociation(opDescription.Endpoint, rpAssociation.Handle));
opAssociation = coordinator.Provider.AssociationStore.GetAssociation(AssociationRelyingPartyType.Smart, rpAssociation.Handle);
Assert.IsNotNull(opAssociation, "The Provider should have stored the association.");
@@ -375,7 +371,7 @@ namespace DotNetOpenAuth.Test.OpenId {
var unencryptedResponse = (AssociateUnencryptedResponse)associateSuccessfulResponse;
}
} else {
- Assert.IsNull(associationManagerAccessor.associationStore.GetAssociation(opDescription.Endpoint, new RelyingPartySecuritySettings()));
+ Assert.IsNull(coordinator.RelyingParty.AssociationManager.AssociationStoreTestHook.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 4ebdf74..7de2a8b 100644
--- a/src/DotNetOpenAuth.Test/OpenId/AuthenticationTests.cs
+++ b/src/DotNetOpenAuth.Test/OpenId/AuthenticationTests.cs
@@ -6,6 +6,7 @@
namespace DotNetOpenAuth.Test.OpenId {
using System;
+ using System.Diagnostics.Contracts;
using DotNetOpenAuth.Messaging;
using DotNetOpenAuth.Messaging.Bindings;
using DotNetOpenAuth.OpenId;
@@ -135,8 +136,8 @@ namespace DotNetOpenAuth.Test.OpenId {
}
private void ParameterizedAuthenticationTest(Protocol protocol, bool statelessRP, bool sharedAssociation, bool positive, bool immediate, bool tamper) {
- ErrorUtilities.VerifyArgument(!statelessRP || !sharedAssociation, "The RP cannot be stateless while sharing an association with the OP.");
- ErrorUtilities.VerifyArgument(positive || !tamper, "Cannot tamper with a negative response.");
+ Contract.Requires<ArgumentException>(!statelessRP || !sharedAssociation, "The RP cannot be stateless while sharing an association with the OP.");
+ Contract.Requires<ArgumentException>(positive || !tamper, "Cannot tamper with a negative response.");
ProviderSecuritySettings securitySettings = new ProviderSecuritySettings();
Association association = sharedAssociation ? HmacShaAssociation.Create(protocol, protocol.Args.SignatureAlgorithm.Best, AssociationRelyingPartyType.Smart, securitySettings) : null;
var coordinator = new OpenIdCoordinator(
diff --git a/src/DotNetOpenAuth.Test/OpenId/ChannelElements/ExtensionsBindingElementTests.cs b/src/DotNetOpenAuth.Test/OpenId/ChannelElements/ExtensionsBindingElementTests.cs
index 5af1caf..29797dc 100644
--- a/src/DotNetOpenAuth.Test/OpenId/ChannelElements/ExtensionsBindingElementTests.cs
+++ b/src/DotNetOpenAuth.Test/OpenId/ChannelElements/ExtensionsBindingElementTests.cs
@@ -7,6 +7,7 @@
namespace DotNetOpenAuth.Test.OpenId.ChannelElements {
using System;
using System.Collections.Generic;
+ using System.Diagnostics.Contracts;
using System.Linq;
using System.Text.RegularExpressions;
using DotNetOpenAuth.Messaging;
@@ -167,7 +168,7 @@ namespace DotNetOpenAuth.Test.OpenId.ChannelElements {
}
private static void RegisterMockExtension(Channel channel) {
- ErrorUtilities.VerifyArgumentNotNull(channel, "channel");
+ Contract.Requires<ArgumentNullException>(channel != null);
ExtensionTestUtilities.RegisterExtension(channel, MockOpenIdExtension.Factory);
}
@@ -178,7 +179,7 @@ namespace DotNetOpenAuth.Test.OpenId.ChannelElements {
/// <param name="protocol">The protocol to construct the message with.</param>
/// <returns>The message ready to send from OP to RP.</returns>
private IndirectSignedResponse CreateResponseWithExtensions(Protocol protocol) {
- ErrorUtilities.VerifyArgumentNotNull(protocol, "protocol");
+ Contract.Requires<ArgumentNullException>(protocol != null);
IndirectSignedResponse response = new IndirectSignedResponse(protocol.Version, RPUri);
response.ProviderEndpoint = OPUri;
diff --git a/src/DotNetOpenAuth.Test/OpenId/ChannelElements/OpenIdChannelTests.cs b/src/DotNetOpenAuth.Test/OpenId/ChannelElements/OpenIdChannelTests.cs
index 385cd19..c9632e1 100644
--- a/src/DotNetOpenAuth.Test/OpenId/ChannelElements/OpenIdChannelTests.cs
+++ b/src/DotNetOpenAuth.Test/OpenId/ChannelElements/OpenIdChannelTests.cs
@@ -24,14 +24,12 @@ namespace DotNetOpenAuth.Test.OpenId.ChannelElements {
public class OpenIdChannelTests : TestBase {
private static readonly TimeSpan maximumMessageAge = TimeSpan.FromHours(3); // good for tests, too long for production
private OpenIdChannel channel;
- private OpenIdChannel_Accessor accessor;
private Mocks.TestWebRequestHandler webHandler;
[TestInitialize]
public void Setup() {
this.webHandler = new Mocks.TestWebRequestHandler();
this.channel = new OpenIdChannel(new AssociationMemoryStore<Uri>(), new NonceMemoryStore(maximumMessageAge), new RelyingPartySecuritySettings());
- this.accessor = OpenIdChannel_Accessor.AttachShadow(this.channel);
this.channel.WebRequestHandler = this.webHandler;
}
@@ -59,7 +57,7 @@ namespace DotNetOpenAuth.Test.OpenId.ChannelElements {
Recipient = new Uri("http://host"),
Name = "Andrew",
};
- HttpWebRequest httpRequest = this.accessor.CreateHttpRequest(requestMessage);
+ HttpWebRequest httpRequest = this.channel.CreateHttpRequestTestHook(requestMessage);
Assert.AreEqual("POST", httpRequest.Method);
StringAssert.Contains(this.webHandler.RequestEntityAsString, "Name=Andrew");
}
@@ -78,9 +76,9 @@ namespace DotNetOpenAuth.Test.OpenId.ChannelElements {
IProtocolMessage message = MessagingTestBase.GetStandardTestMessage(MessagingTestBase.FieldFill.AllRequired);
MessageDictionary messageFields = this.MessageDescriptions.GetAccessor(message);
byte[] expectedBytes = KeyValueFormEncoding.GetBytes(messageFields);
- string expectedContentType = OpenIdChannel_Accessor.KeyValueFormContentType;
+ string expectedContentType = OpenIdChannel.KeyValueFormContentType;
- OutgoingWebResponse directResponse = this.accessor.PrepareDirectResponse(message);
+ 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);
@@ -99,7 +97,7 @@ namespace DotNetOpenAuth.Test.OpenId.ChannelElements {
var response = new CachedDirectWebResponse {
CachedResponseStream = new MemoryStream(KeyValueFormEncoding.GetBytes(fields)),
};
- Assert.IsTrue(MessagingUtilities.AreEquivalent(fields, this.accessor.ReadFromResponseCore(response)));
+ Assert.IsTrue(MessagingUtilities.AreEquivalent(fields, this.channel.ReadFromResponseCoreTestHook(response)));
}
/// <summary>
@@ -108,13 +106,13 @@ namespace DotNetOpenAuth.Test.OpenId.ChannelElements {
[TestMethod]
public void SendDirectMessageResponseHonorsHttpStatusCodes() {
IProtocolMessage message = MessagingTestBase.GetStandardTestMessage(MessagingTestBase.FieldFill.AllRequired);
- OutgoingWebResponse directResponse = this.accessor.PrepareDirectResponse(message);
+ OutgoingWebResponse directResponse = this.channel.PrepareDirectResponseTestHook(message);
Assert.AreEqual(HttpStatusCode.OK, directResponse.Status);
var httpMessage = new TestDirectResponseMessageWithHttpStatus();
MessagingTestBase.GetStandardTestMessage(MessagingTestBase.FieldFill.AllRequired, httpMessage);
httpMessage.HttpStatusCode = HttpStatusCode.NotAcceptable;
- directResponse = this.accessor.PrepareDirectResponse(httpMessage);
+ directResponse = this.channel.PrepareDirectResponseTestHook(httpMessage);
Assert.AreEqual(HttpStatusCode.NotAcceptable, directResponse.Status);
}
}
diff --git a/src/DotNetOpenAuth.Test/OpenId/Extensions/AttributeExchange/AttributeRequestTests.cs b/src/DotNetOpenAuth.Test/OpenId/Extensions/AttributeExchange/AttributeRequestTests.cs
index 228bda3..48b5727 100644
--- a/src/DotNetOpenAuth.Test/OpenId/Extensions/AttributeExchange/AttributeRequestTests.cs
+++ b/src/DotNetOpenAuth.Test/OpenId/Extensions/AttributeExchange/AttributeRequestTests.cs
@@ -25,7 +25,7 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions {
new AttributeRequest(string.Empty);
}
- [TestMethod, ExpectedException(typeof(ArgumentNullException))]
+ [TestMethod, ExpectedException(typeof(ArgumentException))]
public void CtorNullTypeUri() {
new AttributeRequest(null);
}
diff --git a/src/DotNetOpenAuth.Test/OpenId/Extensions/ExtensionTestUtilities.cs b/src/DotNetOpenAuth.Test/OpenId/Extensions/ExtensionTestUtilities.cs
index 47c8ec4..334fc93 100644
--- a/src/DotNetOpenAuth.Test/OpenId/Extensions/ExtensionTestUtilities.cs
+++ b/src/DotNetOpenAuth.Test/OpenId/Extensions/ExtensionTestUtilities.cs
@@ -5,7 +5,9 @@
//-----------------------------------------------------------------------
namespace DotNetOpenAuth.Test.OpenId.Extensions {
+ using System;
using System.Collections.Generic;
+ using System.Diagnostics.Contracts;
using System.Linq;
using DotNetOpenAuth.Messaging;
using DotNetOpenAuth.OpenId;
@@ -71,7 +73,7 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions {
}
internal static void RegisterExtension(Channel channel, StandardOpenIdExtensionFactory.CreateDelegate extensionFactory) {
- ErrorUtilities.VerifyArgumentNotNull(channel, "channel");
+ Contract.Requires<ArgumentNullException>(channel != null);
var factory = (OpenIdExtensionFactoryAggregator)channel.BindingElements.OfType<ExtensionsBindingElement>().Single().ExtensionFactory;
factory.Factories.OfType<StandardOpenIdExtensionFactory>().Single().RegisterExtension(extensionFactory);
diff --git a/src/DotNetOpenAuth.Test/OpenId/Extensions/ExtensionsInteropHelperOPTests.cs b/src/DotNetOpenAuth.Test/OpenId/Extensions/ExtensionsInteropHelperOPTests.cs
index 1fb3160..3a45d58 100644
--- a/src/DotNetOpenAuth.Test/OpenId/Extensions/ExtensionsInteropHelperOPTests.cs
+++ b/src/DotNetOpenAuth.Test/OpenId/Extensions/ExtensionsInteropHelperOPTests.cs
@@ -132,8 +132,8 @@ namespace DotNetOpenAuth.Test.OpenId.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));
+ axInjected.Attributes.AddOptional(ExtensionsInteropHelper.TransformAXFormatTestHook(WellKnownAttributes.Name.Alias, format));
+ axInjected.Attributes.AddRequired(ExtensionsInteropHelper.TransformAXFormatTestHook(WellKnownAttributes.Name.FullName, format));
this.extensions.Add(axInjected);
var sreg = ExtensionsInteropHelper.UnifyExtensionsAsSreg(this.request);
Assert.AreSame(sreg, this.request.GetExtension<ClaimsRequest>());
@@ -147,7 +147,7 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions {
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)));
+ 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 7edec09..b691697 100644
--- a/src/DotNetOpenAuth.Test/OpenId/Extensions/ExtensionsInteropHelperRPRequestTests.cs
+++ b/src/DotNetOpenAuth.Test/OpenId/Extensions/ExtensionsInteropHelperRPRequestTests.cs
@@ -75,8 +75,8 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions {
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)));
+ Assert.IsTrue(ax.Attributes.Contains(ExtensionsInteropHelper.TransformAXFormatTestHook(WellKnownAttributes.Name.Alias, AXAttributeFormats.SchemaOpenIdNet)));
+ Assert.IsFalse(ax.Attributes.Contains(ExtensionsInteropHelper.TransformAXFormatTestHook(WellKnownAttributes.Name.Alias, AXAttributeFormats.OpenIdNetSchema)));
}
/// <summary>
@@ -99,7 +99,7 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions {
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.IsFalse(ax.Attributes.Contains(ExtensionsInteropHelper.TransformAXFormatTestHook(WellKnownAttributes.Contact.Email, AXAttributeFormats.OpenIdNetSchema)));
Assert.IsTrue(ax.Attributes.Contains(WellKnownAttributes.Contact.Email));
}
@@ -108,9 +108,9 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions {
/// </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));
+ Assert.AreEqual(WellKnownAttributes.Name.Alias, ExtensionsInteropHelper.TransformAXFormatTestHook(WellKnownAttributes.Name.Alias, AXAttributeFormats.AXSchemaOrg));
+ Assert.AreEqual("http://schema.openid.net/namePerson/friendly", ExtensionsInteropHelper.TransformAXFormatTestHook(WellKnownAttributes.Name.Alias, AXAttributeFormats.SchemaOpenIdNet));
+ Assert.AreEqual("http://openid.net/schema/namePerson/friendly", ExtensionsInteropHelper.TransformAXFormatTestHook(WellKnownAttributes.Name.Alias, AXAttributeFormats.OpenIdNetSchema));
}
/// <summary>
@@ -118,11 +118,8 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions {
/// </summary>
/// <param name="typeUri">The type URI.</param>
private void InjectAdvertisedTypeUri(string typeUri) {
- var serviceEndpoint = ServiceEndpoint_Accessor.AttachShadow(((ServiceEndpoint)this.authReq.Provider));
- serviceEndpoint.ProviderDescription = ProviderEndpointDescription_Accessor.AttachShadow(
- new ProviderEndpointDescription(
- serviceEndpoint.ProviderDescription.Endpoint,
- serviceEndpoint.ProviderDescription.Capabilities.Concat(new[] { typeUri })));
+ var serviceEndpoint = (ServiceEndpoint)this.authReq.Provider;
+ serviceEndpoint.SetCapabilitiesForTestHook(serviceEndpoint.ProviderDescription.Capabilities.Concat(new[] { typeUri }));
}
}
}
diff --git a/src/DotNetOpenAuth.Test/OpenId/Extensions/ExtensionsInteropHelperRPResponseTests.cs b/src/DotNetOpenAuth.Test/OpenId/Extensions/ExtensionsInteropHelperRPResponseTests.cs
index 655e616..358d466 100644
--- a/src/DotNetOpenAuth.Test/OpenId/Extensions/ExtensionsInteropHelperRPResponseTests.cs
+++ b/src/DotNetOpenAuth.Test/OpenId/Extensions/ExtensionsInteropHelperRPResponseTests.cs
@@ -74,7 +74,7 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions {
[TestMethod]
public void UnifyExtensionsasSregFromSchemaOpenIdNet() {
var axInjected = new FetchResponse();
- axInjected.Attributes.Add(ExtensionsInteropHelper_Accessor.TransformAXFormat(WellKnownAttributes.Name.Alias, AXAttributeFormats.SchemaOpenIdNet), "nate");
+ axInjected.Attributes.Add(ExtensionsInteropHelper.TransformAXFormatTestHook(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/IdentifierTests.cs b/src/DotNetOpenAuth.Test/OpenId/IdentifierTests.cs
index 3e599e9..cc02265 100644
--- a/src/DotNetOpenAuth.Test/OpenId/IdentifierTests.cs
+++ b/src/DotNetOpenAuth.Test/OpenId/IdentifierTests.cs
@@ -75,7 +75,7 @@ namespace DotNetOpenAuth.Test.OpenId {
Assert.AreEqual(this.uri, ((UriIdentifier)id).Uri.AbsoluteUri);
}
- [TestMethod, ExpectedException(typeof(ArgumentNullException))]
+ [TestMethod, ExpectedException(typeof(ArgumentException))]
public void ParseNull() {
Identifier.Parse(null);
}
diff --git a/src/DotNetOpenAuth.Test/OpenId/Messages/IndirectSignedResponseTests.cs b/src/DotNetOpenAuth.Test/OpenId/Messages/IndirectSignedResponseTests.cs
index e140b24..ae592c5 100644
--- a/src/DotNetOpenAuth.Test/OpenId/Messages/IndirectSignedResponseTests.cs
+++ b/src/DotNetOpenAuth.Test/OpenId/Messages/IndirectSignedResponseTests.cs
@@ -63,25 +63,23 @@ namespace DotNetOpenAuth.Test.OpenId.Messages {
[TestMethod]
public void ResponseNonceSetter() {
const string HybridValue = CreationDateString + "UNIQUE";
- var responseAccessor = IndirectSignedResponse_Accessor.AttachShadow(this.response);
IReplayProtectedProtocolMessage responseReplay = this.response;
- responseAccessor.ResponseNonce = HybridValue;
- Assert.AreEqual(HybridValue, responseAccessor.ResponseNonce);
+ this.response.ResponseNonceTestHook = HybridValue;
+ Assert.AreEqual(HybridValue, this.response.ResponseNonceTestHook);
Assert.AreEqual(this.creationDate, responseReplay.UtcCreationDate);
Assert.AreEqual("UNIQUE", responseReplay.Nonce);
- responseAccessor.ResponseNonce = null;
+ this.response.ResponseNonceTestHook = null;
Assert.IsNull(responseReplay.Nonce);
}
[TestMethod]
public void ResponseNonceGetter() {
- var responseAccessor = IndirectSignedResponse_Accessor.AttachShadow(this.response);
IReplayProtectedProtocolMessage responseReplay = this.response;
responseReplay.Nonce = "UnIqUe";
responseReplay.UtcCreationDate = this.creationDate;
- Assert.AreEqual(CreationDateString + "UnIqUe", responseAccessor.ResponseNonce);
+ Assert.AreEqual(CreationDateString + "UnIqUe", this.response.ResponseNonceTestHook);
Assert.AreEqual("UnIqUe", responseReplay.Nonce);
Assert.AreEqual(this.creationDate, responseReplay.UtcCreationDate);
}
@@ -127,7 +125,7 @@ namespace DotNetOpenAuth.Test.OpenId.Messages {
}
}
- [TestMethod, ExpectedException(typeof(ArgumentNullException))]
+ [TestMethod, ExpectedException(typeof(ArgumentException))]
public void GetReturnToArgumentNullKey() {
this.response.GetReturnToArgument(null);
}
diff --git a/src/DotNetOpenAuth.Test/OpenId/OpenIdCoordinator.cs b/src/DotNetOpenAuth.Test/OpenId/OpenIdCoordinator.cs
index af9c5db..0f9d472 100644
--- a/src/DotNetOpenAuth.Test/OpenId/OpenIdCoordinator.cs
+++ b/src/DotNetOpenAuth.Test/OpenId/OpenIdCoordinator.cs
@@ -6,6 +6,7 @@
namespace DotNetOpenAuth.Test.OpenId {
using System;
+ using System.Diagnostics.Contracts;
using DotNetOpenAuth.Messaging;
using DotNetOpenAuth.Messaging.Bindings;
using DotNetOpenAuth.OpenId;
@@ -36,7 +37,7 @@ namespace DotNetOpenAuth.Test.OpenId {
}
private static Action<OpenIdRelyingParty> WrapAction(Action<OpenIdRelyingParty> action) {
- ErrorUtilities.VerifyArgumentNotNull(action, "action");
+ Contract.Requires<ArgumentNullException>(action != null);
return rp => {
action(rp);
@@ -45,7 +46,7 @@ namespace DotNetOpenAuth.Test.OpenId {
}
private static Action<OpenIdProvider> WrapAction(Action<OpenIdProvider> action) {
- ErrorUtilities.VerifyArgumentNotNull(action, "action");
+ Contract.Requires<ArgumentNullException>(action != null);
return op => {
action(op);
diff --git a/src/DotNetOpenAuth.Test/OpenId/OpenIdTestBase.cs b/src/DotNetOpenAuth.Test/OpenId/OpenIdTestBase.cs
index 5034b7e..af84b0f 100644
--- a/src/DotNetOpenAuth.Test/OpenId/OpenIdTestBase.cs
+++ b/src/DotNetOpenAuth.Test/OpenId/OpenIdTestBase.cs
@@ -88,11 +88,9 @@ namespace DotNetOpenAuth.Test.OpenId {
/// <param name="providerEndpoint">The provider endpoint.</param>
/// <param name="association">The association.</param>
internal static void StoreAssociation(OpenIdRelyingParty relyingParty, Uri providerEndpoint, Association association) {
- var associationManagerAccessor = AssociationManager_Accessor.AttachShadow(relyingParty.AssociationManager);
-
// Only store the association if the RP is not in stateless mode.
- if (associationManagerAccessor.associationStore != null) {
- associationManagerAccessor.associationStore.StoreAssociation(providerEndpoint, association);
+ if (relyingParty.AssociationManager.AssociationStoreTestHook != null) {
+ relyingParty.AssociationManager.AssociationStoreTestHook.StoreAssociation(providerEndpoint, association);
}
}
diff --git a/src/DotNetOpenAuth.Test/OpenId/Provider/AuthenticationRequestTest.cs b/src/DotNetOpenAuth.Test/OpenId/Provider/AuthenticationRequestTest.cs
index accbd97..518cdaf 100644
--- a/src/DotNetOpenAuth.Test/OpenId/Provider/AuthenticationRequestTest.cs
+++ b/src/DotNetOpenAuth.Test/OpenId/Provider/AuthenticationRequestTest.cs
@@ -35,8 +35,8 @@ namespace DotNetOpenAuth.Test.OpenId.Provider {
// Now construct a new request as if it had just come in.
HttpRequestInfo httpRequest = new HttpRequestInfo { UrlBeforeRewriting = userSetupUrl };
- var setupRequest = AuthenticationRequest_Accessor.AttachShadow(provider.GetRequest(httpRequest));
- CheckIdRequest_Accessor setupRequestMessage = setupRequest.RequestMessage;
+ var setupRequest = (AuthenticationRequest)provider.GetRequest(httpRequest);
+ var setupRequestMessage = (CheckIdRequest)setupRequest.RequestMessage;
// And make sure all the right properties are set.
Assert.IsFalse(setupRequestMessage.Immediate);
diff --git a/src/DotNetOpenAuth.Test/OpenId/Provider/OpenIdProviderTests.cs b/src/DotNetOpenAuth.Test/OpenId/Provider/OpenIdProviderTests.cs
index 0a6cdcc..8528aa7 100644
--- a/src/DotNetOpenAuth.Test/OpenId/Provider/OpenIdProviderTests.cs
+++ b/src/DotNetOpenAuth.Test/OpenId/Provider/OpenIdProviderTests.cs
@@ -7,6 +7,7 @@
namespace DotNetOpenAuth.Test.OpenId.Provider {
using System;
using System.IO;
+ using System.Web;
using DotNetOpenAuth.Messaging;
using DotNetOpenAuth.OpenId;
using DotNetOpenAuth.OpenId.Extensions;
@@ -74,6 +75,7 @@ namespace DotNetOpenAuth.Test.OpenId.Provider {
/// </summary>
[TestMethod, ExpectedException(typeof(InvalidOperationException))]
public void GetRequestNoContext() {
+ HttpContext.Current = null;
this.provider.GetRequest();
}
diff --git a/src/DotNetOpenAuth.Test/OpenId/ProviderEndpointDescriptionTests.cs b/src/DotNetOpenAuth.Test/OpenId/ProviderEndpointDescriptionTests.cs
index 005b8a0..089265f 100644
--- a/src/DotNetOpenAuth.Test/OpenId/ProviderEndpointDescriptionTests.cs
+++ b/src/DotNetOpenAuth.Test/OpenId/ProviderEndpointDescriptionTests.cs
@@ -29,7 +29,7 @@ namespace DotNetOpenAuth.Test.OpenId {
this.se.IsExtensionSupported((Type)null);
}
- [TestMethod, ExpectedException(typeof(ArgumentNullException))]
+ [TestMethod, ExpectedException(typeof(ArgumentException))]
public void IsExtensionSupportedNullString() {
this.se.IsExtensionSupported((string)null);
}
diff --git a/src/DotNetOpenAuth.Test/OpenId/RelyingParty/AuthenticationRequestTests.cs b/src/DotNetOpenAuth.Test/OpenId/RelyingParty/AuthenticationRequestTests.cs
index 0ddc76b..dfe4744 100644
--- a/src/DotNetOpenAuth.Test/OpenId/RelyingParty/AuthenticationRequestTests.cs
+++ b/src/DotNetOpenAuth.Test/OpenId/RelyingParty/AuthenticationRequestTests.cs
@@ -37,7 +37,7 @@ namespace DotNetOpenAuth.Test.OpenId.RelyingParty {
/// </summary>
[TestMethod]
public void IsDirectedIdentity() {
- IAuthenticationRequest_Accessor iauthRequest = this.CreateAuthenticationRequest(this.claimedId, this.claimedId);
+ var iauthRequest = this.CreateAuthenticationRequest(this.claimedId, this.claimedId);
Assert.IsFalse(iauthRequest.IsDirectedIdentity);
iauthRequest = this.CreateAuthenticationRequest(IdentifierSelect, IdentifierSelect);
@@ -49,7 +49,7 @@ namespace DotNetOpenAuth.Test.OpenId.RelyingParty {
/// </summary>
[TestMethod]
public void ClaimedIdentifier() {
- IAuthenticationRequest_Accessor iauthRequest = this.CreateAuthenticationRequest(this.claimedId, this.delegatedLocalId);
+ var iauthRequest = this.CreateAuthenticationRequest(this.claimedId, this.delegatedLocalId);
Assert.AreEqual(this.claimedId, iauthRequest.ClaimedIdentifier);
iauthRequest = this.CreateAuthenticationRequest(IdentifierSelect, IdentifierSelect);
@@ -62,7 +62,7 @@ namespace DotNetOpenAuth.Test.OpenId.RelyingParty {
[TestMethod]
public void ProviderVersion() {
var authRequest = this.CreateAuthenticationRequest(this.claimedId, this.claimedId);
- Assert.AreEqual(this.protocol.Version, authRequest.endpoint.Protocol.Version);
+ Assert.AreEqual(this.protocol.Version, authRequest.Endpoint.Protocol.Version);
}
/// <summary>
@@ -85,8 +85,8 @@ namespace DotNetOpenAuth.Test.OpenId.RelyingParty {
authRequest.AddExtension(sregRequest);
// Construct the actual authentication request message.
- var authRequestAccessor = AuthenticationRequest_Accessor.AttachShadow(authRequest);
- var req = authRequestAccessor.CreateRequestMessage();
+ var authRequestAccessor = (AuthenticationRequest)authRequest;
+ var req = authRequestAccessor.CreateRequestMessageTestHook();
Assert.IsNotNull(req);
// Verify that callback arguments were included.
@@ -124,7 +124,7 @@ namespace DotNetOpenAuth.Test.OpenId.RelyingParty {
/// </summary>
[TestMethod]
public void Provider() {
- IAuthenticationRequest_Accessor authRequest = this.CreateAuthenticationRequest(this.claimedId, this.claimedId);
+ var authRequest = this.CreateAuthenticationRequest(this.claimedId, this.claimedId);
Assert.IsNotNull(authRequest.Provider);
Assert.AreEqual(OPUri, authRequest.Provider.Uri);
Assert.AreEqual(this.protocol.Version, authRequest.Provider.Version);
@@ -135,7 +135,7 @@ namespace DotNetOpenAuth.Test.OpenId.RelyingParty {
/// </summary>
[TestMethod]
public void AddCallbackArgument() {
- IAuthenticationRequest_Accessor authRequest = this.CreateAuthenticationRequest(this.claimedId, this.claimedId);
+ var authRequest = this.CreateAuthenticationRequest(this.claimedId, this.claimedId);
Assert.AreEqual(this.returnTo, authRequest.ReturnToUrl);
authRequest.AddCallbackArguments("p1", "v1");
var req = (SignedResponseRequest)authRequest.RedirectingResponse.OriginalMessage;
@@ -152,7 +152,7 @@ namespace DotNetOpenAuth.Test.OpenId.RelyingParty {
UriBuilder returnToWithArgs = new UriBuilder(this.returnTo);
returnToWithArgs.AppendQueryArgs(new Dictionary<string, string> { { "p1", "v1" } });
this.returnTo = returnToWithArgs.Uri;
- IAuthenticationRequest_Accessor authRequest = this.CreateAuthenticationRequest(this.claimedId, this.claimedId);
+ var authRequest = this.CreateAuthenticationRequest(this.claimedId, this.claimedId);
authRequest.AddCallbackArguments("p1", "v2");
var req = (SignedResponseRequest)authRequest.RedirectingResponse.OriginalMessage;
NameValueCollection query = HttpUtility.ParseQueryString(req.ReturnTo.Query);
@@ -164,7 +164,7 @@ namespace DotNetOpenAuth.Test.OpenId.RelyingParty {
/// </summary>
[TestMethod]
public void NonIdentityRequest() {
- IAuthenticationRequest_Accessor authRequest = this.CreateAuthenticationRequest(this.claimedId, this.claimedId);
+ var authRequest = this.CreateAuthenticationRequest(this.claimedId, this.claimedId);
authRequest.IsExtensionOnly = true;
Assert.IsTrue(authRequest.IsExtensionOnly);
var req = (SignedResponseRequest)authRequest.RedirectingResponse.OriginalMessage;
@@ -181,12 +181,11 @@ namespace DotNetOpenAuth.Test.OpenId.RelyingParty {
Assert.Inconclusive("Not yet implemented.");
}
- private AuthenticationRequest_Accessor CreateAuthenticationRequest(Identifier claimedIdentifier, Identifier providerLocalIdentifier) {
+ private AuthenticationRequest CreateAuthenticationRequest(Identifier claimedIdentifier, Identifier providerLocalIdentifier) {
ProviderEndpointDescription providerEndpoint = new ProviderEndpointDescription(OPUri, this.protocol.Version);
ServiceEndpoint endpoint = ServiceEndpoint.CreateForClaimedIdentifier(claimedIdentifier, providerLocalIdentifier, providerEndpoint, 10, 5);
- ServiceEndpoint_Accessor endpointAccessor = ServiceEndpoint_Accessor.AttachShadow(endpoint);
OpenIdRelyingParty rp = this.CreateRelyingParty();
- AuthenticationRequest_Accessor authRequest = new AuthenticationRequest_Accessor(endpointAccessor, this.realm, this.returnTo, rp);
+ AuthenticationRequest authRequest = AuthenticationRequest.CreateForTest(endpoint, this.realm, this.returnTo, rp);
return authRequest;
}
}
diff --git a/src/DotNetOpenAuth.Test/OpenId/RelyingParty/OpenIdTextBoxTests.cs b/src/DotNetOpenAuth.Test/OpenId/RelyingParty/OpenIdTextBoxTests.cs
new file mode 100644
index 0000000..67255e3
--- /dev/null
+++ b/src/DotNetOpenAuth.Test/OpenId/RelyingParty/OpenIdTextBoxTests.cs
@@ -0,0 +1,49 @@
+//-----------------------------------------------------------------------
+// <copyright file="OpenIdTextBoxTests.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.Test.OpenId.RelyingParty {
+ using DotNetOpenAuth.OpenId.RelyingParty;
+ using Microsoft.VisualStudio.TestTools.UnitTesting;
+
+ [TestClass]
+ public class OpenIdTextBoxTests : OpenIdTestBase {
+ /// <summary>
+ /// Verifies that the Text and Identifier properties interact correctly.
+ /// </summary>
+ [TestMethod]
+ public void IdentifierTextInteraction() {
+ var box = new OpenIdTextBox();
+ Assert.AreEqual(string.Empty, box.Text);
+ Assert.IsNull(box.Identifier);
+
+ box.Text = "=arnott";
+ Assert.AreEqual("=arnott", box.Text);
+ Assert.AreEqual("=arnott", box.Identifier.ToString());
+
+ box.Identifier = "=bob";
+ Assert.AreEqual("=bob", box.Text);
+ Assert.AreEqual("=bob", box.Identifier.ToString());
+
+ box.Text = string.Empty;
+ Assert.AreEqual(string.Empty, box.Text);
+ Assert.IsNull(box.Identifier);
+
+ box.Text = null;
+ Assert.AreEqual(string.Empty, box.Text);
+ Assert.IsNull(box.Identifier);
+
+ // Invalid identifier case
+ box.Text = "/";
+ Assert.AreEqual("/", box.Text);
+ Assert.IsNull(box.Identifier);
+
+ // blank out the invalid case
+ box.Identifier = null;
+ Assert.AreEqual(string.Empty, box.Text);
+ Assert.IsNull(box.Identifier);
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth.Test/OpenId/RelyingParty/PositiveAuthenticationResponseTests.cs b/src/DotNetOpenAuth.Test/OpenId/RelyingParty/PositiveAuthenticationResponseTests.cs
index 083b988..5297335 100644
--- a/src/DotNetOpenAuth.Test/OpenId/RelyingParty/PositiveAuthenticationResponseTests.cs
+++ b/src/DotNetOpenAuth.Test/OpenId/RelyingParty/PositiveAuthenticationResponseTests.cs
@@ -34,11 +34,10 @@ namespace DotNetOpenAuth.Test.OpenId.RelyingParty {
assertion.Extensions.Add(extension);
var rp = CreateRelyingParty();
var authResponse = new PositiveAuthenticationResponse(assertion, rp);
- var authResponseAccessor = PositiveAuthenticationResponse_Accessor.AttachShadow(authResponse);
Assert.AreEqual(AuthenticationStatus.Authenticated, authResponse.Status);
Assert.IsNull(authResponse.Exception);
Assert.AreEqual<string>(assertion.ClaimedIdentifier, authResponse.ClaimedIdentifier);
- Assert.AreEqual<string>(authResponseAccessor.endpoint.FriendlyIdentifierForDisplay, authResponse.FriendlyIdentifierForDisplay);
+ Assert.AreEqual<string>(authResponse.Endpoint.FriendlyIdentifierForDisplay, authResponse.FriendlyIdentifierForDisplay);
Assert.AreSame(extension, authResponse.GetUntrustedExtension(typeof(ClaimsResponse)));
Assert.AreSame(extension, authResponse.GetUntrustedExtension<ClaimsResponse>());
Assert.IsNull(authResponse.GetCallbackArgument("a"));
diff --git a/src/DotNetOpenAuth.Test/OpenId/RelyingParty/ServiceEndpointTests.cs b/src/DotNetOpenAuth.Test/OpenId/RelyingParty/ServiceEndpointTests.cs
index bd09bc9..ff15aa3 100644
--- a/src/DotNetOpenAuth.Test/OpenId/RelyingParty/ServiceEndpointTests.cs
+++ b/src/DotNetOpenAuth.Test/OpenId/RelyingParty/ServiceEndpointTests.cs
@@ -138,14 +138,14 @@ namespace DotNetOpenAuth.Test.OpenId.RelyingParty {
};
ServiceEndpoint se;
- // strip of protocol and fragment
+ // strip of protocol, port, query and fragment
se = ServiceEndpoint.CreateForClaimedIdentifier(
- "http://someprovider.somedomain.com:79/someuser#frag",
+ "http://someprovider.somedomain.com:79/someuser?query#frag",
localId,
new ProviderEndpointDescription(providerEndpoint, serviceTypeUris),
null,
null);
- Assert.AreEqual("someprovider.somedomain.com:79/someuser", se.FriendlyIdentifierForDisplay);
+ Assert.AreEqual("someprovider.somedomain.com/someuser", se.FriendlyIdentifierForDisplay);
// unescape characters
Uri foreignUri = new Uri("http://server崎/村");
@@ -180,7 +180,7 @@ namespace DotNetOpenAuth.Test.OpenId.RelyingParty {
Assert.IsFalse(se.IsTypeUriPresent("http://someother"));
}
- [TestMethod, ExpectedException(typeof(ArgumentNullException))]
+ [TestMethod, ExpectedException(typeof(ArgumentException))]
public void IsTypeUriPresentNull() {
ServiceEndpoint se = ServiceEndpoint.CreateForClaimedIdentifier(this.claimedXri, this.userSuppliedXri, this.localId, new ProviderEndpointDescription(this.providerEndpoint, this.v20TypeUris), this.servicePriority, this.uriPriority);
se.IsTypeUriPresent(null);
diff --git a/src/DotNetOpenAuth.Test/OpenId/UriIdentifierTests.cs b/src/DotNetOpenAuth.Test/OpenId/UriIdentifierTests.cs
index f1823e6..5a5182f 100644
--- a/src/DotNetOpenAuth.Test/OpenId/UriIdentifierTests.cs
+++ b/src/DotNetOpenAuth.Test/OpenId/UriIdentifierTests.cs
@@ -31,7 +31,7 @@ namespace DotNetOpenAuth.Test.OpenId {
new UriIdentifier((Uri)null);
}
- [TestMethod, ExpectedException(typeof(ArgumentNullException))]
+ [TestMethod, ExpectedException(typeof(ArgumentException))]
public void CtorNullString() {
new UriIdentifier((string)null);
}
diff --git a/src/DotNetOpenAuth.Test/OpenId/XriIdentifierTests.cs b/src/DotNetOpenAuth.Test/OpenId/XriIdentifierTests.cs
index 87ecd4b..46427bb 100644
--- a/src/DotNetOpenAuth.Test/OpenId/XriIdentifierTests.cs
+++ b/src/DotNetOpenAuth.Test/OpenId/XriIdentifierTests.cs
@@ -22,7 +22,7 @@ namespace DotNetOpenAuth.Test.OpenId {
base.SetUp();
}
- [TestMethod, ExpectedException(typeof(ArgumentNullException))]
+ [TestMethod, ExpectedException(typeof(ArgumentException))]
public void CtorNull() {
new XriIdentifier(null);
}
diff --git a/src/DotNetOpenAuth.Test/Properties/AssemblyInfo.cs b/src/DotNetOpenAuth.Test/Properties/AssemblyInfo.cs
index d6fd020..4744bfe 100644
--- a/src/DotNetOpenAuth.Test/Properties/AssemblyInfo.cs
+++ b/src/DotNetOpenAuth.Test/Properties/AssemblyInfo.cs
@@ -29,4 +29,4 @@ using System.Runtime.InteropServices;
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("aef0bb13-b79c-4854-a69a-de58b8feb5d1")]
-[assembly: ContractVerification(false)] \ No newline at end of file
+[assembly: ContractVerification(true)] \ No newline at end of file
diff --git a/src/DotNetOpenAuth.Test/TestBase.cs b/src/DotNetOpenAuth.Test/TestBase.cs
index f9db40c..c6508f6 100644
--- a/src/DotNetOpenAuth.Test/TestBase.cs
+++ b/src/DotNetOpenAuth.Test/TestBase.cs
@@ -7,6 +7,7 @@
namespace DotNetOpenAuth.Test {
using System.IO;
using System.Reflection;
+ using System.Web;
using DotNetOpenAuth.Messaging.Reflection;
using DotNetOpenAuth.OAuth.Messages;
using log4net;
@@ -48,6 +49,7 @@ namespace DotNetOpenAuth.Test {
log4net.Config.XmlConfigurator.Configure(Assembly.GetExecutingAssembly().GetManifestResourceStream("DotNetOpenAuth.Test.Logging.config"));
MessageBase.LowSecurityMode = true;
this.messageDescriptions = new MessageDescriptionCollection();
+ SetMockHttpContext();
}
/// <summary>
@@ -58,6 +60,16 @@ namespace DotNetOpenAuth.Test {
log4net.LogManager.Shutdown();
}
+ /// <summary>
+ /// Sets HttpContext.Current to some empty (but non-null!) value.
+ /// </summary>
+ protected internal static void SetMockHttpContext() {
+ HttpContext.Current = new HttpContext(
+ new HttpRequest("mock", "http://mock", "mock"),
+ new HttpResponse(new StringWriter()));
+ }
+
+#pragma warning disable 0618
protected internal static void SuspendLogging() {
LogManager.GetLoggerRepository().Threshold = LogManager.GetLoggerRepository().LevelMap["OFF"];
}
@@ -65,5 +77,6 @@ namespace DotNetOpenAuth.Test {
protected internal static void ResumeLogging() {
LogManager.GetLoggerRepository().Threshold = LogManager.GetLoggerRepository().LevelMap["ALL"];
}
+#pragma warning restore 0618
}
}