diff options
Diffstat (limited to 'src/DotNetOpenAuth.Test')
42 files changed, 421 insertions, 69 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..d4997ae 100644 --- a/src/DotNetOpenAuth.Test/DotNetOpenAuth.Test.csproj +++ b/src/DotNetOpenAuth.Test/DotNetOpenAuth.Test.csproj @@ -21,12 +21,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 +44,8 @@ <CodeContractsRunInBackground>True</CodeContractsRunInBackground> <CodeContractsShowSquigglies>False</CodeContractsShowSquigglies> <CodeContractsRuntimeOnlyPublicSurface>False</CodeContractsRuntimeOnlyPublicSurface> + <CodeContractsRuntimeThrowOnFailure>True</CodeContractsRuntimeThrowOnFailure> + <CodeContractsRuntimeCallSiteRequires>False</CodeContractsRuntimeCallSiteRequires> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> <DebugType>pdbonly</DebugType> @@ -52,10 +54,34 @@ <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> </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 +97,7 @@ </CodeContractsCustomRewriterAssembly> <CodeContractsCustomRewriterClass> </CodeContractsCustomRewriterClass> - <CodeContractsRuntimeCheckingLevel>Full</CodeContractsRuntimeCheckingLevel> + <CodeContractsRuntimeCheckingLevel>None</CodeContractsRuntimeCheckingLevel> <CodeContractsRunCodeAnalysis>True</CodeContractsRunCodeAnalysis> <CodeContractsBuildReferenceAssembly>False</CodeContractsBuildReferenceAssembly> <CodeContractsNonNullObligations>False</CodeContractsNonNullObligations> @@ -87,6 +113,10 @@ <CodeContractsUseBaseLine>False</CodeContractsUseBaseLine> <CodeContractsRunInBackground>True</CodeContractsRunInBackground> <CodeContractsShowSquigglies>True</CodeContractsShowSquigglies> + <CodeContractsRuntimeOnlyPublicSurface>False</CodeContractsRuntimeOnlyPublicSurface> + <CodeContractsRuntimeThrowOnFailure>True</CodeContractsRuntimeThrowOnFailure> + <CodeContractsRuntimeCallSiteRequires>False</CodeContractsRuntimeCallSiteRequires> + <CodeContractsArithmeticObligations>False</CodeContractsArithmeticObligations> </PropertyGroup> <ItemGroup> <Reference Include="log4net, Version=1.2.10.0, Culture=neutral, PublicKeyToken=1b44e1d426115821, processorArchitecture=MSIL"> @@ -131,10 +161,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 +265,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" /> @@ -296,4 +329,4 @@ </ItemGroup> <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" /> <Import Project="..\..\tools\DotNetOpenAuth.Versioning.targets" /> -</Project>
\ No newline at end of file +</Project> 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..7846411 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(); } 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..16386de 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; @@ -220,7 +221,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,7 +252,7 @@ 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; 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 48547b7..35672d7 100644 --- a/src/DotNetOpenAuth.Test/Mocks/InMemoryTokenManager.cs +++ b/src/DotNetOpenAuth.Test/Mocks/InMemoryTokenManager.cs @@ -106,6 +106,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..0213a33 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"); + Contract.Requires<ArgumentNullException>(endpoint != 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/OAuthChannelTests.cs b/src/DotNetOpenAuth.Test/OAuth/ChannelElements/OAuthChannelTests.cs index 856f164..b721fb7 100644 --- a/src/DotNetOpenAuth.Test/OAuth/ChannelElements/OAuthChannelTests.cs +++ b/src/DotNetOpenAuth.Test/OAuth/ChannelElements/OAuthChannelTests.cs @@ -8,6 +8,7 @@ namespace DotNetOpenAuth.Test.ChannelElements { using System; using System.Collections.Generic; using System.Collections.Specialized; + using System.Diagnostics.Contracts; using System.IO; using System.Net; using System.Text; @@ -34,13 +35,13 @@ namespace DotNetOpenAuth.Test.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()); } @@ -226,6 +227,11 @@ namespace DotNetOpenAuth.Test.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> @@ -243,7 +249,7 @@ namespace DotNetOpenAuth.Test.ChannelElements { } 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 +328,7 @@ namespace DotNetOpenAuth.Test.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 627db8f..01d51a3 100644 --- a/src/DotNetOpenAuth.Test/OAuth/ChannelElements/PlaintextSigningBindingElementTest.cs +++ b/src/DotNetOpenAuth.Test/OAuth/ChannelElements/PlaintextSigningBindingElementTest.cs @@ -9,6 +9,7 @@ namespace DotNetOpenAuth.Test.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.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.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.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.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.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/OAuthCoordinator.cs b/src/DotNetOpenAuth.Test/OAuth/OAuthCoordinator.cs index ce548a9..5967a03 100644 --- a/src/DotNetOpenAuth.Test/OAuth/OAuthCoordinator.cs +++ b/src/DotNetOpenAuth.Test/OAuth/OAuthCoordinator.cs @@ -6,6 +6,7 @@ namespace DotNetOpenAuth.Test { using System; + using System.Diagnostics.Contracts; using DotNetOpenAuth.Messaging; using DotNetOpenAuth.Messaging.Bindings; using DotNetOpenAuth.OAuth; @@ -26,8 +27,8 @@ namespace DotNetOpenAuth.Test { /// <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/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/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/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..8b0937a 100644 --- a/src/DotNetOpenAuth.Test/OpenId/Messages/IndirectSignedResponseTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/Messages/IndirectSignedResponseTests.cs @@ -127,7 +127,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/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/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..701bcae 100644 --- a/src/DotNetOpenAuth.Test/OpenId/RelyingParty/PositiveAuthenticationResponseTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/RelyingParty/PositiveAuthenticationResponseTests.cs @@ -38,7 +38,7 @@ namespace DotNetOpenAuth.Test.OpenId.RelyingParty { 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 } } |