diff options
Diffstat (limited to 'src/DotNetOpenAuth.Test')
112 files changed, 2219 insertions, 1738 deletions
diff --git a/src/DotNetOpenAuth.Test/AssemblyTesting.cs b/src/DotNetOpenAuth.Test/AssemblyTesting.cs index 7659a82..92b08ec 100644 --- a/src/DotNetOpenAuth.Test/AssemblyTesting.cs +++ b/src/DotNetOpenAuth.Test/AssemblyTesting.cs @@ -6,12 +6,12 @@ namespace DotNetOpenAuth.Test { using System.Diagnostics.Contracts; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; - [TestClass] + [SetUpFixture] public class AssemblyTesting { - [AssemblyInitialize] - public static void AssemblyInitialize(TestContext tc) { + [SetUp] + public static void AssemblyInitialize() { // Make contract failures become test failures. Contract.ContractFailed += (sender, e) => { // For now, we have tests that verify that preconditions throw exceptions. diff --git a/src/DotNetOpenAuth.Test/Configuration/SectionTests.cs b/src/DotNetOpenAuth.Test/Configuration/SectionTests.cs index 73aad6d..e423053 100644 --- a/src/DotNetOpenAuth.Test/Configuration/SectionTests.cs +++ b/src/DotNetOpenAuth.Test/Configuration/SectionTests.cs @@ -9,11 +9,11 @@ namespace DotNetOpenAuth.Test.Configuration { using System.Linq; using DotNetOpenAuth.Configuration; using DotNetOpenAuth.OpenId; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; - [TestClass] + [TestFixture] public class SectionTests { - [TestMethod] + [TestCase] public void UntrustedWebRequest() { var uwr = DotNetOpenAuthSection.Configuration.Messaging.UntrustedWebRequest; @@ -29,12 +29,12 @@ namespace DotNetOpenAuth.Test.Configuration { Assert.IsTrue(uwr.WhitelistHostsRegex.KeysAsStrings.Contains(".+trusted.+")); } - [TestMethod] + [TestCase] public void OpenIdMaxAuthenticationTime() { Assert.AreEqual(TimeSpan.Parse("00:08:17"), DotNetOpenAuthSection.Configuration.OpenId.MaxAuthenticationTime); } - [TestMethod] + [TestCase] public void OpenIdRelyingParty() { var rp = DotNetOpenAuthSection.Configuration.OpenId.RelyingParty; Assert.IsNull(rp.ApplicationStore.CustomType); @@ -45,7 +45,7 @@ namespace DotNetOpenAuth.Test.Configuration { Assert.IsFalse(rp.SecuritySettings.RequireSsl); } - [TestMethod] + [TestCase] public void OpenIdProvider() { var op = DotNetOpenAuthSection.Configuration.OpenId.Provider; Assert.IsNull(op.ApplicationStore.CustomType); diff --git a/src/DotNetOpenAuth.Test/CoordinatorBase.cs b/src/DotNetOpenAuth.Test/CoordinatorBase.cs index df331f3..f25964c 100644 --- a/src/DotNetOpenAuth.Test/CoordinatorBase.cs +++ b/src/DotNetOpenAuth.Test/CoordinatorBase.cs @@ -11,7 +11,7 @@ namespace DotNetOpenAuth.Test { using DotNetOpenAuth.Messaging; using DotNetOpenAuth.OpenId.RelyingParty; using DotNetOpenAuth.Test.Mocks; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; internal abstract class CoordinatorBase<T1, T2> { private Action<T1> party1Action; @@ -84,7 +84,7 @@ namespace DotNetOpenAuth.Test { // Use the failing reason of a failing sub-thread as our reason, if anything failed. if (failingException != null) { - throw new AssertFailedException("Coordinator thread threw unhandled exception: " + failingException, failingException); + throw new AssertionException("Coordinator thread threw unhandled exception: " + failingException, failingException); } } } diff --git a/src/DotNetOpenAuth.Test/DotNetOpenAuth.Test.csproj b/src/DotNetOpenAuth.Test/DotNetOpenAuth.Test.csproj index d4997ae..df29b1f 100644 --- a/src/DotNetOpenAuth.Test/DotNetOpenAuth.Test.csproj +++ b/src/DotNetOpenAuth.Test/DotNetOpenAuth.Test.csproj @@ -1,7 +1,12 @@ -<Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> +<?xml version="1.0" encoding="utf-8"?> +<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <PropertyGroup> + <ProjectRoot Condition="'$(ProjectRoot)' == ''">$(MSBuildProjectDirectory)\..\..\</ProjectRoot> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> + </PropertyGroup> + <Import Project="$(ProjectRoot)tools\DotNetOpenAuth.props" /> + <PropertyGroup> <ProductVersion>9.0.30729</ProductVersion> <SchemaVersion>2.0</SchemaVersion> <ProjectGuid>{4376ECC9-C346-4A99-B13C-FA93C0FBD2C9}</ProjectGuid> @@ -9,15 +14,31 @@ <AppDesignerFolder>Properties</AppDesignerFolder> <RootNamespace>DotNetOpenAuth.Test</RootNamespace> <AssemblyName>DotNetOpenAuth.Test</AssemblyName> - <TargetFrameworkVersion>v3.5</TargetFrameworkVersion> <FileAlignment>512</FileAlignment> - <ProjectTypeGuids>{3AC096D0-A1C2-E12C-1390-A8335801FDAB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids> + <FileUpgradeFlags> + </FileUpgradeFlags> + <OldToolsVersion>3.5</OldToolsVersion> + <UpgradeBackupLocation /> + <PublishUrl>publish\</PublishUrl> + <Install>true</Install> + <InstallFrom>Disk</InstallFrom> + <UpdateEnabled>false</UpdateEnabled> + <UpdateMode>Foreground</UpdateMode> + <UpdateInterval>7</UpdateInterval> + <UpdateIntervalUnits>Days</UpdateIntervalUnits> + <UpdatePeriodically>false</UpdatePeriodically> + <UpdateRequired>false</UpdateRequired> + <MapFileExtensions>true</MapFileExtensions> + <ApplicationRevision>0</ApplicationRevision> + <ApplicationVersion>1.0.0.%2a</ApplicationVersion> + <IsWebBootstrapper>false</IsWebBootstrapper> + <UseApplicationTrust>false</UseApplicationTrust> + <BootstrapperEnabled>true</BootstrapperEnabled> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <DebugSymbols>true</DebugSymbols> <DebugType>full</DebugType> <Optimize>false</Optimize> - <OutputPath>..\..\bin\Debug\</OutputPath> <DefineConstants>DEBUG;TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> @@ -46,11 +67,11 @@ <CodeContractsRuntimeOnlyPublicSurface>False</CodeContractsRuntimeOnlyPublicSurface> <CodeContractsRuntimeThrowOnFailure>True</CodeContractsRuntimeThrowOnFailure> <CodeContractsRuntimeCallSiteRequires>False</CodeContractsRuntimeCallSiteRequires> + <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> <DebugType>pdbonly</DebugType> <Optimize>true</Optimize> - <OutputPath>..\..\bin\Release\</OutputPath> <DefineConstants>TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> @@ -79,13 +100,10 @@ <CodeContractsUseBaseLine>False</CodeContractsUseBaseLine> <CodeContractsRunInBackground>True</CodeContractsRunInBackground> <CodeContractsShowSquigglies>False</CodeContractsShowSquigglies> - </PropertyGroup> - <PropertyGroup> - <SignAssembly>true</SignAssembly> + <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'CodeAnalysis|AnyCPU' "> <DebugSymbols>true</DebugSymbols> - <OutputPath>..\..\bin\CodeAnalysis\</OutputPath> <DefineConstants>DEBUG;TRACE</DefineConstants> <DebugType>full</DebugType> <PlatformTarget>AnyCPU</PlatformTarget> @@ -117,21 +135,13 @@ <CodeContractsRuntimeThrowOnFailure>True</CodeContractsRuntimeThrowOnFailure> <CodeContractsRuntimeCallSiteRequires>False</CodeContractsRuntimeCallSiteRequires> <CodeContractsArithmeticObligations>False</CodeContractsArithmeticObligations> + <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet> </PropertyGroup> <ItemGroup> - <Reference Include="log4net, Version=1.2.10.0, Culture=neutral, PublicKeyToken=1b44e1d426115821, processorArchitecture=MSIL"> - <SpecificVersion>False</SpecificVersion> - <HintPath>..\..\lib\log4net.dll</HintPath> - </Reference> - <Reference Include="Microsoft.Contracts, Version=1.0.0.0, Culture=neutral, PublicKeyToken=736440c9b414ea16, processorArchitecture=MSIL"> - <SpecificVersion>False</SpecificVersion> - <HintPath>..\..\lib\Microsoft.Contracts.dll</HintPath> - </Reference> - <Reference Include="Microsoft.VisualStudio.QualityTools.UnitTestFramework, Version=9.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL" /> - <Reference Include="Moq, Version=3.1.416.3, Culture=neutral, PublicKeyToken=69f491c39445e920, processorArchitecture=MSIL"> - <SpecificVersion>False</SpecificVersion> - <HintPath>..\..\lib\Moq.dll</HintPath> - </Reference> + <Reference Include="log4net" /> + <Reference Include="Microsoft.VisualStudio.QualityTools.UnitTestFramework" /> + <Reference Include="Moq" /> + <Reference Include="NUnit.Framework"/> <Reference Include="System" /> <Reference Include="System.configuration" /> <Reference Include="System.Core"> @@ -185,6 +195,7 @@ <Compile Include="Mocks\InMemoryTokenManager.cs" /> <Compile Include="Mocks\MockHttpRequest.cs" /> <Compile Include="Mocks\MockIdentifier.cs" /> + <Compile Include="Mocks\MockIdentifierDiscoveryService.cs" /> <Compile Include="Mocks\MockOpenIdExtension.cs" /> <Compile Include="Mocks\MockRealm.cs" /> <Compile Include="Mocks\MockTransformationBindingElement.cs" /> @@ -219,6 +230,8 @@ <Compile Include="Messaging\Bindings\StandardReplayProtectionBindingElementTests.cs" /> <Compile Include="OpenId\ChannelElements\SigningBindingElementTests.cs" /> <Compile Include="OpenId\DiffieHellmanTests.cs" /> + <Compile Include="OpenId\DiscoveryServices\UriDiscoveryServiceTests.cs" /> + <Compile Include="OpenId\DiscoveryServices\XriDiscoveryProxyServiceTests.cs" /> <Compile Include="OpenId\Extensions\AttributeExchange\FetchRequestTests.cs" /> <Compile Include="OpenId\Extensions\AttributeExchange\FetchResponseTests.cs" /> <Compile Include="OpenId\Extensions\AttributeExchange\AttributeExchangeRoundtripTests.cs" /> @@ -255,6 +268,7 @@ <Compile Include="OpenId\OpenIdCoordinator.cs" /> <Compile Include="OpenId\AssociationHandshakeTests.cs" /> <Compile Include="OpenId\OpenIdTestBase.cs" /> + <Compile Include="OpenId\OpenIdUtilitiesTests.cs" /> <Compile Include="OpenId\Provider\PerformanceTests.cs" /> <Compile Include="OpenId\ProviderEndpointDescriptionTests.cs" /> <Compile Include="OpenId\Provider\AnonymousRequestTests.cs" /> @@ -267,10 +281,11 @@ <Compile Include="OpenId\RelyingParty\NegativeAuthenticationResponseTests.cs" /> <Compile Include="OpenId\RelyingParty\OpenIdTextBoxTests.cs" /> <Compile Include="OpenId\RelyingParty\PositiveAnonymousResponseTests.cs" /> + <Compile Include="OpenId\RelyingParty\PositiveAuthenticationResponseSnapshotTests.cs" /> <Compile Include="OpenId\RelyingParty\PositiveAuthenticationResponseTests.cs" /> <Compile Include="OpenId\RelyingParty\OpenIdRelyingPartyTests.cs" /> <Compile Include="OpenId\RelyingParty\RelyingPartySecuritySettingsTests.cs" /> - <Compile Include="OpenId\RelyingParty\ServiceEndpointTests.cs" /> + <Compile Include="OpenId\RelyingParty\IdentifierDiscoveryResultTests.cs" /> <Compile Include="OpenId\UriIdentifierTests.cs" /> <Compile Include="OpenId\XriIdentifierTests.cs" /> <Compile Include="Properties\AssemblyInfo.cs" /> @@ -287,15 +302,13 @@ <ProjectReference Include="..\DotNetOpenAuth\DotNetOpenAuth.csproj"> <Project>{3191B653-F76D-4C1A-9A5A-347BC3AAAAB7}</Project> <Name>DotNetOpenAuth</Name> + <Shadow>true</Shadow> </ProjectReference> </ItemGroup> <ItemGroup> <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" /> @@ -325,8 +338,39 @@ <None Include="App.config" /> </ItemGroup> <ItemGroup> + <EmbeddedResource Include="OpenId\Discovery\xrdsdiscovery\xrds20dual.xml" /> + </ItemGroup> + <ItemGroup> <Folder Include="OpenId\UI\" /> </ItemGroup> - <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" /> - <Import Project="..\..\tools\DotNetOpenAuth.Versioning.targets" /> -</Project> + <ItemGroup> + <BootstrapperPackage Include=".NETFramework,Version=v4.0"> + <Visible>False</Visible> + <ProductName>Microsoft .NET Framework 4 %28x86 and x64%29</ProductName> + <Install>true</Install> + </BootstrapperPackage> + <BootstrapperPackage Include="Microsoft.Net.Client.3.5"> + <Visible>False</Visible> + <ProductName>.NET Framework 3.5 SP1 Client Profile</ProductName> + <Install>false</Install> + </BootstrapperPackage> + <BootstrapperPackage Include="Microsoft.Net.Framework.3.5.SP1"> + <Visible>False</Visible> + <ProductName>.NET Framework 3.5 SP1</ProductName> + <Install>false</Install> + </BootstrapperPackage> + <BootstrapperPackage Include="Microsoft.Windows.Installer.3.1"> + <Visible>False</Visible> + <ProductName>Windows Installer 3.1</ProductName> + <Install>true</Install> + </BootstrapperPackage> + </ItemGroup> + <ItemGroup> + <EmbeddedResource Include="OpenId\Discovery\htmldiscovery\html20provWithEmptyXrds.html" /> + </ItemGroup> + <ItemGroup> + <EmbeddedResource Include="OpenId\Discovery\htmldiscovery\html20provWithBadXrds.html" /> + </ItemGroup> + <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> + <Import Project="$(ProjectRoot)tools\DotNetOpenAuth.targets" /> +</Project>
\ No newline at end of file diff --git a/src/DotNetOpenAuth.Test/Hosting/HostingTests.cs b/src/DotNetOpenAuth.Test/Hosting/HostingTests.cs index d7de7a1..b7e04f7 100644 --- a/src/DotNetOpenAuth.Test/Hosting/HostingTests.cs +++ b/src/DotNetOpenAuth.Test/Hosting/HostingTests.cs @@ -12,11 +12,11 @@ namespace DotNetOpenAuth.Test.Hosting { using System.Net; using System.Text; using DotNetOpenAuth.Test.OpenId; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; - [TestClass] + [TestFixture, Category("HostASPNET")] public class HostingTests : TestBase { - [TestMethod] + [TestCase] public void AspHostBasicTest() { try { using (AspNetHost host = AspNetHost.CreateHost(TestWebDirectory)) { @@ -25,7 +25,7 @@ namespace DotNetOpenAuth.Test.Hosting { Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); using (StreamReader sr = new StreamReader(response.GetResponseStream())) { string content = sr.ReadToEnd(); - StringAssert.Contains(content, "Test home page"); + StringAssert.Contains("Test home page", content); } } } diff --git a/src/DotNetOpenAuth.Test/LocalizationTests.cs b/src/DotNetOpenAuth.Test/LocalizationTests.cs index 50e9a34..4920deb 100644 --- a/src/DotNetOpenAuth.Test/LocalizationTests.cs +++ b/src/DotNetOpenAuth.Test/LocalizationTests.cs @@ -8,19 +8,21 @@ namespace DotNetOpenAuth.Test { using System; using System.Globalization; using System.Threading; + using System.Web; using DotNetOpenAuth.Messaging; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; /// <summary> /// Tests various localized resources work as expected. /// </summary> - [TestClass] - public class LocalizationTests { + [TestFixture] + public class LocalizationTests : TestBase { /// <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.")] + [TestCase, ExpectedException(typeof(InvalidOperationException), ExpectedMessage = "Ovaj metod zahteva tekući HttpContext. Kao alternativa, koristite preklopljeni metod koji dozvoljava da se prosledi informacija bez HttpContext-a.")] public void Serbian() { + HttpContext.Current = null; // our testbase initializes this, but it must be null to throw Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("sr"); ErrorUtilities.VerifyHttpContext(); } diff --git a/src/DotNetOpenAuth.Test/Logging.config b/src/DotNetOpenAuth.Test/Logging.config index cd19de2..87da027 100644 --- a/src/DotNetOpenAuth.Test/Logging.config +++ b/src/DotNetOpenAuth.Test/Logging.config @@ -30,7 +30,4 @@ <logger name="DotNetOpenAuth.Test"> <level value="Debug" /> </logger> - <logger name="DotNetOpenAuth.OpenId.ChannelElements.SigningBindingElement"> - <level value="WARN" /> - </logger> </log4net> diff --git a/src/DotNetOpenAuth.Test/Messaging/Bindings/StandardExpirationBindingElementTests.cs b/src/DotNetOpenAuth.Test/Messaging/Bindings/StandardExpirationBindingElementTests.cs index 3cc792b..9ba433d 100644 --- a/src/DotNetOpenAuth.Test/Messaging/Bindings/StandardExpirationBindingElementTests.cs +++ b/src/DotNetOpenAuth.Test/Messaging/Bindings/StandardExpirationBindingElementTests.cs @@ -9,11 +9,11 @@ namespace DotNetOpenAuth.Test.Messaging.Bindings { using DotNetOpenAuth.Messaging; using DotNetOpenAuth.Messaging.Bindings; using DotNetOpenAuth.Test.Mocks; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; - [TestClass] + [TestFixture] public class StandardExpirationBindingElementTests : MessagingTestBase { - [TestMethod] + [TestCase] public void SendSetsTimestamp() { TestExpiringMessage message = new TestExpiringMessage(MessageTransport.Indirect); message.Recipient = new Uri("http://localtest"); @@ -24,13 +24,13 @@ namespace DotNetOpenAuth.Test.Messaging.Bindings { Assert.IsTrue(DateTime.UtcNow - ((IExpiringProtocolMessage)message).UtcCreationDate < TimeSpan.FromSeconds(3), "The timestamp on the message was not set on send."); } - [TestMethod] + [TestCase] public void VerifyGoodTimestampIsAccepted() { this.Channel = CreateChannel(MessageProtections.Expiration); this.ParameterizedReceiveProtectedTest(DateTime.UtcNow, false); } - [TestMethod, ExpectedException(typeof(ExpiredMessageException))] + [TestCase, ExpectedException(typeof(ExpiredMessageException))] public void VerifyBadTimestampIsRejected() { this.Channel = CreateChannel(MessageProtections.Expiration); 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 14651bc..d8698ce 100644 --- a/src/DotNetOpenAuth.Test/Messaging/Bindings/StandardReplayProtectionBindingElementTests.cs +++ b/src/DotNetOpenAuth.Test/Messaging/Bindings/StandardReplayProtectionBindingElementTests.cs @@ -15,16 +15,16 @@ namespace DotNetOpenAuth.Test.Messaging.Bindings { using DotNetOpenAuth.OpenId.ChannelElements; using DotNetOpenAuth.OpenId.Messages; using DotNetOpenAuth.Test.Mocks; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; - [TestClass] + [TestFixture] public class StandardReplayProtectionBindingElementTests : MessagingTestBase { private Protocol protocol; private StandardReplayProtectionBindingElement nonceElement; private IReplayProtectedProtocolMessage message; private INonceStore nonceStore; - [TestInitialize] + [SetUp] public override void SetUp() { base.SetUp(); @@ -39,7 +39,7 @@ namespace DotNetOpenAuth.Test.Messaging.Bindings { /// <summary> /// Verifies that the generated nonce includes random characters. /// </summary> - [TestMethod] + [TestCase] public void RandomCharactersTest() { Assert.IsNotNull(this.nonceElement.ProcessOutgoingMessage(this.message)); Assert.IsNotNull(this.message.Nonce, "No nonce was set on the message."); @@ -56,7 +56,7 @@ namespace DotNetOpenAuth.Test.Messaging.Bindings { /// <summary> /// Verifies that a message is received correctly. /// </summary> - [TestMethod] + [TestCase] public void ValidMessageReceivedTest() { this.message.Nonce = "a"; Assert.IsNotNull(this.nonceElement.ProcessIncomingMessage(this.message)); @@ -65,7 +65,7 @@ namespace DotNetOpenAuth.Test.Messaging.Bindings { /// <summary> /// Verifies that a message that doesn't have a string of random characters is received correctly. /// </summary> - [TestMethod] + [TestCase] public void ValidMessageNoNonceReceivedTest() { this.message.Nonce = string.Empty; this.nonceElement.AllowZeroLengthNonce = true; @@ -75,7 +75,7 @@ namespace DotNetOpenAuth.Test.Messaging.Bindings { /// <summary> /// Verifies that a message that doesn't have a string of random characters is received correctly. /// </summary> - [TestMethod, ExpectedException(typeof(ProtocolException))] + [TestCase, ExpectedException(typeof(ProtocolException))] public void InvalidMessageNoNonceReceivedTest() { this.message.Nonce = string.Empty; this.nonceElement.AllowZeroLengthNonce = false; @@ -85,7 +85,7 @@ namespace DotNetOpenAuth.Test.Messaging.Bindings { /// <summary> /// Verifies that a replayed message is rejected. /// </summary> - [TestMethod, ExpectedException(typeof(ReplayedMessageException))] + [TestCase, ExpectedException(typeof(ReplayedMessageException))] public void ReplayDetectionTest() { this.message.Nonce = "a"; Assert.IsNotNull(this.nonceElement.ProcessIncomingMessage(this.message)); diff --git a/src/DotNetOpenAuth.Test/Messaging/ChannelTests.cs b/src/DotNetOpenAuth.Test/Messaging/ChannelTests.cs index 7846411..d22c2f7 100644 --- a/src/DotNetOpenAuth.Test/Messaging/ChannelTests.cs +++ b/src/DotNetOpenAuth.Test/Messaging/ChannelTests.cs @@ -13,23 +13,23 @@ namespace DotNetOpenAuth.Test.Messaging { using DotNetOpenAuth.Messaging; using DotNetOpenAuth.Messaging.Bindings; using DotNetOpenAuth.Test.Mocks; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; - [TestClass] + [TestFixture] public class ChannelTests : MessagingTestBase { - [TestMethod, ExpectedException(typeof(ArgumentNullException))] + [TestCase, ExpectedException(typeof(ArgumentNullException))] public void CtorNull() { // This bad channel is deliberately constructed to pass null to // its protected base class' constructor. new TestBadChannel(true); } - [TestMethod] + [TestCase] public void ReadFromRequestQueryString() { this.ParameterizedReceiveTest("GET"); } - [TestMethod] + [TestCase] public void ReadFromRequestForm() { this.ParameterizedReceiveTest("POST"); } @@ -38,37 +38,37 @@ namespace DotNetOpenAuth.Test.Messaging { /// Verifies compliance to OpenID 2.0 section 5.1.1 by verifying the channel /// will reject messages that come with an unexpected HTTP verb. /// </summary> - [TestMethod, ExpectedException(typeof(ProtocolException))] + [TestCase, ExpectedException(typeof(ProtocolException))] public void ReadFromRequestDisallowedHttpMethod() { var fields = GetStandardTestFields(FieldFill.CompleteBeforeBindings); fields["GetOnly"] = "true"; this.Channel.ReadFromRequest(CreateHttpRequestInfo("POST", fields)); } - [TestMethod, ExpectedException(typeof(ArgumentNullException))] + [TestCase, ExpectedException(typeof(ArgumentNullException))] public void SendNull() { this.Channel.PrepareResponse(null); } - [TestMethod, ExpectedException(typeof(ArgumentException))] + [TestCase, ExpectedException(typeof(ArgumentException))] public void SendIndirectedUndirectedMessage() { IProtocolMessage message = new TestDirectedMessage(MessageTransport.Indirect); this.Channel.PrepareResponse(message); } - [TestMethod, ExpectedException(typeof(ArgumentException))] + [TestCase, ExpectedException(typeof(ArgumentException))] public void SendDirectedNoRecipientMessage() { IProtocolMessage message = new TestDirectedMessage(MessageTransport.Indirect); this.Channel.PrepareResponse(message); } - [TestMethod, ExpectedException(typeof(ArgumentException))] + [TestCase, ExpectedException(typeof(ArgumentException))] public void SendInvalidMessageTransport() { IProtocolMessage message = new TestDirectedMessage((MessageTransport)100); this.Channel.PrepareResponse(message); } - [TestMethod] + [TestCase] public void SendIndirectMessage301Get() { TestDirectedMessage message = new TestDirectedMessage(MessageTransport.Indirect); GetStandardTestMessage(FieldFill.CompleteBeforeBindings, message); @@ -77,29 +77,29 @@ namespace DotNetOpenAuth.Test.Messaging { OutgoingWebResponse response = this.Channel.PrepareResponse(message); Assert.AreEqual(HttpStatusCode.Redirect, response.Status); - StringAssert.StartsWith(response.Headers[HttpResponseHeader.Location], "http://provider/path"); + StringAssert.StartsWith("http://provider/path", response.Headers[HttpResponseHeader.Location]); foreach (var pair in expected) { string key = MessagingUtilities.EscapeUriDataStringRfc3986(pair.Key); string value = MessagingUtilities.EscapeUriDataStringRfc3986(pair.Value); string substring = string.Format("{0}={1}", key, value); - StringAssert.Contains(response.Headers[HttpResponseHeader.Location], substring); + StringAssert.Contains(substring, response.Headers[HttpResponseHeader.Location]); } } - [TestMethod, ExpectedException(typeof(ArgumentNullException))] + [TestCase, ExpectedException(typeof(ArgumentNullException))] public void SendIndirectMessage301GetNullMessage() { TestBadChannel badChannel = new TestBadChannel(false); badChannel.Create301RedirectResponse(null, new Dictionary<string, string>()); } - [TestMethod, ExpectedException(typeof(ArgumentException))] + [TestCase, ExpectedException(typeof(ArgumentException))] public void SendIndirectMessage301GetEmptyRecipient() { TestBadChannel badChannel = new TestBadChannel(false); var message = new TestDirectedMessage(MessageTransport.Indirect); badChannel.Create301RedirectResponse(message, new Dictionary<string, string>()); } - [TestMethod, ExpectedException(typeof(ArgumentNullException))] + [TestCase, ExpectedException(typeof(ArgumentNullException))] public void SendIndirectMessage301GetNullFields() { TestBadChannel badChannel = new TestBadChannel(false); var message = new TestDirectedMessage(MessageTransport.Indirect); @@ -107,7 +107,7 @@ namespace DotNetOpenAuth.Test.Messaging { badChannel.Create301RedirectResponse(message, null); } - [TestMethod] + [TestCase] public void SendIndirectMessageFormPost() { // We craft a very large message to force fallback to form POST. // We'll also stick some HTML reserved characters in the string value @@ -122,29 +122,29 @@ namespace DotNetOpenAuth.Test.Messaging { Assert.AreEqual(HttpStatusCode.OK, response.Status, "A form redirect should be an HTTP successful response."); Assert.IsNull(response.Headers[HttpResponseHeader.Location], "There should not be a redirection header in the response."); string body = response.Body; - StringAssert.Contains(body, "<form "); - StringAssert.Contains(body, "action=\"http://provider/path\""); - StringAssert.Contains(body, "method=\"post\""); - StringAssert.Contains(body, "<input type=\"hidden\" name=\"age\" value=\"15\" />"); - StringAssert.Contains(body, "<input type=\"hidden\" name=\"Location\" value=\"http://host/path\" />"); - StringAssert.Contains(body, "<input type=\"hidden\" name=\"Name\" value=\"" + HttpUtility.HtmlEncode(message.Name) + "\" />"); - StringAssert.Contains(body, ".submit()", "There should be some javascript to automate form submission."); + StringAssert.Contains("<form ", body); + StringAssert.Contains("action=\"http://provider/path\"", body); + StringAssert.Contains("method=\"post\"", body); + StringAssert.Contains("<input type=\"hidden\" name=\"age\" value=\"15\" />", body); + StringAssert.Contains("<input type=\"hidden\" name=\"Location\" value=\"http://host/path\" />", body); + StringAssert.Contains("<input type=\"hidden\" name=\"Name\" value=\"" + HttpUtility.HtmlEncode(message.Name) + "\" />", body); + StringAssert.Contains(".submit()", body, "There should be some javascript to automate form submission."); } - [TestMethod, ExpectedException(typeof(ArgumentNullException))] + [TestCase, ExpectedException(typeof(ArgumentNullException))] public void SendIndirectMessageFormPostNullMessage() { TestBadChannel badChannel = new TestBadChannel(false); badChannel.CreateFormPostResponse(null, new Dictionary<string, string>()); } - [TestMethod, ExpectedException(typeof(ArgumentException))] + [TestCase, ExpectedException(typeof(ArgumentException))] public void SendIndirectMessageFormPostEmptyRecipient() { TestBadChannel badChannel = new TestBadChannel(false); var message = new TestDirectedMessage(MessageTransport.Indirect); badChannel.CreateFormPostResponse(message, new Dictionary<string, string>()); } - [TestMethod, ExpectedException(typeof(ArgumentNullException))] + [TestCase, ExpectedException(typeof(ArgumentNullException))] public void SendIndirectMessageFormPostNullFields() { TestBadChannel badChannel = new TestBadChannel(false); var message = new TestDirectedMessage(MessageTransport.Indirect); @@ -159,7 +159,7 @@ namespace DotNetOpenAuth.Test.Messaging { /// Since this is a mock channel that doesn't actually formulate a direct message response, /// we just check that the right method was called. /// </remarks> - [TestMethod, ExpectedException(typeof(NotImplementedException), "SendDirectMessageResponse")] + [TestCase, ExpectedException(typeof(NotImplementedException))] public void SendDirectMessageResponse() { IProtocolMessage message = new TestDirectedMessage { Age = 15, @@ -169,25 +169,25 @@ namespace DotNetOpenAuth.Test.Messaging { this.Channel.PrepareResponse(message); } - [TestMethod, ExpectedException(typeof(ArgumentNullException))] + [TestCase, ExpectedException(typeof(ArgumentNullException))] public void SendIndirectMessageNull() { TestBadChannel badChannel = new TestBadChannel(false); badChannel.PrepareIndirectResponse(null); } - [TestMethod, ExpectedException(typeof(ArgumentNullException))] + [TestCase, ExpectedException(typeof(ArgumentNullException))] public void ReceiveNull() { TestBadChannel badChannel = new TestBadChannel(false); badChannel.Receive(null, null); } - [TestMethod] + [TestCase] public void ReceiveUnrecognizedMessage() { TestBadChannel badChannel = new TestBadChannel(false); Assert.IsNull(badChannel.Receive(new Dictionary<string, string>(), null)); } - [TestMethod] + [TestCase] public void ReadFromRequestWithContext() { var fields = GetStandardTestFields(FieldFill.AllRequired); TestMessage expectedMessage = GetStandardTestMessage(FieldFill.AllRequired); @@ -195,24 +195,24 @@ namespace DotNetOpenAuth.Test.Messaging { HttpContext.Current = new HttpContext(request, new HttpResponse(new StringWriter())); IProtocolMessage message = this.Channel.ReadFromRequest(); Assert.IsNotNull(message); - Assert.IsInstanceOfType(message, typeof(TestMessage)); + Assert.IsInstanceOf<TestMessage>(message); Assert.AreEqual(expectedMessage.Age, ((TestMessage)message).Age); } - [TestMethod, ExpectedException(typeof(InvalidOperationException))] + [TestCase, ExpectedException(typeof(InvalidOperationException))] public void ReadFromRequestNoContext() { HttpContext.Current = null; TestBadChannel badChannel = new TestBadChannel(false); badChannel.ReadFromRequest(); } - [TestMethod, ExpectedException(typeof(ArgumentNullException))] + [TestCase, ExpectedException(typeof(ArgumentNullException))] public void ReadFromRequestNull() { TestBadChannel badChannel = new TestBadChannel(false); badChannel.ReadFromRequest(null); } - [TestMethod] + [TestCase] public void SendReplayProtectedMessageSetsNonce() { TestReplayProtectedMessage message = new TestReplayProtectedMessage(MessageTransport.Indirect); message.Recipient = new Uri("http://localtest"); @@ -222,33 +222,33 @@ namespace DotNetOpenAuth.Test.Messaging { Assert.IsNotNull(((IReplayProtectedProtocolMessage)message).Nonce); } - [TestMethod, ExpectedException(typeof(InvalidSignatureException))] + [TestCase, ExpectedException(typeof(InvalidSignatureException))] public void ReceivedInvalidSignature() { this.Channel = CreateChannel(MessageProtections.TamperProtection); this.ParameterizedReceiveProtectedTest(DateTime.UtcNow, true); } - [TestMethod] + [TestCase] public void ReceivedReplayProtectedMessageJustOnce() { this.Channel = CreateChannel(MessageProtections.ReplayProtection); this.ParameterizedReceiveProtectedTest(DateTime.UtcNow, false); } - [TestMethod, ExpectedException(typeof(ReplayedMessageException))] + [TestCase, ExpectedException(typeof(ReplayedMessageException))] public void ReceivedReplayProtectedMessageTwice() { this.Channel = CreateChannel(MessageProtections.ReplayProtection); this.ParameterizedReceiveProtectedTest(DateTime.UtcNow, false); this.ParameterizedReceiveProtectedTest(DateTime.UtcNow, false); } - [TestMethod, ExpectedException(typeof(ProtocolException))] + [TestCase, ExpectedException(typeof(ProtocolException))] public void MessageExpirationWithoutTamperResistance() { new TestChannel( new TestMessageFactory(), new StandardExpirationBindingElement()); } - [TestMethod, ExpectedException(typeof(ProtocolException))] + [TestCase, ExpectedException(typeof(ProtocolException))] public void TooManyBindingElementsProvidingSameProtection() { Channel channel = new TestChannel( new TestMessageFactory(), @@ -258,7 +258,7 @@ namespace DotNetOpenAuth.Test.Messaging { accessor.ProcessOutgoingMessage(new TestSignedDirectedMessage()); } - [TestMethod] + [TestCase] public void BindingElementsOrdering() { IChannelBindingElement transformA = new MockTransformationBindingElement("a"); IChannelBindingElement transformB = new MockTransformationBindingElement("b"); @@ -282,20 +282,20 @@ namespace DotNetOpenAuth.Test.Messaging { Assert.AreSame(sign, channel.BindingElements[4]); } - [TestMethod, ExpectedException(typeof(UnprotectedMessageException))] + [TestCase, ExpectedException(typeof(UnprotectedMessageException))] public void InsufficientlyProtectedMessageSent() { var message = new TestSignedDirectedMessage(MessageTransport.Direct); message.Recipient = new Uri("http://localtest"); this.Channel.PrepareResponse(message); } - [TestMethod, ExpectedException(typeof(UnprotectedMessageException))] + [TestCase, ExpectedException(typeof(UnprotectedMessageException))] public void InsufficientlyProtectedMessageReceived() { this.Channel = CreateChannel(MessageProtections.None, MessageProtections.TamperProtection); this.ParameterizedReceiveProtectedTest(DateTime.Now, false); } - [TestMethod, ExpectedException(typeof(ProtocolException))] + [TestCase, ExpectedException(typeof(ProtocolException))] public void IncomingMessageMissingRequiredParameters() { var fields = GetStandardTestFields(FieldFill.IdentifiableButNotAllRequired); this.Channel.ReadFromRequest(CreateHttpRequestInfo("GET", fields)); diff --git a/src/DotNetOpenAuth.Test/Messaging/CollectionAssert.cs b/src/DotNetOpenAuth.Test/Messaging/CollectionAssert.cs index db136f5..506a6b2 100644 --- a/src/DotNetOpenAuth.Test/Messaging/CollectionAssert.cs +++ b/src/DotNetOpenAuth.Test/Messaging/CollectionAssert.cs @@ -11,7 +11,7 @@ namespace DotNetOpenAuth.Test.Messaging { using System.Diagnostics.Contracts; using System.Linq; using DotNetOpenAuth.Messaging; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; internal class CollectionAssert<T> { internal static void AreEquivalent(ICollection<T> expected, ICollection<T> actual) { diff --git a/src/DotNetOpenAuth.Test/Messaging/EnumerableCacheTests.cs b/src/DotNetOpenAuth.Test/Messaging/EnumerableCacheTests.cs index 55f4394..1c9f5a8 100644 --- a/src/DotNetOpenAuth.Test/Messaging/EnumerableCacheTests.cs +++ b/src/DotNetOpenAuth.Test/Messaging/EnumerableCacheTests.cs @@ -11,12 +11,12 @@ namespace DotNetOpenAuth.Test.Messaging { using System.Collections.ObjectModel; using System.Linq; using DotNetOpenAuth.Messaging; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; /// <summary> /// Tests for cached enumeration. /// </summary> - [TestClass] + [TestFixture] public class EnumerableCacheTests { /// <summary> /// The number of times the generator method's implementation is started. @@ -29,20 +29,15 @@ namespace DotNetOpenAuth.Test.Messaging { private int generatorCompleted; /// <summary> - /// Gets or sets the test context. - /// </summary> - public TestContext TestContext { get; set; } - - /// <summary> /// Sets up a test. /// </summary> - [TestInitialize] + [SetUp] public void Setup() { this.generatorInvocations = 0; this.generatorCompleted = 0; } - [TestMethod] + [TestCase] public void EnumerableCache() { // Baseline var generator = this.NumberGenerator(); @@ -63,7 +58,7 @@ namespace DotNetOpenAuth.Test.Messaging { CollectionAssert.AreEqual(list1, list4); } - [TestMethod] + [TestCase] public void GeneratesOnlyRequiredElements() { var generator = this.NumberGenerator().CacheGeneratedResults(); Assert.AreEqual(0, this.generatorInvocations); @@ -72,28 +67,28 @@ namespace DotNetOpenAuth.Test.Messaging { Assert.AreEqual(0, this.generatorCompleted, "Only taking part of the list should not have completed the generator."); } - [TestMethod] + [TestCase] public void PassThruDoubleCache() { var cache1 = this.NumberGenerator().CacheGeneratedResults(); var cache2 = cache1.CacheGeneratedResults(); Assert.AreSame(cache1, cache2, "Two caches were set up rather than just sharing the first one."); } - [TestMethod] + [TestCase] public void PassThruList() { var list = this.NumberGenerator().ToList(); var cache = list.CacheGeneratedResults(); Assert.AreSame(list, cache); } - [TestMethod] + [TestCase] public void PassThruArray() { var array = this.NumberGenerator().ToArray(); var cache = array.CacheGeneratedResults(); Assert.AreSame(array, cache); } - [TestMethod] + [TestCase] public void PassThruCollection() { var collection = new Collection<int>(); var cache = collection.CacheGeneratedResults(); @@ -103,7 +98,7 @@ namespace DotNetOpenAuth.Test.Messaging { /// <summary> /// Tests calling IEnumerator.Current before first call to MoveNext. /// </summary> - [TestMethod, ExpectedException(typeof(InvalidOperationException))] + [TestCase, ExpectedException(typeof(InvalidOperationException))] public void EnumerableCacheCurrentThrowsBefore() { var foo = this.NumberGenerator().CacheGeneratedResults().GetEnumerator().Current; } @@ -111,7 +106,7 @@ namespace DotNetOpenAuth.Test.Messaging { /// <summary> /// Tests calling IEnumerator.Current after MoveNext returns false. /// </summary> - [TestMethod, ExpectedException(typeof(InvalidOperationException))] + [TestCase, ExpectedException(typeof(InvalidOperationException))] public void EnumerableCacheCurrentThrowsAfter() { var enumerator = this.NumberGenerator().CacheGeneratedResults().GetEnumerator(); while (enumerator.MoveNext()) { diff --git a/src/DotNetOpenAuth.Test/Messaging/ErrorUtilitiesTests.cs b/src/DotNetOpenAuth.Test/Messaging/ErrorUtilitiesTests.cs index 36b6ae7..4408708 100644 --- a/src/DotNetOpenAuth.Test/Messaging/ErrorUtilitiesTests.cs +++ b/src/DotNetOpenAuth.Test/Messaging/ErrorUtilitiesTests.cs @@ -7,31 +7,31 @@ namespace DotNetOpenAuth.Test.Messaging { using System; using DotNetOpenAuth.Messaging; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; - [TestClass] + [TestFixture] public class ErrorUtilitiesTests { - [TestMethod, ExpectedException(typeof(ArgumentNullException))] + [TestCase, ExpectedException(typeof(ArgumentNullException))] public void VerifyArgumentNotNullThrows() { ErrorUtilities.VerifyArgumentNotNull(null, "someArg"); } - [TestMethod] + [TestCase] public void VerifyArgumentNotNullDoesNotThrow() { ErrorUtilities.VerifyArgumentNotNull("hi", "someArg"); } - [TestMethod, ExpectedException(typeof(ArgumentNullException))] + [TestCase, ExpectedException(typeof(ArgumentNullException))] public void VerifyNonZeroLengthOnNull() { ErrorUtilities.VerifyNonZeroLength(null, "someArg"); } - [TestMethod, ExpectedException(typeof(ArgumentException))] + [TestCase, ExpectedException(typeof(ArgumentException))] public void VerifyNonZeroLengthOnEmpty() { ErrorUtilities.VerifyNonZeroLength(string.Empty, "someArg"); } - [TestMethod] + [TestCase] public void VerifyNonZeroLengthOnNonEmpty() { ErrorUtilities.VerifyNonZeroLength("some Value", "someArg"); } diff --git a/src/DotNetOpenAuth.Test/Messaging/HttpRequestInfoTests.cs b/src/DotNetOpenAuth.Test/Messaging/HttpRequestInfoTests.cs index fd77746..0085d59 100644 --- a/src/DotNetOpenAuth.Test/Messaging/HttpRequestInfoTests.cs +++ b/src/DotNetOpenAuth.Test/Messaging/HttpRequestInfoTests.cs @@ -9,17 +9,17 @@ namespace DotNetOpenAuth.Test.Messaging { using System.Collections.Specialized; using System.Web; using DotNetOpenAuth.Messaging; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; - [TestClass] + [TestFixture] public class HttpRequestInfoTests : TestBase { - [TestMethod] + [TestCase] public void CtorDefault() { HttpRequestInfo info = new HttpRequestInfo(); Assert.AreEqual("GET", info.HttpMethod); } - [TestMethod] + [TestCase] public void CtorRequest() { HttpRequest request = new HttpRequest("file", "http://someserver?a=b", "a=b"); ////request.Headers["headername"] = "headervalue"; // PlatformNotSupportedException prevents us mocking this up @@ -33,7 +33,7 @@ namespace DotNetOpenAuth.Test.Messaging { } // All these tests are ineffective because ServerVariables[] cannot be set. - ////[TestMethod] + ////[TestCase] ////public void CtorRequestWithDifferentPublicHttpHost() { //// HttpRequest request = new HttpRequest("file", "http://someserver?a=b", "a=b"); //// request.ServerVariables["HTTP_HOST"] = "publichost"; @@ -44,7 +44,7 @@ namespace DotNetOpenAuth.Test.Messaging { //// Assert.AreEqual(request.QueryString["a"], info.QueryString["a"]); ////} - ////[TestMethod] + ////[TestCase] ////public void CtorRequestWithDifferentPublicHttpsHost() { //// HttpRequest request = new HttpRequest("file", "https://someserver?a=b", "a=b"); //// request.ServerVariables["HTTP_HOST"] = "publichost"; @@ -55,7 +55,7 @@ namespace DotNetOpenAuth.Test.Messaging { //// Assert.AreEqual(request.QueryString["a"], info.QueryString["a"]); ////} - ////[TestMethod] + ////[TestCase] ////public void CtorRequestWithDifferentPublicHostNonstandardPort() { //// HttpRequest request = new HttpRequest("file", "http://someserver?a=b", "a=b"); //// request.ServerVariables["HTTP_HOST"] = "publichost:550"; @@ -66,7 +66,7 @@ namespace DotNetOpenAuth.Test.Messaging { //// Assert.AreEqual(request.QueryString["a"], info.QueryString["a"]); ////} - ////[TestMethod] + ////[TestCase] ////public void CtorRequestWithDifferentPublicIPv6Host() { //// HttpRequest request = new HttpRequest("file", "http://[fe80::587e:c6e5:d3aa:657a]:8089/v3.1/", ""); //// request.ServerVariables["HTTP_HOST"] = "[fe80::587e:c6e5:d3aa:657b]:8089"; @@ -80,7 +80,7 @@ namespace DotNetOpenAuth.Test.Messaging { /// Checks that a property dependent on another null property /// doesn't generate a NullReferenceException. /// </summary> - [TestMethod] + [TestCase] public void QueryBeforeSettingUrl() { HttpRequestInfo info = new HttpRequestInfo(); Assert.IsNull(info.Query); @@ -89,7 +89,7 @@ namespace DotNetOpenAuth.Test.Messaging { /// <summary> /// Verifies that looking up a querystring variable is gracefully handled without a query in the URL. /// </summary> - [TestMethod] + [TestCase] public void QueryStringLookupWithoutQuery() { HttpRequestInfo info = new HttpRequestInfo(); Assert.IsNull(info.QueryString["hi"]); @@ -98,7 +98,7 @@ namespace DotNetOpenAuth.Test.Messaging { /// <summary> /// Verifies SSL forwarders are correctly handled when they supply X_FORWARDED_PROTO and HOST /// </summary> - [TestMethod] + [TestCase] public void GetPublicFacingUrlSSLForwarder1() { HttpRequest req = new HttpRequest("a.aspx", "http://someinternalhost/a.aspx?a=b", "a=b"); var serverVariables = new NameValueCollection(); @@ -112,7 +112,7 @@ namespace DotNetOpenAuth.Test.Messaging { /// <summary> /// Verifies SSL forwarders are correctly handled when they supply X_FORWARDED_PROTO and HOST:port /// </summary> - [TestMethod] + [TestCase] public void GetPublicFacingUrlSSLForwarder2() { HttpRequest req = new HttpRequest("a.aspx", "http://someinternalhost/a.aspx?a=b", "a=b"); var serverVariables = new NameValueCollection(); @@ -126,7 +126,7 @@ namespace DotNetOpenAuth.Test.Messaging { /// <summary> /// Verifies SSL forwarders are correctly handled when they supply just HOST /// </summary> - [TestMethod] + [TestCase] public void GetPublicFacingUrlSSLForwarder3() { HttpRequest req = new HttpRequest("a.aspx", "http://someinternalhost/a.aspx?a=b", "a=b"); var serverVariables = new NameValueCollection(); @@ -139,7 +139,7 @@ namespace DotNetOpenAuth.Test.Messaging { /// <summary> /// Verifies SSL forwarders are correctly handled when they supply just HOST:port /// </summary> - [TestMethod] + [TestCase] public void GetPublicFacingUrlSSLForwarder4() { HttpRequest req = new HttpRequest("a.aspx", "http://someinternalhost/a.aspx?a=b", "a=b"); var serverVariables = new NameValueCollection(); diff --git a/src/DotNetOpenAuth.Test/Messaging/MessageSerializerTests.cs b/src/DotNetOpenAuth.Test/Messaging/MessageSerializerTests.cs index 481a715..91cccf1 100644 --- a/src/DotNetOpenAuth.Test/Messaging/MessageSerializerTests.cs +++ b/src/DotNetOpenAuth.Test/Messaging/MessageSerializerTests.cs @@ -9,30 +9,30 @@ namespace DotNetOpenAuth.Test.Messaging { using System.Collections.Generic; using System.Xml; using DotNetOpenAuth.Messaging; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; /// <summary> /// Tests for the <see cref="MessageSerializer"/> class. /// </summary> - [TestClass()] + [TestFixture()] public class MessageSerializerTests : MessagingTestBase { - [TestMethod, ExpectedException(typeof(ArgumentNullException))] + [TestCase, ExpectedException(typeof(ArgumentNullException))] public void SerializeNull() { var serializer = MessageSerializer.Get(typeof(Mocks.TestMessage)); serializer.Serialize(null); } - [TestMethod, ExpectedException(typeof(ArgumentException))] + [TestCase, ExpectedException(typeof(ArgumentException))] public void GetInvalidMessageType() { MessageSerializer.Get(typeof(string)); } - [TestMethod, ExpectedException(typeof(ArgumentNullException))] + [TestCase, ExpectedException(typeof(ArgumentNullException))] public void GetNullType() { MessageSerializer.Get(null); } - [TestMethod()] + [TestCase()] public void SerializeTest() { var serializer = MessageSerializer.Get(typeof(Mocks.TestMessage)); var message = GetStandardTestMessage(FieldFill.CompleteBeforeBindings); @@ -52,13 +52,13 @@ namespace DotNetOpenAuth.Test.Messaging { Assert.IsFalse(actual.ContainsKey("EmptyMember")); } - [TestMethod, ExpectedException(typeof(ArgumentNullException))] + [TestCase, ExpectedException(typeof(ArgumentNullException))] public void DeserializeNull() { var serializer = MessageSerializer.Get(typeof(Mocks.TestMessage)); serializer.Deserialize(null, null); } - [TestMethod] + [TestCase] public void DeserializeSimple() { var serializer = MessageSerializer.Get(typeof(Mocks.TestMessage)); Dictionary<string, string> fields = new Dictionary<string, string>(StringComparer.Ordinal); @@ -81,7 +81,7 @@ namespace DotNetOpenAuth.Test.Messaging { /// The element sorting rules are first inheritance order, then alphabetical order. /// This test validates correct behavior on both. /// </remarks> - [TestMethod] + [TestCase] public void DeserializeVerifyElementOrdering() { var serializer = MessageSerializer.Get(typeof(Mocks.TestDerivedMessage)); Dictionary<string, string> fields = new Dictionary<string, string>(StringComparer.Ordinal); @@ -105,7 +105,7 @@ namespace DotNetOpenAuth.Test.Messaging { Assert.AreEqual("privateValue", actual.PrivatePropertyAccessor); } - [TestMethod] + [TestCase] public void DeserializeWithExtraFields() { var serializer = MessageSerializer.Get(typeof(Mocks.TestMessage)); Dictionary<string, string> fields = new Dictionary<string, string>(StringComparer.Ordinal); @@ -122,7 +122,7 @@ namespace DotNetOpenAuth.Test.Messaging { Assert.IsNull(actual.EmptyMember); } - [TestMethod, ExpectedException(typeof(ProtocolException))] + [TestCase, ExpectedException(typeof(ProtocolException))] public void DeserializeInvalidMessage() { IProtocolMessage message = new Mocks.TestDirectedMessage(); var serializer = MessageSerializer.Get(message.GetType()); diff --git a/src/DotNetOpenAuth.Test/Messaging/MessagingTestBase.cs b/src/DotNetOpenAuth.Test/Messaging/MessagingTestBase.cs index accb182..72f3359 100644 --- a/src/DotNetOpenAuth.Test/Messaging/MessagingTestBase.cs +++ b/src/DotNetOpenAuth.Test/Messaging/MessagingTestBase.cs @@ -13,7 +13,7 @@ namespace DotNetOpenAuth.Test { using DotNetOpenAuth.Messaging; using DotNetOpenAuth.Messaging.Bindings; using DotNetOpenAuth.Test.Mocks; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; /// <summary> /// The base class that all messaging test classes inherit from. @@ -45,7 +45,7 @@ namespace DotNetOpenAuth.Test { internal Channel Channel { get; set; } - [TestInitialize] + [SetUp] public override void SetUp() { base.SetUp(); @@ -156,7 +156,7 @@ namespace DotNetOpenAuth.Test { IDirectedProtocolMessage requestMessage = this.Channel.ReadFromRequest(CreateHttpRequestInfo(method, fields)); Assert.IsNotNull(requestMessage); - Assert.IsInstanceOfType(requestMessage, typeof(TestMessage)); + Assert.IsInstanceOf<TestMessage>(requestMessage); TestMessage actualMessage = (TestMessage)requestMessage; Assert.AreEqual(expectedMessage.Age, actualMessage.Age); Assert.AreEqual(expectedMessage.Name, actualMessage.Name); @@ -174,7 +174,7 @@ namespace DotNetOpenAuth.Test { } IProtocolMessage requestMessage = this.Channel.ReadFromRequest(CreateHttpRequestInfo("GET", fields)); Assert.IsNotNull(requestMessage); - Assert.IsInstanceOfType(requestMessage, typeof(TestSignedDirectedMessage)); + Assert.IsInstanceOf<TestSignedDirectedMessage>(requestMessage); TestSignedDirectedMessage actualMessage = (TestSignedDirectedMessage)requestMessage; Assert.AreEqual(expectedMessage.Age, actualMessage.Age); Assert.AreEqual(expectedMessage.Name, actualMessage.Name); diff --git a/src/DotNetOpenAuth.Test/Messaging/MessagingUtilitiesTests.cs b/src/DotNetOpenAuth.Test/Messaging/MessagingUtilitiesTests.cs index 4fc89a7..2b0e8f9 100644 --- a/src/DotNetOpenAuth.Test/Messaging/MessagingUtilitiesTests.cs +++ b/src/DotNetOpenAuth.Test/Messaging/MessagingUtilitiesTests.cs @@ -15,11 +15,11 @@ namespace DotNetOpenAuth.Test.Messaging using System.Web; using DotNetOpenAuth.Messaging; using DotNetOpenAuth.Test.Mocks; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; - [TestClass] + [TestFixture] public class MessagingUtilitiesTests : TestBase { - [TestMethod] + [TestCase] public void CreateQueryString() { var args = new Dictionary<string, string>(); args.Add("a", "b"); @@ -27,17 +27,17 @@ namespace DotNetOpenAuth.Test.Messaging Assert.AreEqual("a=b&c%2Fd=e%2Ff", MessagingUtilities.CreateQueryString(args)); } - [TestMethod] + [TestCase] public void CreateQueryStringEmptyCollection() { Assert.AreEqual(0, MessagingUtilities.CreateQueryString(new Dictionary<string, string>()).Length); } - [TestMethod, ExpectedException(typeof(ArgumentNullException))] + [TestCase, ExpectedException(typeof(ArgumentNullException))] public void CreateQueryStringNullDictionary() { MessagingUtilities.CreateQueryString(null); } - [TestMethod] + [TestCase] public void AppendQueryArgs() { UriBuilder uri = new UriBuilder("http://baseline.org/page"); var args = new Dictionary<string, string>(); @@ -51,17 +51,17 @@ namespace DotNetOpenAuth.Test.Messaging Assert.AreEqual("http://baseline.org/page?a=b&c%2Fd=e%2Ff&g=h", uri.Uri.AbsoluteUri); } - [TestMethod, ExpectedException(typeof(ArgumentNullException))] + [TestCase, ExpectedException(typeof(ArgumentNullException))] public void AppendQueryArgsNullUriBuilder() { MessagingUtilities.AppendQueryArgs(null, new Dictionary<string, string>()); } - [TestMethod] + [TestCase] public void AppendQueryArgsNullDictionary() { MessagingUtilities.AppendQueryArgs(new UriBuilder(), null); } - [TestMethod] + [TestCase] public void ToDictionary() { NameValueCollection nvc = new NameValueCollection(); nvc["a"] = "b"; @@ -73,7 +73,7 @@ namespace DotNetOpenAuth.Test.Messaging Assert.AreEqual(nvc["c"], actual["c"]); } - [TestMethod, ExpectedException(typeof(ArgumentException))] + [TestCase, ExpectedException(typeof(ArgumentException))] public void ToDictionaryWithNullKey() { NameValueCollection nvc = new NameValueCollection(); nvc[null] = "a"; @@ -81,7 +81,7 @@ namespace DotNetOpenAuth.Test.Messaging nvc.ToDictionary(true); } - [TestMethod] + [TestCase] public void ToDictionaryWithSkippedNullKey() { NameValueCollection nvc = new NameValueCollection(); nvc[null] = "a"; @@ -91,27 +91,27 @@ namespace DotNetOpenAuth.Test.Messaging Assert.AreEqual(nvc["b"], dictionary["b"]); } - [TestMethod] + [TestCase] public void ToDictionaryNull() { Assert.IsNull(MessagingUtilities.ToDictionary(null)); } - [TestMethod, ExpectedException(typeof(ArgumentNullException))] + [TestCase, ExpectedException(typeof(ArgumentNullException))] public void ApplyHeadersToResponseNullAspNetResponse() { MessagingUtilities.ApplyHeadersToResponse(new WebHeaderCollection(), (HttpResponse)null); } - [TestMethod, ExpectedException(typeof(ArgumentNullException))] + [TestCase, ExpectedException(typeof(ArgumentNullException))] public void ApplyHeadersToResponseNullListenerResponse() { MessagingUtilities.ApplyHeadersToResponse(new WebHeaderCollection(), (HttpListenerResponse)null); } - [TestMethod, ExpectedException(typeof(ArgumentNullException))] + [TestCase, ExpectedException(typeof(ArgumentNullException))] public void ApplyHeadersToResponseNullHeaders() { MessagingUtilities.ApplyHeadersToResponse(null, new HttpResponse(new StringWriter())); } - [TestMethod] + [TestCase] public void ApplyHeadersToResponse() { var headers = new WebHeaderCollection(); headers[HttpResponseHeader.ContentType] = "application/binary"; @@ -128,7 +128,7 @@ namespace DotNetOpenAuth.Test.Messaging /// <remarks> /// The tests in this method come from http://wiki.oauth.net/TestCases /// </remarks> - [TestMethod] + [TestCase] public void EscapeUriDataStringRfc3986Tests() { Assert.AreEqual("abcABC123", MessagingUtilities.EscapeUriDataStringRfc3986("abcABC123")); Assert.AreEqual("-._~", MessagingUtilities.EscapeUriDataStringRfc3986("-._~")); @@ -145,7 +145,7 @@ namespace DotNetOpenAuth.Test.Messaging /// <summary> /// Verifies the overall format of the multipart POST is correct. /// </summary> - [TestMethod] + [TestCase] public void PostMultipart() { var httpHandler = new TestWebRequestHandler(); bool callbackTriggered = false; @@ -174,7 +174,7 @@ namespace DotNetOpenAuth.Test.Messaging /// <summary> /// Verifies proper behavior of GetHttpVerb /// </summary> - [TestMethod] + [TestCase] public void GetHttpVerbTest() { Assert.AreEqual("GET", MessagingUtilities.GetHttpVerb(HttpDeliveryMethods.GetRequest)); Assert.AreEqual("POST", MessagingUtilities.GetHttpVerb(HttpDeliveryMethods.PostRequest)); @@ -192,7 +192,7 @@ namespace DotNetOpenAuth.Test.Messaging /// <summary> /// Verifies proper behavior of GetHttpVerb on invalid input. /// </summary> - [TestMethod, ExpectedException(typeof(ArgumentException))] + [TestCase, ExpectedException(typeof(ArgumentException))] public void GetHttpVerbOutOfRangeTest() { MessagingUtilities.GetHttpVerb(HttpDeliveryMethods.PutRequest | HttpDeliveryMethods.PostRequest); } @@ -200,7 +200,7 @@ namespace DotNetOpenAuth.Test.Messaging /// <summary> /// Verifies proper behavior of GetHttpDeliveryMethod /// </summary> - [TestMethod] + [TestCase] public void GetHttpDeliveryMethodTest() { Assert.AreEqual(HttpDeliveryMethods.GetRequest, MessagingUtilities.GetHttpDeliveryMethod("GET")); Assert.AreEqual(HttpDeliveryMethods.PostRequest, MessagingUtilities.GetHttpDeliveryMethod("POST")); @@ -212,7 +212,7 @@ namespace DotNetOpenAuth.Test.Messaging /// <summary> /// Verifies proper behavior of GetHttpDeliveryMethod for an unexpected input /// </summary> - [TestMethod, ExpectedException(typeof(ArgumentException))] + [TestCase, 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 index 57614ba..08524b2 100644 --- a/src/DotNetOpenAuth.Test/Messaging/MultipartPostPartTests.cs +++ b/src/DotNetOpenAuth.Test/Messaging/MultipartPostPartTests.cs @@ -11,14 +11,14 @@ namespace DotNetOpenAuth.Test.Messaging { using System.IO; using System.Net; using DotNetOpenAuth.Messaging; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; - [TestClass] + [TestFixture] public class MultipartPostPartTests : TestBase { /// <summary> /// Verifies that the Length property matches the length actually serialized. /// </summary> - [TestMethod] + [TestCase] public void FormDataSerializeMatchesLength() { var part = MultipartPostPart.CreateFormPart("a", "b"); VerifyLength(part); @@ -27,7 +27,7 @@ namespace DotNetOpenAuth.Test.Messaging { /// <summary> /// Verifies that the length property matches the length actually serialized. /// </summary> - [TestMethod] + [TestCase] public void FileSerializeMatchesLength() { using (TempFileCollection tfc = new TempFileCollection()) { string file = tfc.AddExtension(".txt"); @@ -40,7 +40,7 @@ namespace DotNetOpenAuth.Test.Messaging { /// <summary> /// Verifies file multiparts identify themselves as files and not merely form-data. /// </summary> - [TestMethod] + [TestCase] public void FilePartAsFile() { var part = MultipartPostPart.CreateFormFilePart("somename", "somefile", "plain/text", new MemoryStream()); Assert.AreEqual("file", part.ContentDisposition); @@ -49,7 +49,7 @@ namespace DotNetOpenAuth.Test.Messaging { /// <summary> /// Verifies MultiPartPost sends the right number of bytes. /// </summary> - [TestMethod] + [TestCase] public void MultiPartPostAscii() { using (TempFileCollection tfc = new TempFileCollection()) { string file = tfc.AddExtension("txt"); @@ -64,7 +64,7 @@ namespace DotNetOpenAuth.Test.Messaging { /// <summary> /// Verifies MultiPartPost sends the right number of bytes. /// </summary> - [TestMethod] + [TestCase] public void MultiPartPostMultiByteCharacters() { using (TempFileCollection tfc = new TempFileCollection()) { string file = tfc.AddExtension("txt"); @@ -94,9 +94,9 @@ namespace DotNetOpenAuth.Test.Messaging { bool posted = false; handler.Callback = req => { foreach (string header in req.Headers) { - TestContext.WriteLine("{0}: {1}", header, req.Headers[header]); + TestUtilities.TestLogger.InfoFormat("{0}: {1}", header, req.Headers[header]); } - TestContext.WriteLine(handler.RequestEntityAsString); + TestUtilities.TestLogger.InfoFormat(handler.RequestEntityAsString); Assert.AreEqual(req.ContentLength, handler.RequestEntityStream.Length); posted = true; return null; diff --git a/src/DotNetOpenAuth.Test/Messaging/OutgoingWebResponseTests.cs b/src/DotNetOpenAuth.Test/Messaging/OutgoingWebResponseTests.cs index 2923af4..10045de 100644 --- a/src/DotNetOpenAuth.Test/Messaging/OutgoingWebResponseTests.cs +++ b/src/DotNetOpenAuth.Test/Messaging/OutgoingWebResponseTests.cs @@ -9,14 +9,14 @@ namespace DotNetOpenAuth.Test.Messaging { using System.Net.Mime; using System.Text; using DotNetOpenAuth.Messaging; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; - [TestClass] + [TestFixture] public class OutgoingWebResponseTests { /// <summary> /// Verifies that setting the Body property correctly converts to a byte stream. /// </summary> - [TestMethod] + [TestCase] public void SetBodyToByteStream() { var response = new OutgoingWebResponse(); string stringValue = "abc"; diff --git a/src/DotNetOpenAuth.Test/Messaging/ProtocolExceptionTests.cs b/src/DotNetOpenAuth.Test/Messaging/ProtocolExceptionTests.cs index 430b929..c9e3d24 100644 --- a/src/DotNetOpenAuth.Test/Messaging/ProtocolExceptionTests.cs +++ b/src/DotNetOpenAuth.Test/Messaging/ProtocolExceptionTests.cs @@ -7,22 +7,22 @@ namespace DotNetOpenAuth.Test.Messaging { using System; using DotNetOpenAuth.Messaging; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; - [TestClass] + [TestFixture] public class ProtocolExceptionTests : TestBase { - [TestMethod] + [TestCase] public void CtorDefault() { ProtocolException ex = new ProtocolException(); } - [TestMethod] + [TestCase] public void CtorWithTextMessage() { ProtocolException ex = new ProtocolException("message"); Assert.AreEqual("message", ex.Message); } - [TestMethod] + [TestCase] public void CtorWithTextMessageAndInnerException() { Exception innerException = new Exception(); ProtocolException ex = new ProtocolException("message", innerException); @@ -30,14 +30,14 @@ namespace DotNetOpenAuth.Test.Messaging { Assert.AreSame(innerException, ex.InnerException); } - [TestMethod] + [TestCase] public void CtorWithProtocolMessage() { IProtocolMessage message = new Mocks.TestDirectedMessage(); ProtocolException ex = new ProtocolException("message", message); Assert.AreSame(message, ex.FaultedMessage); } - [TestMethod, ExpectedException(typeof(ArgumentNullException))] + [TestCase, ExpectedException(typeof(ArgumentNullException))] public void CtorWithNullProtocolMessage() { new ProtocolException("message", (IProtocolMessage)null); } diff --git a/src/DotNetOpenAuth.Test/Messaging/Reflection/MessageDescriptionTests.cs b/src/DotNetOpenAuth.Test/Messaging/Reflection/MessageDescriptionTests.cs index 76c454a..e57df65 100644 --- a/src/DotNetOpenAuth.Test/Messaging/Reflection/MessageDescriptionTests.cs +++ b/src/DotNetOpenAuth.Test/Messaging/Reflection/MessageDescriptionTests.cs @@ -8,26 +8,26 @@ namespace DotNetOpenAuth.Test.Messaging.Reflection { using System; using DotNetOpenAuth.Messaging; using DotNetOpenAuth.Messaging.Reflection; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; - [TestClass] + [TestFixture] public class MessageDescriptionTests : MessagingTestBase { - [TestMethod, ExpectedException(typeof(ArgumentNullException))] + [TestCase, ExpectedException(typeof(ArgumentNullException))] public void CtorNullType() { new MessageDescription(null, new Version(1, 0)); } - [TestMethod, ExpectedException(typeof(ArgumentNullException))] + [TestCase, ExpectedException(typeof(ArgumentNullException))] public void CtorNullVersion() { new MessageDescription(typeof(Mocks.TestMessage), null); } - [TestMethod, ExpectedException(typeof(ArgumentException))] + [TestCase, ExpectedException(typeof(ArgumentException))] public void CtorNonMessageType() { new MessageDescription(typeof(string), new Version(1, 0)); } - [TestMethod] + [TestCase] public void MultiVersionedMessageTest() { var v10 = new MessageDescription(typeof(MultiVersionMessage), new Version(1, 0)); var v20 = new MessageDescription(typeof(MultiVersionMessage), new Version(2, 0)); diff --git a/src/DotNetOpenAuth.Test/Messaging/Reflection/MessageDictionaryTests.cs b/src/DotNetOpenAuth.Test/Messaging/Reflection/MessageDictionaryTests.cs index b9e7436..9e3f4c5 100644 --- a/src/DotNetOpenAuth.Test/Messaging/Reflection/MessageDictionaryTests.cs +++ b/src/DotNetOpenAuth.Test/Messaging/Reflection/MessageDictionaryTests.cs @@ -12,20 +12,20 @@ namespace DotNetOpenAuth.Test.Messaging.Reflection { using System.Xml; using DotNetOpenAuth.Messaging; using DotNetOpenAuth.Messaging.Reflection; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; - [TestClass] + [TestFixture] public class MessageDictionaryTests : MessagingTestBase { private Mocks.TestMessage message; - [TestInitialize] + [SetUp] public override void SetUp() { base.SetUp(); this.message = new Mocks.TestDirectedMessage(); } - [TestMethod, ExpectedException(typeof(ArgumentNullException))] + [TestCase, ExpectedException(typeof(ArgumentNullException))] public void CtorNull() { this.MessageDescriptions.GetAccessor(null); } @@ -33,7 +33,7 @@ namespace DotNetOpenAuth.Test.Messaging.Reflection { /// <summary> /// A test for System.Collections.Generic.IDictionary<System.String,System.String>.Values /// </summary> - [TestMethod] + [TestCase] public void Values() { IDictionary<string, string> target = this.MessageDescriptions.GetAccessor(this.message); Collection<string> expected = new Collection<string> { @@ -59,7 +59,7 @@ namespace DotNetOpenAuth.Test.Messaging.Reflection { /// <summary> /// A test for System.Collections.Generic.IDictionary<System.String,System.String>.Keys /// </summary> - [TestMethod] + [TestCase] public void Keys() { // We expect that non-nullable value type fields will automatically have keys // in the dictionary for them. @@ -80,7 +80,7 @@ namespace DotNetOpenAuth.Test.Messaging.Reflection { /// <summary> /// A test for System.Collections.Generic.IDictionary<System.String,System.String>.Item /// </summary> - [TestMethod] + [TestCase] public void Item() { IDictionary<string, string> target = this.MessageDescriptions.GetAccessor(this.message); @@ -103,7 +103,7 @@ namespace DotNetOpenAuth.Test.Messaging.Reflection { /// <summary> /// A test for System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<System.String,System.String<<.IsReadOnly /// </summary> - [TestMethod] + [TestCase] public void IsReadOnly() { ICollection<KeyValuePair<string, string>> target = this.MessageDescriptions.GetAccessor(this.message); Assert.IsFalse(target.IsReadOnly); @@ -112,7 +112,7 @@ namespace DotNetOpenAuth.Test.Messaging.Reflection { /// <summary> /// A test for System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<System.String,System.String<<.Count /// </summary> - [TestMethod] + [TestCase] public void Count() { ICollection<KeyValuePair<string, string>> target = this.MessageDescriptions.GetAccessor(this.message); IDictionary<string, string> targetDictionary = (IDictionary<string, string>)target; @@ -124,7 +124,7 @@ namespace DotNetOpenAuth.Test.Messaging.Reflection { /// <summary> /// A test for System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<System.String,System.String<<.GetEnumerator /// </summary> - [TestMethod] + [TestCase] public void GetEnumerator() { IEnumerable<KeyValuePair<string, string>> target = this.MessageDescriptions.GetAccessor(this.message); IDictionary<string, string> targetDictionary = (IDictionary<string, string>)target; @@ -147,7 +147,7 @@ namespace DotNetOpenAuth.Test.Messaging.Reflection { Assert.IsTrue(keysLast == valuesLast && keysLast == actualLast); } - [TestMethod] + [TestCase] public void GetEnumeratorUntyped() { IEnumerable target = this.MessageDescriptions.GetAccessor(this.message); IDictionary<string, string> targetDictionary = (IDictionary<string, string>)target; @@ -174,7 +174,7 @@ namespace DotNetOpenAuth.Test.Messaging.Reflection { /// <summary> /// A test for System.Collections.Generic.IDictionary<System.String,System.String>.TryGetValue /// </summary> - [TestMethod] + [TestCase] public void TryGetValue() { IDictionary<string, string> target = this.MessageDescriptions.GetAccessor(this.message); this.message.Name = "andrew"; @@ -194,7 +194,7 @@ namespace DotNetOpenAuth.Test.Messaging.Reflection { /// <summary> /// A test for System.Collections.Generic.IDictionary<System.String,System.String>.Remove /// </summary> - [TestMethod] + [TestCase] public void RemoveTest1() { IDictionary<string, string> target = this.MessageDescriptions.GetAccessor(this.message); this.message.Name = "andrew"; @@ -211,7 +211,7 @@ namespace DotNetOpenAuth.Test.Messaging.Reflection { /// <summary> /// A test for System.Collections.Generic.IDictionary<System.String,System.String>.ContainsKey /// </summary> - [TestMethod] + [TestCase] public void ContainsKey() { IDictionary<string, string> target = this.MessageDescriptions.GetAccessor(this.message); Assert.IsTrue(target.ContainsKey("age"), "Value type declared element should have a key."); @@ -225,7 +225,7 @@ namespace DotNetOpenAuth.Test.Messaging.Reflection { /// <summary> /// A test for System.Collections.Generic.IDictionary<System.String,System.String>.Add /// </summary> - [TestMethod] + [TestCase] public void AddByKeyAndValue() { IDictionary<string, string> target = this.MessageDescriptions.GetAccessor(this.message); target.Add("extra", "value"); @@ -234,7 +234,7 @@ namespace DotNetOpenAuth.Test.Messaging.Reflection { Assert.AreEqual("Andrew", this.message.Name); } - [TestMethod, ExpectedException(typeof(ArgumentNullException))] + [TestCase, ExpectedException(typeof(ArgumentNullException))] public void AddNullValue() { IDictionary<string, string> target = this.MessageDescriptions.GetAccessor(this.message); target.Add("extra", null); @@ -243,35 +243,35 @@ namespace DotNetOpenAuth.Test.Messaging.Reflection { /// <summary> /// A test for System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<System.String,System.String<<.Add /// </summary> - [TestMethod] + [TestCase] public void AddByKeyValuePair() { IDictionary<string, string> target = this.MessageDescriptions.GetAccessor(this.message); target.Add(new KeyValuePair<string, string>("extra", "value")); Assert.IsTrue(target.Contains(new KeyValuePair<string, string>("extra", "value"))); } - [TestMethod, ExpectedException(typeof(ArgumentException))] + [TestCase, ExpectedException(typeof(ArgumentException))] public void AddExtraFieldThatAlreadyExists() { IDictionary<string, string> target = this.MessageDescriptions.GetAccessor(this.message); target.Add("extra", "value"); target.Add("extra", "value"); } - [TestMethod, ExpectedException(typeof(ArgumentException))] + [TestCase, ExpectedException(typeof(ArgumentException))] public void AddDeclaredValueThatAlreadyExists() { IDictionary<string, string> target = this.MessageDescriptions.GetAccessor(this.message); target.Add("Name", "andrew"); target.Add("Name", "andrew"); } - [TestMethod] + [TestCase] public void DefaultReferenceTypeDeclaredPropertyHasNoKey() { IDictionary<string, string> target = this.MessageDescriptions.GetAccessor(this.message); Assert.IsFalse(target.ContainsKey("Name"), "A null value should result in no key."); Assert.IsFalse(target.Keys.Contains("Name"), "A null value should result in no key."); } - [TestMethod] + [TestCase] public void RemoveStructDeclaredProperty() { IDictionary<string, string> target = this.MessageDescriptions.GetAccessor(this.message); this.message.Age = 5; @@ -284,7 +284,7 @@ namespace DotNetOpenAuth.Test.Messaging.Reflection { /// <summary> /// A test for System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<System.String,System.String<<.Remove /// </summary> - [TestMethod] + [TestCase] public void RemoveByKeyValuePair() { ICollection<KeyValuePair<string, string>> target = this.MessageDescriptions.GetAccessor(this.message); this.message.Name = "Andrew"; @@ -297,7 +297,7 @@ namespace DotNetOpenAuth.Test.Messaging.Reflection { /// <summary> /// A test for System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<System.String,System.String<<.CopyTo /// </summary> - [TestMethod] + [TestCase] public void CopyTo() { ICollection<KeyValuePair<string, string>> target = this.MessageDescriptions.GetAccessor(this.message); IDictionary<string, string> targetAsDictionary = (IDictionary<string, string>)target; @@ -314,7 +314,7 @@ namespace DotNetOpenAuth.Test.Messaging.Reflection { /// <summary> /// A test for System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<System.String,System.String<<.Contains /// </summary> - [TestMethod] + [TestCase] public void ContainsKeyValuePair() { ICollection<KeyValuePair<string, string>> target = this.MessageDescriptions.GetAccessor(this.message); IDictionary<string, string> targetAsDictionary = (IDictionary<string, string>)target; @@ -330,7 +330,7 @@ namespace DotNetOpenAuth.Test.Messaging.Reflection { /// <summary> /// A test for System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<System.String,System.String<<.Clear /// </summary> - [TestMethod] + [TestCase] public void ClearValues() { MessageDictionary target = this.MessageDescriptions.GetAccessor(this.message); IDictionary<string, string> targetAsDictionary = (IDictionary<string, string>)target; @@ -347,7 +347,7 @@ namespace DotNetOpenAuth.Test.Messaging.Reflection { /// <summary> /// Verifies that the Clear method throws the expected exception. /// </summary> - [TestMethod, ExpectedException(typeof(NotSupportedException))] + [TestCase, ExpectedException(typeof(NotSupportedException))] public void Clear() { MessageDictionary target = this.MessageDescriptions.GetAccessor(this.message); target.Clear(); diff --git a/src/DotNetOpenAuth.Test/Messaging/Reflection/MessagePartTests.cs b/src/DotNetOpenAuth.Test/Messaging/Reflection/MessagePartTests.cs index 19e6a82..66237e7 100644 --- a/src/DotNetOpenAuth.Test/Messaging/Reflection/MessagePartTests.cs +++ b/src/DotNetOpenAuth.Test/Messaging/Reflection/MessagePartTests.cs @@ -12,42 +12,47 @@ namespace DotNetOpenAuth.Test.Messaging.Reflection { using DotNetOpenAuth.Messaging; using DotNetOpenAuth.Messaging.Reflection; using DotNetOpenAuth.Test.Mocks; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; - [TestClass] + [TestFixture] public class MessagePartTests : MessagingTestBase { - [TestMethod, ExpectedException(typeof(ArgumentException))] + [TestCase, ExpectedException(typeof(ArgumentException))] public void OptionalNonNullableStruct() { this.ParameterizedMessageTypeTest(typeof(MessageWithNonNullableOptionalStruct)); } - [TestMethod] + [TestCase] public void RequiredNonNullableStruct() { this.ParameterizedMessageTypeTest(typeof(MessageWithNonNullableRequiredStruct)); } - [TestMethod] + [TestCase] public void OptionalNullableStruct() { - this.ParameterizedMessageTypeTest(typeof(MessageWithNullableOptionalStruct)); + var message = new MessageWithNullableOptionalStruct(); + var part = this.ParameterizedMessageTypeTest(message.GetType()); + + Assert.IsNull(part.GetValue(message)); + part.SetValue(message, "3"); + Assert.AreEqual("3", part.GetValue(message)); } - [TestMethod] + [TestCase] public void RequiredNullableStruct() { this.ParameterizedMessageTypeTest(typeof(MessageWithNullableRequiredStruct)); } - [TestMethod, ExpectedException(typeof(ArgumentNullException))] + [TestCase, ExpectedException(typeof(ArgumentNullException))] public void CtorNullMember() { new MessagePart(null, new MessagePartAttribute()); } - [TestMethod, ExpectedException(typeof(ArgumentNullException))] + [TestCase, ExpectedException(typeof(ArgumentNullException))] public void CtorNullAttribute() { PropertyInfo field = typeof(MessageWithNullableOptionalStruct).GetProperty("OptionalInt", BindingFlags.NonPublic | BindingFlags.Instance); new MessagePart(field, null); } - [TestMethod] + [TestCase] public void SetValue() { var message = new MessageWithNonNullableRequiredStruct(); MessagePart part = this.ParameterizedMessageTypeTest(message.GetType()); @@ -55,7 +60,7 @@ namespace DotNetOpenAuth.Test.Messaging.Reflection { Assert.AreEqual(5, message.OptionalInt); } - [TestMethod] + [TestCase] public void GetValue() { var message = new MessageWithNonNullableRequiredStruct(); message.OptionalInt = 8; @@ -63,7 +68,7 @@ namespace DotNetOpenAuth.Test.Messaging.Reflection { Assert.AreEqual("8", part.GetValue(message)); } - [TestMethod] + [TestCase] public void Base64Member() { var message = new MessageWithBase64EncodedString(); message.LastName = "andrew"; @@ -73,7 +78,7 @@ namespace DotNetOpenAuth.Test.Messaging.Reflection { Assert.AreEqual("arnott", message.LastName); } - [TestMethod] + [TestCase] public void ConstantFieldMemberValidValues() { var message = new MessageWithConstantField(); MessagePart part = GetMessagePart(message.GetType(), "ConstantField"); @@ -82,20 +87,20 @@ namespace DotNetOpenAuth.Test.Messaging.Reflection { Assert.AreEqual("abc", part.GetValue(message)); } - [TestMethod, ExpectedException(typeof(ProtocolException))] + [TestCase, ExpectedException(typeof(ProtocolException))] public void ConstantFieldMemberInvalidValues() { var message = new MessageWithConstantField(); MessagePart part = GetMessagePart(message.GetType(), "ConstantField"); part.SetValue(message, "def"); } - [TestMethod, ExpectedException(typeof(ArgumentException))] + [TestCase, ExpectedException(typeof(ArgumentException))] public void NonFieldOrPropertyMember() { MemberInfo method = typeof(MessageWithNullableOptionalStruct).GetMethod("Equals", BindingFlags.Public | BindingFlags.Instance); new MessagePart(method, new MessagePartAttribute()); } - [TestMethod] + [TestCase] public void RequiredMinAndMaxVersions() { Type messageType = typeof(MessageWithMinAndMaxVersionParts); FieldInfo newIn2Field = messageType.GetField("NewIn2", BindingFlags.Public | BindingFlags.Instance); diff --git a/src/DotNetOpenAuth.Test/Messaging/Reflection/ValueMappingTests.cs b/src/DotNetOpenAuth.Test/Messaging/Reflection/ValueMappingTests.cs index c4a79b5..60c8bc3 100644 --- a/src/DotNetOpenAuth.Test/Messaging/Reflection/ValueMappingTests.cs +++ b/src/DotNetOpenAuth.Test/Messaging/Reflection/ValueMappingTests.cs @@ -7,18 +7,18 @@ namespace DotNetOpenAuth.Test.Messaging.Reflection { using System; using DotNetOpenAuth.Messaging.Reflection; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; - [TestClass] + [TestFixture] public class ValueMappingTests { - [TestMethod, ExpectedException(typeof(ArgumentNullException))] + [TestCase, ExpectedException(typeof(ArgumentNullException))] public void CtorNullToString() { - new ValueMapping(null, str => new object()); + new ValueMapping(null, null, str => new object()); } - [TestMethod, ExpectedException(typeof(ArgumentNullException))] + [TestCase, ExpectedException(typeof(ArgumentNullException))] public void CtorNullToObject() { - new ValueMapping(obj => obj.ToString(), null); + new ValueMapping(obj => obj.ToString(), null, null); } } } diff --git a/src/DotNetOpenAuth.Test/Messaging/ResponseTests.cs b/src/DotNetOpenAuth.Test/Messaging/ResponseTests.cs index 89d165a..63be45a 100644 --- a/src/DotNetOpenAuth.Test/Messaging/ResponseTests.cs +++ b/src/DotNetOpenAuth.Test/Messaging/ResponseTests.cs @@ -9,17 +9,17 @@ namespace DotNetOpenAuth.Test.Messaging { using System.IO; using System.Web; using DotNetOpenAuth.Messaging; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; - [TestClass] + [TestFixture] public class ResponseTests : TestBase { - [TestMethod, ExpectedException(typeof(InvalidOperationException))] + [TestCase, ExpectedException(typeof(InvalidOperationException))] public void SendWithoutAspNetContext() { HttpContext.Current = null; new OutgoingWebResponse().Send(); } - [TestMethod] + [TestCase] public void Send() { StringWriter writer = new StringWriter(); HttpRequest httpRequest = new HttpRequest("file", "http://server", string.Empty); diff --git a/src/DotNetOpenAuth.Test/Mocks/CoordinatingChannel.cs b/src/DotNetOpenAuth.Test/Mocks/CoordinatingChannel.cs index 16386de..0bb35bc 100644 --- a/src/DotNetOpenAuth.Test/Mocks/CoordinatingChannel.cs +++ b/src/DotNetOpenAuth.Test/Mocks/CoordinatingChannel.cs @@ -14,7 +14,7 @@ namespace DotNetOpenAuth.Test.Mocks { using DotNetOpenAuth.Messaging; using DotNetOpenAuth.Messaging.Reflection; using DotNetOpenAuth.Test.OpenId; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; internal class CoordinatingChannel : Channel { /// <summary> diff --git a/src/DotNetOpenAuth.Test/Mocks/MockHttpRequest.cs b/src/DotNetOpenAuth.Test/Mocks/MockHttpRequest.cs index 0213a33..c18ea33 100644 --- a/src/DotNetOpenAuth.Test/Mocks/MockHttpRequest.cs +++ b/src/DotNetOpenAuth.Test/Mocks/MockHttpRequest.cs @@ -83,7 +83,7 @@ namespace DotNetOpenAuth.Test.Mocks { } } - internal void RegisterMockXrdsResponse(ServiceEndpoint endpoint) { + internal void RegisterMockXrdsResponse(IdentifierDiscoveryResult endpoint) { Contract.Requires<ArgumentNullException>(endpoint != null); string identityUri; @@ -92,10 +92,10 @@ namespace DotNetOpenAuth.Test.Mocks { } else { identityUri = endpoint.UserSuppliedIdentifier ?? endpoint.ClaimedIdentifier; } - this.RegisterMockXrdsResponse(new Uri(identityUri), new ServiceEndpoint[] { endpoint }); + this.RegisterMockXrdsResponse(new Uri(identityUri), new IdentifierDiscoveryResult[] { endpoint }); } - internal void RegisterMockXrdsResponse(Uri respondingUri, IEnumerable<ServiceEndpoint> endpoints) { + internal void RegisterMockXrdsResponse(Uri respondingUri, IEnumerable<IdentifierDiscoveryResult> endpoints) { Contract.Requires<ArgumentNullException>(endpoints != null); StringBuilder xrds = new StringBuilder(); @@ -130,12 +130,12 @@ namespace DotNetOpenAuth.Test.Mocks { this.RegisterMockResponse(respondingUri, ContentTypes.Xrds, xrds.ToString()); } - internal void RegisterMockXrdsResponse(UriIdentifier directedIdentityAssignedIdentifier, ServiceEndpoint providerEndpoint) { - ServiceEndpoint identityEndpoint = ServiceEndpoint.CreateForClaimedIdentifier( + internal void RegisterMockXrdsResponse(UriIdentifier directedIdentityAssignedIdentifier, IdentifierDiscoveryResult providerEndpoint) { + IdentifierDiscoveryResult identityEndpoint = IdentifierDiscoveryResult.CreateForClaimedIdentifier( directedIdentityAssignedIdentifier, directedIdentityAssignedIdentifier, - providerEndpoint.ProviderEndpoint, - providerEndpoint.ProviderDescription, + providerEndpoint.ProviderLocalIdentifier, + new ProviderEndpointDescription(providerEndpoint.ProviderEndpoint, providerEndpoint.Capabilities), 10, 10); this.RegisterMockXrdsResponse(identityEndpoint); diff --git a/src/DotNetOpenAuth.Test/Mocks/MockIdentifier.cs b/src/DotNetOpenAuth.Test/Mocks/MockIdentifier.cs index 346dde9..9f032b8 100644 --- a/src/DotNetOpenAuth.Test/Mocks/MockIdentifier.cs +++ b/src/DotNetOpenAuth.Test/Mocks/MockIdentifier.cs @@ -18,13 +18,13 @@ namespace DotNetOpenAuth.Test.Mocks { /// having a dependency on a hosted web site to actually perform discovery on. /// </summary> internal class MockIdentifier : Identifier { - private IEnumerable<ServiceEndpoint> endpoints; + private IEnumerable<IdentifierDiscoveryResult> endpoints; private MockHttpRequest mockHttpRequest; private Identifier wrappedIdentifier; - public MockIdentifier(Identifier wrappedIdentifier, MockHttpRequest mockHttpRequest, IEnumerable<ServiceEndpoint> endpoints) + public MockIdentifier(Identifier wrappedIdentifier, MockHttpRequest mockHttpRequest, IEnumerable<IdentifierDiscoveryResult> endpoints) : base(wrappedIdentifier.OriginalString, false) { Contract.Requires<ArgumentNullException>(wrappedIdentifier != null); Contract.Requires<ArgumentNullException>(mockHttpRequest != null); @@ -39,6 +39,10 @@ namespace DotNetOpenAuth.Test.Mocks { mockHttpRequest.RegisterMockXrdsResponse(new Uri(wrappedIdentifier.ToString()), endpoints); } + internal IEnumerable<IdentifierDiscoveryResult> DiscoveryEndpoints { + get { return this.endpoints; } + } + public override string ToString() { return this.wrappedIdentifier.ToString(); } @@ -51,10 +55,6 @@ namespace DotNetOpenAuth.Test.Mocks { return this.wrappedIdentifier.GetHashCode(); } - internal override IEnumerable<ServiceEndpoint> Discover(IDirectWebRequestHandler requestHandler) { - return this.endpoints; - } - internal override Identifier TrimFragment() { return this; } diff --git a/src/DotNetOpenAuth.Test/Mocks/MockIdentifierDiscoveryService.cs b/src/DotNetOpenAuth.Test/Mocks/MockIdentifierDiscoveryService.cs new file mode 100644 index 0000000..d74258d --- /dev/null +++ b/src/DotNetOpenAuth.Test/Mocks/MockIdentifierDiscoveryService.cs @@ -0,0 +1,47 @@ +//----------------------------------------------------------------------- +// <copyright file="MockIdentifierDiscoveryService.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.Test.Mocks { + using System; + using System.Collections.Generic; + using System.Linq; + using System.Text; + using DotNetOpenAuth.Messaging; + using DotNetOpenAuth.OpenId; + using DotNetOpenAuth.OpenId.RelyingParty; + + internal class MockIdentifierDiscoveryService : IIdentifierDiscoveryService { + /// <summary> + /// Initializes a new instance of the <see cref="MockIdentifierDiscoveryService"/> class. + /// </summary> + public MockIdentifierDiscoveryService() { + } + + #region IIdentifierDiscoveryService Members + + /// <summary> + /// Performs discovery on the specified identifier. + /// </summary> + /// <param name="identifier">The identifier to perform discovery on.</param> + /// <param name="requestHandler">The means to place outgoing HTTP requests.</param> + /// <param name="abortDiscoveryChain">if set to <c>true</c>, no further discovery services will be called for this identifier.</param> + /// <returns> + /// A sequence of service endpoints yielded by discovery. Must not be null, but may be empty. + /// </returns> + public IEnumerable<IdentifierDiscoveryResult> Discover(Identifier identifier, IDirectWebRequestHandler requestHandler, out bool abortDiscoveryChain) { + var mockIdentifier = identifier as MockIdentifier; + if (mockIdentifier == null) { + abortDiscoveryChain = false; + return Enumerable.Empty<IdentifierDiscoveryResult>(); + } + + abortDiscoveryChain = true; + return mockIdentifier.DiscoveryEndpoints; + } + + #endregion + } +} diff --git a/src/DotNetOpenAuth.Test/Mocks/MockReplayProtectionBindingElement.cs b/src/DotNetOpenAuth.Test/Mocks/MockReplayProtectionBindingElement.cs index 75281e2..96bd40d 100644 --- a/src/DotNetOpenAuth.Test/Mocks/MockReplayProtectionBindingElement.cs +++ b/src/DotNetOpenAuth.Test/Mocks/MockReplayProtectionBindingElement.cs @@ -7,7 +7,7 @@ namespace DotNetOpenAuth.Test.Mocks { using DotNetOpenAuth.Messaging; using DotNetOpenAuth.Messaging.Bindings; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; internal class MockReplayProtectionBindingElement : IChannelBindingElement { private bool messageReceived; diff --git a/src/DotNetOpenAuth.Test/Mocks/MockTransformationBindingElement.cs b/src/DotNetOpenAuth.Test/Mocks/MockTransformationBindingElement.cs index e88fe52..1db9c68 100644 --- a/src/DotNetOpenAuth.Test/Mocks/MockTransformationBindingElement.cs +++ b/src/DotNetOpenAuth.Test/Mocks/MockTransformationBindingElement.cs @@ -10,7 +10,7 @@ namespace DotNetOpenAuth.Test.Mocks { using System.Linq; using System.Text; using DotNetOpenAuth.Messaging; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; internal class MockTransformationBindingElement : IChannelBindingElement { private string transform; @@ -47,7 +47,7 @@ namespace DotNetOpenAuth.Test.Mocks { MessageProtections? IChannelBindingElement.ProcessIncomingMessage(IProtocolMessage message) { var testMessage = message as TestMessage; if (testMessage != null) { - StringAssert.StartsWith(testMessage.Name, this.transform); + StringAssert.StartsWith(this.transform, testMessage.Name); testMessage.Name = testMessage.Name.Substring(this.transform.Length); return MessageProtections.None; } diff --git a/src/DotNetOpenAuth.Test/OAuth/AppendixScenarios.cs b/src/DotNetOpenAuth.Test/OAuth/AppendixScenarios.cs index c009a83..5584a7b 100644 --- a/src/DotNetOpenAuth.Test/OAuth/AppendixScenarios.cs +++ b/src/DotNetOpenAuth.Test/OAuth/AppendixScenarios.cs @@ -12,11 +12,11 @@ namespace DotNetOpenAuth.Test.OAuth { using DotNetOpenAuth.OAuth; using DotNetOpenAuth.OAuth.ChannelElements; using DotNetOpenAuth.Test.Mocks; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; - [TestClass] + [TestFixture] public class AppendixScenarios : TestBase { - [TestMethod] + [TestCase] public void SpecAppendixAExample() { ServiceProviderDescription serviceDescription = new ServiceProviderDescription() { RequestTokenEndpoint = new MessageReceivingEndpoint("https://photos.example.net/request_token", HttpDeliveryMethods.PostRequest), diff --git a/src/DotNetOpenAuth.Test/OAuth/ChannelElements/HmacSha1SigningBindingElementTests.cs b/src/DotNetOpenAuth.Test/OAuth/ChannelElements/HmacSha1SigningBindingElementTests.cs index fcdb5e8..a11c67d 100644 --- a/src/DotNetOpenAuth.Test/OAuth/ChannelElements/HmacSha1SigningBindingElementTests.cs +++ b/src/DotNetOpenAuth.Test/OAuth/ChannelElements/HmacSha1SigningBindingElementTests.cs @@ -8,11 +8,11 @@ namespace DotNetOpenAuth.Test.ChannelElements { using DotNetOpenAuth.OAuth.ChannelElements; using DotNetOpenAuth.OAuth.Messages; using DotNetOpenAuth.Test.Mocks; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; - [TestClass] + [TestFixture] public class HmacSha1SigningBindingElementTests : MessagingTestBase { - [TestMethod] + [TestCase] public void SignatureTest() { UnauthorizedTokenRequest message = SigningBindingElementBaseTests.CreateTestRequestTokenMessage(this.MessageDescriptions, null); diff --git a/src/DotNetOpenAuth.Test/OAuth/ChannelElements/OAuthChannelTests.cs b/src/DotNetOpenAuth.Test/OAuth/ChannelElements/OAuthChannelTests.cs index b721fb7..c7b9f89 100644 --- a/src/DotNetOpenAuth.Test/OAuth/ChannelElements/OAuthChannelTests.cs +++ b/src/DotNetOpenAuth.Test/OAuth/ChannelElements/OAuthChannelTests.cs @@ -19,9 +19,9 @@ namespace DotNetOpenAuth.Test.ChannelElements { using DotNetOpenAuth.Messaging.Reflection; using DotNetOpenAuth.OAuth.ChannelElements; using DotNetOpenAuth.Test.Mocks; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; - [TestClass] + [TestFixture] public class OAuthChannelTests : TestBase { private OAuthChannel channel; private OAuthChannel_Accessor accessor; @@ -29,7 +29,7 @@ namespace DotNetOpenAuth.Test.ChannelElements { private SigningBindingElementBase signingElement; private INonceStore nonceStore; - [TestInitialize] + [SetUp] public override void SetUp() { base.SetUp(); @@ -41,32 +41,32 @@ namespace DotNetOpenAuth.Test.ChannelElements { this.channel.WebRequestHandler = this.webRequestHandler; } - [TestMethod, ExpectedException(typeof(ArgumentNullException))] + [TestCase, ExpectedException(typeof(ArgumentNullException))] public void CtorNullSigner() { new OAuthChannel(null, this.nonceStore, new InMemoryTokenManager(), new TestMessageFactory()); } - [TestMethod, ExpectedException(typeof(ArgumentNullException))] + [TestCase, ExpectedException(typeof(ArgumentNullException))] public void CtorNullStore() { new OAuthChannel(new RsaSha1SigningBindingElement(new InMemoryTokenManager()), null, new InMemoryTokenManager(), new TestMessageFactory()); } - [TestMethod, ExpectedException(typeof(ArgumentNullException))] + [TestCase, ExpectedException(typeof(ArgumentNullException))] public void CtorNullTokenManager() { new OAuthChannel(new RsaSha1SigningBindingElement(new InMemoryTokenManager()), this.nonceStore, null, new TestMessageFactory()); } - [TestMethod] + [TestCase] public void CtorSimpleConsumer() { new OAuthChannel(new RsaSha1SigningBindingElement(new InMemoryTokenManager()), this.nonceStore, (IConsumerTokenManager)new InMemoryTokenManager()); } - [TestMethod] + [TestCase] public void CtorSimpleServiceProvider() { new OAuthChannel(new RsaSha1SigningBindingElement(new InMemoryTokenManager()), this.nonceStore, (IServiceProviderTokenManager)new InMemoryTokenManager()); } - [TestMethod] + [TestCase] public void ReadFromRequestAuthorization() { this.ParameterizedReceiveTest(HttpDeliveryMethods.AuthorizationHeaderRequest); } @@ -75,7 +75,7 @@ namespace DotNetOpenAuth.Test.ChannelElements { /// Verifies that the OAuth ReadFromRequest method gathers parameters /// from the Authorization header, the query string and the entity form data. /// </summary> - [TestMethod] + [TestCase] public void ReadFromRequestAuthorizationScattered() { // Start by creating a standard POST HTTP request. var fields = new Dictionary<string, string> { @@ -99,24 +99,24 @@ namespace DotNetOpenAuth.Test.ChannelElements { IDirectedProtocolMessage requestMessage = this.channel.ReadFromRequest(requestInfo); Assert.IsNotNull(requestMessage); - Assert.IsInstanceOfType(requestMessage, typeof(TestMessage)); + Assert.IsInstanceOf<TestMessage>(requestMessage); TestMessage testMessage = (TestMessage)requestMessage; Assert.AreEqual(15, testMessage.Age); Assert.AreEqual("Andrew", testMessage.Name); Assert.AreEqual("http://hostb/pathB", testMessage.Location.AbsoluteUri); } - [TestMethod] + [TestCase] public void ReadFromRequestForm() { this.ParameterizedReceiveTest(HttpDeliveryMethods.PostRequest); } - [TestMethod] + [TestCase] public void ReadFromRequestQueryString() { this.ParameterizedReceiveTest(HttpDeliveryMethods.GetRequest); } - [TestMethod] + [TestCase] public void SendDirectMessageResponse() { IProtocolMessage message = new TestDirectedMessage { Age = 15, @@ -135,7 +135,7 @@ namespace DotNetOpenAuth.Test.ChannelElements { Assert.AreEqual("http://hostb/pathB", body["Location"]); } - [TestMethod] + [TestCase] public void ReadFromResponse() { var fields = new Dictionary<string, string> { { "age", "15" }, @@ -157,18 +157,18 @@ namespace DotNetOpenAuth.Test.ChannelElements { } } - [TestMethod, ExpectedException(typeof(ArgumentNullException))] + [TestCase, ExpectedException(typeof(ArgumentNullException))] public void RequestNull() { this.channel.Request(null); } - [TestMethod, ExpectedException(typeof(ArgumentException))] + [TestCase, ExpectedException(typeof(ArgumentException))] public void RequestNullRecipient() { IDirectedProtocolMessage message = new TestDirectedMessage(MessageTransport.Direct); this.channel.Request(message); } - [TestMethod, ExpectedException(typeof(NotSupportedException))] + [TestCase, ExpectedException(typeof(NotSupportedException))] public void RequestBadPreferredScheme() { TestDirectedMessage message = new TestDirectedMessage(MessageTransport.Direct); message.Recipient = new Uri("http://localtest"); @@ -176,7 +176,7 @@ namespace DotNetOpenAuth.Test.ChannelElements { this.channel.Request(message); } - [TestMethod] + [TestCase] public void RequestUsingAuthorizationHeader() { this.ParameterizedRequestTest(HttpDeliveryMethods.AuthorizationHeaderRequest); } @@ -184,7 +184,7 @@ namespace DotNetOpenAuth.Test.ChannelElements { /// <summary> /// Verifies that message parts can be distributed to the query, form, and Authorization header. /// </summary> - [TestMethod] + [TestCase] public void RequestUsingAuthorizationHeaderScattered() { TestDirectedMessage request = new TestDirectedMessage(MessageTransport.Direct) { Age = 15, @@ -217,17 +217,17 @@ namespace DotNetOpenAuth.Test.ChannelElements { Assert.AreEqual("appearinform=formish", this.webRequestHandler.RequestEntityAsString); } - [TestMethod] + [TestCase] public void RequestUsingGet() { this.ParameterizedRequestTest(HttpDeliveryMethods.GetRequest); } - [TestMethod] + [TestCase] public void RequestUsingPost() { this.ParameterizedRequestTest(HttpDeliveryMethods.PostRequest); } - [TestMethod] + [TestCase] public void RequestUsingHead() { this.ParameterizedRequestTest(HttpDeliveryMethods.HeadRequest); } @@ -235,7 +235,7 @@ namespace DotNetOpenAuth.Test.ChannelElements { /// <summary> /// Verifies that messages asking for special HTTP status codes get them. /// </summary> - [TestMethod] + [TestCase] public void SendDirectMessageResponseHonorsHttpStatusCodes() { IProtocolMessage message = MessagingTestBase.GetStandardTestMessage(MessagingTestBase.FieldFill.AllRequired); OutgoingWebResponse directResponse = this.accessor.PrepareDirectResponse(message); @@ -349,7 +349,7 @@ namespace DotNetOpenAuth.Test.ChannelElements { IProtocolMessage response = this.channel.Request(request); Assert.IsNotNull(response); - Assert.IsInstanceOfType(response, typeof(TestMessage)); + Assert.IsInstanceOf<TestMessage>(response); TestMessage responseMessage = (TestMessage)response; Assert.AreEqual(request.Age, responseMessage.Age); Assert.AreEqual(request.Name, responseMessage.Name); @@ -365,7 +365,7 @@ namespace DotNetOpenAuth.Test.ChannelElements { }; IProtocolMessage requestMessage = this.channel.ReadFromRequest(CreateHttpRequestInfo(scheme, fields)); Assert.IsNotNull(requestMessage); - Assert.IsInstanceOfType(requestMessage, typeof(TestMessage)); + Assert.IsInstanceOf<TestMessage>(requestMessage); TestMessage testMessage = (TestMessage)requestMessage; Assert.AreEqual(15, testMessage.Age); Assert.AreEqual("Andrew", testMessage.Name); diff --git a/src/DotNetOpenAuth.Test/OAuth/ChannelElements/PlaintextSigningBindingElementTest.cs b/src/DotNetOpenAuth.Test/OAuth/ChannelElements/PlaintextSigningBindingElementTest.cs index 01d51a3..b81eefa 100644 --- a/src/DotNetOpenAuth.Test/OAuth/ChannelElements/PlaintextSigningBindingElementTest.cs +++ b/src/DotNetOpenAuth.Test/OAuth/ChannelElements/PlaintextSigningBindingElementTest.cs @@ -10,11 +10,11 @@ namespace DotNetOpenAuth.Test.ChannelElements { using DotNetOpenAuth.OAuth.ChannelElements; using DotNetOpenAuth.OAuth.Messages; using DotNetOpenAuth.Test.Mocks; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; - [TestClass] + [TestFixture] public class PlaintextSigningBindingElementTest { - [TestMethod] + [TestCase] public void HttpsSignatureGeneration() { SigningBindingElementBase target = new PlaintextSigningBindingElement(); target.Channel = new TestChannel(); @@ -27,7 +27,7 @@ namespace DotNetOpenAuth.Test.ChannelElements { Assert.AreEqual("cs&ts", message.Signature); } - [TestMethod] + [TestCase] public void HttpsSignatureVerification() { MessageReceivingEndpoint endpoint = new MessageReceivingEndpoint("https://localtest", HttpDeliveryMethods.GetRequest); ITamperProtectionChannelBindingElement target = new PlaintextSigningBindingElement(); @@ -40,7 +40,7 @@ namespace DotNetOpenAuth.Test.ChannelElements { Assert.IsNotNull(target.ProcessIncomingMessage(message)); } - [TestMethod] + [TestCase] public void HttpsSignatureVerificationNotApplicable() { SigningBindingElementBase target = new PlaintextSigningBindingElement(); target.Channel = new TestChannel(); @@ -53,7 +53,7 @@ namespace DotNetOpenAuth.Test.ChannelElements { Assert.AreEqual(MessageProtections.None, target.ProcessIncomingMessage(message), "PLAINTEXT binding element should opt-out where it doesn't understand."); } - [TestMethod] + [TestCase] public void HttpSignatureGeneration() { SigningBindingElementBase target = new PlaintextSigningBindingElement(); target.Channel = new TestChannel(); @@ -68,7 +68,7 @@ namespace DotNetOpenAuth.Test.ChannelElements { Assert.IsNull(message.Signature); } - [TestMethod] + [TestCase] public void HttpSignatureVerification() { SigningBindingElementBase target = new PlaintextSigningBindingElement(); target.Channel = new TestChannel(); diff --git a/src/DotNetOpenAuth.Test/OAuth/ChannelElements/SigningBindingElementBaseTests.cs b/src/DotNetOpenAuth.Test/OAuth/ChannelElements/SigningBindingElementBaseTests.cs index 6e566c8..c2ae65e 100644 --- a/src/DotNetOpenAuth.Test/OAuth/ChannelElements/SigningBindingElementBaseTests.cs +++ b/src/DotNetOpenAuth.Test/OAuth/ChannelElements/SigningBindingElementBaseTests.cs @@ -10,11 +10,11 @@ namespace DotNetOpenAuth.Test.ChannelElements { using DotNetOpenAuth.OAuth; using DotNetOpenAuth.OAuth.ChannelElements; using DotNetOpenAuth.OAuth.Messages; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; - [TestClass] + [TestFixture] public class SigningBindingElementBaseTests : MessagingTestBase { - [TestMethod] + [TestCase] public void BaseSignatureStringTest() { // Tests a message sent by HTTP GET, with no query string included in the endpoint. UnauthorizedTokenRequest message = CreateTestRequestTokenMessage( diff --git a/src/DotNetOpenAuth.Test/OAuth/ChannelElements/UriOrOobEncodingTests.cs b/src/DotNetOpenAuth.Test/OAuth/ChannelElements/UriOrOobEncodingTests.cs index 40fc93e..715669a 100644 --- a/src/DotNetOpenAuth.Test/OAuth/ChannelElements/UriOrOobEncodingTests.cs +++ b/src/DotNetOpenAuth.Test/OAuth/ChannelElements/UriOrOobEncodingTests.cs @@ -10,13 +10,13 @@ namespace DotNetOpenAuth.Test.OAuth.ChannelElements { using System.Linq; using System.Text; using DotNetOpenAuth.OAuth.ChannelElements; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; - [TestClass] + [TestFixture] public class UriOrOobEncodingTests : TestBase { private UriOrOobEncoding encoding; - [TestInitialize] + [SetUp] public void Setup() { this.encoding = new UriOrOobEncoding(); } @@ -24,7 +24,7 @@ namespace DotNetOpenAuth.Test.OAuth.ChannelElements { /// <summary> /// Verifies null value encoding /// </summary> - [TestMethod] + [TestCase] public void NullValueEncoding() { Assert.AreEqual("oob", this.encoding.EncodedNullValue); } @@ -32,7 +32,7 @@ namespace DotNetOpenAuth.Test.OAuth.ChannelElements { /// <summary> /// Verifies decoding "oob" results in a null uri. /// </summary> - [TestMethod] + [TestCase] public void DecodeOobToNullUri() { Assert.IsNull(this.encoding.Decode("oob")); } @@ -40,7 +40,7 @@ namespace DotNetOpenAuth.Test.OAuth.ChannelElements { /// <summary> /// Verifies that decoding an empty string generates an exception. /// </summary> - [TestMethod, ExpectedException(typeof(UriFormatException))] + [TestCase, ExpectedException(typeof(UriFormatException))] public void DecodeEmptyStringFails() { this.encoding.Decode(string.Empty); } @@ -48,7 +48,7 @@ namespace DotNetOpenAuth.Test.OAuth.ChannelElements { /// <summary> /// Verifies proper decoding/encoding of a Uri /// </summary> - [TestMethod] + [TestCase] public void UriEncodeDecode() { Uri original = new Uri("http://somehost/p?q=a#frag"); string encodedValue = this.encoding.Encode(original); @@ -60,7 +60,7 @@ namespace DotNetOpenAuth.Test.OAuth.ChannelElements { /// <summary> /// Verifies failure to decode a relative Uri /// </summary> - [TestMethod, ExpectedException(typeof(UriFormatException))] + [TestCase, ExpectedException(typeof(UriFormatException))] public void RelativeUriDecodeFails() { this.encoding.Decode("../a/b"); } diff --git a/src/DotNetOpenAuth.Test/OAuth/ProtocolTests.cs b/src/DotNetOpenAuth.Test/OAuth/ProtocolTests.cs index ce8070b..f866990 100644 --- a/src/DotNetOpenAuth.Test/OAuth/ProtocolTests.cs +++ b/src/DotNetOpenAuth.Test/OAuth/ProtocolTests.cs @@ -6,27 +6,27 @@ namespace DotNetOpenAuth.Test { using DotNetOpenAuth.OAuth; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; - [TestClass] + [TestFixture] public class ProtocolTests { - [TestMethod] + [TestCase] public void Default() { Assert.AreSame(Protocol.V10a, Protocol.Default); } - [TestMethod] + [TestCase] public void DataContractNamespace() { Assert.AreEqual("http://oauth.net/core/1.0/", Protocol.V10.DataContractNamespace); Assert.AreEqual("http://oauth.net/core/1.0/", Protocol.DataContractNamespaceV10); } - [TestMethod] + [TestCase] public void AuthorizationHeaderScheme() { Assert.AreEqual("OAuth", Protocol.AuthorizationHeaderScheme); } - [TestMethod] + [TestCase] public void ParameterPrefix() { Assert.AreEqual("oauth_", Protocol.ParameterPrefix); } diff --git a/src/DotNetOpenAuth.Test/OAuth/ServiceProviderDescriptionTests.cs b/src/DotNetOpenAuth.Test/OAuth/ServiceProviderDescriptionTests.cs index 760a9e9..4ed1c74 100644 --- a/src/DotNetOpenAuth.Test/OAuth/ServiceProviderDescriptionTests.cs +++ b/src/DotNetOpenAuth.Test/OAuth/ServiceProviderDescriptionTests.cs @@ -8,17 +8,17 @@ namespace DotNetOpenAuth.Test { using System; using DotNetOpenAuth.Messaging; using DotNetOpenAuth.OAuth; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; /// <summary> /// Tests for the <see cref="ServiceProviderEndpoints"/> class. /// </summary> - [TestClass] + [TestFixture] public class ServiceProviderDescriptionTests : TestBase { /// <summary> /// A test for UserAuthorizationUri /// </summary> - [TestMethod] + [TestCase] public void UserAuthorizationUriTest() { ServiceProviderDescription target = new ServiceProviderDescription(); MessageReceivingEndpoint expected = new MessageReceivingEndpoint("http://localhost/authorization", HttpDeliveryMethods.GetRequest); @@ -34,7 +34,7 @@ namespace DotNetOpenAuth.Test { /// <summary> /// A test for RequestTokenUri /// </summary> - [TestMethod] + [TestCase] public void RequestTokenUriTest() { var target = new ServiceProviderDescription(); MessageReceivingEndpoint expected = new MessageReceivingEndpoint("http://localhost/requesttoken", HttpDeliveryMethods.GetRequest); @@ -51,7 +51,7 @@ namespace DotNetOpenAuth.Test { /// Verifies that oauth parameters are not allowed in <see cref="ServiceProvider.RequestTokenUri"/>, /// per section OAuth 1.0 section 4.1. /// </summary> - [TestMethod, ExpectedException(typeof(ArgumentException))] + [TestCase, ExpectedException(typeof(ArgumentException))] public void RequestTokenUriWithOAuthParametersTest() { var target = new ServiceProviderDescription(); target.RequestTokenEndpoint = new MessageReceivingEndpoint("http://localhost/requesttoken?oauth_token=something", HttpDeliveryMethods.GetRequest); @@ -60,7 +60,7 @@ namespace DotNetOpenAuth.Test { /// <summary> /// A test for AccessTokenUri /// </summary> - [TestMethod] + [TestCase] public void AccessTokenUriTest() { var target = new ServiceProviderDescription(); MessageReceivingEndpoint expected = new MessageReceivingEndpoint("http://localhost/accesstoken", HttpDeliveryMethods.GetRequest); diff --git a/src/DotNetOpenAuth.Test/OAuth/ServiceProviderTests.cs b/src/DotNetOpenAuth.Test/OAuth/ServiceProviderTests.cs index 2a443ce..ceb9a60 100644 --- a/src/DotNetOpenAuth.Test/OAuth/ServiceProviderTests.cs +++ b/src/DotNetOpenAuth.Test/OAuth/ServiceProviderTests.cs @@ -11,14 +11,14 @@ namespace DotNetOpenAuth.Test.OAuth { using System.Text; using DotNetOpenAuth.Messaging; using DotNetOpenAuth.OAuth; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; - [TestClass] + [TestFixture] public class ServiceProviderTests : TestBase { /// <summary> /// Verifies the CreateVerificationCode method. /// </summary> - [TestMethod] + [TestCase] public void CreateVerificationCode() { this.TestCode(VerificationCodeFormat.Numeric, 3, MessagingUtilities.Digits); this.TestCode(VerificationCodeFormat.AlphaLower, 5, MessagingUtilities.LowercaseLetters); @@ -28,7 +28,7 @@ namespace DotNetOpenAuth.Test.OAuth { private void TestCode(VerificationCodeFormat format, int length, string allowableCharacters) { string code = ServiceProvider.CreateVerificationCode(format, length); - TestContext.WriteLine("{0} of length {2}: {1}", format, code, length); + TestUtilities.TestLogger.InfoFormat("{0} of length {2}: {1}", format, code, length); Assert.AreEqual(length, code.Length); foreach (char ch in code) { Assert.IsTrue(allowableCharacters.Contains(ch)); diff --git a/src/DotNetOpenAuth.Test/OpenId/AssociationHandshakeTests.cs b/src/DotNetOpenAuth.Test/OpenId/AssociationHandshakeTests.cs index af3b1b1..8c2b5bd 100644 --- a/src/DotNetOpenAuth.Test/OpenId/AssociationHandshakeTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/AssociationHandshakeTests.cs @@ -12,21 +12,21 @@ namespace DotNetOpenAuth.Test.OpenId { using DotNetOpenAuth.OpenId.Provider; using DotNetOpenAuth.OpenId.RelyingParty; using DotNetOpenAuth.Test.Mocks; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; - [TestClass] + [TestFixture] public class AssociationHandshakeTests : OpenIdTestBase { - [TestInitialize] + [SetUp] public override void SetUp() { base.SetUp(); } - [TestMethod] + [TestCase] public void AssociateUnencrypted() { this.ParameterizedAssociationTest(new Uri("https://host")); } - [TestMethod] + [TestCase] public void AssociateDiffieHellmanOverHttp() { this.ParameterizedAssociationTest(new Uri("http://host")); } @@ -38,7 +38,7 @@ namespace DotNetOpenAuth.Test.OpenId { /// Some OPs out there flatly refuse to do this, and the spec doesn't forbid /// putting the two together, so we verify that DNOI can handle it. /// </remarks> - [TestMethod] + [TestCase] public void AssociateDiffieHellmanOverHttps() { Protocol protocol = Protocol.V20; OpenIdCoordinator coordinator = new OpenIdCoordinator( @@ -62,7 +62,7 @@ namespace DotNetOpenAuth.Test.OpenId { /// Verifies that the RP and OP can renegotiate an association type if the RP's /// initial request for an association is for a type the OP doesn't support. /// </summary> - [TestMethod] + [TestCase] public void AssociateRenegotiateBitLength() { Protocol protocol = Protocol.V20; @@ -80,7 +80,7 @@ namespace DotNetOpenAuth.Test.OpenId { op.SecuritySettings.MaximumHashBitLength = 160; // Force OP to reject HMAC-SHA256 // Receive initial request for an HMAC-SHA256 association. - AutoResponsiveRequest req = (AutoResponsiveRequest) op.GetRequest(); + AutoResponsiveRequest req = (AutoResponsiveRequest)op.GetRequest(); AutoResponsiveRequest_Accessor reqAccessor = AutoResponsiveRequest_Accessor.AttachShadow(req); AssociateRequest associateRequest = (AssociateRequest)reqAccessor.RequestMessage; Assert.AreEqual(protocol.Args.SignatureAlgorithm.HMAC_SHA256, associateRequest.AssociationType); @@ -110,7 +110,7 @@ namespace DotNetOpenAuth.Test.OpenId { /// <remarks> /// Verifies OP's compliance with OpenID 2.0 section 8.4.1. /// </remarks> - [TestMethod] + [TestCase] public void OPRejectsHttpNoEncryptionAssociateRequests() { Protocol protocol = Protocol.V20; OpenIdCoordinator coordinator = new OpenIdCoordinator( @@ -131,7 +131,7 @@ namespace DotNetOpenAuth.Test.OpenId { /// Verifies that the OP rejects an associate request /// when the HMAC and DH bit lengths do not match. /// </summary> - [TestMethod] + [TestCase] public void OPRejectsMismatchingAssociationAndSessionTypes() { Protocol protocol = Protocol.V20; OpenIdCoordinator coordinator = new OpenIdCoordinator( @@ -154,7 +154,7 @@ namespace DotNetOpenAuth.Test.OpenId { /// <summary> /// Verifies that the RP quietly rejects an OP that suggests an unknown association type. /// </summary> - [TestMethod] + [TestCase] public void RPRejectsUnrecognizedAssociationType() { Protocol protocol = Protocol.V20; OpenIdCoordinator coordinator = new OpenIdCoordinator( @@ -181,7 +181,7 @@ namespace DotNetOpenAuth.Test.OpenId { /// <remarks> /// Verifies RP's compliance with OpenID 2.0 section 8.4.1. /// </remarks> - [TestMethod] + [TestCase] public void RPRejectsUnencryptedSuggestion() { Protocol protocol = Protocol.V20; OpenIdCoordinator coordinator = new OpenIdCoordinator( @@ -206,7 +206,7 @@ namespace DotNetOpenAuth.Test.OpenId { /// Verifies that the RP rejects an associate renegotiate request /// when the HMAC and DH bit lengths do not match. /// </summary> - [TestMethod] + [TestCase] public void RPRejectsMismatchingAssociationAndSessionBitLengths() { Protocol protocol = Protocol.V20; OpenIdCoordinator coordinator = new OpenIdCoordinator( @@ -231,7 +231,7 @@ namespace DotNetOpenAuth.Test.OpenId { /// Verifies that the RP cannot get caught in an infinite loop if a bad OP /// keeps sending it association retry messages. /// </summary> - [TestMethod] + [TestCase] public void RPOnlyRenegotiatesOnce() { Protocol protocol = Protocol.V20; OpenIdCoordinator coordinator = new OpenIdCoordinator( @@ -264,7 +264,7 @@ namespace DotNetOpenAuth.Test.OpenId { /// <summary> /// Verifies security settings limit RP's acceptance of OP's counter-suggestion /// </summary> - [TestMethod] + [TestCase] public void AssociateRenegotiateLimitedByRPSecuritySettings() { Protocol protocol = Protocol.V20; OpenIdCoordinator coordinator = new OpenIdCoordinator( @@ -284,7 +284,7 @@ namespace DotNetOpenAuth.Test.OpenId { /// Verifies that the RP can recover from an invalid or non-existent /// response from the OP, for example in the HTTP timeout case. /// </summary> - [TestMethod] + [TestCase] public void AssociateQuietlyFailsAfterHttpError() { this.MockResponder.RegisterMockNotFound(OPUri); var rp = this.CreateRelyingParty(); @@ -318,9 +318,9 @@ namespace DotNetOpenAuth.Test.OpenId { private void ParameterizedAssociationTest( ProviderEndpointDescription opDescription, string expectedAssociationType) { - Protocol protocol = Protocol.Lookup(opDescription.ProtocolVersion); + Protocol protocol = Protocol.Lookup(Protocol.Lookup(opDescription.Version).ProtocolVersion); bool expectSuccess = expectedAssociationType != null; - bool expectDiffieHellman = !opDescription.Endpoint.IsTransportSecure(); + bool expectDiffieHellman = !opDescription.Uri.IsTransportSecure(); Association rpAssociation = null, opAssociation; AssociateSuccessfulResponse associateSuccessfulResponse = null; AssociateUnsuccessfulResponse associateUnsuccessfulResponse = null; @@ -337,7 +337,7 @@ namespace DotNetOpenAuth.Test.OpenId { op.SendResponse(req); }); coordinator.IncomingMessageFilter = message => { - Assert.AreSame(opDescription.ProtocolVersion, message.Version, "The message was recognized as version {0} but was expected to be {1}.", message.Version, opDescription.ProtocolVersion); + Assert.AreSame(opDescription.Version, message.Version, "The message was recognized as version {0} but was expected to be {1}.", message.Version, Protocol.Lookup(opDescription.Version).ProtocolVersion); var associateSuccess = message as AssociateSuccessfulResponse; var associateFailed = message as AssociateUnsuccessfulResponse; if (associateSuccess != null) { @@ -348,7 +348,7 @@ namespace DotNetOpenAuth.Test.OpenId { } }; coordinator.OutgoingMessageFilter = message => { - Assert.AreSame(opDescription.ProtocolVersion, message.Version, "The message was for version {0} but was expected to be for {1}.", message.Version, opDescription.ProtocolVersion); + Assert.AreEqual(opDescription.Version, message.Version, "The message was for version {0} but was expected to be for {1}.", message.Version, opDescription.Version); }; coordinator.Run(); @@ -356,7 +356,7 @@ namespace DotNetOpenAuth.Test.OpenId { if (expectSuccess) { Assert.IsNotNull(rpAssociation); - Assert.AreSame(rpAssociation, associationManagerAccessor.associationStore.GetAssociation(opDescription.Endpoint, rpAssociation.Handle)); + Assert.AreSame(rpAssociation, associationManagerAccessor.associationStore.GetAssociation(opDescription.Uri, rpAssociation.Handle)); opAssociation = coordinator.Provider.AssociationStore.GetAssociation(AssociationRelyingPartyType.Smart, rpAssociation.Handle); Assert.IsNotNull(opAssociation, "The Provider should have stored the association."); @@ -367,15 +367,15 @@ namespace DotNetOpenAuth.Test.OpenId { Assert.IsTrue(MessagingUtilities.AreEquivalent(opAssociation.SecretKey, rpAssociation.SecretKey)); if (expectDiffieHellman) { - Assert.IsInstanceOfType(associateSuccessfulResponse, typeof(AssociateDiffieHellmanResponse)); + Assert.IsInstanceOf<AssociateDiffieHellmanResponse>(associateSuccessfulResponse); var diffieHellmanResponse = (AssociateDiffieHellmanResponse)associateSuccessfulResponse; Assert.IsFalse(MessagingUtilities.AreEquivalent(diffieHellmanResponse.EncodedMacKey, rpAssociation.SecretKey), "Key should have been encrypted."); } else { - Assert.IsInstanceOfType(associateSuccessfulResponse, typeof(AssociateUnencryptedResponse)); + Assert.IsInstanceOf<AssociateUnencryptedResponse>(associateSuccessfulResponse); var unencryptedResponse = (AssociateUnencryptedResponse)associateSuccessfulResponse; } } else { - Assert.IsNull(associationManagerAccessor.associationStore.GetAssociation(opDescription.Endpoint, new RelyingPartySecuritySettings())); + Assert.IsNull(associationManagerAccessor.associationStore.GetAssociation(opDescription.Uri, new RelyingPartySecuritySettings())); Assert.IsNull(coordinator.Provider.AssociationStore.GetAssociation(AssociationRelyingPartyType.Smart, new ProviderSecuritySettings())); } } diff --git a/src/DotNetOpenAuth.Test/OpenId/AssociationTests.cs b/src/DotNetOpenAuth.Test/OpenId/AssociationTests.cs index 6881255..a70189f 100644 --- a/src/DotNetOpenAuth.Test/OpenId/AssociationTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/AssociationTests.cs @@ -12,16 +12,16 @@ namespace DotNetOpenAuth.Test.OpenId { using System.Text; using DotNetOpenAuth.Messaging; using DotNetOpenAuth.OpenId; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; - [TestClass] + [TestFixture] public class AssociationTests : OpenIdTestBase { private static readonly TimeSpan deltaDateTime = TimeSpan.FromSeconds(2); private static readonly HashAlgorithm sha1 = DiffieHellmanUtilities.Lookup(Protocol.Default, Protocol.Default.Args.SessionType.DH_SHA1); private byte[] sha1Secret; private byte[] sha1Secret2; - [TestInitialize] + [SetUp] public override void SetUp() { base.SetUp(); @@ -35,7 +35,7 @@ namespace DotNetOpenAuth.Test.OpenId { this.sha1Secret2[1] = 0xcc; } - [TestMethod] + [TestCase] public void Properties() { string handle = "somehandle"; TimeSpan lifetime = TimeSpan.FromMinutes(2); @@ -49,7 +49,7 @@ namespace DotNetOpenAuth.Test.OpenId { Assert.AreEqual(0, assoc.Issued.Millisecond, "No milliseconds because this can be cut off in conversions."); } - [TestMethod] + [TestCase] public void Sign() { Association assoc1 = HmacShaAssociation.Create(Protocol.Default, Protocol.Default.Args.SignatureAlgorithm.HMAC_SHA1, "h1", this.sha1Secret, TimeSpan.FromMinutes(2)); Association assoc2 = HmacShaAssociation.Create(Protocol.Default, Protocol.Default.Args.SignatureAlgorithm.HMAC_SHA1, "h2", this.sha1Secret2, TimeSpan.FromMinutes(2)); diff --git a/src/DotNetOpenAuth.Test/OpenId/AssociationsTests.cs b/src/DotNetOpenAuth.Test/OpenId/AssociationsTests.cs index a0c4770..b3d7e4d 100644 --- a/src/DotNetOpenAuth.Test/OpenId/AssociationsTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/AssociationsTests.cs @@ -11,31 +11,31 @@ namespace DotNetOpenAuth.Test.OpenId { using System.Security.Cryptography; using System.Text; using DotNetOpenAuth.OpenId; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; - [TestClass] + [TestFixture] public class AssociationsTests : OpenIdTestBase { private static readonly HashAlgorithm sha1 = DiffieHellmanUtilities.Lookup(Protocol.Default, Protocol.Default.Args.SessionType.DH_SHA1); private byte[] sha1Secret; private Associations assocs; - [TestInitialize] + [TestFixtureSetUp] public override void SetUp() { this.sha1Secret = new byte[sha1.HashSize / 8]; this.assocs = new Associations(); } - [TestMethod] + [TestCase] public void GetNonexistentHandle() { Assert.IsNull(this.assocs.Get("someinvalidhandle")); } - [TestMethod] + [TestCase] public void RemoveNonexistentHandle() { Assert.IsFalse(this.assocs.Remove("someinvalidhandle")); } - [TestMethod] + [TestCase] public void HandleLifecycle() { Association a = HmacShaAssociation.Create( Protocol.Default, @@ -50,7 +50,7 @@ namespace DotNetOpenAuth.Test.OpenId { Assert.IsFalse(this.assocs.Remove(a.Handle)); } - [TestMethod] + [TestCase] public void Best() { Association a = HmacShaAssociation.Create( Protocol.Default, diff --git a/src/DotNetOpenAuth.Test/OpenId/AuthenticationTests.cs b/src/DotNetOpenAuth.Test/OpenId/AuthenticationTests.cs index 7de2a8b..27db93e 100644 --- a/src/DotNetOpenAuth.Test/OpenId/AuthenticationTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/AuthenticationTests.cs @@ -14,16 +14,16 @@ namespace DotNetOpenAuth.Test.OpenId { using DotNetOpenAuth.OpenId.Provider; using DotNetOpenAuth.OpenId.RelyingParty; using DotNetOpenAuth.Test.Mocks; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; - [TestClass] + [TestFixture] public class AuthenticationTests : OpenIdTestBase { - [TestInitialize] + [SetUp] public override void SetUp() { base.SetUp(); } - [TestMethod] + [TestCase] public void SharedAssociationPositive() { this.ParameterizedAuthenticationTest(true, true, false); } @@ -31,17 +31,17 @@ namespace DotNetOpenAuth.Test.OpenId { /// <summary> /// Verifies that a shared association protects against tampering. /// </summary> - [TestMethod] + [TestCase] public void SharedAssociationTampered() { this.ParameterizedAuthenticationTest(true, true, true); } - [TestMethod] + [TestCase] public void SharedAssociationNegative() { this.ParameterizedAuthenticationTest(true, false, false); } - [TestMethod] + [TestCase] public void PrivateAssociationPositive() { this.ParameterizedAuthenticationTest(false, true, false); } @@ -49,17 +49,17 @@ namespace DotNetOpenAuth.Test.OpenId { /// <summary> /// Verifies that a private association protects against tampering. /// </summary> - [TestMethod] + [TestCase] public void PrivateAssociationTampered() { this.ParameterizedAuthenticationTest(false, true, true); } - [TestMethod] + [TestCase] public void NoAssociationNegative() { this.ParameterizedAuthenticationTest(false, false, false); } - [TestMethod] + [TestCase] public void UnsolicitedAssertion() { this.MockResponder.RegisterMockRPDiscovery(); OpenIdCoordinator coordinator = new OpenIdCoordinator( @@ -77,7 +77,7 @@ namespace DotNetOpenAuth.Test.OpenId { coordinator.Run(); } - [TestMethod] + [TestCase] public void UnsolicitedAssertionRejected() { this.MockResponder.RegisterMockRPDiscovery(); OpenIdCoordinator coordinator = new OpenIdCoordinator( @@ -100,7 +100,7 @@ namespace DotNetOpenAuth.Test.OpenId { /// Verifies that delegating identifiers are rejected in unsolicited assertions /// when the appropriate security setting is set. /// </summary> - [TestMethod] + [TestCase] public void UnsolicitedDelegatingIdentifierRejection() { this.MockResponder.RegisterMockRPDiscovery(); OpenIdCoordinator coordinator = new OpenIdCoordinator( diff --git a/src/DotNetOpenAuth.Test/OpenId/ChannelElements/ExtensionsBindingElementTests.cs b/src/DotNetOpenAuth.Test/OpenId/ChannelElements/ExtensionsBindingElementTests.cs index 29797dc..5edd51f 100644 --- a/src/DotNetOpenAuth.Test/OpenId/ChannelElements/ExtensionsBindingElementTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/ChannelElements/ExtensionsBindingElementTests.cs @@ -18,15 +18,15 @@ namespace DotNetOpenAuth.Test.OpenId.ChannelElements { using DotNetOpenAuth.OpenId.RelyingParty; using DotNetOpenAuth.Test.Mocks; using DotNetOpenAuth.Test.OpenId.Extensions; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; - [TestClass] + [TestFixture] public class ExtensionsBindingElementTests : OpenIdTestBase { private StandardOpenIdExtensionFactory factory; private ExtensionsBindingElement rpElement; private IProtocolMessageWithExtensions request; - [TestInitialize] + [SetUp] public override void SetUp() { base.SetUp(); @@ -37,7 +37,7 @@ namespace DotNetOpenAuth.Test.OpenId.ChannelElements { this.request = new SignedResponseRequest(Protocol.Default.Version, OpenIdTestBase.OPUri, AuthenticationRequestMode.Immediate); } - [TestMethod] + [TestCase] public void RoundTripFullStackTest() { IOpenIdMessageExtension request = new MockOpenIdExtension("requestPart", "requestData"); IOpenIdMessageExtension response = new MockOpenIdExtension("responsePart", "responseData"); @@ -47,12 +47,12 @@ namespace DotNetOpenAuth.Test.OpenId.ChannelElements { new IOpenIdMessageExtension[] { response }); } - [TestMethod] + [TestCase] public void ExtensionFactory() { Assert.AreSame(this.factory, this.rpElement.ExtensionFactory); } - [TestMethod, ExpectedException(typeof(ArgumentNullException))] + [TestCase, ExpectedException(typeof(ArgumentNullException))] public void PrepareMessageForSendingNull() { this.rpElement.ProcessOutgoingMessage(null); } @@ -60,13 +60,13 @@ namespace DotNetOpenAuth.Test.OpenId.ChannelElements { /// <summary> /// Verifies that false is returned when a non-extendable message is sent. /// </summary> - [TestMethod] + [TestCase] public void PrepareMessageForSendingNonExtendableMessage() { IProtocolMessage request = new AssociateDiffieHellmanRequest(Protocol.Default.Version, OpenIdTestBase.OPUri); Assert.IsNull(this.rpElement.ProcessOutgoingMessage(request)); } - [TestMethod] + [TestCase] public void PrepareMessageForSending() { this.request.Extensions.Add(new MockOpenIdExtension("part", "extra")); Assert.IsNotNull(this.rpElement.ProcessOutgoingMessage(this.request)); @@ -77,7 +77,7 @@ namespace DotNetOpenAuth.Test.OpenId.ChannelElements { Assert.AreEqual("extra", this.request.ExtraData["openid." + alias + ".data"]); } - [TestMethod] + [TestCase] public void PrepareMessageForReceiving() { this.request.ExtraData["openid.ns.mock"] = MockOpenIdExtension.MockTypeUri; this.request.ExtraData["openid.mock.Part"] = "part"; @@ -91,7 +91,7 @@ namespace DotNetOpenAuth.Test.OpenId.ChannelElements { /// <summary> /// Verifies that extension responses are included in the OP's signature. /// </summary> - [TestMethod] + [TestCase] public void ExtensionResponsesAreSigned() { Protocol protocol = Protocol.Default; var op = this.CreateProvider(); @@ -113,7 +113,7 @@ namespace DotNetOpenAuth.Test.OpenId.ChannelElements { /// <summary> /// Verifies that unsigned extension responses (where any or all fields are unsigned) are ignored. /// </summary> - [TestMethod] + [TestCase] public void ExtensionsAreIdentifiedAsSignedOrUnsigned() { Protocol protocol = Protocol.Default; OpenIdCoordinator coordinator = new OpenIdCoordinator( @@ -144,7 +144,7 @@ namespace DotNetOpenAuth.Test.OpenId.ChannelElements { /// OpenID Authentication 2.0 section 12 states that /// "A namespace MUST NOT be assigned more than one alias in the same message". /// </remarks> - [TestMethod] + [TestCase] public void TwoExtensionsSameTypeUri() { IOpenIdMessageExtension request1 = new MockOpenIdExtension("requestPart1", "requestData1"); IOpenIdMessageExtension request2 = new MockOpenIdExtension("requestPart2", "requestData2"); @@ -154,8 +154,8 @@ namespace DotNetOpenAuth.Test.OpenId.ChannelElements { new IOpenIdMessageExtension[] { request1, request2 }, new IOpenIdMessageExtension[0]); Assert.Fail("Expected ProtocolException not thrown."); - } catch (AssertFailedException ex) { - Assert.IsInstanceOfType(ex.InnerException, typeof(ProtocolException)); + } catch (AssertionException ex) { + Assert.IsInstanceOf<ProtocolException>(ex.InnerException); } } diff --git a/src/DotNetOpenAuth.Test/OpenId/ChannelElements/KeyValueFormEncodingTests.cs b/src/DotNetOpenAuth.Test/OpenId/ChannelElements/KeyValueFormEncodingTests.cs index 92170c4..75ac503 100644 --- a/src/DotNetOpenAuth.Test/OpenId/ChannelElements/KeyValueFormEncodingTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/ChannelElements/KeyValueFormEncodingTests.cs @@ -14,9 +14,9 @@ namespace DotNetOpenAuth.Test.OpenId.ChannelElements { using DotNetOpenAuth.Messaging; using DotNetOpenAuth.Messaging.Reflection; using DotNetOpenAuth.OpenId.ChannelElements; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; - [TestClass] + [TestFixture] public class KeyValueFormEncodingTests : TestBase { private Dictionary<string, string> sampleData = new Dictionary<string, string> { { "key1", "value1" }, @@ -33,7 +33,7 @@ namespace DotNetOpenAuth.Test.OpenId.ChannelElements { Both = 0x3, } - [TestMethod] + [TestCase] public void BasicEncodingTest() { byte[] kvfBytes = KeyValueFormEncoding.GetBytes(this.sampleData); string responseString = Encoding.UTF8.GetString(kvfBytes); @@ -69,7 +69,7 @@ namespace DotNetOpenAuth.Test.OpenId.ChannelElements { } } - [TestMethod] + [TestCase] public void EncodeDecode() { this.KVDictTest(UTF8Encoding.UTF8.GetBytes(string.Empty), new Dictionary<string, string>(), TestMode.Both); @@ -117,35 +117,35 @@ namespace DotNetOpenAuth.Test.OpenId.ChannelElements { this.KVDictTest(UTF8Encoding.UTF8.GetBytes("east:west\nnorth:south"), d10, TestMode.Decoder); } - [TestMethod, ExpectedException(typeof(FormatException))] + [TestCase, ExpectedException(typeof(FormatException))] public void NoValue() { this.Illegal("x\n", KeyValueFormConformanceLevel.OpenId11); } - [TestMethod, ExpectedException(typeof(FormatException))] + [TestCase, ExpectedException(typeof(FormatException))] public void NoValueLoose() { Dictionary<string, string> d = new Dictionary<string, string>(); this.KVDictTest(Encoding.UTF8.GetBytes("x\n"), d, TestMode.Decoder); } - [TestMethod, ExpectedException(typeof(FormatException))] + [TestCase, ExpectedException(typeof(FormatException))] public void EmptyLine() { this.Illegal("x:b\n\n", KeyValueFormConformanceLevel.OpenId20); } - [TestMethod] + [TestCase] public void EmptyLineLoose() { Dictionary<string, string> d = new Dictionary<string, string>(); d.Add("x", "b"); this.KVDictTest(Encoding.UTF8.GetBytes("x:b\n\n"), d, TestMode.Decoder); } - [TestMethod, ExpectedException(typeof(FormatException))] + [TestCase, ExpectedException(typeof(FormatException))] public void LastLineNotTerminated() { this.Illegal("x:y\na:b", KeyValueFormConformanceLevel.OpenId11); } - [TestMethod] + [TestCase] public void LastLineNotTerminatedLoose() { Dictionary<string, string> d = new Dictionary<string, string>(); d.Add("x", "y"); diff --git a/src/DotNetOpenAuth.Test/OpenId/ChannelElements/OpenIdChannelTests.cs b/src/DotNetOpenAuth.Test/OpenId/ChannelElements/OpenIdChannelTests.cs index 385cd19..97a40e8 100644 --- a/src/DotNetOpenAuth.Test/OpenId/ChannelElements/OpenIdChannelTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/ChannelElements/OpenIdChannelTests.cs @@ -18,16 +18,16 @@ namespace DotNetOpenAuth.Test.OpenId.ChannelElements { using DotNetOpenAuth.OpenId.ChannelElements; using DotNetOpenAuth.OpenId.RelyingParty; using DotNetOpenAuth.Test.Mocks; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; - [TestClass] + [TestFixture] public class OpenIdChannelTests : TestBase { private static readonly TimeSpan maximumMessageAge = TimeSpan.FromHours(3); // good for tests, too long for production private OpenIdChannel channel; private OpenIdChannel_Accessor accessor; private Mocks.TestWebRequestHandler webHandler; - [TestInitialize] + [SetUp] public void Setup() { this.webHandler = new Mocks.TestWebRequestHandler(); this.channel = new OpenIdChannel(new AssociationMemoryStore<Uri>(), new NonceMemoryStore(maximumMessageAge), new RelyingPartySecuritySettings()); @@ -35,7 +35,7 @@ namespace DotNetOpenAuth.Test.OpenId.ChannelElements { this.channel.WebRequestHandler = this.webHandler; } - [TestMethod] + [TestCase] public void Ctor() { // Verify that the channel stack includes the expected types. // While other binding elements may be substituted for these, we'd then have @@ -53,7 +53,7 @@ namespace DotNetOpenAuth.Test.OpenId.ChannelElements { /// <summary> /// Verifies that the channel sends direct message requests as HTTP POST requests. /// </summary> - [TestMethod] + [TestCase] public void DirectRequestsUsePost() { IDirectedProtocolMessage requestMessage = new Mocks.TestDirectedMessage(MessageTransport.Direct) { Recipient = new Uri("http://host"), @@ -61,7 +61,7 @@ namespace DotNetOpenAuth.Test.OpenId.ChannelElements { }; HttpWebRequest httpRequest = this.accessor.CreateHttpRequest(requestMessage); Assert.AreEqual("POST", httpRequest.Method); - StringAssert.Contains(this.webHandler.RequestEntityAsString, "Name=Andrew"); + StringAssert.Contains("Name=Andrew", this.webHandler.RequestEntityAsString); } /// <summary> @@ -73,7 +73,7 @@ namespace DotNetOpenAuth.Test.OpenId.ChannelElements { /// class is verified elsewhere. We're only checking that the KVF class is being used by the /// <see cref="OpenIdChannel.SendDirectMessageResponse"/> method. /// </remarks> - [TestMethod] + [TestCase] public void DirectResponsesSentUsingKeyValueForm() { IProtocolMessage message = MessagingTestBase.GetStandardTestMessage(MessagingTestBase.FieldFill.AllRequired); MessageDictionary messageFields = this.MessageDescriptions.GetAccessor(message); @@ -90,7 +90,7 @@ namespace DotNetOpenAuth.Test.OpenId.ChannelElements { /// <summary> /// Verifies that direct message responses are read in using the Key Value Form decoder. /// </summary> - [TestMethod] + [TestCase] public void DirectResponsesReceivedAsKeyValueForm() { var fields = new Dictionary<string, string> { { "var1", "value1" }, @@ -105,7 +105,7 @@ namespace DotNetOpenAuth.Test.OpenId.ChannelElements { /// <summary> /// Verifies that messages asking for special HTTP status codes get them. /// </summary> - [TestMethod] + [TestCase] public void SendDirectMessageResponseHonorsHttpStatusCodes() { IProtocolMessage message = MessagingTestBase.GetStandardTestMessage(MessagingTestBase.FieldFill.AllRequired); OutgoingWebResponse directResponse = this.accessor.PrepareDirectResponse(message); diff --git a/src/DotNetOpenAuth.Test/OpenId/ChannelElements/SigningBindingElementTests.cs b/src/DotNetOpenAuth.Test/OpenId/ChannelElements/SigningBindingElementTests.cs index 3ab6559..6160680 100644 --- a/src/DotNetOpenAuth.Test/OpenId/ChannelElements/SigningBindingElementTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/ChannelElements/SigningBindingElementTests.cs @@ -12,16 +12,16 @@ namespace DotNetOpenAuth.Test.OpenId.ChannelElements { using DotNetOpenAuth.OpenId.Messages; using DotNetOpenAuth.OpenId.Provider; using DotNetOpenAuth.Test.Mocks; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; - [TestClass] + [TestFixture] public class SigningBindingElementTests : OpenIdTestBase { /// <summary> /// Verifies that the signatures generated match Known Good signatures. /// </summary> - [TestMethod] + [TestCase] public void SignaturesMatchKnownGood() { - Protocol protocol = Protocol.Default; + Protocol protocol = Protocol.V20; var settings = new ProviderSecuritySettings(); var store = new AssociationMemoryStore<AssociationRelyingPartyType>(); byte[] associationSecret = Convert.FromBase64String("rsSwv1zPWfjPRQU80hciu8FPDC+GONAMJQ/AvSo1a2M="); @@ -42,7 +42,7 @@ namespace DotNetOpenAuth.Test.OpenId.ChannelElements { /// <summary> /// Verifies that all parameters in ExtraData in signed responses are signed. /// </summary> - [TestMethod] + [TestCase] public void SignedResponsesIncludeExtraDataInSignature() { Protocol protocol = Protocol.Default; SigningBindingElement sbe = new SigningBindingElement(new AssociationMemoryStore<AssociationRelyingPartyType>(), new ProviderSecuritySettings()); diff --git a/src/DotNetOpenAuth.Test/OpenId/DiffieHellmanTests.cs b/src/DotNetOpenAuth.Test/OpenId/DiffieHellmanTests.cs index 426e19a..9e89b03 100644 --- a/src/DotNetOpenAuth.Test/OpenId/DiffieHellmanTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/DiffieHellmanTests.cs @@ -9,12 +9,12 @@ namespace DotNetOpenAuth.Test.OpenId { using System.IO; using DotNetOpenAuth.OpenId; using DotNetOpenAuth.OpenId.Messages; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; using Org.Mentalis.Security.Cryptography; - [TestClass] + [TestFixture] public class DiffieHellmanTests : OpenIdTestBase { - [TestMethod] + [TestCase] public void Test() { string s1 = Test1(); string s2 = Test1(); @@ -22,7 +22,7 @@ namespace DotNetOpenAuth.Test.OpenId { Assert.AreNotEqual(s1, s2, "Secret keys should NOT be the same."); } - [TestMethod, Timeout(15000)] + [TestCase, Timeout(15000), Category("Slow"), Category("Performance")] public void TestPublic() { TextReader reader = new StringReader(OpenIdTestBase.LoadEmbeddedFile("dhpriv.txt")); @@ -30,7 +30,7 @@ namespace DotNetOpenAuth.Test.OpenId { string line; int lineNumber = 0; while ((line = reader.ReadLine()) != null) { - TestContext.WriteLine("\tLine {0}", ++lineNumber); + TestUtilities.TestLogger.InfoFormat("\tLine {0}", ++lineNumber); string[] parts = line.Trim().Split(' '); byte[] x = Convert.FromBase64String(parts[0]); DiffieHellmanManaged dh = new DiffieHellmanManaged(AssociateDiffieHellmanRequest.DefaultMod, AssociateDiffieHellmanRequest.DefaultGen, x); diff --git a/src/DotNetOpenAuth.Test/OpenId/Discovery/htmldiscovery/html20provWithBadXrds.html b/src/DotNetOpenAuth.Test/OpenId/Discovery/htmldiscovery/html20provWithBadXrds.html new file mode 100644 index 0000000..e695116 --- /dev/null +++ b/src/DotNetOpenAuth.Test/OpenId/Discovery/htmldiscovery/html20provWithBadXrds.html @@ -0,0 +1,10 @@ +<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> +<html xmlns="http://www.w3.org/1999/xhtml"> +<head> + <title>Untitled Page</title> + <meta http-equiv="X-XRDS-Location" content="http://localhost/xrds-notfound.xml"/> + <link rel="openid2.provider" href="http://a/b" /> +</head> +<body> +</body> +</html> diff --git a/src/DotNetOpenAuth.Test/OpenId/Discovery/htmldiscovery/html20provWithEmptyXrds.html b/src/DotNetOpenAuth.Test/OpenId/Discovery/htmldiscovery/html20provWithEmptyXrds.html new file mode 100644 index 0000000..97ad7dc --- /dev/null +++ b/src/DotNetOpenAuth.Test/OpenId/Discovery/htmldiscovery/html20provWithEmptyXrds.html @@ -0,0 +1,10 @@ +<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> +<html xmlns="http://www.w3.org/1999/xhtml"> +<head> + <title>Untitled Page</title> + <meta http-equiv="X-XRDS-Location" content="http://localhost/xrds-irrelevant.xml"/> + <link rel="openid2.provider" href="http://a/b" /> +</head> +<body> +</body> +</html> diff --git a/src/DotNetOpenAuth.Test/OpenId/Discovery/xrdsdiscovery/xrds20dual.xml b/src/DotNetOpenAuth.Test/OpenId/Discovery/xrdsdiscovery/xrds20dual.xml new file mode 100644 index 0000000..9e6a66b --- /dev/null +++ b/src/DotNetOpenAuth.Test/OpenId/Discovery/xrdsdiscovery/xrds20dual.xml @@ -0,0 +1,13 @@ +<?xml version="1.0" encoding="UTF-8"?> +<xrds:XRDS + xmlns:xrds="xri://$xrds" + xmlns:openid="http://openid.net/xmlns/1.0" + xmlns="xri://$xrd*($v*2.0)"> + <XRD> + <Service priority="10"> + <Type>http://specs.openid.net/auth/2.0/signon</Type> + <Type>http://specs.openid.net/auth/2.0/server</Type> + <URI>http://a/b</URI> + </Service> + </XRD> +</xrds:XRDS> diff --git a/src/DotNetOpenAuth.Test/OpenId/DiscoveryServices/UriDiscoveryServiceTests.cs b/src/DotNetOpenAuth.Test/OpenId/DiscoveryServices/UriDiscoveryServiceTests.cs new file mode 100644 index 0000000..1050b4b --- /dev/null +++ b/src/DotNetOpenAuth.Test/OpenId/DiscoveryServices/UriDiscoveryServiceTests.cs @@ -0,0 +1,303 @@ +//----------------------------------------------------------------------- +// <copyright file="UriDiscoveryServiceTests.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.Test.OpenId.DiscoveryServices { + using System; + using System.Collections.Generic; + using System.Linq; + using System.Net; + using System.Text; + using System.Web; + using DotNetOpenAuth.Messaging; + using DotNetOpenAuth.OpenId; + using DotNetOpenAuth.OpenId.Extensions.SimpleRegistration; + using DotNetOpenAuth.OpenId.RelyingParty; + using NUnit.Framework; + + [TestFixture] + public class UriDiscoveryServiceTests : OpenIdTestBase { + [TestCase] + public void DiscoveryWithRedirects() { + Identifier claimedId = this.GetMockIdentifier(ProtocolVersion.V20, false); + + // Add a couple of chained redirect pages that lead to the claimedId. + Uri userSuppliedUri = new Uri("https://localhost/someSecurePage"); + Uri insecureMidpointUri = new Uri("http://localhost/insecureStop"); + this.MockResponder.RegisterMockRedirect(userSuppliedUri, insecureMidpointUri); + this.MockResponder.RegisterMockRedirect(insecureMidpointUri, new Uri(claimedId.ToString())); + + // don't require secure SSL discovery for this test. + Identifier userSuppliedIdentifier = new UriIdentifier(userSuppliedUri, false); + Assert.AreEqual(1, this.Discover(userSuppliedIdentifier).Count()); + } + + [TestCase] + public void DiscoverRequireSslWithSecureRedirects() { + Identifier claimedId = this.GetMockIdentifier(ProtocolVersion.V20, true); + + // Add a couple of chained redirect pages that lead to the claimedId. + // All redirects should be secure. + Uri userSuppliedUri = new Uri("https://localhost/someSecurePage"); + Uri secureMidpointUri = new Uri("https://localhost/secureStop"); + this.MockResponder.RegisterMockRedirect(userSuppliedUri, secureMidpointUri); + this.MockResponder.RegisterMockRedirect(secureMidpointUri, new Uri(claimedId.ToString())); + + Identifier userSuppliedIdentifier = new UriIdentifier(userSuppliedUri, true); + Assert.AreEqual(1, this.Discover(userSuppliedIdentifier).Count()); + } + + [TestCase, ExpectedException(typeof(ProtocolException))] + public void DiscoverRequireSslWithInsecureRedirect() { + Identifier claimedId = this.GetMockIdentifier(ProtocolVersion.V20, true); + + // Add a couple of chained redirect pages that lead to the claimedId. + // Include an insecure HTTP jump in those redirects to verify that + // the ultimate endpoint is never found as a result of high security profile. + Uri userSuppliedUri = new Uri("https://localhost/someSecurePage"); + Uri insecureMidpointUri = new Uri("http://localhost/insecureStop"); + this.MockResponder.RegisterMockRedirect(userSuppliedUri, insecureMidpointUri); + this.MockResponder.RegisterMockRedirect(insecureMidpointUri, new Uri(claimedId.ToString())); + + Identifier userSuppliedIdentifier = new UriIdentifier(userSuppliedUri, true); + this.Discover(userSuppliedIdentifier); + } + + [TestCase] + public void DiscoveryRequireSslWithInsecureXrdsInSecureHtmlHead() { + var insecureXrdsSource = this.GetMockIdentifier(ProtocolVersion.V20, false); + Uri secureClaimedUri = new Uri("https://localhost/secureId"); + + string html = string.Format("<html><head><meta http-equiv='X-XRDS-Location' content='{0}'/></head><body></body></html>", insecureXrdsSource); + this.MockResponder.RegisterMockResponse(secureClaimedUri, "text/html", html); + + Identifier userSuppliedIdentifier = new UriIdentifier(secureClaimedUri, true); + Assert.AreEqual(0, this.Discover(userSuppliedIdentifier).Count()); + } + + [TestCase] + public void DiscoveryRequireSslWithInsecureXrdsInSecureHttpHeader() { + var insecureXrdsSource = this.GetMockIdentifier(ProtocolVersion.V20, false); + + string html = "<html><head></head><body></body></html>"; + WebHeaderCollection headers = new WebHeaderCollection { + { "X-XRDS-Location", insecureXrdsSource } + }; + this.MockResponder.RegisterMockResponse(VanityUriSsl, VanityUriSsl, "text/html", headers, html); + + Identifier userSuppliedIdentifier = new UriIdentifier(VanityUriSsl, true); + Assert.AreEqual(0, this.Discover(userSuppliedIdentifier).Count()); + } + + [TestCase] + public void DiscoveryRequireSslWithInsecureXrdsButSecureLinkTags() { + var insecureXrdsSource = this.GetMockIdentifier(ProtocolVersion.V20, false); + string html = string.Format( + @" + <html><head> + <meta http-equiv='X-XRDS-Location' content='{0}'/> <!-- this one will be insecure and ignored --> + <link rel='openid2.provider' href='{1}' /> + <link rel='openid2.local_id' href='{2}' /> + </head><body></body></html>", + HttpUtility.HtmlEncode(insecureXrdsSource), + HttpUtility.HtmlEncode(OPUriSsl.AbsoluteUri), + HttpUtility.HtmlEncode(OPLocalIdentifiersSsl[1].AbsoluteUri)); + this.MockResponder.RegisterMockResponse(VanityUriSsl, "text/html", html); + + Identifier userSuppliedIdentifier = new UriIdentifier(VanityUriSsl, true); + + // We verify that the XRDS was ignored and the LINK tags were used + // because the XRDS OP-LocalIdentifier uses different local identifiers. + Assert.AreEqual(OPLocalIdentifiersSsl[1].AbsoluteUri, this.Discover(userSuppliedIdentifier).Single().ProviderLocalIdentifier.ToString()); + } + + [TestCase] + public void DiscoveryRequiresSslIgnoresInsecureEndpointsInXrds() { + var insecureEndpoint = GetServiceEndpoint(0, ProtocolVersion.V20, 10, false); + var secureEndpoint = GetServiceEndpoint(1, ProtocolVersion.V20, 20, true); + UriIdentifier secureClaimedId = new UriIdentifier(VanityUriSsl, true); + this.MockResponder.RegisterMockXrdsResponse(secureClaimedId, new IdentifierDiscoveryResult[] { insecureEndpoint, secureEndpoint }); + Assert.AreEqual(secureEndpoint.ProviderLocalIdentifier, this.Discover(secureClaimedId).Single().ProviderLocalIdentifier); + } + + [TestCase] + public void XrdsDirectDiscovery_10() { + this.FailDiscoverXrds("xrds-irrelevant"); + this.DiscoverXrds("xrds10", ProtocolVersion.V10, null, "http://a/b"); + this.DiscoverXrds("xrds11", ProtocolVersion.V11, null, "http://a/b"); + this.DiscoverXrds("xrds1020", ProtocolVersion.V10, null, "http://a/b"); + } + + [TestCase] + public void XrdsDirectDiscovery_20() { + this.DiscoverXrds("xrds20", ProtocolVersion.V20, null, "http://a/b"); + this.DiscoverXrds("xrds2010a", ProtocolVersion.V20, null, "http://a/b"); + this.DiscoverXrds("xrds2010b", ProtocolVersion.V20, null, "http://a/b"); + } + + [TestCase] + public void HtmlDiscover_11() { + this.DiscoverHtml("html10prov", ProtocolVersion.V11, null, "http://a/b"); + this.DiscoverHtml("html10both", ProtocolVersion.V11, "http://c/d", "http://a/b"); + this.FailDiscoverHtml("html10del"); + + // Verify that HTML discovery generates the 1.x endpoints when appropriate + this.DiscoverHtml("html2010", ProtocolVersion.V11, "http://g/h", "http://e/f"); + this.DiscoverHtml("html1020", ProtocolVersion.V11, "http://g/h", "http://e/f"); + this.DiscoverHtml("html2010combinedA", ProtocolVersion.V11, "http://c/d", "http://a/b"); + this.DiscoverHtml("html2010combinedB", ProtocolVersion.V11, "http://c/d", "http://a/b"); + this.DiscoverHtml("html2010combinedC", ProtocolVersion.V11, "http://c/d", "http://a/b"); + } + + [TestCase] + public void HtmlDiscover_20() { + this.DiscoverHtml("html20prov", ProtocolVersion.V20, null, "http://a/b"); + this.DiscoverHtml("html20both", ProtocolVersion.V20, "http://c/d", "http://a/b"); + this.FailDiscoverHtml("html20del"); + this.DiscoverHtml("html2010", ProtocolVersion.V20, "http://c/d", "http://a/b"); + this.DiscoverHtml("html1020", ProtocolVersion.V20, "http://c/d", "http://a/b"); + this.DiscoverHtml("html2010combinedA", ProtocolVersion.V20, "http://c/d", "http://a/b"); + this.DiscoverHtml("html2010combinedB", ProtocolVersion.V20, "http://c/d", "http://a/b"); + this.DiscoverHtml("html2010combinedC", ProtocolVersion.V20, "http://c/d", "http://a/b"); + this.FailDiscoverHtml("html20relative"); + } + + [TestCase] + public void XrdsDiscoveryFromHead() { + this.MockResponder.RegisterMockResponse(new Uri("http://localhost/xrds1020.xml"), "application/xrds+xml", LoadEmbeddedFile("/Discovery/xrdsdiscovery/xrds1020.xml")); + this.DiscoverXrds("XrdsReferencedInHead.html", ProtocolVersion.V10, null, "http://a/b"); + } + + [TestCase] + public void XrdsDiscoveryFromHttpHeader() { + WebHeaderCollection headers = new WebHeaderCollection(); + headers.Add("X-XRDS-Location", new Uri("http://localhost/xrds1020.xml").AbsoluteUri); + this.MockResponder.RegisterMockResponse(new Uri("http://localhost/xrds1020.xml"), "application/xrds+xml", LoadEmbeddedFile("/Discovery/xrdsdiscovery/xrds1020.xml")); + this.DiscoverXrds("XrdsReferencedInHttpHeader.html", ProtocolVersion.V10, null, "http://a/b", headers); + } + + /// <summary> + /// Verifies HTML discovery proceeds if an XRDS document is referenced that doesn't contain OpenID endpoints. + /// </summary> + [TestCase] + public void HtmlDiscoveryProceedsIfXrdsIsEmpty() { + this.MockResponder.RegisterMockResponse(new Uri("http://localhost/xrds-irrelevant.xml"), "application/xrds+xml", LoadEmbeddedFile("/Discovery/xrdsdiscovery/xrds-irrelevant.xml")); + this.DiscoverHtml("html20provWithEmptyXrds", ProtocolVersion.V20, null, "http://a/b"); + } + + /// <summary> + /// Verifies HTML discovery proceeds if the XRDS that is referenced cannot be found. + /// </summary> + [TestCase] + public void HtmlDiscoveryProceedsIfXrdsIsBadOrMissing() { + this.DiscoverHtml("html20provWithBadXrds", ProtocolVersion.V20, null, "http://a/b"); + } + + /// <summary> + /// Verifies that a dual identifier yields only one service endpoint by default. + /// </summary> + [TestCase] + public void DualIdentifierOffByDefault() { + this.MockResponder.RegisterMockResponse(VanityUri, "application/xrds+xml", LoadEmbeddedFile("/Discovery/xrdsdiscovery/xrds20dual.xml")); + var results = this.Discover(VanityUri).ToList(); + Assert.AreEqual(1, results.Count(r => r.ClaimedIdentifier == r.Protocol.ClaimedIdentifierForOPIdentifier), "OP Identifier missing from discovery results."); + Assert.AreEqual(1, results.Count, "Unexpected additional services discovered."); + } + + /// <summary> + /// Verifies that a dual identifier yields two service endpoints when that feature is turned on. + /// </summary> + [TestCase] + public void DualIdentifier() { + this.MockResponder.RegisterMockResponse(VanityUri, "application/xrds+xml", LoadEmbeddedFile("/Discovery/xrdsdiscovery/xrds20dual.xml")); + var rp = this.CreateRelyingParty(true); + rp.Channel.WebRequestHandler = this.RequestHandler; + rp.SecuritySettings.AllowDualPurposeIdentifiers = true; + var results = rp.Discover(VanityUri).ToList(); + Assert.AreEqual(1, results.Count(r => r.ClaimedIdentifier == r.Protocol.ClaimedIdentifierForOPIdentifier), "OP Identifier missing from discovery results."); + Assert.AreEqual(1, results.Count(r => r.ClaimedIdentifier == VanityUri), "Claimed identifier missing from discovery results."); + Assert.AreEqual(2, results.Count, "Unexpected additional services discovered."); + } + + private void Discover(string url, ProtocolVersion version, Identifier expectedLocalId, string providerEndpoint, bool expectSreg, bool useRedirect) { + this.Discover(url, version, expectedLocalId, providerEndpoint, expectSreg, useRedirect, null); + } + + private void Discover(string url, ProtocolVersion version, Identifier expectedLocalId, string providerEndpoint, bool expectSreg, bool useRedirect, WebHeaderCollection headers) { + Protocol protocol = Protocol.Lookup(version); + Uri baseUrl = new Uri("http://localhost/"); + UriIdentifier claimedId = new Uri(baseUrl, url); + UriIdentifier userSuppliedIdentifier = new Uri(baseUrl, "Discovery/htmldiscovery/redirect.aspx?target=" + url); + if (expectedLocalId == null) { + expectedLocalId = claimedId; + } + Identifier idToDiscover = useRedirect ? userSuppliedIdentifier : claimedId; + + string contentType; + if (url.EndsWith("html")) { + contentType = "text/html"; + } else if (url.EndsWith("xml")) { + contentType = "application/xrds+xml"; + } else { + throw new InvalidOperationException(); + } + this.MockResponder.RegisterMockResponse(new Uri(idToDiscover), claimedId, contentType, headers ?? new WebHeaderCollection(), LoadEmbeddedFile(url)); + + IdentifierDiscoveryResult expected = IdentifierDiscoveryResult.CreateForClaimedIdentifier( + claimedId, + expectedLocalId, + new ProviderEndpointDescription(new Uri(providerEndpoint), new string[] { protocol.ClaimedIdentifierServiceTypeURI }), // services aren't checked by Equals + null, + null); + + IdentifierDiscoveryResult se = this.Discover(idToDiscover).FirstOrDefault(ep => ep.Equals(expected)); + Assert.IsNotNull(se, url + " failed to be discovered."); + + // Do extra checking of service type URIs, which aren't included in + // the ServiceEndpoint.Equals method. + Assert.AreEqual(expectSreg ? 2 : 1, se.Capabilities.Count); + Assert.IsTrue(se.Capabilities.Contains(protocol.ClaimedIdentifierServiceTypeURI)); + Assert.AreEqual(expectSreg, se.IsExtensionSupported<ClaimsRequest>()); + } + + private void DiscoverXrds(string page, ProtocolVersion version, Identifier expectedLocalId, string providerEndpoint) { + this.DiscoverXrds(page, version, expectedLocalId, providerEndpoint, null); + } + + private void DiscoverXrds(string page, ProtocolVersion version, Identifier expectedLocalId, string providerEndpoint, WebHeaderCollection headers) { + if (!page.Contains(".")) { + page += ".xml"; + } + this.Discover("/Discovery/xrdsdiscovery/" + page, version, expectedLocalId, providerEndpoint, true, false, headers); + this.Discover("/Discovery/xrdsdiscovery/" + page, version, expectedLocalId, providerEndpoint, true, true, headers); + } + + private void DiscoverHtml(string page, ProtocolVersion version, Identifier expectedLocalId, string providerEndpoint, bool useRedirect) { + this.Discover("/Discovery/htmldiscovery/" + page, version, expectedLocalId, providerEndpoint, false, useRedirect); + } + + private void DiscoverHtml(string scenario, ProtocolVersion version, Identifier expectedLocalId, string providerEndpoint) { + string page = scenario + ".html"; + this.DiscoverHtml(page, version, expectedLocalId, providerEndpoint, false); + this.DiscoverHtml(page, version, expectedLocalId, providerEndpoint, true); + } + + private void FailDiscover(string url) { + UriIdentifier userSuppliedId = new Uri(new Uri("http://localhost"), url); + + this.MockResponder.RegisterMockResponse(new Uri(userSuppliedId), userSuppliedId, "text/html", LoadEmbeddedFile(url)); + + Assert.AreEqual(0, this.Discover(userSuppliedId).Count()); // ... but that no endpoint info is discoverable + } + + private void FailDiscoverHtml(string scenario) { + this.FailDiscover("/Discovery/htmldiscovery/" + scenario + ".html"); + } + + private void FailDiscoverXrds(string scenario) { + this.FailDiscover("/Discovery/xrdsdiscovery/" + scenario + ".xml"); + } + } +} diff --git a/src/DotNetOpenAuth.Test/OpenId/DiscoveryServices/XriDiscoveryProxyServiceTests.cs b/src/DotNetOpenAuth.Test/OpenId/DiscoveryServices/XriDiscoveryProxyServiceTests.cs new file mode 100644 index 0000000..5d914f5 --- /dev/null +++ b/src/DotNetOpenAuth.Test/OpenId/DiscoveryServices/XriDiscoveryProxyServiceTests.cs @@ -0,0 +1,394 @@ +//----------------------------------------------------------------------- +// <copyright file="XriDiscoveryProxyServiceTests.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.Test.OpenId.DiscoveryServices { + using System; + using System.Collections.Generic; + using System.Linq; + using System.Text; + using DotNetOpenAuth.OpenId; + using DotNetOpenAuth.OpenId.RelyingParty; + using NUnit.Framework; + + [TestFixture] + public class XriDiscoveryProxyServiceTests : OpenIdTestBase { + [TestCase] + public void Discover() { + string xrds = @"<?xml version='1.0' encoding='UTF-8'?> +<XRD version='2.0' xmlns='xri://$xrd*($v*2.0)'> + <Query>*Arnott</Query> + <Status ceid='off' cid='verified' code='100'/> + <Expires>2008-07-14T02:03:24.000Z</Expires> + <ProviderID>xri://=</ProviderID> + <LocalID>!9b72.7dd1.50a9.5ccd</LocalID> + <CanonicalID>=!9B72.7DD1.50A9.5CCD</CanonicalID> + + <Service priority='10'> + <ProviderID>xri://!!1008</ProviderID> + <Type select='true'>xri://+i-service*(+contact)*($v*1.0)</Type> + <Type match='default' select='false'/> + <Path select='true'>(+contact)</Path> + <Path match='null' select='false'/> + <URI append='qxri' priority='1'>http://1id.com/contact/</URI> + + </Service> + <Service priority='10'> + <ProviderID>xri://!!1008</ProviderID> + <Type select='true'>xri://+i-service*(+forwarding)*($v*1.0)</Type> + <Type match='null' select='false'/> + <URI append='qxri' priority='1'>http://1id.com/</URI> + </Service> + + <Service priority='10'> + <ProviderID>xri://!!1008</ProviderID> + <Type select='true'>http://openid.net/signon/1.0</Type> + <URI append='none' priority='10'>http://1id.com/sso</URI> + </Service> +</XRD>"; + Dictionary<string, string> mocks = new Dictionary<string, string> { + { "https://xri.net/=Arnott?_xrd_r=application/xrd%2Bxml;sep=false", xrds }, + { "https://xri.net/=!9B72.7DD1.50A9.5CCD?_xrd_r=application/xrd%2Bxml;sep=false", xrds }, + }; + this.MockResponder.RegisterMockXrdsResponses(mocks); + + string expectedCanonicalId = "=!9B72.7DD1.50A9.5CCD"; + IdentifierDiscoveryResult se = this.VerifyCanonicalId("=Arnott", expectedCanonicalId); + Assert.AreEqual(Protocol.V10, Protocol.Lookup(se.Version)); + Assert.AreEqual("http://1id.com/sso", se.ProviderEndpoint.ToString()); + Assert.AreEqual(se.ClaimedIdentifier, se.ProviderLocalIdentifier); + Assert.AreEqual("=Arnott", se.FriendlyIdentifierForDisplay); + } + + [TestCase] + public void DiscoverCommunityInameCanonicalIDs() { + string llliResponse = @"<?xml version='1.0' encoding='UTF-8'?> +<XRD version='2.0' xmlns='xri://$xrd*($v*2.0)'> + <Query>*llli</Query> + <Status ceid='off' cid='verified' code='100'/> + <Expires>2008-07-14T02:21:06.000Z</Expires> + <ProviderID>xri://@</ProviderID> + <LocalID>!72cd.a072.157e.a9c6</LocalID> + <CanonicalID>@!72CD.A072.157E.A9C6</CanonicalID> + <Service priority='10'> + <ProviderID>xri://!!1003!103</ProviderID> + <Type select='true'>http://openid.net/signon/1.0</Type> + <URI append='none' priority='1'>https://login.llli.org/server/</URI> + </Service> + <Service priority='1'> + <ProviderID>xri://!!1003!103</ProviderID> + <Type match='null' select='false'/> + <Type select='true'>xri://+i-service*(+forwarding)*($v*1.0)</Type> + <Path match='default'/> + <Path>(+index)</Path> + <URI append='qxri' priority='1'>http://linksafe-forward.ezibroker.net/forwarding/</URI> + </Service> + <Service priority='10'> + <ProviderID>xri://!!1003!103</ProviderID> + <Type select='true'>xri://$res*auth*($v*2.0)</Type> + <MediaType>application/xrds+xml;trust=none</MediaType> + <URI priority='10'>http://resolve.ezibroker.net/resolve/@llli/</URI> + </Service> + <Service priority='10'> + <ProviderID>xri://!!1003!103</ProviderID> + <Type select='true'>xri://+i-service*(+contact)*($v*1.0)</Type> + <Type match='null'/> + <Path select='true'>(+contact)</Path> + <Path match='null'/> + <URI append='authority' priority='1'>http://linksafe-contact.ezibroker.net/contact/</URI> + </Service> +</XRD> +"; + string llliAreaResponse = @"<?xml version='1.0' encoding='UTF-8'?> +<XRD xmlns='xri://$xrd*($v*2.0)'> + <Query>*area</Query> + <Status cid='verified' code='100'>SUCCESS</Status> + <ServerStatus code='100'>SUCCESS</ServerStatus> + <Expires>2008-07-15T01:21:07.000Z</Expires> + <ProviderID>xri://!!1003</ProviderID> + <LocalID>0000.0000.3B9A.CA0C</LocalID> + <CanonicalID>@!72CD.A072.157E.A9C6!0000.0000.3B9A.CA0C</CanonicalID> + <Service> + <ProviderID>xri://!!1003!103</ProviderID> + <Type select='true'>http://openid.net/signon/1.0</Type> + <URI append='none' priority='1'>https://login.llli.org/server/</URI> + </Service> + <Service> + <ProviderID>xri://!!1003!103</ProviderID> + <Type select='true'>xri://+i-service*(+contact)*($v*1.0)</Type> + <Type match='null'/> + <Path select='true'>(+contact)</Path> + <Path match='null'/> + <URI append='authority' priority='1'>http://linksafe-contact.ezibroker.net/contact/</URI> + </Service> + <Service priority='1'> + <ProviderID>xri://!!1003!103</ProviderID> + <Type select='true'>xri://+i-service*(+forwarding)*($v*1.0)</Type> + <Type match='null' select='false'/> + <Path>(+index)</Path> + <Path match='default'/> + <URI append='qxri' priority='1'>http://linksafe-forward.ezibroker.net/forwarding/</URI> + </Service> + <Service> + <ProviderID>xri://!!1003!103</ProviderID> + <Type select='true'>xri://$res*auth*($v*2.0)</Type> + <MediaType>application/xrds+xml;trust=none</MediaType> + <URI>http://resolve.ezibroker.net/resolve/@llli*area/</URI> + </Service> +</XRD>"; + string llliAreaCanadaUnattachedResponse = @"<?xml version='1.0' encoding='UTF-8'?> +<XRD xmlns='xri://$xrd*($v*2.0)'> + <Query>*canada.unattached</Query> + <Status cid='verified' code='100'>SUCCESS</Status> + <ServerStatus code='100'>SUCCESS</ServerStatus> + <Expires>2008-07-15T01:21:08.000Z</Expires> + <ProviderID>xri://!!1003</ProviderID> + <LocalID>0000.0000.3B9A.CA41</LocalID> + <CanonicalID>@!72CD.A072.157E.A9C6!0000.0000.3B9A.CA0C!0000.0000.3B9A.CA41</CanonicalID> + <Service> + <ProviderID>xri://!!1003!103</ProviderID> + <Type select='true'>http://openid.net/signon/1.0</Type> + <URI append='none' priority='1'>https://login.llli.org/server/</URI> + </Service> + <Service> + <ProviderID>xri://!!1003!103</ProviderID> + <Type select='true'>xri://+i-service*(+contact)*($v*1.0)</Type> + <Type match='null'/> + <Path select='true'>(+contact)</Path> + <Path match='null'/> + <URI append='authority' priority='1'>http://linksafe-contact.ezibroker.net/contact/</URI> + </Service> + <Service priority='1'> + <ProviderID>xri://!!1003!103</ProviderID> + <Type select='true'>xri://+i-service*(+forwarding)*($v*1.0)</Type> + <Type match='null' select='false'/> + <Path>(+index)</Path> + <Path match='default'/> + <URI append='qxri' priority='1'>http://linksafe-forward.ezibroker.net/forwarding/</URI> + </Service> + <Service> + <ProviderID>xri://!!1003!103</ProviderID> + <Type select='true'>xri://$res*auth*($v*2.0)</Type> + <MediaType>application/xrds+xml;trust=none</MediaType> + <URI>http://resolve.ezibroker.net/resolve/@llli*area*canada.unattached/</URI> + </Service> +</XRD>"; + string llliAreaCanadaUnattachedAdaResponse = @"<?xml version='1.0' encoding='UTF-8'?> +<XRD xmlns='xri://$xrd*($v*2.0)'> + <Query>*ada</Query> + <Status cid='verified' code='100'>SUCCESS</Status> + <ServerStatus code='100'>SUCCESS</ServerStatus> + <Expires>2008-07-15T01:21:10.000Z</Expires> + <ProviderID>xri://!!1003</ProviderID> + <LocalID>0000.0000.3B9A.CA01</LocalID> + <CanonicalID>@!72CD.A072.157E.A9C6!0000.0000.3B9A.CA0C!0000.0000.3B9A.CA41!0000.0000.3B9A.CA01</CanonicalID> + <Service> + <ProviderID>xri://!!1003!103</ProviderID> + <Type select='true'>http://openid.net/signon/1.0</Type> + <URI append='none' priority='1'>https://login.llli.org/server/</URI> + </Service> + <Service> + <ProviderID>xri://!!1003!103</ProviderID> + <Type select='true'>xri://+i-service*(+contact)*($v*1.0)</Type> + <Type match='null'/> + <Path select='true'>(+contact)</Path> + <Path match='null'/> + <URI append='authority' priority='1'>http://linksafe-contact.ezibroker.net/contact/</URI> + </Service> + <Service priority='1'> + <ProviderID>xri://!!1003!103</ProviderID> + <Type select='true'>xri://+i-service*(+forwarding)*($v*1.0)</Type> + <Type match='null' select='false'/> + <Path>(+index)</Path> + <Path match='default'/> + <URI append='qxri' priority='1'>http://linksafe-forward.ezibroker.net/forwarding/</URI> + </Service> +</XRD>"; + string webResponse = @"<?xml version='1.0' encoding='UTF-8'?> +<XRD version='2.0' xmlns='xri://$xrd*($v*2.0)'> + <Query>*Web</Query> + <Status ceid='off' cid='verified' code='100'/> + <Expires>2008-07-14T02:21:12.000Z</Expires> + <ProviderID>xri://=</ProviderID> + <LocalID>!91f2.8153.f600.ae24</LocalID> + <CanonicalID>=!91F2.8153.F600.AE24</CanonicalID> + <Service priority='10'> + <Type select='true'>xri://+i-service*(+locator)*($v*1.0)</Type> + <Path select='true'>(+locator)</Path> + <MediaType match='default' select='false'/> + <URI append='qxri'>http://locator.fullxri.com/locator/</URI> + </Service> + <Service priority='10'> + <ProviderID>xri://=web</ProviderID> + <Type select='true'>xri://$res*auth*($v*2.0)</Type> + <Type select='true'>xri://$res*auth*($v*2.0)</Type> + <MediaType select='true'>application/xrds+xml</MediaType> + <URI append='qxri' priority='1'>https://resolve.freexri.com/ns/=web/</URI> + <URI append='qxri' priority='2'>http://resolve.freexri.com/ns/=web/</URI> + </Service> + <Service priority='10'> + <Type select='true'>http://openid.net/signon/1.0</Type> + <Type select='true'>http://specs.openid.net/auth/2.0/signon</Type> + <Path select='true'>(+login)</Path> + <Path match='default' select='false'/> + <MediaType match='default' select='false'/> + <URI append='none' priority='2'>http://authn.fullxri.com/authentication/</URI> + <URI append='none' priority='1'>https://authn.fullxri.com/authentication/</URI> + </Service> + <Service priority='10'> + <Type select='true'>xri://+i-service*(+contact)*($v*1.0)</Type> + <Type match='null' select='false'/> + <Path select='true'>(+contact)</Path> + <Path match='null' select='false'/> + <MediaType match='default' select='false'/> + <URI append='qxri'>http://contact.fullxri.com/contact/</URI> + </Service> + <KeyInfo xmlns='http://www.w3.org/2000/09/xmldsig#'> + <X509Data> + <X509Certificate> +MIIExzCCA6+gAwIBAgIJAM+MlFr0Sth6MA0GCSqGSIb3DQEBBQUAMIGdMR8wHQYD +VQQDExZTdXBlcnZpbGxhaW46IFRoZSBSb290MQswCQYDVQQGEwJVUzERMA8GA1UE +CBMITmV3IFlvcmsxDzANBgNVBAcTBkdvdGhhbTEgMB4GA1UEChMXU3VwZXJ2aWxs +YWluIFVuaXZlcnNpdHkxJzAlBgkqhkiG9w0BCQEWGHBlbmd1aW5Ac3VwZXJ2aWxs +YWluLmVkdTAeFw0wNjA4MTcxOTU5NTNaFw0xMTA4MTYxOTU5NTNaMIGdMR8wHQYD +VQQDExZTdXBlcnZpbGxhaW46IFRoZSBSb290MQswCQYDVQQGEwJVUzERMA8GA1UE +CBMITmV3IFlvcmsxDzANBgNVBAcTBkdvdGhhbTEgMB4GA1UEChMXU3VwZXJ2aWxs +YWluIFVuaXZlcnNpdHkxJzAlBgkqhkiG9w0BCQEWGHBlbmd1aW5Ac3VwZXJ2aWxs +YWluLmVkdTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAL6uFqas4dK6 +A2wTZL0viRQNJrPyFnFBDSZGib/2ijhgzed/vvmZIBM9sFpwahcuR5hvyKUe37/c +/RSZXoNDi/eiNOx4qb0l9UB6bd8qvc4V1PnLE7L+ZYcmwrvTKm4x8qXMgEv1wca2 +FPsreHNPdLiTUZ8v0tDTWi3Mgi7y47VTzJaTkcfmO1nL6xAtln5sLdH0PbMM3LAp +T1d3nwI3VdbhqqZ+6+OKEuC8gk5iH4lfrbr6C9bYS6vzIKrotHpZ3N2aIC3NMjJD +PMw/mfCuADfRNlHXgZW+0zyUkwGTMDea8qgsoAMWJGdeTIw8I1I3RhnbgLzdsNQl +b/1ZXx1uJRUCAwEAAaOCAQYwggECMB0GA1UdDgQWBBQe+xSjYTrlfraJARjMxscb +j36jvDCB0gYDVR0jBIHKMIHHgBQe+xSjYTrlfraJARjMxscbj36jvKGBo6SBoDCB +nTEfMB0GA1UEAxMWU3VwZXJ2aWxsYWluOiBUaGUgUm9vdDELMAkGA1UEBhMCVVMx +ETAPBgNVBAgTCE5ldyBZb3JrMQ8wDQYDVQQHEwZHb3RoYW0xIDAeBgNVBAoTF1N1 +cGVydmlsbGFpbiBVbml2ZXJzaXR5MScwJQYJKoZIhvcNAQkBFhhwZW5ndWluQHN1 +cGVydmlsbGFpbi5lZHWCCQDPjJRa9ErYejAMBgNVHRMEBTADAQH/MA0GCSqGSIb3 +DQEBBQUAA4IBAQC4SPBDGYAxfbXd8N5OvG0drM7a5hjXfcCZpiILlPSRpxp79yh7 +I5vVWxBxUfolwbei7PTBVy7CE27SUbSICeqWjcDCfjNjiZk6mLS80rm/TdLrHSyM ++Ujlw9MGcBGaLI+sdziDUMtTQDpeAyQTaGVbh1mx5874Hlo1VXqGYNo0RwR+iLfs +x48VuO6GbWVyxtktkE2ypz1KLWiyI056YynydRvuBCBHeRqGUixPlH9CrmeSCP2S +sfbiKnMOGXjIYbvbsTAMdW2iqg6IWa/fgxhvZoAXChM9bkhisJQc0qD0J5TJQwgr +uEyb50RJ7DWmXctSC0b3eymZ2lSXxAWNOsNy + </X509Certificate> + </X509Data> + </KeyInfo> +</XRD>"; + this.MockResponder.RegisterMockXrdsResponses(new Dictionary<string, string> { + { "https://xri.net/@llli?_xrd_r=application/xrd%2Bxml;sep=false", llliResponse }, + { "https://xri.net/@llli*area?_xrd_r=application/xrd%2Bxml;sep=false", llliAreaResponse }, + { "https://xri.net/@llli*area*canada.unattached?_xrd_r=application/xrd%2Bxml;sep=false", llliAreaCanadaUnattachedResponse }, + { "https://xri.net/@llli*area*canada.unattached*ada?_xrd_r=application/xrd%2Bxml;sep=false", llliAreaCanadaUnattachedAdaResponse }, + { "https://xri.net/=Web?_xrd_r=application/xrd%2Bxml;sep=false", webResponse }, + }); + this.VerifyCanonicalId("@llli", "@!72CD.A072.157E.A9C6"); + this.VerifyCanonicalId("@llli*area", "@!72CD.A072.157E.A9C6!0000.0000.3B9A.CA0C"); + this.VerifyCanonicalId("@llli*area*canada.unattached", "@!72CD.A072.157E.A9C6!0000.0000.3B9A.CA0C!0000.0000.3B9A.CA41"); + this.VerifyCanonicalId("@llli*area*canada.unattached*ada", "@!72CD.A072.157E.A9C6!0000.0000.3B9A.CA0C!0000.0000.3B9A.CA41!0000.0000.3B9A.CA01"); + this.VerifyCanonicalId("=Web", "=!91F2.8153.F600.AE24"); + } + + [TestCase] + public void DiscoveryCommunityInameDelegateWithoutCanonicalID() { + this.MockResponder.RegisterMockXrdsResponses(new Dictionary<string, string> { + { "https://xri.net/=Web*andrew.arnott?_xrd_r=application/xrd%2Bxml;sep=false", @"<?xml version='1.0' encoding='UTF-8'?> +<XRD xmlns='xri://$xrd*($v*2.0)'> + <Query>*andrew.arnott</Query> + <Status cid='absent' code='100'>Success</Status> + <ServerStatus code='100'>Success</ServerStatus> + <Expires>2008-07-14T03:30:59.722Z</Expires> + <ProviderID>=!91F2.8153.F600.AE24</ProviderID> + <Service> + <Type select='true'>http://openid.net/signon/1.0</Type> + <Path select='true'>(+login)</Path> + <Path match='default'/> + <MediaType match='default'/> + <URI append='none' priority='2'>http://www.myopenid.com/server</URI> + <openid:Delegate xmlns:openid='http://openid.net/xmlns/1.0'>http://blog.nerdbank.net</openid:Delegate> + </Service> + <Service> + <ProviderID>@!7F6F.F50.A4E4.1133</ProviderID> + <Type select='true'>xri://+i-service*(+contact)*($v*1.0)</Type> + <Type match='null'/> + <Path select='true'>(+contact)</Path> + <Path match='null'/> + <MediaType match='default'/> + <URI append='qxri'>http://contact.freexri.com/contact/</URI> + </Service> + <Service> + <ProviderID>@!7F6F.F50.A4E4.1133</ProviderID> + <Type select='true'>xri://+i-service*(+forwarding)*($v*1.0)</Type> + <Path select='true'>(+index)</Path> + <Path match='default'/> + <MediaType match='default'/> + <URI append='qxri'>http://forwarding.freexri.com/forwarding/</URI> + </Service> + <Service> + <ProviderID>@!7F6F.F50.A4E4.1133</ProviderID> + <Type select='true'>http://openid.net/signon/1.0</Type> + <Path select='true'>(+login)</Path> + <Path match='default'/> + <MediaType match='default'/> + <URI append='none' priority='2'>http://authn.freexri.com/authentication/</URI> + <URI append='none' priority='1'>https://authn.freexri.com/authentication/</URI> + </Service> + <ServedBy>OpenXRI</ServedBy> +</XRD>" }, + { "https://xri.net/@id*andrewarnott?_xrd_r=application/xrd%2Bxml;sep=false", @"<?xml version='1.0' encoding='UTF-8'?> +<XRD xmlns='xri://$xrd*($v*2.0)'> + <Query>*andrewarnott</Query> + <Status cid='absent' code='100'>Success</Status> + <ServerStatus code='100'>Success</ServerStatus> + <Expires>2008-07-14T03:31:00.466Z</Expires> + <ProviderID>@!B1E8.C27B.E41C.25C3</ProviderID> + <Service> + <Type select='true'>http://openid.net/signon/1.0</Type> + <Path select='true'>(+login)</Path> + <Path match='default'/> + <MediaType match='default'/> + <URI append='none' priority='2'>http://www.myopenid.com/server</URI> + <openid:Delegate xmlns:openid='http://openid.net/xmlns/1.0'>http://blog.nerdbank.net</openid:Delegate> + </Service> + <Service> + <ProviderID>@!7F6F.F50.A4E4.1133</ProviderID> + <Type select='true'>xri://+i-service*(+contact)*($v*1.0)</Type> + <Type match='null'/> + <Path select='true'>(+contact)</Path> + <Path match='null'/> + <MediaType match='default'/> + <URI append='qxri'>http://contact.freexri.com/contact/</URI> + </Service> + <Service> + <ProviderID>@!7F6F.F50.A4E4.1133</ProviderID> + <Type select='true'>xri://+i-service*(+forwarding)*($v*1.0)</Type> + <Path select='true'>(+index)</Path> + <Path match='default'/> + <MediaType match='default'/> + <URI append='qxri'>http://forwarding.freexri.com/forwarding/</URI> + </Service> + <ServedBy>OpenXRI</ServedBy> +</XRD>" }, + }); + // Consistent with spec section 7.3.2.3, we do not permit + // delegation on XRI discovery when there is no CanonicalID present. + this.VerifyCanonicalId("=Web*andrew.arnott", null); + this.VerifyCanonicalId("@id*andrewarnott", null); + } + + private IdentifierDiscoveryResult VerifyCanonicalId(Identifier iname, string expectedClaimedIdentifier) { + var se = this.Discover(iname).FirstOrDefault(); + if (expectedClaimedIdentifier != null) { + Assert.IsNotNull(se); + Assert.AreEqual(expectedClaimedIdentifier, se.ClaimedIdentifier.ToString(), "i-name {0} discovery resulted in unexpected CanonicalId", iname); + Assert.IsTrue(se.Capabilities.Count > 0); + } else { + Assert.IsNull(se); + } + return se; + } + } +} diff --git a/src/DotNetOpenAuth.Test/OpenId/Extensions/AttributeExchange/AttributeExchangeRoundtripTests.cs b/src/DotNetOpenAuth.Test/OpenId/Extensions/AttributeExchange/AttributeExchangeRoundtripTests.cs index fa05e94..3433cfa 100644 --- a/src/DotNetOpenAuth.Test/OpenId/Extensions/AttributeExchange/AttributeExchangeRoundtripTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/Extensions/AttributeExchange/AttributeExchangeRoundtripTests.cs @@ -7,16 +7,16 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions { using DotNetOpenAuth.OpenId; using DotNetOpenAuth.OpenId.Extensions.AttributeExchange; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; - [TestClass] + [TestFixture] public class AttributeExchangeRoundtripTests : OpenIdTestBase { private const string NicknameTypeUri = WellKnownAttributes.Name.Alias; private const string EmailTypeUri = WellKnownAttributes.Contact.Email; private const string IncrementingAttribute = "http://incatt"; private int incrementingAttributeValue = 1; - [TestMethod] + [TestCase] public void Fetch() { var request = new FetchRequest(); request.Attributes.Add(new AttributeRequest(NicknameTypeUri)); @@ -29,7 +29,7 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions { ExtensionTestUtilities.Roundtrip(Protocol.Default, new[] { request }, new[] { response }); } - [TestMethod] + [TestCase] public void Store() { var request = new StoreRequest(); var newAttribute = new AttributeValues( diff --git a/src/DotNetOpenAuth.Test/OpenId/Extensions/AttributeExchange/AttributeRequestTests.cs b/src/DotNetOpenAuth.Test/OpenId/Extensions/AttributeExchange/AttributeRequestTests.cs index 48b5727..5cc8ec1 100644 --- a/src/DotNetOpenAuth.Test/OpenId/Extensions/AttributeExchange/AttributeRequestTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/Extensions/AttributeExchange/AttributeRequestTests.cs @@ -8,11 +8,11 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions { using System; using DotNetOpenAuth.OpenId.Extensions.AttributeExchange; using DotNetOpenAuth.Test.OpenId; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; - [TestClass] + [TestFixture] public class AttributeRequestTests : OpenIdTestBase { - [TestMethod] + [TestCase] public void CtorDefault() { AttributeRequest req = new AttributeRequest(); Assert.AreEqual(1, req.Count); @@ -20,27 +20,27 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions { Assert.IsFalse(req.IsRequired); } - [TestMethod, ExpectedException(typeof(ArgumentException))] + [TestCase, ExpectedException(typeof(ArgumentException))] public void CtorEmptyTypeUri() { new AttributeRequest(string.Empty); } - [TestMethod, ExpectedException(typeof(ArgumentException))] + [TestCase, ExpectedException(typeof(ArgumentException))] public void CtorNullTypeUri() { new AttributeRequest(null); } - [TestMethod, ExpectedException(typeof(ArgumentOutOfRangeException))] + [TestCase, ExpectedException(typeof(ArgumentOutOfRangeException))] public void CtorCountZero() { new AttributeRequest(WellKnownAttributes.Contact.Email, false, 0); } - [TestMethod, ExpectedException(typeof(ArgumentOutOfRangeException))] + [TestCase, ExpectedException(typeof(ArgumentOutOfRangeException))] public void CtorCountNegative() { new AttributeRequest(WellKnownAttributes.Contact.Email, false, -1); } - [TestMethod] + [TestCase] public void CtorFull() { var req = new AttributeRequest(WellKnownAttributes.Contact.Email, true, 5); Assert.AreEqual(WellKnownAttributes.Contact.Email, req.TypeUri); @@ -48,19 +48,19 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions { Assert.AreEqual(5, req.Count); } - [TestMethod, ExpectedException(typeof(ArgumentOutOfRangeException))] + [TestCase, ExpectedException(typeof(ArgumentOutOfRangeException))] public void SetCountZero() { var req = new AttributeRequest(); req.Count = 0; } - [TestMethod, ExpectedException(typeof(ArgumentOutOfRangeException))] + [TestCase, ExpectedException(typeof(ArgumentOutOfRangeException))] public void SetCountNegative() { var req = new AttributeRequest(); req.Count = -1; } - [TestMethod] + [TestCase] public void EqualityTests() { var req1 = new AttributeRequest(); var req2 = new AttributeRequest(); diff --git a/src/DotNetOpenAuth.Test/OpenId/Extensions/AttributeExchange/AttributeValuesTests.cs b/src/DotNetOpenAuth.Test/OpenId/Extensions/AttributeExchange/AttributeValuesTests.cs index 1f7e17c..6c28461 100644 --- a/src/DotNetOpenAuth.Test/OpenId/Extensions/AttributeExchange/AttributeValuesTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/Extensions/AttributeExchange/AttributeValuesTests.cs @@ -10,11 +10,11 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions.AttributeExchange { using System.Linq; using System.Text; using DotNetOpenAuth.OpenId.Extensions.AttributeExchange; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; - [TestClass] + [TestFixture] public class AttributeValuesTests : OpenIdTestBase { - [TestMethod] + [TestCase] public void Ctor() { var att = new AttributeValues(); Assert.IsNull(att.TypeUri); @@ -37,7 +37,7 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions.AttributeExchange { /// <summary> /// Verifies the Equals method. /// </summary> - [TestMethod] + [TestCase] public void EqualityTests() { var att1 = new AttributeValues(); var att2 = new AttributeValues(); diff --git a/src/DotNetOpenAuth.Test/OpenId/Extensions/AttributeExchange/FetchRequestTests.cs b/src/DotNetOpenAuth.Test/OpenId/Extensions/AttributeExchange/FetchRequestTests.cs index 43eba3f..2388798 100644 --- a/src/DotNetOpenAuth.Test/OpenId/Extensions/AttributeExchange/FetchRequestTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/Extensions/AttributeExchange/FetchRequestTests.cs @@ -9,35 +9,35 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions { using System.IO; using DotNetOpenAuth.OpenId.Extensions.AttributeExchange; using DotNetOpenAuth.Test.OpenId; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; - [TestClass] + [TestFixture] public class FetchRequestTests : OpenIdTestBase { - [TestMethod, ExpectedException(typeof(ArgumentNullException))] + [TestCase, ExpectedException(typeof(ArgumentNullException))] public void AddAttributeRequestNull() { new FetchRequest().Attributes.Add(null); } - [TestMethod] + [TestCase] public void AddAttributeRequest() { var req = new FetchRequest(); req.Attributes.Add(new AttributeRequest() { TypeUri = "http://someUri" }); } - [TestMethod] + [TestCase] public void AddAttributeRequestStrangeUri() { var req = new FetchRequest(); req.Attributes.Add(new AttributeRequest() { TypeUri = "=someUri*who*knows*but*this*is*legal" }); } - [TestMethod, ExpectedException(typeof(ArgumentException))] + [TestCase, ExpectedException(typeof(ArgumentException))] public void AddAttributeRequestAgain() { var req = new FetchRequest(); req.Attributes.Add(new AttributeRequest() { TypeUri = "http://UriTwice" }); req.Attributes.Add(new AttributeRequest() { TypeUri = "http://UriTwice" }); } - [TestMethod] + [TestCase] public void RespondSimpleValue() { var req = new AttributeRequest(); req.TypeUri = "http://someType"; @@ -47,7 +47,7 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions { Assert.AreEqual("value", resp.Values[0]); } - [TestMethod] + [TestCase] public void RespondTwoValues() { var req = new AttributeRequest(); req.TypeUri = "http://someType"; @@ -59,7 +59,7 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions { Assert.AreEqual("value2", resp.Values[1]); } - [TestMethod, ExpectedException(typeof(ArgumentException))] + [TestCase, ExpectedException(typeof(ArgumentException))] public void RespondTooManyValues() { var req = new AttributeRequest(); req.TypeUri = "http://someType"; @@ -67,7 +67,7 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions { req.Respond("value1", "value2"); } - [TestMethod, ExpectedException(typeof(ArgumentNullException))] + [TestCase, ExpectedException(typeof(ArgumentNullException))] public void RespondNull() { var req = new AttributeRequest(); req.TypeUri = "http://someType"; @@ -75,7 +75,7 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions { req.Respond(null); } - [TestMethod] + [TestCase] public void EqualityTests() { var req1 = new FetchRequest(); var req2 = new FetchRequest(); @@ -100,7 +100,7 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions { /// <summary> /// Verifies that the class is serializable. /// </summary> - [TestMethod] + [TestCase] public void Serializable() { var fetch = new FetchRequest(); fetch.Attributes.AddRequired("http://someAttribute"); diff --git a/src/DotNetOpenAuth.Test/OpenId/Extensions/AttributeExchange/FetchResponseTests.cs b/src/DotNetOpenAuth.Test/OpenId/Extensions/AttributeExchange/FetchResponseTests.cs index d7082c3..c545a46 100644 --- a/src/DotNetOpenAuth.Test/OpenId/Extensions/AttributeExchange/FetchResponseTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/Extensions/AttributeExchange/FetchResponseTests.cs @@ -9,37 +9,37 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions { using System.IO; using DotNetOpenAuth.OpenId.Extensions.AttributeExchange; using DotNetOpenAuth.Test.OpenId; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; - [TestClass] + [TestFixture] public class FetchResponseTests : OpenIdTestBase { - [TestMethod] + [TestCase] public void AddAttribute() { var response = new FetchResponse(); response.Attributes.Add(new AttributeValues("http://someattribute", "Value1")); } - [TestMethod] + [TestCase] public void AddTwoAttributes() { var response = new FetchResponse(); response.Attributes.Add(new AttributeValues("http://someattribute", "Value1")); response.Attributes.Add(new AttributeValues("http://someOtherAttribute", "Value2")); } - [TestMethod, ExpectedException(typeof(ArgumentException))] + [TestCase, ExpectedException(typeof(ArgumentException))] public void AddAttributeTwice() { var response = new FetchResponse(); response.Attributes.Add(new AttributeValues("http://someattribute", "Value1")); response.Attributes.Add(new AttributeValues("http://someattribute", "Value1")); } - [TestMethod, ExpectedException(typeof(ArgumentNullException))] + [TestCase, ExpectedException(typeof(ArgumentNullException))] public void AddAttributeNull() { var response = new FetchResponse(); response.Attributes.Add(null); } - [TestMethod] + [TestCase] public void GetAttributeValue() { var response = new FetchResponse(); @@ -55,7 +55,7 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions { Assert.AreEqual("a", response.GetAttributeValue("http://someattribute3")); } - [TestMethod] + [TestCase] public void EqualityTests() { var response1 = new FetchResponse(); var response2 = new FetchResponse(); @@ -80,7 +80,7 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions { /// <summary> /// Verifies that the class is serializable. /// </summary> - [TestMethod] + [TestCase] public void Serializable() { var fetch = new FetchResponse(); fetch.Attributes.Add("http://someAttribute", "val1", "val2"); diff --git a/src/DotNetOpenAuth.Test/OpenId/Extensions/AttributeExchange/StoreRequestTests.cs b/src/DotNetOpenAuth.Test/OpenId/Extensions/AttributeExchange/StoreRequestTests.cs index b11c469..fc486aa 100644 --- a/src/DotNetOpenAuth.Test/OpenId/Extensions/AttributeExchange/StoreRequestTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/Extensions/AttributeExchange/StoreRequestTests.cs @@ -12,14 +12,14 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions.AttributeExchange { using System.Text; using DotNetOpenAuth.Messaging; using DotNetOpenAuth.OpenId.Extensions.AttributeExchange; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; - [TestClass] + [TestFixture] public class StoreRequestTests { /// <summary> /// Verifies the constructor behavior. /// </summary> - [TestMethod] + [TestCase] public void Ctor() { var req = new StoreRequest(); Assert.IsFalse(req.Attributes.Any()); @@ -28,7 +28,7 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions.AttributeExchange { /// <summary> /// Verifies the AddAttribute method. /// </summary> - [TestMethod] + [TestCase] public void AddAttributeByValue() { var req = new StoreRequest(); AttributeValues value = new AttributeValues(); @@ -39,7 +39,7 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions.AttributeExchange { /// <summary> /// Verifies the AddAttribute method. /// </summary> - [TestMethod] + [TestCase] public void AddAttributeByPrimitives() { var req = new StoreRequest(); req.Attributes.Add("http://att1", "value1", "value2"); @@ -51,7 +51,7 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions.AttributeExchange { /// <summary> /// Verifies the Equals method. /// </summary> - [TestMethod] + [TestCase] public void EqualityTests() { var req1 = new StoreRequest(); var req2 = new StoreRequest(); @@ -71,7 +71,7 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions.AttributeExchange { /// <summary> /// Verifies that the class is serializable. /// </summary> - [TestMethod] + [TestCase] public void Serializable() { var store = new StoreRequest(); store.Attributes.Add("http://someAttribute", "val1", "val2"); diff --git a/src/DotNetOpenAuth.Test/OpenId/Extensions/AttributeExchange/StoreResponseTests.cs b/src/DotNetOpenAuth.Test/OpenId/Extensions/AttributeExchange/StoreResponseTests.cs index 4e432e1..564ef7f 100644 --- a/src/DotNetOpenAuth.Test/OpenId/Extensions/AttributeExchange/StoreResponseTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/Extensions/AttributeExchange/StoreResponseTests.cs @@ -7,14 +7,14 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions.AttributeExchange { using System.IO; using DotNetOpenAuth.OpenId.Extensions.AttributeExchange; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; - [TestClass] + [TestFixture] public class StoreResponseTests { /// <summary> /// Verifies the constructor's behavior. /// </summary> - [TestMethod] + [TestCase] public void Ctor() { var response = new StoreResponse(); Assert.IsTrue(response.Succeeded, "The default status should be Succeeded."); @@ -28,7 +28,7 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions.AttributeExchange { /// <summary> /// Verifies the Equals method. /// </summary> - [TestMethod] + [TestCase] public void EqualityTests() { var response1 = new StoreResponse(); var response2 = new StoreResponse(); @@ -51,7 +51,7 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions.AttributeExchange { /// <summary> /// Verifies that the class is serializable. /// </summary> - [TestMethod] + [TestCase] public void Serializable() { var store = new StoreResponse(); store.Succeeded = false; diff --git a/src/DotNetOpenAuth.Test/OpenId/Extensions/ExtensionsInteropHelperOPTests.cs b/src/DotNetOpenAuth.Test/OpenId/Extensions/ExtensionsInteropHelperOPTests.cs index 1fb3160..1b1dd49 100644 --- a/src/DotNetOpenAuth.Test/OpenId/Extensions/ExtensionsInteropHelperOPTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/Extensions/ExtensionsInteropHelperOPTests.cs @@ -14,14 +14,14 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions { using DotNetOpenAuth.OpenId.Extensions.SimpleRegistration; using DotNetOpenAuth.OpenId.Messages; using DotNetOpenAuth.OpenId.Provider; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; - [TestClass] + [TestFixture] public class ExtensionsInteropHelperOPTests : OpenIdTestBase { private AuthenticationRequest request; private IList<IExtensionMessage> extensions; - [TestInitialize] + [SetUp] public override void SetUp() { base.SetUp(); @@ -36,7 +36,7 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions { /// <summary> /// Verifies no extensions appear as no extensions /// </summary> - [TestMethod] + [TestCase] public void NoRequestedExtensions() { var sreg = ExtensionsInteropHelper.UnifyExtensionsAsSreg(this.request); Assert.IsNull(sreg); @@ -51,7 +51,7 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions { Assert.AreSame(sregResponse, extensions.Single()); } - [TestMethod] + [TestCase] public void NegativeResponse() { this.request.IsAuthenticated = false; ExtensionsInteropHelper.ConvertSregToMatchRequest(this.request); @@ -60,7 +60,7 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions { /// <summary> /// Verifies sreg coming in is seen as sreg. /// </summary> - [TestMethod] + [TestCase] public void UnifyExtensionsAsSregWithSreg() { var sregInjected = new ClaimsRequest(DotNetOpenAuth.OpenId.Extensions.SimpleRegistration.Constants.sreg_ns) { Nickname = DemandLevel.Request, @@ -81,7 +81,7 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions { /// <summary> /// Verifies AX coming in looks like sreg. /// </summary> - [TestMethod] + [TestCase] public void UnifyExtensionsAsSregWithAX() { this.ParameterizedAXTest(AXAttributeFormats.AXSchemaOrg); } @@ -89,7 +89,7 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions { /// <summary> /// Verifies AX coming in looks like sreg. /// </summary> - [TestMethod] + [TestCase] public void UnifyExtensionsAsSregWithAXSchemaOpenIdNet() { this.ParameterizedAXTest(AXAttributeFormats.SchemaOpenIdNet); } @@ -97,7 +97,7 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions { /// <summary> /// Verifies sreg and AX in one request has a preserved sreg request. /// </summary> - [TestMethod] + [TestCase] public void UnifyExtensionsAsSregWithBothSregAndAX() { var sregInjected = new ClaimsRequest(DotNetOpenAuth.OpenId.Extensions.SimpleRegistration.Constants.sreg_ns) { Nickname = DemandLevel.Request, diff --git a/src/DotNetOpenAuth.Test/OpenId/Extensions/ExtensionsInteropHelperRPRequestTests.cs b/src/DotNetOpenAuth.Test/OpenId/Extensions/ExtensionsInteropHelperRPRequestTests.cs index 7edec09..44a629a 100644 --- a/src/DotNetOpenAuth.Test/OpenId/Extensions/ExtensionsInteropHelperRPRequestTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/Extensions/ExtensionsInteropHelperRPRequestTests.cs @@ -5,20 +5,21 @@ //----------------------------------------------------------------------- namespace DotNetOpenAuth.Test.OpenId.Extensions { + using System.Collections.ObjectModel; using System.Linq; using DotNetOpenAuth.OpenId; using DotNetOpenAuth.OpenId.Extensions; using DotNetOpenAuth.OpenId.Extensions.AttributeExchange; using DotNetOpenAuth.OpenId.Extensions.SimpleRegistration; using DotNetOpenAuth.OpenId.RelyingParty; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; - [TestClass] + [TestFixture] public class ExtensionsInteropHelperRPRequestTests : OpenIdTestBase { private AuthenticationRequest authReq; private ClaimsRequest sreg; - [TestInitialize] + [SetUp] public override void SetUp() { base.SetUp(); @@ -41,7 +42,7 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions { /// <summary> /// Verifies that without an Sreg extension to copy from, no AX extension request is added. /// </summary> - [TestMethod] + [TestCase] public void SpreadSregToAXNoExtensions() { ExtensionsInteropHelper.SpreadSregToAX(this.authReq, AXAttributeFormats.AXSchemaOrg); Assert.AreEqual(0, this.authReq.AppliedExtensions.Count()); @@ -50,7 +51,7 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions { /// <summary> /// Verifies that Sreg requests are correctly copied to axschema.org AX requests. /// </summary> - [TestMethod] + [TestCase] public void SpreadSregToAXBasic() { this.authReq.AddExtension(this.sreg); ExtensionsInteropHelper.SpreadSregToAX(this.authReq, AXAttributeFormats.AXSchemaOrg); @@ -69,7 +70,7 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions { /// <summary> /// Verifies that sreg can spread to multiple AX schemas. /// </summary> - [TestMethod] + [TestCase] public void SpreadSregToAxMultipleSchemas() { this.authReq.AddExtension(this.sreg); ExtensionsInteropHelper.SpreadSregToAX(this.authReq, AXAttributeFormats.AXSchemaOrg | AXAttributeFormats.SchemaOpenIdNet); @@ -82,7 +83,7 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions { /// <summary> /// Verifies no spread if the OP advertises sreg support. /// </summary> - [TestMethod] + [TestCase] public void SpreadSregToAxNoOpIfOPSupportsSreg() { this.authReq.AddExtension(this.sreg); this.InjectAdvertisedTypeUri(DotNetOpenAuth.OpenId.Extensions.SimpleRegistration.Constants.sreg_ns); @@ -93,7 +94,7 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions { /// <summary> /// Verifies a targeted AX request if the OP advertises a recognized type URI format. /// </summary> - [TestMethod] + [TestCase] public void SpreadSregToAxTargetedAtOPFormat() { this.authReq.AddExtension(this.sreg); this.InjectAdvertisedTypeUri(WellKnownAttributes.Name.FullName); @@ -106,7 +107,7 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions { /// <summary> /// Verifies that TransformAXFormat correctly translates AX schema Type URIs. /// </summary> - [TestMethod] + [TestCase] public void TransformAXFormatTest() { Assert.AreEqual(WellKnownAttributes.Name.Alias, ExtensionsInteropHelper_Accessor.TransformAXFormat(WellKnownAttributes.Name.Alias, AXAttributeFormats.AXSchemaOrg)); Assert.AreEqual("http://schema.openid.net/namePerson/friendly", ExtensionsInteropHelper_Accessor.TransformAXFormat(WellKnownAttributes.Name.Alias, AXAttributeFormats.SchemaOpenIdNet)); @@ -118,11 +119,9 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions { /// </summary> /// <param name="typeUri">The type URI.</param> private void InjectAdvertisedTypeUri(string typeUri) { - var serviceEndpoint = ServiceEndpoint_Accessor.AttachShadow(((ServiceEndpoint)this.authReq.Provider)); - serviceEndpoint.ProviderDescription = ProviderEndpointDescription_Accessor.AttachShadow( - new ProviderEndpointDescription( - serviceEndpoint.ProviderDescription.Endpoint, - serviceEndpoint.ProviderDescription.Capabilities.Concat(new[] { typeUri }))); + var serviceEndpoint = (IdentifierDiscoveryResult)this.authReq.Provider; + serviceEndpoint.SetCapabilitiesForTestHook( + new ReadOnlyCollection<string>(serviceEndpoint.Capabilities.Concat(new[] { typeUri }).ToList())); } } } diff --git a/src/DotNetOpenAuth.Test/OpenId/Extensions/ExtensionsInteropHelperRPResponseTests.cs b/src/DotNetOpenAuth.Test/OpenId/Extensions/ExtensionsInteropHelperRPResponseTests.cs index 655e616..7b528d0 100644 --- a/src/DotNetOpenAuth.Test/OpenId/Extensions/ExtensionsInteropHelperRPResponseTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/Extensions/ExtensionsInteropHelperRPResponseTests.cs @@ -13,14 +13,14 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions { using DotNetOpenAuth.OpenId.Extensions.SimpleRegistration; using DotNetOpenAuth.OpenId.Messages; using DotNetOpenAuth.OpenId.RelyingParty; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; - [TestClass] + [TestFixture] public class ExtensionsInteropHelperRPResponseTests : OpenIdTestBase { private IAuthenticationResponse response; private IList<IExtensionMessage> extensions; - [TestInitialize] + [SetUp] public override void SetUp() { base.SetUp(); @@ -32,7 +32,7 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions { /// <summary> /// Verifies that with no extensions present, UnifyExtensionsAsSreg returns an empty ClaimsResponse. /// </summary> - [TestMethod] + [TestCase] public void UnifyExtensionsAsSregNoExtensions() { var sreg = ExtensionsInteropHelper.UnifyExtensionsAsSreg(this.response, true); Assert.IsNotNull(sreg); @@ -42,7 +42,7 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions { /// <summary> /// Verifies that with sreg and AX extensions present, the sreg extension is returned. /// </summary> - [TestMethod] + [TestCase] public void UnifyExtensionsAsSregWithSreg() { var sregInjected = new ClaimsResponse { Nickname = "andy", @@ -59,7 +59,7 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions { /// <summary> /// Verifies UnifyExtensionsAsSreg correctly converts AX to sreg. /// </summary> - [TestMethod] + [TestCase] public void UnifyExtensionsAsSregFromAXSchemaOrg() { var axInjected = new FetchResponse(); axInjected.Attributes.Add(WellKnownAttributes.Name.Alias, "nate"); @@ -71,7 +71,7 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions { /// <summary> /// Verifies UnifyExtensionsAsSreg correctly converts AX in a non-standard format to sreg. /// </summary> - [TestMethod] + [TestCase] public void UnifyExtensionsasSregFromSchemaOpenIdNet() { var axInjected = new FetchResponse(); axInjected.Attributes.Add(ExtensionsInteropHelper_Accessor.TransformAXFormat(WellKnownAttributes.Name.Alias, AXAttributeFormats.SchemaOpenIdNet), "nate"); diff --git a/src/DotNetOpenAuth.Test/OpenId/Extensions/ProviderAuthenticationPolicy/PapeRoundTripTests.cs b/src/DotNetOpenAuth.Test/OpenId/Extensions/ProviderAuthenticationPolicy/PapeRoundTripTests.cs index 75737ab..6f35f85 100644 --- a/src/DotNetOpenAuth.Test/OpenId/Extensions/ProviderAuthenticationPolicy/PapeRoundTripTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/Extensions/ProviderAuthenticationPolicy/PapeRoundTripTests.cs @@ -9,18 +9,18 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions.ProviderAuthenticationPolicy { using DotNetOpenAuth.OpenId; using DotNetOpenAuth.OpenId.Extensions.ProviderAuthenticationPolicy; using DotNetOpenAuth.Test.OpenId.Extensions; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; - [TestClass] + [TestFixture] public class PapeRoundTripTests : OpenIdTestBase { - [TestMethod] + [TestCase] public void Trivial() { var request = new PolicyRequest(); var response = new PolicyResponse(); ExtensionTestUtilities.Roundtrip(Protocol.Default, new[] { request }, new[] { response }); } - [TestMethod] + [TestCase] public void Full() { var request = new PolicyRequest(); request.MaximumAuthenticationAge = TimeSpan.FromMinutes(10); diff --git a/src/DotNetOpenAuth.Test/OpenId/Extensions/ProviderAuthenticationPolicy/PolicyRequestTests.cs b/src/DotNetOpenAuth.Test/OpenId/Extensions/ProviderAuthenticationPolicy/PolicyRequestTests.cs index 303c747..d75eccc 100644 --- a/src/DotNetOpenAuth.Test/OpenId/Extensions/ProviderAuthenticationPolicy/PolicyRequestTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/Extensions/ProviderAuthenticationPolicy/PolicyRequestTests.cs @@ -13,11 +13,11 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions.ProviderAuthenticationPolicy { using DotNetOpenAuth.Messaging; using DotNetOpenAuth.Messaging.Reflection; using DotNetOpenAuth.OpenId.Extensions.ProviderAuthenticationPolicy; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; - [TestClass] + [TestFixture] public class PolicyRequestTests : OpenIdTestBase { - [TestMethod] + [TestCase] public void Ctor() { PolicyRequest req = new PolicyRequest(); Assert.IsNull(req.MaximumAuthenticationAge); @@ -25,7 +25,7 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions.ProviderAuthenticationPolicy { Assert.AreEqual(0, req.PreferredPolicies.Count); } - [TestMethod] + [TestCase] public void MaximumAuthenticationAgeTest() { PolicyRequest req = new PolicyRequest(); req.MaximumAuthenticationAge = TimeSpan.FromHours(1); @@ -35,7 +35,7 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions.ProviderAuthenticationPolicy { Assert.IsNull(req.MaximumAuthenticationAge); } - [TestMethod] + [TestCase] public void AddPolicies() { PolicyRequest resp = new PolicyRequest(); resp.PreferredPolicies.Add(AuthenticationPolicies.MultiFactor); @@ -45,7 +45,7 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions.ProviderAuthenticationPolicy { Assert.AreEqual(AuthenticationPolicies.PhishingResistant, resp.PreferredPolicies[1]); } - [TestMethod] + [TestCase] public void AddPolicyMultipleTimes() { // Although this isn't really the desired behavior (we'd prefer to see an // exception thrown), since we're using a List<string> internally we can't @@ -57,7 +57,7 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions.ProviderAuthenticationPolicy { Assert.AreEqual(2, resp.PreferredPolicies.Count); } - [TestMethod] + [TestCase] public void AddAuthLevelTypes() { PolicyRequest req = new PolicyRequest(); req.PreferredAuthLevelTypes.Add(Constants.AssuranceLevels.NistTypeUri); @@ -65,7 +65,7 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions.ProviderAuthenticationPolicy { Assert.IsTrue(req.PreferredAuthLevelTypes.Contains(Constants.AssuranceLevels.NistTypeUri)); } - [TestMethod] + [TestCase] public void EqualsTest() { PolicyRequest req = new PolicyRequest(); PolicyRequest req2 = new PolicyRequest(); @@ -104,7 +104,7 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions.ProviderAuthenticationPolicy { Assert.AreEqual(req, req2); } - [TestMethod] + [TestCase] public void Serialize() { PolicyRequest req = new PolicyRequest(); IMessageWithEvents reqEvents = req; diff --git a/src/DotNetOpenAuth.Test/OpenId/Extensions/ProviderAuthenticationPolicy/PolicyResponseTests.cs b/src/DotNetOpenAuth.Test/OpenId/Extensions/ProviderAuthenticationPolicy/PolicyResponseTests.cs index e0faaac..7491e21 100644 --- a/src/DotNetOpenAuth.Test/OpenId/Extensions/ProviderAuthenticationPolicy/PolicyResponseTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/Extensions/ProviderAuthenticationPolicy/PolicyResponseTests.cs @@ -12,15 +12,15 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions.ProviderAuthenticationPolicy { using DotNetOpenAuth.Messaging; using DotNetOpenAuth.Messaging.Reflection; using DotNetOpenAuth.OpenId.Extensions.ProviderAuthenticationPolicy; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; - [TestClass] + [TestFixture] public class PolicyResponseTests : OpenIdTestBase { private static readonly DateTime someLocalTime = new DateTime(2008, 1, 1, 1, 1, 1, 0, DateTimeKind.Local); private static readonly DateTime someUtcTime = new DateTime(2008, 1, 1, 1, 1, 1, 0, DateTimeKind.Utc); private static readonly DateTime someUnspecifiedTime = new DateTime(2008, 1, 1, 1, 1, 1, 0, DateTimeKind.Unspecified); - [TestMethod] + [TestCase] public void Ctor() { PolicyResponse resp = new PolicyResponse(); Assert.IsNotNull(resp.ActualPolicies); @@ -29,7 +29,7 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions.ProviderAuthenticationPolicy { Assert.IsNull(resp.NistAssuranceLevel); } - [TestMethod] + [TestCase] public void AddPolicies() { PolicyResponse resp = new PolicyResponse(); resp.ActualPolicies.Add(AuthenticationPolicies.MultiFactor); @@ -39,7 +39,7 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions.ProviderAuthenticationPolicy { Assert.AreEqual(AuthenticationPolicies.PhishingResistant, resp.ActualPolicies[1]); } - [TestMethod] + [TestCase] public void AddPolicyMultipleTimes() { // Although this isn't really the desired behavior (we'd prefer to see an // exception thrown), since we're using a List<string> internally we can't @@ -51,7 +51,7 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions.ProviderAuthenticationPolicy { Assert.AreEqual(2, resp.ActualPolicies.Count); } - [TestMethod] + [TestCase] public void AuthenticationTimeUtcConvertsToUtc() { PolicyResponse resp = new PolicyResponse(); resp.AuthenticationTimeUtc = someLocalTime; @@ -60,20 +60,20 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions.ProviderAuthenticationPolicy { Assert.AreEqual(someLocalTime.ToUniversalTime(), resp.AuthenticationTimeUtc.Value); } - [TestMethod] + [TestCase] public void AuthenticationTimeUtcSetUtc() { PolicyResponse resp = new PolicyResponse(); resp.AuthenticationTimeUtc = someUtcTime; Assert.AreEqual(someUtcTime, resp.AuthenticationTimeUtc); } - [TestMethod, ExpectedException(typeof(ArgumentException))] + [TestCase, ExpectedException(typeof(ArgumentException))] public void AuthenticationTimeUtcSetUnspecified() { PolicyResponse resp = new PolicyResponse(); resp.AuthenticationTimeUtc = someUnspecifiedTime; } - [TestMethod] + [TestCase] public void AuthenticationTimeUtcSetNull() { PolicyResponse resp = new PolicyResponse(); resp.AuthenticationTimeUtc = null; @@ -84,7 +84,7 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions.ProviderAuthenticationPolicy { Assert.IsNull(resp.AuthenticationTimeUtc); } - [TestMethod] + [TestCase] public void NistAssuranceLevelSetVarious() { PolicyResponse resp = new PolicyResponse(); resp.NistAssuranceLevel = NistAssuranceLevel.Level1; @@ -95,7 +95,7 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions.ProviderAuthenticationPolicy { Assert.AreEqual(NistAssuranceLevel.InsufficientForLevel1, resp.NistAssuranceLevel); } - [TestMethod] + [TestCase] public void AssuranceLevels() { PolicyResponse resp = new PolicyResponse(); Assert.AreEqual(0, resp.AssuranceLevels.Count); @@ -108,7 +108,7 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions.ProviderAuthenticationPolicy { Assert.IsNull(resp.NistAssuranceLevel); } - [TestMethod] + [TestCase] public void EqualsTest() { PolicyResponse resp = new PolicyResponse(); PolicyResponse resp2 = new PolicyResponse(); @@ -164,7 +164,7 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions.ProviderAuthenticationPolicy { Assert.AreEqual(resp, resp2); } - [TestMethod] + [TestCase] public void Serialize() { PolicyResponse resp = new PolicyResponse(); IMessageWithEvents respEvents = resp; diff --git a/src/DotNetOpenAuth.Test/OpenId/Extensions/SimpleRegistration/ClaimsRequestTests.cs b/src/DotNetOpenAuth.Test/OpenId/Extensions/SimpleRegistration/ClaimsRequestTests.cs index 3af54d3..f7a948e 100644 --- a/src/DotNetOpenAuth.Test/OpenId/Extensions/SimpleRegistration/ClaimsRequestTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/Extensions/SimpleRegistration/ClaimsRequestTests.cs @@ -8,11 +8,11 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions { using DotNetOpenAuth.Messaging.Reflection; using DotNetOpenAuth.OpenId.Extensions.SimpleRegistration; using DotNetOpenAuth.OpenId.Messages; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; - [TestClass] + [TestFixture] public class ClaimsRequestTests : OpenIdTestBase { - [TestMethod] + [TestCase] public void CreateResponse() { // some unofficial type URIs... this.ParameterizedTypeUriPreservedTest("http://openid.net/sreg/1.0"); @@ -21,7 +21,7 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions { this.ParameterizedTypeUriPreservedTest("http://openid.net/extensions/sreg/1.1"); } - [TestMethod] + [TestCase] public void RequiredOptionalLists() { ClaimsRequest req = new ClaimsRequest(); MessageDictionary dictionary = this.MessageDescriptions.GetAccessor(req); @@ -39,7 +39,7 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions { Assert.AreEqual("nickname,postcode", dictionary["required"]); } - [TestMethod] + [TestCase] public void EqualityTests() { ClaimsRequest req1 = new ClaimsRequest(); ClaimsRequest req2 = new ClaimsRequest(); diff --git a/src/DotNetOpenAuth.Test/OpenId/Extensions/SimpleRegistration/ClaimsResponseTests.cs b/src/DotNetOpenAuth.Test/OpenId/Extensions/SimpleRegistration/ClaimsResponseTests.cs index 6dbfa4f..0bdc36e 100644 --- a/src/DotNetOpenAuth.Test/OpenId/Extensions/SimpleRegistration/ClaimsResponseTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/Extensions/SimpleRegistration/ClaimsResponseTests.cs @@ -12,18 +12,18 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions { using System.Runtime.Serialization.Formatters.Binary; using System.Xml.Serialization; using DotNetOpenAuth.OpenId.Extensions.SimpleRegistration; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; - [TestClass] + [TestFixture] public class ClaimsResponseTests { - [TestMethod] + [TestCase] public void EmptyMailAddress() { ClaimsResponse response = new ClaimsResponse(Constants.sreg_ns); response.Email = string.Empty; Assert.IsNull(response.MailAddress); } - [TestMethod, Ignore] // serialization no longer supported + [TestCase, Ignore("serialization no longer supported")] public void BinarySerialization() { ClaimsResponse fields = this.GetFilledData(); MemoryStream ms = new MemoryStream(); @@ -35,7 +35,7 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions { Assert.AreEqual(fields, fields2); } - [TestMethod, Ignore] // serialization no longer supported + [TestCase, Ignore("serialization no longer supported")] public void XmlSerialization() { ClaimsResponse fields = this.GetFilledData(); MemoryStream ms = new MemoryStream(); @@ -47,7 +47,7 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions { Assert.AreEqual(fields, fields2); } - [TestMethod] + [TestCase] public void EqualityTest() { ClaimsResponse fields1 = this.GetFilledData(); @@ -95,7 +95,7 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions { Assert.AreNotEqual(fields1, fields2); } - [TestMethod] + [TestCase] public void Birthdates() { var response = new ClaimsResponse(); // Verify that they both start out as null @@ -124,7 +124,7 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions { Assert.IsFalse(response.BirthDate.HasValue); } - [TestMethod, ExpectedException(typeof(ArgumentException))] + [TestCase, ExpectedException(typeof(ArgumentException))] public void InvalidRawBirthdate() { var response = new ClaimsResponse(); response.BirthDateRaw = "2008"; diff --git a/src/DotNetOpenAuth.Test/OpenId/Extensions/UI/UIRequestTests.cs b/src/DotNetOpenAuth.Test/OpenId/Extensions/UI/UIRequestTests.cs index 7a60a32..389fa5d 100644 --- a/src/DotNetOpenAuth.Test/OpenId/Extensions/UI/UIRequestTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/Extensions/UI/UIRequestTests.cs @@ -8,19 +8,36 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions.UI { using System.Globalization; using DotNetOpenAuth.Messaging.Reflection; using DotNetOpenAuth.OpenId.Extensions.UI; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; - [TestClass] + [TestFixture] public class UIRequestTests : OpenIdTestBase { - [TestMethod] + [TestCase] public void Defaults() { - UIRequest request = new UIRequest(); + var request = new UIRequest(); Assert.AreEqual("popup", request.Mode); Assert.AreEqual(1, request.LanguagePreference.Length); Assert.AreEqual(CultureInfo.CurrentUICulture, request.LanguagePreference[0]); + Assert.IsFalse(request.Icon.HasValue); + } + + [TestCase] + public void IconEncodingDecoding() + { + var request = new UIRequest(); + MessageDictionary dictionary = this.MessageDescriptions.GetAccessor(request); + Assert.IsFalse(dictionary.ContainsKey("icon")); + + Assert.IsFalse(request.Icon.HasValue); + dictionary["icon"] = "true"; + Assert.IsTrue(request.Icon.Value); + + dictionary.ClearValues(); + request.Icon = true; + Assert.AreEqual("true", dictionary["icon"]); } - [TestMethod] + [TestCase] public void LanguagePreferenceEncodingDecoding() { var request = new UIRequest(); MessageDictionary dictionary = this.MessageDescriptions.GetAccessor(request); @@ -42,7 +59,7 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions.UI { Assert.AreEqual(new CultureInfo("es-ES"), request.LanguagePreference[1]); } - [TestMethod] + [TestCase] public void ModeEncoding() { var request = new UIRequest(); MessageDictionary dictionary = this.MessageDescriptions.GetAccessor(request); diff --git a/src/DotNetOpenAuth.Test/OpenId/IdentifierTests.cs b/src/DotNetOpenAuth.Test/OpenId/IdentifierTests.cs index cc02265..01e2fdc 100644 --- a/src/DotNetOpenAuth.Test/OpenId/IdentifierTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/IdentifierTests.cs @@ -9,23 +9,23 @@ namespace DotNetOpenAuth.Test.OpenId { using System.Collections.Generic; using System.Linq; using DotNetOpenAuth.OpenId; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; - [TestClass] + [TestFixture] public class IdentifierTests { private string uri = "http://www.yahoo.com/"; private string uriNoScheme = "www.yahoo.com"; private string uriHttps = "https://www.yahoo.com/"; private string xri = "=arnott*andrew"; - [TestMethod] + [TestCase] public void TryParseNoThrow() { Identifier id; Assert.IsFalse(Identifier.TryParse(null, out id)); Assert.IsFalse(Identifier.TryParse(string.Empty, out id)); } - [TestMethod] + [TestCase] public void TryParse() { Identifier id; Assert.IsTrue(Identifier.TryParse("http://host/path", out id)); @@ -34,16 +34,16 @@ namespace DotNetOpenAuth.Test.OpenId { Assert.AreEqual("=arnott", id.ToString()); } - [TestMethod] + [TestCase] public void Parse() { - Assert.IsInstanceOfType(Identifier.Parse(this.uri), typeof(UriIdentifier)); - Assert.IsInstanceOfType(Identifier.Parse(this.xri), typeof(XriIdentifier)); + Assert.IsInstanceOf<UriIdentifier>(Identifier.Parse(this.uri)); + Assert.IsInstanceOf<XriIdentifier>(Identifier.Parse(this.xri)); } /// <summary> /// Tests conformance with 2.0 spec section 7.2#2 /// </summary> - [TestMethod] + [TestCase] public void ParseEndUserSuppliedXriIdentifer() { List<char> symbols = new List<char>(XriIdentifier.GlobalContextSymbols); symbols.Add('('); @@ -52,35 +52,35 @@ namespace DotNetOpenAuth.Test.OpenId { prefixes.AddRange(symbols.Select(s => "xri://" + s.ToString())); foreach (string prefix in prefixes) { var id = Identifier.Parse(prefix + "andrew"); - Assert.IsInstanceOfType(id, typeof(XriIdentifier)); + Assert.IsInstanceOf<XriIdentifier>(id); } } /// <summary> /// Verifies conformance with 2.0 spec section 7.2#3 /// </summary> - [TestMethod] + [TestCase] public void ParseEndUserSuppliedUriIdentifier() { // verify a fully-qualified Uri var id = Identifier.Parse(this.uri); - Assert.IsInstanceOfType(id, typeof(UriIdentifier)); + Assert.IsInstanceOf<UriIdentifier>(id); Assert.AreEqual(this.uri, ((UriIdentifier)id).Uri.AbsoluteUri); // verify an HTTPS Uri id = Identifier.Parse(this.uriHttps); - Assert.IsInstanceOfType(id, typeof(UriIdentifier)); + Assert.IsInstanceOf<UriIdentifier>(id); Assert.AreEqual(this.uriHttps, ((UriIdentifier)id).Uri.AbsoluteUri); // verify that if the scheme is missing it is added automatically id = Identifier.Parse(this.uriNoScheme); - Assert.IsInstanceOfType(id, typeof(UriIdentifier)); + Assert.IsInstanceOf<UriIdentifier>(id); Assert.AreEqual(this.uri, ((UriIdentifier)id).Uri.AbsoluteUri); } - [TestMethod, ExpectedException(typeof(ArgumentException))] + [TestCase, ExpectedException(typeof(ArgumentException))] public void ParseNull() { Identifier.Parse(null); } - [TestMethod, ExpectedException(typeof(ArgumentException))] + [TestCase, ExpectedException(typeof(ArgumentException))] public void ParseEmpty() { Identifier.Parse(string.Empty); } diff --git a/src/DotNetOpenAuth.Test/OpenId/Messages/AssociateDiffieHellmanRequestTests.cs b/src/DotNetOpenAuth.Test/OpenId/Messages/AssociateDiffieHellmanRequestTests.cs index a8648ac..b091062 100644 --- a/src/DotNetOpenAuth.Test/OpenId/Messages/AssociateDiffieHellmanRequestTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/Messages/AssociateDiffieHellmanRequestTests.cs @@ -8,24 +8,24 @@ namespace DotNetOpenAuth.Test.OpenId.Messages { using System; using DotNetOpenAuth.OpenId; using DotNetOpenAuth.OpenId.Messages; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; - [TestClass] + [TestFixture] public class AssociateDiffieHellmanRequestTests { private static readonly Uri Recipient = new Uri("http://host"); private AssociateDiffieHellmanRequest request; - [TestInitialize] + [SetUp] public void Setup() { this.request = new AssociateDiffieHellmanRequest(Protocol.V20.Version, Recipient); } - [TestMethod] + [TestCase] public void Ctor() { Assert.AreEqual(Recipient, this.request.Recipient); } - [TestMethod] + [TestCase] public void Mode() { Assert.AreEqual("associate", this.request.Mode); } diff --git a/src/DotNetOpenAuth.Test/OpenId/Messages/AssociateRequestTests.cs b/src/DotNetOpenAuth.Test/OpenId/Messages/AssociateRequestTests.cs index 0957118..f3c18d9 100644 --- a/src/DotNetOpenAuth.Test/OpenId/Messages/AssociateRequestTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/Messages/AssociateRequestTests.cs @@ -11,31 +11,31 @@ namespace DotNetOpenAuth.Test.OpenId.Messages { using DotNetOpenAuth.OpenId; using DotNetOpenAuth.OpenId.Messages; using DotNetOpenAuth.OpenId.RelyingParty; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; - [TestClass] + [TestFixture] public class AssociateRequestTests : OpenIdTestBase { private readonly Protocol protocol = Protocol.V20; private Uri secureRecipient = new Uri("https://hi"); private Uri insecureRecipient = new Uri("http://hi"); private AssociateRequest request; - [TestInitialize] + [SetUp] public void Setup() { this.request = new AssociateUnencryptedRequest(this.protocol.Version, this.secureRecipient); } - [TestMethod] + [TestCase] public void ConstructorTest() { Assert.AreEqual(this.secureRecipient, this.request.Recipient); } - [TestMethod] + [TestCase] public void Mode() { Assert.AreEqual(this.protocol.Args.Mode.associate, this.request.Mode); } - [TestMethod] + [TestCase] public void MessagePartsTest() { this.request.AssociationType = this.protocol.Args.SignatureAlgorithm.HMAC_SHA1; this.request.SessionType = this.protocol.Args.SessionType.NoEncryption; @@ -51,26 +51,26 @@ namespace DotNetOpenAuth.Test.OpenId.Messages { Assert.AreEqual(this.protocol.Args.SessionType.NoEncryption, dict[this.protocol.openid.session_type]); } - [TestMethod] + [TestCase] public void ValidMessageTest() { this.request = new AssociateUnencryptedRequest(Protocol.V20.Version, this.secureRecipient); this.request.AssociationType = this.protocol.Args.SignatureAlgorithm.HMAC_SHA1; this.request.EnsureValidMessage(); } - [TestMethod, ExpectedException(typeof(ProtocolException))] + [TestCase, ExpectedException(typeof(ProtocolException))] public void InvalidMessageTest() { this.request = new AssociateUnencryptedRequest(Protocol.V20.Version, this.insecureRecipient); this.request.AssociationType = this.protocol.Args.SignatureAlgorithm.HMAC_SHA1; this.request.EnsureValidMessage(); // no-encryption only allowed for secure channels. } - [TestMethod] + [TestCase] public void RequiredProtection() { Assert.AreEqual(MessageProtections.None, this.request.RequiredProtection); } - [TestMethod] + [TestCase] public void Transport() { Assert.AreEqual(MessageTransport.Direct, this.request.Transport); } @@ -78,7 +78,7 @@ namespace DotNetOpenAuth.Test.OpenId.Messages { /// <summary> /// Verifies security settings limit RP's initial associate request /// </summary> - [TestMethod] + [TestCase] public void AssociateRequestDeterminedBySecuritySettings() { Protocol protocol = Protocol.V20; SecuritySettings securitySettings = new RelyingPartySecuritySettings(); diff --git a/src/DotNetOpenAuth.Test/OpenId/Messages/AssociateUnencryptedResponseTests.cs b/src/DotNetOpenAuth.Test/OpenId/Messages/AssociateUnencryptedResponseTests.cs index 1f5e87c..37be1cb 100644 --- a/src/DotNetOpenAuth.Test/OpenId/Messages/AssociateUnencryptedResponseTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/Messages/AssociateUnencryptedResponseTests.cs @@ -9,20 +9,20 @@ namespace DotNetOpenAuth.Test.OpenId.Messages { using DotNetOpenAuth.Messaging; using DotNetOpenAuth.OpenId; using DotNetOpenAuth.OpenId.Messages; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; - [TestClass] + [TestFixture] public class AssociateUnencryptedResponseTests : OpenIdTestBase { private AssociateUnencryptedResponse response; - [TestInitialize] + [SetUp] public override void SetUp() { base.SetUp(); var request = new AssociateUnencryptedRequest(Protocol.V20.Version, new Uri("http://host")); this.response = new AssociateUnencryptedResponse(request.Version, request); } - [TestMethod] + [TestCase] public void ParameterNames() { this.response.AssociationHandle = "HANDLE"; this.response.AssociationType = "HMAC-SHA1"; @@ -38,12 +38,12 @@ namespace DotNetOpenAuth.Test.OpenId.Messages { Assert.AreEqual("50", fields["expires_in"]); } - [TestMethod] + [TestCase] public void RequiredProtection() { Assert.AreEqual(MessageProtections.None, this.response.RequiredProtection); } - [TestMethod] + [TestCase] public void Transport() { Assert.AreEqual(MessageTransport.Direct, this.response.Transport); } diff --git a/src/DotNetOpenAuth.Test/OpenId/Messages/AssociateUnsuccessfulResponseTests.cs b/src/DotNetOpenAuth.Test/OpenId/Messages/AssociateUnsuccessfulResponseTests.cs index a6a691d..9b76473 100644 --- a/src/DotNetOpenAuth.Test/OpenId/Messages/AssociateUnsuccessfulResponseTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/Messages/AssociateUnsuccessfulResponseTests.cs @@ -9,20 +9,20 @@ namespace DotNetOpenAuth.Test.OpenId.Messages { using DotNetOpenAuth.Messaging; using DotNetOpenAuth.OpenId; using DotNetOpenAuth.OpenId.Messages; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; - [TestClass] + [TestFixture] public class AssociateUnsuccessfulResponseTests : OpenIdTestBase { private AssociateUnsuccessfulResponse response; - [TestInitialize] + [SetUp] public override void SetUp() { base.SetUp(); var request = new AssociateUnencryptedRequest(Protocol.V20.Version, new Uri("http://host")); this.response = new AssociateUnsuccessfulResponse(request.Version, request); } - [TestMethod] + [TestCase] public void ParameterNames() { this.response.ErrorMessage = "Some Error"; this.response.AssociationType = "HMAC-SHA1"; diff --git a/src/DotNetOpenAuth.Test/OpenId/Messages/CheckAuthenticationRequestTests.cs b/src/DotNetOpenAuth.Test/OpenId/Messages/CheckAuthenticationRequestTests.cs index 96a2e23..d2d2cc4 100644 --- a/src/DotNetOpenAuth.Test/OpenId/Messages/CheckAuthenticationRequestTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/Messages/CheckAuthenticationRequestTests.cs @@ -6,16 +6,37 @@ namespace DotNetOpenAuth.Test.OpenId.Messages { using System; - using System.Collections.Generic; - using System.Linq; - using System.Text; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using DotNetOpenAuth.OpenId; + using DotNetOpenAuth.OpenId.Messages; + using NUnit.Framework; - [TestClass] + [TestFixture] public class CheckAuthenticationRequestTests : OpenIdTestBase { - [TestInitialize] - public override void SetUp() { - base.SetUp(); + /// <summary> + /// Verifies that the check_auth request is sent preserving EXACTLY (non-normalized) + /// what is in the positive assertion. + /// </summary> + /// <remarks> + /// This is very important because any normalization + /// (like changing https://host:443/ to https://host/) in the message will invalidate the signature + /// and cause the authentication to inappropriately fail. + /// Designed to verify fix to Trac #198. + /// </remarks> + [TestCase] + public void ExactPositiveAssertionPreservation() { + var rp = CreateRelyingParty(true); + + // Initialize the positive assertion response with some data that is NOT in normalized form. + var positiveAssertion = new PositiveAssertionResponse(Protocol.Default.Version, RPUri) + { + ClaimedIdentifier = "https://HOST:443/a", + ProviderEndpoint = new Uri("https://anotherHOST:443/b"), + }; + + var checkAuth = new CheckAuthenticationRequest(positiveAssertion, rp.Channel); + var actual = rp.Channel.MessageDescriptions.GetAccessor(checkAuth); + Assert.AreEqual("https://HOST:443/a", actual["openid.claimed_id"]); + Assert.AreEqual("https://anotherHOST:443/b", actual["openid.op_endpoint"]); } } } diff --git a/src/DotNetOpenAuth.Test/OpenId/Messages/CheckAuthenticationResponseTests.cs b/src/DotNetOpenAuth.Test/OpenId/Messages/CheckAuthenticationResponseTests.cs index 1e773bd..cbe6638 100644 --- a/src/DotNetOpenAuth.Test/OpenId/Messages/CheckAuthenticationResponseTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/Messages/CheckAuthenticationResponseTests.cs @@ -12,16 +12,16 @@ namespace DotNetOpenAuth.Test.OpenId.Messages { using DotNetOpenAuth.Messaging.Reflection; using DotNetOpenAuth.OpenId; using DotNetOpenAuth.OpenId.Messages; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; - [TestClass] + [TestFixture] public class CheckAuthenticationResponseTests : OpenIdTestBase { - [TestInitialize] + [SetUp] public override void SetUp() { base.SetUp(); } - [TestMethod] + [TestCase] public void IsValid() { Protocol protocol = Protocol.Default; var request = new CheckAuthenticationRequest(protocol.Version, OPUri); diff --git a/src/DotNetOpenAuth.Test/OpenId/Messages/CheckIdRequestTests.cs b/src/DotNetOpenAuth.Test/OpenId/Messages/CheckIdRequestTests.cs index 2c9ea12..e33a191 100644 --- a/src/DotNetOpenAuth.Test/OpenId/Messages/CheckIdRequestTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/Messages/CheckIdRequestTests.cs @@ -12,11 +12,11 @@ namespace DotNetOpenAuth.Test.OpenId.Messages { using DotNetOpenAuth.Messaging; using DotNetOpenAuth.OpenId; using DotNetOpenAuth.OpenId.Messages; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; - [TestClass] + [TestFixture] public class CheckIdRequestTests : OpenIdTestBase { - [TestInitialize] + [SetUp] public override void SetUp() { base.SetUp(); } diff --git a/src/DotNetOpenAuth.Test/OpenId/Messages/DirectErrorResponseTests.cs b/src/DotNetOpenAuth.Test/OpenId/Messages/DirectErrorResponseTests.cs index 02fa7df..039748f 100644 --- a/src/DotNetOpenAuth.Test/OpenId/Messages/DirectErrorResponseTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/Messages/DirectErrorResponseTests.cs @@ -10,13 +10,13 @@ namespace DotNetOpenAuth.Test.OpenId.Messages { using DotNetOpenAuth.Messaging; using DotNetOpenAuth.OpenId; using DotNetOpenAuth.OpenId.Messages; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; - [TestClass] + [TestFixture] public class DirectErrorResponseTests : OpenIdTestBase { private DirectErrorResponse response; - [TestInitialize] + [SetUp] public override void SetUp() { base.SetUp(); @@ -24,7 +24,7 @@ namespace DotNetOpenAuth.Test.OpenId.Messages { this.response = new DirectErrorResponse(request.Version, request); } - [TestMethod] + [TestCase] public void ParameterNames() { this.response.ErrorMessage = "Some Error"; this.response.Contact = "Andrew Arnott"; @@ -42,7 +42,7 @@ namespace DotNetOpenAuth.Test.OpenId.Messages { /// Verifies that error messages are created as HTTP 400 errors, /// per OpenID 2.0 section 5.1.2.2. /// </summary> - [TestMethod] + [TestCase] public void ErrorMessagesAsHttp400() { var httpStatusMessage = (IHttpDirectResponse)this.response; Assert.AreEqual(HttpStatusCode.BadRequest, httpStatusMessage.HttpStatusCode); diff --git a/src/DotNetOpenAuth.Test/OpenId/Messages/IndirectErrorResponseTests.cs b/src/DotNetOpenAuth.Test/OpenId/Messages/IndirectErrorResponseTests.cs index fdb08eb..c9fb535 100644 --- a/src/DotNetOpenAuth.Test/OpenId/Messages/IndirectErrorResponseTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/Messages/IndirectErrorResponseTests.cs @@ -10,25 +10,25 @@ namespace DotNetOpenAuth.Test.OpenId.Messages { using DotNetOpenAuth.OpenId; using DotNetOpenAuth.OpenId.Messages; using DotNetOpenAuth.OpenId.RelyingParty; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; - [TestClass] + [TestFixture] public class IndirectErrorResponseTests : OpenIdTestBase { private IndirectErrorResponse response; - [TestInitialize] + [SetUp] public void Setup() { CheckIdRequest request = new CheckIdRequest(Protocol.V20.Version, OPUri, AuthenticationRequestMode.Immediate); request.ReturnTo = RPUri; this.response = new IndirectErrorResponse(request); } - [TestMethod] + [TestCase] public void Ctor() { Assert.AreEqual(RPUri, this.response.Recipient); } - [TestMethod] + [TestCase] public void ParameterNames() { this.response.ErrorMessage = "Some Error"; this.response.Contact = "Andrew Arnott"; diff --git a/src/DotNetOpenAuth.Test/OpenId/Messages/IndirectSignedResponseTests.cs b/src/DotNetOpenAuth.Test/OpenId/Messages/IndirectSignedResponseTests.cs index 8b0937a..ad6b15d 100644 --- a/src/DotNetOpenAuth.Test/OpenId/Messages/IndirectSignedResponseTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/Messages/IndirectSignedResponseTests.cs @@ -16,9 +16,9 @@ namespace DotNetOpenAuth.Test.OpenId.Messages { using DotNetOpenAuth.OpenId.ChannelElements; using DotNetOpenAuth.OpenId.Messages; using DotNetOpenAuth.OpenId.RelyingParty; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; - [TestClass] + [TestFixture] public class IndirectSignedResponseTests : OpenIdTestBase { private const string CreationDateString = "2005-05-15T17:11:51Z"; private readonly DateTime creationDate = DateTime.Parse(CreationDateString, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal); @@ -27,7 +27,7 @@ namespace DotNetOpenAuth.Test.OpenId.Messages { private IndirectSignedResponse unsolicited; private Protocol protocol; - [TestInitialize] + [SetUp] public override void SetUp() { base.SetUp(); @@ -39,7 +39,7 @@ namespace DotNetOpenAuth.Test.OpenId.Messages { this.unsolicited = new IndirectSignedResponse(this.protocol.Version, RPUri); } - [TestMethod] + [TestCase] public void CtorFromRequest() { Assert.AreEqual(this.protocol.Args.Mode.id_res, this.response.Mode); Assert.AreEqual(this.request.Version, this.response.Version); @@ -48,7 +48,7 @@ namespace DotNetOpenAuth.Test.OpenId.Messages { Assert.IsTrue(DateTime.UtcNow - ((ITamperResistantOpenIdMessage)this.response).UtcCreationDate < TimeSpan.FromSeconds(5)); } - [TestMethod] + [TestCase] public void CtorUnsolicited() { Assert.AreEqual(this.protocol.Args.Mode.id_res, this.unsolicited.Mode); Assert.AreEqual(this.protocol.Version, this.unsolicited.Version); @@ -60,7 +60,7 @@ namespace DotNetOpenAuth.Test.OpenId.Messages { Assert.AreEqual(OPUri, this.unsolicited.ProviderEndpoint); } - [TestMethod] + [TestCase] public void ResponseNonceSetter() { const string HybridValue = CreationDateString + "UNIQUE"; var responseAccessor = IndirectSignedResponse_Accessor.AttachShadow(this.response); @@ -74,7 +74,7 @@ namespace DotNetOpenAuth.Test.OpenId.Messages { Assert.IsNull(responseReplay.Nonce); } - [TestMethod] + [TestCase] public void ResponseNonceGetter() { var responseAccessor = IndirectSignedResponse_Accessor.AttachShadow(this.response); IReplayProtectedProtocolMessage responseReplay = this.response; @@ -86,7 +86,7 @@ namespace DotNetOpenAuth.Test.OpenId.Messages { Assert.AreEqual(this.creationDate, responseReplay.UtcCreationDate); } - [TestMethod] + [TestCase] public void UtcCreationDateConvertsToUniversal() { IReplayProtectedProtocolMessage responseReplay = this.response; DateTime local = DateTime.Parse("1982-01-01", CultureInfo.InvariantCulture, DateTimeStyles.AssumeLocal); @@ -109,7 +109,7 @@ namespace DotNetOpenAuth.Test.OpenId.Messages { Assert.AreEqual(this.creationDate.Hour, utcCreationDate.Hour, "The hour should match since both times are UTC time."); } - [TestMethod] + [TestCase] public void ReturnToDoesNotMatchRecipient() { // Make sure its valid first, so we know that when it's invalid // it is due to our tampering. @@ -127,24 +127,24 @@ namespace DotNetOpenAuth.Test.OpenId.Messages { } } - [TestMethod, ExpectedException(typeof(ArgumentException))] + [TestCase, ExpectedException(typeof(ArgumentException))] public void GetReturnToArgumentNullKey() { this.response.GetReturnToArgument(null); } - [TestMethod, ExpectedException(typeof(ArgumentException))] + [TestCase, ExpectedException(typeof(ArgumentException))] public void GetReturnToArgumentEmptyKey() { this.response.GetReturnToArgument(string.Empty); } - [TestMethod] + [TestCase] public void GetReturnToArgumentDoesNotReturnExtraArgs() { this.response.ExtraData["a"] = "b"; Assert.IsNull(this.response.GetReturnToArgument("a")); Assert.AreEqual(0, this.response.GetReturnToParameterNames().Count()); } - [TestMethod] + [TestCase] public void GetReturnToArgumentAndNames() { UriBuilder returnToBuilder = new UriBuilder(this.response.ReturnTo); returnToBuilder.AppendQueryArgs(new Dictionary<string, string> { { "a", "b" } }); diff --git a/src/DotNetOpenAuth.Test/OpenId/Messages/NegativeAssertionResponseTests.cs b/src/DotNetOpenAuth.Test/OpenId/Messages/NegativeAssertionResponseTests.cs index 7876732..c35780d 100644 --- a/src/DotNetOpenAuth.Test/OpenId/Messages/NegativeAssertionResponseTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/Messages/NegativeAssertionResponseTests.cs @@ -13,16 +13,16 @@ namespace DotNetOpenAuth.Test.OpenId.Messages { using DotNetOpenAuth.OpenId; using DotNetOpenAuth.OpenId.Messages; using DotNetOpenAuth.OpenId.RelyingParty; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; - [TestClass] + [TestFixture] public class NegativeAssertionResponseTests : OpenIdTestBase { - [TestInitialize] + [SetUp] public override void SetUp() { base.SetUp(); } - [TestMethod] + [TestCase] public void Mode() { var setupRequestV1 = new CheckIdRequest(Protocol.V10.Version, OPUri, AuthenticationRequestMode.Setup); setupRequestV1.ReturnTo = RPUri; @@ -45,14 +45,14 @@ namespace DotNetOpenAuth.Test.OpenId.Messages { Assert.IsFalse(new NegativeAssertionResponse(setupRequestV2).Immediate); } - [TestMethod, ExpectedException(typeof(ProtocolException))] + [TestCase, ExpectedException(typeof(ProtocolException))] public void UserSetupUrlRequiredInV1Immediate() { var immediateRequestV1 = new CheckIdRequest(Protocol.V10.Version, OPUri, AuthenticationRequestMode.Immediate); immediateRequestV1.ReturnTo = RPUri; new NegativeAssertionResponse(immediateRequestV1).EnsureValidMessage(); } - [TestMethod] + [TestCase] public void UserSetupUrlSetForV1Immediate() { var immediateRequestV1 = new CheckIdRequest(Protocol.V10.Version, OPUri, AuthenticationRequestMode.Immediate); immediateRequestV1.ReturnTo = RPUri; @@ -61,7 +61,7 @@ namespace DotNetOpenAuth.Test.OpenId.Messages { response.EnsureValidMessage(); } - [TestMethod] + [TestCase] public void UserSetupUrlNotRequiredInV1SetupOrV2() { var setupRequestV1 = new CheckIdRequest(Protocol.V10.Version, OPUri, AuthenticationRequestMode.Setup); setupRequestV1.ReturnTo = RPUri; diff --git a/src/DotNetOpenAuth.Test/OpenId/Messages/PositiveAssertionResponseTests.cs b/src/DotNetOpenAuth.Test/OpenId/Messages/PositiveAssertionResponseTests.cs index faa6a91..90d24b1 100644 --- a/src/DotNetOpenAuth.Test/OpenId/Messages/PositiveAssertionResponseTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/Messages/PositiveAssertionResponseTests.cs @@ -15,9 +15,9 @@ namespace DotNetOpenAuth.Test.OpenId.Messages { using DotNetOpenAuth.OpenId; using DotNetOpenAuth.OpenId.Messages; using DotNetOpenAuth.OpenId.RelyingParty; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; - [TestClass] + [TestFixture] public class PositiveAssertionResponseTests : OpenIdTestBase { private const string CreationDateString = "2005-05-15T17:11:51Z"; private readonly DateTime creationDate = DateTime.Parse(CreationDateString, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal); @@ -26,7 +26,7 @@ namespace DotNetOpenAuth.Test.OpenId.Messages { private PositiveAssertionResponse unsolicited; private Protocol protocol; - [TestInitialize] + [SetUp] public override void SetUp() { base.SetUp(); @@ -38,7 +38,7 @@ namespace DotNetOpenAuth.Test.OpenId.Messages { this.unsolicited = new PositiveAssertionResponse(this.protocol.Version, RPUri); } - [TestMethod] + [TestCase] public void CtorFromRequest() { Assert.AreEqual(this.protocol.Args.Mode.id_res, this.response.Mode); Assert.AreEqual(this.request.Version, this.response.Version); @@ -46,7 +46,7 @@ namespace DotNetOpenAuth.Test.OpenId.Messages { Assert.AreEqual(OPUri, this.response.ProviderEndpoint); } - [TestMethod] + [TestCase] public void CtorUnsolicited() { Assert.AreEqual(this.protocol.Args.Mode.id_res, this.unsolicited.Mode); Assert.AreEqual(this.protocol.Version, this.unsolicited.Version); @@ -60,7 +60,7 @@ namespace DotNetOpenAuth.Test.OpenId.Messages { /// <summary> /// Verifies that local_id and claimed_id can either be null or specified. /// </summary> - [TestMethod] + [TestCase] public void ClaimedIdAndLocalIdSpecifiedIsValid() { this.response.LocalIdentifier = "http://local"; this.response.ClaimedIdentifier = "http://claimedid"; diff --git a/src/DotNetOpenAuth.Test/OpenId/Messages/SignedResponseRequestTests.cs b/src/DotNetOpenAuth.Test/OpenId/Messages/SignedResponseRequestTests.cs index 0177685..bc95f8b 100644 --- a/src/DotNetOpenAuth.Test/OpenId/Messages/SignedResponseRequestTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/Messages/SignedResponseRequestTests.cs @@ -10,9 +10,9 @@ namespace DotNetOpenAuth.Test.OpenId.Messages { using DotNetOpenAuth.OpenId; using DotNetOpenAuth.OpenId.Messages; using DotNetOpenAuth.OpenId.RelyingParty; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; - [TestClass] + [TestFixture] public class SignedResponseRequestTests : OpenIdTestBase { private Uri providerEndpoint; private SignedResponseRequest immediatev1; @@ -20,7 +20,7 @@ namespace DotNetOpenAuth.Test.OpenId.Messages { private SignedResponseRequest immediatev2; private SignedResponseRequest setupv2; - [TestInitialize] + [SetUp] public override void SetUp() { base.SetUp(); @@ -55,7 +55,7 @@ namespace DotNetOpenAuth.Test.OpenId.Messages { /// This test does not test all the realm-return_to matching rules as that is done in the Realm tests. /// This test merely checks that the compatibility match occurs at all. /// </remarks> - [TestMethod, ExpectedException(typeof(ProtocolException))] + [TestCase, ExpectedException(typeof(ProtocolException))] public void RealmReturnToMismatchV2() { this.setupv2.Realm = "http://somehost/"; this.setupv2.ReturnTo = new Uri("http://someotherhost/"); @@ -66,7 +66,7 @@ namespace DotNetOpenAuth.Test.OpenId.Messages { /// Verifies that the validation check throws if the return_to and the realm /// values are not compatible. /// </summary> - [TestMethod, ExpectedException(typeof(ProtocolException))] + [TestCase, ExpectedException(typeof(ProtocolException))] public void RealmReturnToMismatchV1() { this.setupv1.Realm = "http://somehost/"; this.setupv1.ReturnTo = new Uri("http://someotherhost/"); diff --git a/src/DotNetOpenAuth.Test/OpenId/NonIdentityTests.cs b/src/DotNetOpenAuth.Test/OpenId/NonIdentityTests.cs index 49bb32c..17ab090 100644 --- a/src/DotNetOpenAuth.Test/OpenId/NonIdentityTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/NonIdentityTests.cs @@ -9,11 +9,11 @@ namespace DotNetOpenAuth.Test.OpenId { using DotNetOpenAuth.OpenId.Messages; using DotNetOpenAuth.OpenId.Provider; using DotNetOpenAuth.OpenId.RelyingParty; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; - [TestClass] + [TestFixture] public class NonIdentityTests : OpenIdTestBase { - [TestMethod] + [TestCase] public void ExtensionOnlyChannelLevel() { Protocol protocol = Protocol.V20; AuthenticationRequestMode mode = AuthenticationRequestMode.Setup; @@ -25,12 +25,12 @@ namespace DotNetOpenAuth.Test.OpenId { }, op => { var request = op.Channel.ReadFromRequest<SignedResponseRequest>(); - Assert.IsNotInstanceOfType(request, typeof(CheckIdRequest)); + Assert.IsNotInstanceOf<CheckIdRequest>(request); }); coordinator.Run(); } - [TestMethod] + [TestCase] public void ExtensionOnlyFacadeLevel() { Protocol protocol = Protocol.V20; var coordinator = new OpenIdCoordinator( @@ -48,7 +48,7 @@ namespace DotNetOpenAuth.Test.OpenId { var request = (IAnonymousRequest)op.GetRequest(); request.IsApproved = true; - Assert.IsNotInstanceOfType(request, typeof(CheckIdRequest)); + Assert.IsNotInstanceOf<CheckIdRequest>(request); op.SendResponse(request); }); coordinator.Run(); diff --git a/src/DotNetOpenAuth.Test/OpenId/OpenIdCoordinator.cs b/src/DotNetOpenAuth.Test/OpenId/OpenIdCoordinator.cs index 0f9d472..d4884e8 100644 --- a/src/DotNetOpenAuth.Test/OpenId/OpenIdCoordinator.cs +++ b/src/DotNetOpenAuth.Test/OpenId/OpenIdCoordinator.cs @@ -57,10 +57,12 @@ namespace DotNetOpenAuth.Test.OpenId { private void EnsurePartiesAreInitialized() { if (this.RelyingParty == null) { this.RelyingParty = new OpenIdRelyingParty(new StandardRelyingPartyApplicationStore()); + this.RelyingParty.DiscoveryServices.Add(new MockIdentifierDiscoveryService()); } if (this.Provider == null) { this.Provider = new OpenIdProvider(new StandardProviderApplicationStore()); + this.Provider.DiscoveryServices.Add(new MockIdentifierDiscoveryService()); } } } diff --git a/src/DotNetOpenAuth.Test/OpenId/OpenIdTestBase.cs b/src/DotNetOpenAuth.Test/OpenId/OpenIdTestBase.cs index 5034b7e..c7df99a 100644 --- a/src/DotNetOpenAuth.Test/OpenId/OpenIdTestBase.cs +++ b/src/DotNetOpenAuth.Test/OpenId/OpenIdTestBase.cs @@ -6,6 +6,7 @@ namespace DotNetOpenAuth.Test.OpenId { using System; + using System.Collections.Generic; using System.IO; using System.Reflection; using DotNetOpenAuth.Configuration; @@ -15,7 +16,7 @@ namespace DotNetOpenAuth.Test.OpenId { using DotNetOpenAuth.OpenId.Provider; using DotNetOpenAuth.OpenId.RelyingParty; using DotNetOpenAuth.Test.Mocks; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; public class OpenIdTestBase : TestBase { internal IDirectWebRequestHandler RequestHandler; @@ -61,7 +62,7 @@ namespace DotNetOpenAuth.Test.OpenId { protected ProviderSecuritySettings ProviderSecuritySettings { get; private set; } - [TestInitialize] + [SetUp] public override void SetUp() { base.SetUp(); @@ -74,7 +75,7 @@ namespace DotNetOpenAuth.Test.OpenId { Identifier.EqualityOnStrings = true; } - [TestCleanup] + [TearDown] public override void Cleanup() { base.Cleanup(); @@ -116,17 +117,17 @@ namespace DotNetOpenAuth.Test.OpenId { } } - internal static ServiceEndpoint GetServiceEndpoint(int user, ProtocolVersion providerVersion, int servicePriority, bool useSsl) { + internal static IdentifierDiscoveryResult GetServiceEndpoint(int user, ProtocolVersion providerVersion, int servicePriority, bool useSsl) { return GetServiceEndpoint(user, providerVersion, servicePriority, useSsl, false); } - internal static ServiceEndpoint GetServiceEndpoint(int user, ProtocolVersion providerVersion, int servicePriority, bool useSsl, bool delegating) { + internal static IdentifierDiscoveryResult GetServiceEndpoint(int user, ProtocolVersion providerVersion, int servicePriority, bool useSsl, bool delegating) { var providerEndpoint = new ProviderEndpointDescription( useSsl ? OpenIdTestBase.OPUriSsl : OpenIdTestBase.OPUri, new string[] { Protocol.Lookup(providerVersion).ClaimedIdentifierServiceTypeURI }); var local_id = useSsl ? OPLocalIdentifiersSsl[user] : OPLocalIdentifiers[user]; var claimed_id = delegating ? (useSsl ? VanityUriSsl : VanityUri) : local_id; - return ServiceEndpoint.CreateForClaimedIdentifier( + return IdentifierDiscoveryResult.CreateForClaimedIdentifier( claimed_id, claimed_id, local_id, @@ -176,6 +177,12 @@ namespace DotNetOpenAuth.Test.OpenId { } } + internal IEnumerable<IdentifierDiscoveryResult> Discover(Identifier identifier) { + var rp = this.CreateRelyingParty(true); + rp.Channel.WebRequestHandler = this.RequestHandler; + return rp.Discover(identifier); + } + protected Realm GetMockRealm(bool useSsl) { var rpDescription = new RelyingPartyEndpointDescription(useSsl ? RPUriSsl : RPUri, new string[] { Protocol.V20.RPReturnToTypeURI }); return new MockRealm(useSsl ? RPRealmUriSsl : RPRealmUri, rpDescription); @@ -190,9 +197,21 @@ namespace DotNetOpenAuth.Test.OpenId { } protected Identifier GetMockIdentifier(ProtocolVersion providerVersion, bool useSsl, bool delegating) { - ServiceEndpoint se = GetServiceEndpoint(0, providerVersion, 10, useSsl, delegating); + var se = GetServiceEndpoint(0, providerVersion, 10, useSsl, delegating); UriIdentifier identityUri = (UriIdentifier)se.ClaimedIdentifier; - return new MockIdentifier(identityUri, this.MockResponder, new ServiceEndpoint[] { se }); + return new MockIdentifier(identityUri, this.MockResponder, new IdentifierDiscoveryResult[] { se }); + } + + protected Identifier GetMockDualIdentifier() { + Protocol protocol = Protocol.Default; + var opDesc = new ProviderEndpointDescription(OPUri, protocol.Version); + var dualResults = new IdentifierDiscoveryResult[] { + IdentifierDiscoveryResult.CreateForClaimedIdentifier(VanityUri.AbsoluteUri, OPLocalIdentifiers[0], opDesc, 10, 10), + IdentifierDiscoveryResult.CreateForProviderIdentifier(protocol.ClaimedIdentifierForOPIdentifier, opDesc, 20, 20), + }; + + Identifier dualId = new MockIdentifier(VanityUri, this.MockResponder, dualResults); + return dualId; } /// <summary> @@ -211,6 +230,7 @@ namespace DotNetOpenAuth.Test.OpenId { protected OpenIdRelyingParty CreateRelyingParty(bool stateless) { var rp = new OpenIdRelyingParty(stateless ? null : new StandardRelyingPartyApplicationStore()); rp.Channel.WebRequestHandler = this.MockResponder.MockWebRequestHandler; + rp.DiscoveryServices.Add(new MockIdentifierDiscoveryService()); return rp; } @@ -221,6 +241,7 @@ namespace DotNetOpenAuth.Test.OpenId { protected OpenIdProvider CreateProvider() { var op = new OpenIdProvider(new StandardProviderApplicationStore()); op.Channel.WebRequestHandler = this.MockResponder.MockWebRequestHandler; + op.DiscoveryServices.Add(new MockIdentifierDiscoveryService()); return op; } } diff --git a/src/DotNetOpenAuth.Test/OpenId/OpenIdUtilitiesTests.cs b/src/DotNetOpenAuth.Test/OpenId/OpenIdUtilitiesTests.cs new file mode 100644 index 0000000..fefb852 --- /dev/null +++ b/src/DotNetOpenAuth.Test/OpenId/OpenIdUtilitiesTests.cs @@ -0,0 +1,20 @@ +//----------------------------------------------------------------------- +// <copyright file="OpenIdUtilitiesTests.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.Test.OpenId { + using System; + using System.Collections.Generic; + using System.Linq; + using System.Text; + using DotNetOpenAuth.OpenId; + using DotNetOpenAuth.OpenId.Extensions.SimpleRegistration; + using DotNetOpenAuth.OpenId.Messages; + using NUnit.Framework; + + [TestFixture] + public class OpenIdUtilitiesTests : OpenIdTestBase { + } +} diff --git a/src/DotNetOpenAuth.Test/OpenId/Provider/AnonymousRequestTests.cs b/src/DotNetOpenAuth.Test/OpenId/Provider/AnonymousRequestTests.cs index 14fef91..1df4c9e 100644 --- a/src/DotNetOpenAuth.Test/OpenId/Provider/AnonymousRequestTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/Provider/AnonymousRequestTests.cs @@ -9,14 +9,14 @@ namespace DotNetOpenAuth.Test.OpenId.Provider { using DotNetOpenAuth.OpenId.Messages; using DotNetOpenAuth.OpenId.Provider; using DotNetOpenAuth.OpenId.RelyingParty; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; - [TestClass] + [TestFixture] public class AnonymousRequestTests : OpenIdTestBase { /// <summary> /// Verifies that IsApproved controls which response message is returned. /// </summary> - [TestMethod] + [TestCase] public void IsApprovedDeterminesReturnedMessage() { var op = CreateProvider(); Protocol protocol = Protocol.V20; @@ -27,11 +27,11 @@ namespace DotNetOpenAuth.Test.OpenId.Provider { Assert.IsFalse(anonReq.IsApproved.HasValue); anonReq.IsApproved = false; - Assert.IsInstanceOfType(anonReq.Response, typeof(NegativeAssertionResponse)); + Assert.IsInstanceOf<NegativeAssertionResponse>(anonReq.Response); anonReq.IsApproved = true; - Assert.IsInstanceOfType(anonReq.Response, typeof(IndirectSignedResponse)); - Assert.IsNotInstanceOfType(anonReq.Response, typeof(PositiveAssertionResponse)); + Assert.IsInstanceOf<IndirectSignedResponse>(anonReq.Response); + Assert.IsNotInstanceOf<PositiveAssertionResponse>(anonReq.Response); } } } diff --git a/src/DotNetOpenAuth.Test/OpenId/Provider/AuthenticationRequestTest.cs b/src/DotNetOpenAuth.Test/OpenId/Provider/AuthenticationRequestTest.cs index accbd97..dc5b3e3 100644 --- a/src/DotNetOpenAuth.Test/OpenId/Provider/AuthenticationRequestTest.cs +++ b/src/DotNetOpenAuth.Test/OpenId/Provider/AuthenticationRequestTest.cs @@ -10,14 +10,14 @@ namespace DotNetOpenAuth.Test.OpenId.Provider { using DotNetOpenAuth.OpenId; using DotNetOpenAuth.OpenId.Messages; using DotNetOpenAuth.OpenId.Provider; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; - [TestClass] + [TestFixture] public class AuthenticationRequestTest : OpenIdTestBase { /// <summary> /// Verifies the user_setup_url is set properly for immediate negative responses. /// </summary> - [TestMethod] + [TestCase] public void UserSetupUrl() { // Construct a V1 immediate request Protocol protocol = Protocol.V11; diff --git a/src/DotNetOpenAuth.Test/OpenId/Provider/HostProcessedRequestTests.cs b/src/DotNetOpenAuth.Test/OpenId/Provider/HostProcessedRequestTests.cs index d308271..9bb8095 100644 --- a/src/DotNetOpenAuth.Test/OpenId/Provider/HostProcessedRequestTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/Provider/HostProcessedRequestTests.cs @@ -9,16 +9,16 @@ namespace DotNetOpenAuth.Test.OpenId.Provider { using DotNetOpenAuth.OpenId; using DotNetOpenAuth.OpenId.Messages; using DotNetOpenAuth.OpenId.Provider; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; - [TestClass] + [TestFixture] public class HostProcessedRequestTests : OpenIdTestBase { private Protocol protocol; private OpenIdProvider provider; private CheckIdRequest checkIdRequest; private AuthenticationRequest request; - [TestInitialize] + [SetUp] public override void SetUp() { base.SetUp(); @@ -30,12 +30,12 @@ namespace DotNetOpenAuth.Test.OpenId.Provider { this.request = new AuthenticationRequest(this.provider, this.checkIdRequest); } - [TestMethod] + [TestCase] public void IsReturnUrlDiscoverableNoResponse() { Assert.AreEqual(RelyingPartyDiscoveryResult.NoServiceDocument, this.request.IsReturnUrlDiscoverable(this.provider)); } - [TestMethod] + [TestCase] public void IsReturnUrlDiscoverableValidResponse() { this.MockResponder.RegisterMockRPDiscovery(); this.request = new AuthenticationRequest(this.provider, this.checkIdRequest); @@ -46,7 +46,7 @@ namespace DotNetOpenAuth.Test.OpenId.Provider { /// Verifies that when discovery would be performed over standard HTTP and RequireSsl /// is set, that discovery fails. /// </summary> - [TestMethod] + [TestCase] public void IsReturnUrlDiscoverableNotSsl() { this.provider.SecuritySettings.RequireSsl = true; this.MockResponder.RegisterMockRPDiscovery(); @@ -56,7 +56,7 @@ namespace DotNetOpenAuth.Test.OpenId.Provider { /// <summary> /// Verifies that when discovery would be performed over HTTPS that discovery succeeds. /// </summary> - [TestMethod] + [TestCase] public void IsReturnUrlDiscoverableRequireSsl() { this.MockResponder.RegisterMockRPDiscovery(); this.checkIdRequest.Realm = RPRealmUriSsl; @@ -73,7 +73,7 @@ namespace DotNetOpenAuth.Test.OpenId.Provider { Assert.AreEqual(RelyingPartyDiscoveryResult.Success, this.request.IsReturnUrlDiscoverable(this.provider)); } - [TestMethod] + [TestCase] public void IsReturnUrlDiscoverableValidButNoMatch() { this.MockResponder.RegisterMockRPDiscovery(); this.provider.SecuritySettings.RequireSsl = false; // reset for another failure test case diff --git a/src/DotNetOpenAuth.Test/OpenId/Provider/OpenIdProviderTests.cs b/src/DotNetOpenAuth.Test/OpenId/Provider/OpenIdProviderTests.cs index 8528aa7..75d871c 100644 --- a/src/DotNetOpenAuth.Test/OpenId/Provider/OpenIdProviderTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/Provider/OpenIdProviderTests.cs @@ -15,13 +15,13 @@ namespace DotNetOpenAuth.Test.OpenId.Provider { using DotNetOpenAuth.OpenId.Provider; using DotNetOpenAuth.OpenId.RelyingParty; using DotNetOpenAuth.Test.Hosting; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; - [TestClass] + [TestFixture] public class OpenIdProviderTests : OpenIdTestBase { private OpenIdProvider provider; - [TestInitialize] + [SetUp] public override void SetUp() { base.SetUp(); @@ -31,7 +31,7 @@ namespace DotNetOpenAuth.Test.OpenId.Provider { /// <summary> /// Verifies that the constructor throws an exception if the app store is null. /// </summary> - [TestMethod, ExpectedException(typeof(ArgumentNullException))] + [TestCase, ExpectedException(typeof(ArgumentNullException))] public void CtorNull() { new OpenIdProvider(null); } @@ -39,7 +39,7 @@ namespace DotNetOpenAuth.Test.OpenId.Provider { /// <summary> /// Verifies that the SecuritySettings property throws when set to null. /// </summary> - [TestMethod, ExpectedException(typeof(ArgumentNullException))] + [TestCase, ExpectedException(typeof(ArgumentNullException))] public void SecuritySettingsSetNull() { this.provider.SecuritySettings = null; } @@ -47,25 +47,25 @@ namespace DotNetOpenAuth.Test.OpenId.Provider { /// <summary> /// Verifies the SecuritySettings property can be set to a new instance. /// </summary> - [TestMethod] + [TestCase] public void SecuritySettings() { var newSettings = new ProviderSecuritySettings(); this.provider.SecuritySettings = newSettings; Assert.AreSame(newSettings, this.provider.SecuritySettings); } - [TestMethod] + [TestCase] public void ExtensionFactories() { var factories = this.provider.ExtensionFactories; Assert.IsNotNull(factories); Assert.AreEqual(1, factories.Count); - Assert.IsInstanceOfType(factories[0], typeof(StandardOpenIdExtensionFactory)); + Assert.IsInstanceOf<StandardOpenIdExtensionFactory>(factories[0]); } /// <summary> /// Verifies the Channel property. /// </summary> - [TestMethod] + [TestCase] public void ChannelGetter() { Assert.IsNotNull(this.provider.Channel); } @@ -73,7 +73,7 @@ namespace DotNetOpenAuth.Test.OpenId.Provider { /// <summary> /// Verifies the GetRequest method throws outside an HttpContext. /// </summary> - [TestMethod, ExpectedException(typeof(InvalidOperationException))] + [TestCase, ExpectedException(typeof(InvalidOperationException))] public void GetRequestNoContext() { HttpContext.Current = null; this.provider.GetRequest(); @@ -82,7 +82,7 @@ namespace DotNetOpenAuth.Test.OpenId.Provider { /// <summary> /// Verifies GetRequest throws on null input. /// </summary> - [TestMethod, ExpectedException(typeof(ArgumentNullException))] + [TestCase, ExpectedException(typeof(ArgumentNullException))] public void GetRequestNull() { this.provider.GetRequest(null); } @@ -90,7 +90,7 @@ namespace DotNetOpenAuth.Test.OpenId.Provider { /// <summary> /// Verifies that GetRequest correctly returns the right messages. /// </summary> - [TestMethod] + [TestCase] public void GetRequest() { HttpRequestInfo httpInfo = new HttpRequestInfo(); httpInfo.UrlBeforeRewriting = new Uri("http://someUri"); @@ -104,13 +104,13 @@ namespace DotNetOpenAuth.Test.OpenId.Provider { }, op => { IRequest request = op.GetRequest(); - Assert.IsInstanceOfType(request, typeof(AutoResponsiveRequest)); + Assert.IsInstanceOf<AutoResponsiveRequest>(request); op.SendResponse(request); }); coordinator.Run(); } - [TestMethod] + [TestCase] public void BadRequestsGenerateValidErrorResponses() { var coordinator = new OpenIdCoordinator( rp => { @@ -127,7 +127,7 @@ namespace DotNetOpenAuth.Test.OpenId.Provider { coordinator.Run(); } - [TestMethod] + [TestCase, Category("HostASPNET")] public void BadRequestsGenerateValidErrorResponsesHosted() { try { using (AspNetHost host = AspNetHost.CreateHost(TestWebDirectory)) { diff --git a/src/DotNetOpenAuth.Test/OpenId/Provider/PerformanceTests.cs b/src/DotNetOpenAuth.Test/OpenId/Provider/PerformanceTests.cs index 9f4727d..7984b58 100644 --- a/src/DotNetOpenAuth.Test/OpenId/Provider/PerformanceTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/Provider/PerformanceTests.cs @@ -18,28 +18,28 @@ namespace DotNetOpenAuth.Test.OpenId.Provider { using DotNetOpenAuth.OpenId.ChannelElements; using DotNetOpenAuth.OpenId.Messages; using DotNetOpenAuth.OpenId.Provider; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; - [TestClass] + [TestFixture, Category("Performance")] public class PerformanceTests : OpenIdTestBase { private const string SharedAssociationHandle = "handle"; private static readonly TimeSpan TestRunTime = TimeSpan.FromSeconds(3); private OpenIdProvider provider; - [TestInitialize] + [SetUp] public override void SetUp() { base.SetUp(); SuspendLogging(); this.provider = CreateProvider(); } - [TestCleanup] + [TearDown] public override void Cleanup() { ResumeLogging(); base.Cleanup(); } - [TestMethod] + [TestCase] public void AssociateDH() { var associateRequest = this.CreateAssociateRequest(OPUri); Stopwatch timer = new Stopwatch(); @@ -48,15 +48,15 @@ namespace DotNetOpenAuth.Test.OpenId.Provider { for (iterations = 0; timer.ElapsedMilliseconds < TestRunTime.TotalMilliseconds; iterations++) { IRequest request = this.provider.GetRequest(associateRequest); var response = this.provider.PrepareResponse(request); - Assert.IsInstanceOfType(response.OriginalMessage, typeof(AssociateSuccessfulResponse)); + Assert.IsInstanceOf<AssociateSuccessfulResponse>(response.OriginalMessage); } timer.Stop(); double executionsPerSecond = GetExecutionsPerSecond(iterations, timer); - TestContext.WriteLine("Created {0} associations in {1}, or {2} per second.", iterations, timer.Elapsed, executionsPerSecond); + TestUtilities.TestLogger.InfoFormat("Created {0} associations in {1}, or {2} per second.", iterations, timer.Elapsed, executionsPerSecond); Assert.IsTrue(executionsPerSecond >= 2, "Too slow ({0} >= 2 executions per second required.)", executionsPerSecond); } - [TestMethod] + [TestCase] public void AssociateClearText() { var associateRequest = this.CreateAssociateRequest(OPUriSsl); // SSL will cause a plaintext association Stopwatch timer = new Stopwatch(); @@ -65,29 +65,29 @@ namespace DotNetOpenAuth.Test.OpenId.Provider { for (iterations = 0; timer.ElapsedMilliseconds < TestRunTime.TotalMilliseconds; iterations++) { IRequest request = this.provider.GetRequest(associateRequest); var response = this.provider.PrepareResponse(request); - Assert.IsInstanceOfType(response.OriginalMessage, typeof(AssociateSuccessfulResponse)); + Assert.IsInstanceOf<AssociateSuccessfulResponse>(response.OriginalMessage); } timer.Stop(); double executionsPerSecond = GetExecutionsPerSecond(iterations, timer); - TestContext.WriteLine("Created {0} associations in {1}, or {2} per second.", iterations, timer.Elapsed, executionsPerSecond); + TestUtilities.TestLogger.InfoFormat("Created {0} associations in {1}, or {2} per second.", iterations, timer.Elapsed, executionsPerSecond); Assert.IsTrue(executionsPerSecond > 1000, "Too slow ({0} > 1000 executions per second required.)", executionsPerSecond); } - [TestMethod] + [TestCase] public void CheckIdSharedHmacSha1Association() { Protocol protocol = Protocol.Default; string assocType = protocol.Args.SignatureAlgorithm.HMAC_SHA1; double executionsPerSecond = this.ParameterizedCheckIdTest(protocol, assocType); - TestContext.WriteLine("{0} executions per second.", executionsPerSecond); + TestUtilities.TestLogger.InfoFormat("{0} executions per second.", executionsPerSecond); Assert.IsTrue(executionsPerSecond > 500, "Too slow ({0} > 500 executions per second required.)", executionsPerSecond); } - [TestMethod] + [TestCase] public void CheckIdSharedHmacSha256Association() { Protocol protocol = Protocol.Default; string assocType = protocol.Args.SignatureAlgorithm.HMAC_SHA256; double executionsPerSecond = this.ParameterizedCheckIdTest(protocol, assocType); - TestContext.WriteLine("{0} executions per second.", executionsPerSecond); + TestUtilities.TestLogger.InfoFormat("{0} executions per second.", executionsPerSecond); Assert.IsTrue(executionsPerSecond > 400, "Too slow ({0} > 400 executions per second required.)", executionsPerSecond); } @@ -110,11 +110,11 @@ namespace DotNetOpenAuth.Test.OpenId.Provider { var request = (IAuthenticationRequest)this.provider.GetRequest(checkidRequest); request.IsAuthenticated = true; var response = this.provider.PrepareResponse(request); - Assert.IsInstanceOfType(response.OriginalMessage, typeof(PositiveAssertionResponse)); + Assert.IsInstanceOf<PositiveAssertionResponse>(response.OriginalMessage); } timer.Stop(); double executionsPerSecond = GetExecutionsPerSecond(iterations, timer); - TestContext.WriteLine("Responded to {0} checkid messages in {1}; or {2} authentications per second.", iterations, timer.Elapsed, executionsPerSecond); + TestUtilities.TestLogger.InfoFormat("Responded to {0} checkid messages in {1}; or {2} authentications per second.", iterations, timer.Elapsed, executionsPerSecond); return executionsPerSecond; } diff --git a/src/DotNetOpenAuth.Test/OpenId/ProviderEndpointDescriptionTests.cs b/src/DotNetOpenAuth.Test/OpenId/ProviderEndpointDescriptionTests.cs index 089265f..65185fc 100644 --- a/src/DotNetOpenAuth.Test/OpenId/ProviderEndpointDescriptionTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/ProviderEndpointDescriptionTests.cs @@ -6,57 +6,23 @@ namespace DotNetOpenAuth.Test.OpenId { using System; + using DotNetOpenAuth.Messaging; using DotNetOpenAuth.OpenId; using DotNetOpenAuth.OpenId.Extensions.SimpleRegistration; using DotNetOpenAuth.OpenId.Messages; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; - [TestClass] + [TestFixture] public class ProviderEndpointDescriptionTests : OpenIdTestBase { - private ProviderEndpointDescription se; - - private string[] v20TypeUris = { Protocol.V20.ClaimedIdentifierServiceTypeURI }; - - [TestInitialize] - public override void SetUp() { - base.SetUp(); - - this.se = new ProviderEndpointDescription(OPUri, Protocol.V20.Version); - } - - [TestMethod, ExpectedException(typeof(ArgumentNullException))] - public void IsExtensionSupportedNullType() { - this.se.IsExtensionSupported((Type)null); - } - - [TestMethod, ExpectedException(typeof(ArgumentException))] - public void IsExtensionSupportedNullString() { - this.se.IsExtensionSupported((string)null); - } - - [TestMethod, ExpectedException(typeof(ArgumentException))] - public void IsExtensionSupportedEmptyString() { - this.se.IsExtensionSupported(string.Empty); + [TestCase] + public void NonNullCapabilities() { + var epd = new ProviderEndpointDescription(OPUri, Protocol.Default.Version); + Assert.IsNotNull(epd.Capabilities); } - [TestMethod, ExpectedException(typeof(ArgumentNullException))] - public void IsExtensionSupportedNullExtension() { - this.se.IsExtensionSupported((IOpenIdMessageExtension)null); - } - - [TestMethod] - public void IsExtensionSupported() { - this.se = new ProviderEndpointDescription(OPUri, this.v20TypeUris); - Assert.IsFalse(this.se.IsExtensionSupported<ClaimsRequest>()); - Assert.IsFalse(this.se.IsExtensionSupported(new ClaimsRequest())); - Assert.IsFalse(this.se.IsExtensionSupported("http://someextension/typeuri")); - - this.se = new ProviderEndpointDescription( - OPUri, - new[] { Protocol.V20.ClaimedIdentifierServiceTypeURI, "http://someextension", Constants.sreg_ns }); - Assert.IsTrue(this.se.IsExtensionSupported<ClaimsRequest>()); - Assert.IsTrue(this.se.IsExtensionSupported(new ClaimsRequest())); - Assert.IsTrue(this.se.IsExtensionSupported("http://someextension")); + [TestCase, ExpectedException(typeof(ProtocolException))] + public void ProtocolDetectionWithoutClues() { + new ProviderEndpointDescription(OPUri, new[] { Protocol.V20.HtmlDiscoveryLocalIdKey }); // random type URI irrelevant to detection } } } diff --git a/src/DotNetOpenAuth.Test/OpenId/RealmTests.cs b/src/DotNetOpenAuth.Test/OpenId/RealmTests.cs index e062e12..fceb15a 100644 --- a/src/DotNetOpenAuth.Test/OpenId/RealmTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/RealmTests.cs @@ -7,11 +7,11 @@ namespace DotNetOpenAuth.Test { using System; using DotNetOpenAuth.OpenId; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; - [TestClass] + [TestFixture] public class RealmTests { - [TestMethod] + [TestCase] public void ValidRealmsTest() { // Just create these. If any are determined to be invalid, // an exception should be thrown that would fail this test. @@ -26,67 +26,67 @@ namespace DotNetOpenAuth.Test { new Realm("http://*.guest.myopenid.com/"); } - [TestMethod] + [TestCase] [ExpectedException(typeof(ArgumentNullException))] public void InvalidRealmNullString() { new Realm((string)null); } - [TestMethod] + [TestCase] [ExpectedException(typeof(ArgumentNullException))] public void InvalidRealmNullUri() { new Realm((Uri)null); } - [TestMethod] + [TestCase] [ExpectedException(typeof(UriFormatException))] public void InvalidRealmEmpty() { new Realm(string.Empty); } - [TestMethod] + [TestCase] [ExpectedException(typeof(UriFormatException))] public void InvalidRealmBadProtocol() { new Realm("asdf://www.microsoft.com/"); } - [TestMethod] + [TestCase] [ExpectedException(typeof(UriFormatException))] public void InvalidRealmNoScheme() { new Realm("www.guy.com"); } - [TestMethod] + [TestCase] [ExpectedException(typeof(UriFormatException))] public void InvalidRealmBadWildcard1() { new Realm("http://*www.my.com"); } - [TestMethod] + [TestCase] [ExpectedException(typeof(UriFormatException))] public void InvalidRealmBadWildcard2() { new Realm("http://www.*.com"); } - [TestMethod] + [TestCase] [ExpectedException(typeof(UriFormatException))] public void InvalidRealmBadWildcard3() { new Realm("http://www.my.*/"); } - [TestMethod] + [TestCase] [ExpectedException(typeof(UriFormatException))] public void InvalidRealmTwoWildcards1() { new Realm("http://**.my.com"); } - [TestMethod] + [TestCase] [ExpectedException(typeof(UriFormatException))] public void InvalidRealmTwoWildcards2() { new Realm("http://*.*.my.com"); } - [TestMethod] + [TestCase] public void IsSaneTest() { Assert.IsTrue(new Realm("http://www.myopenid.com").IsSane); Assert.IsTrue(new Realm("http://myopenid.com").IsSane); @@ -98,7 +98,7 @@ namespace DotNetOpenAuth.Test { Assert.IsFalse(new Realm("http://*.co.uk").IsSane); } - [TestMethod] + [TestCase] public void IsUrlWithinRealmTests() { /* * The openid.return_to URL MUST descend from the openid.trust_root, or the @@ -166,7 +166,7 @@ namespace DotNetOpenAuth.Test { Assert.IsFalse(new Realm("http://www.my.com/abc").Contains("http://www.my.com/ABC")); } - [TestMethod] + [TestCase] public void ImplicitConversionFromStringTests() { Realm realm = "http://host"; Assert.AreEqual("host", realm.Host); @@ -174,7 +174,7 @@ namespace DotNetOpenAuth.Test { Assert.IsNull(realm); } - [TestMethod] + [TestCase] public void ImplicitConversionToStringTests() { Realm realm = new Realm("http://host/"); string realmString = realm; @@ -184,7 +184,7 @@ namespace DotNetOpenAuth.Test { Assert.IsNull(realmString); } - [TestMethod] + [TestCase] public void ImplicitConverstionFromUriTests() { Uri uri = new Uri("http://host"); Realm realm = uri; @@ -194,7 +194,7 @@ namespace DotNetOpenAuth.Test { Assert.IsNull(realm); } - [TestMethod] + [TestCase] public void EqualsTest() { Realm testRealm1a = new Realm("http://www.yahoo.com"); Realm testRealm1b = new Realm("http://www.yahoo.com"); diff --git a/src/DotNetOpenAuth.Test/OpenId/RelyingParty/AuthenticationRequestTests.cs b/src/DotNetOpenAuth.Test/OpenId/RelyingParty/AuthenticationRequestTests.cs index 0ddc76b..001f3fa 100644 --- a/src/DotNetOpenAuth.Test/OpenId/RelyingParty/AuthenticationRequestTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/RelyingParty/AuthenticationRequestTests.cs @@ -16,9 +16,10 @@ namespace DotNetOpenAuth.Test.OpenId.RelyingParty { using DotNetOpenAuth.OpenId.Extensions.SimpleRegistration; using DotNetOpenAuth.OpenId.Messages; using DotNetOpenAuth.OpenId.RelyingParty; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using DotNetOpenAuth.Test.Mocks; + using NUnit.Framework; - [TestClass] + [TestFixture] public class AuthenticationRequestTests : OpenIdTestBase { private readonly Realm realm = new Realm("http://localhost/rp.aspx"); private readonly Identifier claimedId = "http://claimedId"; @@ -26,7 +27,7 @@ namespace DotNetOpenAuth.Test.OpenId.RelyingParty { private readonly Protocol protocol = Protocol.Default; private Uri returnTo; - [TestInitialize] + [SetUp] public override void SetUp() { base.SetUp(); this.returnTo = new Uri("http://localhost/rp.aspx"); @@ -35,9 +36,9 @@ namespace DotNetOpenAuth.Test.OpenId.RelyingParty { /// <summary> /// Verifies IsDirectedIdentity returns true when appropriate. /// </summary> - [TestMethod] + [TestCase] public void IsDirectedIdentity() { - IAuthenticationRequest_Accessor iauthRequest = this.CreateAuthenticationRequest(this.claimedId, this.claimedId); + var iauthRequest = this.CreateAuthenticationRequest(this.claimedId, this.claimedId); Assert.IsFalse(iauthRequest.IsDirectedIdentity); iauthRequest = this.CreateAuthenticationRequest(IdentifierSelect, IdentifierSelect); @@ -47,9 +48,9 @@ namespace DotNetOpenAuth.Test.OpenId.RelyingParty { /// <summary> /// Verifies ClaimedIdentifier behavior. /// </summary> - [TestMethod] + [TestCase] public void ClaimedIdentifier() { - IAuthenticationRequest_Accessor iauthRequest = this.CreateAuthenticationRequest(this.claimedId, this.delegatedLocalId); + var iauthRequest = this.CreateAuthenticationRequest(this.claimedId, this.delegatedLocalId); Assert.AreEqual(this.claimedId, iauthRequest.ClaimedIdentifier); iauthRequest = this.CreateAuthenticationRequest(IdentifierSelect, IdentifierSelect); @@ -59,16 +60,16 @@ namespace DotNetOpenAuth.Test.OpenId.RelyingParty { /// <summary> /// Verifies ProviderVersion behavior. /// </summary> - [TestMethod] + [TestCase] public void ProviderVersion() { var authRequest = this.CreateAuthenticationRequest(this.claimedId, this.claimedId); - Assert.AreEqual(this.protocol.Version, authRequest.endpoint.Protocol.Version); + Assert.AreEqual(this.protocol.Version, authRequest.DiscoveryResult.Version); } /// <summary> /// Verifies RedirectingResponse. /// </summary> - [TestMethod] + [TestCase] public void CreateRequestMessage() { OpenIdCoordinator coordinator = new OpenIdCoordinator( rp => { @@ -106,7 +107,7 @@ namespace DotNetOpenAuth.Test.OpenId.RelyingParty { /// <summary> /// Verifies that delegating authentication requests are filtered out when configured to do so. /// </summary> - [TestMethod] + [TestCase] public void CreateFiltersDelegatingIdentifiers() { Identifier id = GetMockIdentifier(ProtocolVersion.V20, false, true); var rp = CreateRelyingParty(); @@ -122,9 +123,9 @@ namespace DotNetOpenAuth.Test.OpenId.RelyingParty { /// <summary> /// Verifies the Provider property returns non-null. /// </summary> - [TestMethod] + [TestCase] public void Provider() { - IAuthenticationRequest_Accessor authRequest = this.CreateAuthenticationRequest(this.claimedId, this.claimedId); + var authRequest = this.CreateAuthenticationRequest(this.claimedId, this.claimedId); Assert.IsNotNull(authRequest.Provider); Assert.AreEqual(OPUri, authRequest.Provider.Uri); Assert.AreEqual(this.protocol.Version, authRequest.Provider.Version); @@ -133,9 +134,9 @@ namespace DotNetOpenAuth.Test.OpenId.RelyingParty { /// <summary> /// Verifies that AddCallbackArguments adds query arguments to the return_to URL of the message. /// </summary> - [TestMethod] + [TestCase] public void AddCallbackArgument() { - IAuthenticationRequest_Accessor authRequest = this.CreateAuthenticationRequest(this.claimedId, this.claimedId); + var authRequest = this.CreateAuthenticationRequest(this.claimedId, this.claimedId); Assert.AreEqual(this.returnTo, authRequest.ReturnToUrl); authRequest.AddCallbackArguments("p1", "v1"); var req = (SignedResponseRequest)authRequest.RedirectingResponse.OriginalMessage; @@ -147,12 +148,12 @@ namespace DotNetOpenAuth.Test.OpenId.RelyingParty { /// Verifies that AddCallbackArguments replaces pre-existing parameter values /// rather than appending them. /// </summary> - [TestMethod] + [TestCase] public void AddCallbackArgumentClearsPreviousArgument() { UriBuilder returnToWithArgs = new UriBuilder(this.returnTo); returnToWithArgs.AppendQueryArgs(new Dictionary<string, string> { { "p1", "v1" } }); this.returnTo = returnToWithArgs.Uri; - IAuthenticationRequest_Accessor authRequest = this.CreateAuthenticationRequest(this.claimedId, this.claimedId); + var authRequest = this.CreateAuthenticationRequest(this.claimedId, this.claimedId); authRequest.AddCallbackArguments("p1", "v2"); var req = (SignedResponseRequest)authRequest.RedirectingResponse.OriginalMessage; NameValueCollection query = HttpUtility.ParseQueryString(req.ReturnTo.Query); @@ -162,32 +163,48 @@ namespace DotNetOpenAuth.Test.OpenId.RelyingParty { /// <summary> /// Verifies identity-less checkid_* request behavior. /// </summary> - [TestMethod] + [TestCase] public void NonIdentityRequest() { - IAuthenticationRequest_Accessor authRequest = this.CreateAuthenticationRequest(this.claimedId, this.claimedId); + var authRequest = this.CreateAuthenticationRequest(this.claimedId, this.claimedId); authRequest.IsExtensionOnly = true; Assert.IsTrue(authRequest.IsExtensionOnly); var req = (SignedResponseRequest)authRequest.RedirectingResponse.OriginalMessage; - Assert.IsNotInstanceOfType(req, typeof(CheckIdRequest), "An unexpected SignedResponseRequest derived type was generated."); + Assert.IsNotInstanceOf<CheckIdRequest>(req, "An unexpected SignedResponseRequest derived type was generated."); + } + + /// <summary> + /// Verifies that discovery on identifiers that serve as OP identifiers and claimed identifiers + /// only generate OP Identifier auth requests. + /// </summary> + [TestCase] + public void DualIdentifierUsedOnlyAsOPIdentifierForAuthRequest() { + var rp = this.CreateRelyingParty(true); + var results = AuthenticationRequest.Create(GetMockDualIdentifier(), rp, this.realm, this.returnTo, false).ToList(); + Assert.AreEqual(1, results.Count); + Assert.IsTrue(results[0].IsDirectedIdentity); + + // Also test when dual identiifer support is turned on. + rp.SecuritySettings.AllowDualPurposeIdentifiers = true; + results = AuthenticationRequest.Create(GetMockDualIdentifier(), rp, this.realm, this.returnTo, false).ToList(); + Assert.AreEqual(1, results.Count); + Assert.IsTrue(results[0].IsDirectedIdentity); } /// <summary> /// Verifies that authentication requests are generated first for OPs that respond /// to authentication requests. /// </summary> - [TestMethod, Ignore] + [TestCase, Ignore("Not yet implemented")] public void UnresponsiveProvidersComeLast() { // TODO: code here Assert.Inconclusive("Not yet implemented."); } - private AuthenticationRequest_Accessor CreateAuthenticationRequest(Identifier claimedIdentifier, Identifier providerLocalIdentifier) { + private AuthenticationRequest CreateAuthenticationRequest(Identifier claimedIdentifier, Identifier providerLocalIdentifier) { ProviderEndpointDescription providerEndpoint = new ProviderEndpointDescription(OPUri, this.protocol.Version); - ServiceEndpoint endpoint = ServiceEndpoint.CreateForClaimedIdentifier(claimedIdentifier, providerLocalIdentifier, providerEndpoint, 10, 5); - ServiceEndpoint_Accessor endpointAccessor = ServiceEndpoint_Accessor.AttachShadow(endpoint); + IdentifierDiscoveryResult endpoint = IdentifierDiscoveryResult.CreateForClaimedIdentifier(claimedIdentifier, providerLocalIdentifier, providerEndpoint, 10, 5); OpenIdRelyingParty rp = this.CreateRelyingParty(); - AuthenticationRequest_Accessor authRequest = new AuthenticationRequest_Accessor(endpointAccessor, this.realm, this.returnTo, rp); - return authRequest; + return AuthenticationRequest.CreateForTest(endpoint, this.realm, this.returnTo, rp); } } } diff --git a/src/DotNetOpenAuth.Test/OpenId/RelyingParty/FailedAuthenticationResponseTests.cs b/src/DotNetOpenAuth.Test/OpenId/RelyingParty/FailedAuthenticationResponseTests.cs index a82634a..43d056f 100644 --- a/src/DotNetOpenAuth.Test/OpenId/RelyingParty/FailedAuthenticationResponseTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/RelyingParty/FailedAuthenticationResponseTests.cs @@ -12,14 +12,14 @@ namespace DotNetOpenAuth.Test.OpenId.RelyingParty { using DotNetOpenAuth.Messaging; using DotNetOpenAuth.OpenId.Extensions.SimpleRegistration; using DotNetOpenAuth.OpenId.RelyingParty; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; - [TestClass] + [TestFixture] public class FailedAuthenticationResponseTests : OpenIdTestBase { private FailedAuthenticationResponse response; private ProtocolException exception; - [TestInitialize] + [SetUp] public override void SetUp() { base.SetUp(); @@ -27,12 +27,12 @@ namespace DotNetOpenAuth.Test.OpenId.RelyingParty { this.response = new FailedAuthenticationResponse(this.exception); } - [TestMethod, ExpectedException(typeof(ArgumentNullException))] + [TestCase, ExpectedException(typeof(ArgumentNullException))] public void CtorNull() { new FailedAuthenticationResponse(null); } - [TestMethod] + [TestCase] public void CommonProperties() { Assert.AreEqual(AuthenticationStatus.Failed, this.response.Status); Assert.AreSame(this.exception, this.response.Exception); @@ -40,7 +40,7 @@ namespace DotNetOpenAuth.Test.OpenId.RelyingParty { Assert.IsNull(this.response.FriendlyIdentifierForDisplay); } - [TestMethod] + [TestCase] public void CommonMethods() { Assert.IsNull(this.response.GetExtension<ClaimsRequest>()); Assert.IsNull(this.response.GetExtension(typeof(ClaimsRequest))); diff --git a/src/DotNetOpenAuth.Test/OpenId/RelyingParty/IdentifierDiscoveryResultTests.cs b/src/DotNetOpenAuth.Test/OpenId/RelyingParty/IdentifierDiscoveryResultTests.cs new file mode 100644 index 0000000..896cf57 --- /dev/null +++ b/src/DotNetOpenAuth.Test/OpenId/RelyingParty/IdentifierDiscoveryResultTests.cs @@ -0,0 +1,199 @@ +//----------------------------------------------------------------------- +// <copyright file="IdentifierDiscoveryResultTests.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.Test.OpenId.RelyingParty { + using System; + using System.Collections.Generic; + using System.Diagnostics; + using System.IO; + using System.Text; + using DotNetOpenAuth.Messaging; + using DotNetOpenAuth.OpenId; + using DotNetOpenAuth.OpenId.Extensions.SimpleRegistration; + using DotNetOpenAuth.OpenId.Messages; + using DotNetOpenAuth.OpenId.RelyingParty; + using DotNetOpenAuth.Test.Messaging; + using NUnit.Framework; + + [TestFixture] + public class IdentifierDiscoveryResultTests : OpenIdTestBase { + private UriIdentifier claimedId = new UriIdentifier("http://claimedid.justatest.com"); + private XriIdentifier claimedXri = new XriIdentifier("=!9B72.7DD1.50A9.5CCD"); + private XriIdentifier userSuppliedXri = new XriIdentifier("=Arnot"); + private Uri providerEndpoint = new Uri("http://someprovider.com"); + private Identifier localId = "http://localid.someprovider.com"; + private string[] v20TypeUris = { Protocol.V20.ClaimedIdentifierServiceTypeURI }; + private string[] v11TypeUris = { Protocol.V11.ClaimedIdentifierServiceTypeURI }; + private int servicePriority = 10; + private int uriPriority = 10; + + [SetUp] + public override void SetUp() { + base.SetUp(); + } + + [TestCase] + public void Ctor() { + IdentifierDiscoveryResult se = IdentifierDiscoveryResult.CreateForClaimedIdentifier(this.claimedId, this.localId, new ProviderEndpointDescription(this.providerEndpoint, this.v20TypeUris), this.servicePriority, this.uriPriority); + Assert.AreEqual(this.claimedId, se.ClaimedIdentifier); + Assert.AreSame(this.providerEndpoint, se.ProviderEndpoint); + Assert.AreSame(this.localId, se.ProviderLocalIdentifier); + CollectionAssert<string>.AreEquivalent(this.v20TypeUris, se.Capabilities); + Assert.AreEqual(this.servicePriority, se.ServicePriority); + } + + [TestCase] + public void CtorImpliedLocalIdentifier() { + IdentifierDiscoveryResult se = IdentifierDiscoveryResult.CreateForClaimedIdentifier(this.claimedId, null, new ProviderEndpointDescription(this.providerEndpoint, this.v20TypeUris), this.servicePriority, this.uriPriority); + Assert.AreEqual(this.claimedId, se.ClaimedIdentifier); + Assert.AreSame(this.providerEndpoint, se.ProviderEndpoint); + Assert.AreSame(this.claimedId, se.ProviderLocalIdentifier); + CollectionAssert<string>.AreEquivalent(this.v20TypeUris, se.Capabilities); + } + + [TestCase] + public void ProtocolDetection() { + IdentifierDiscoveryResult se = IdentifierDiscoveryResult.CreateForClaimedIdentifier(this.claimedId, this.localId, new ProviderEndpointDescription(this.providerEndpoint, this.v20TypeUris), this.servicePriority, this.uriPriority); + Assert.AreSame(Protocol.V20, se.Protocol); + se = IdentifierDiscoveryResult.CreateForClaimedIdentifier( + this.claimedId, + this.localId, + new ProviderEndpointDescription(this.providerEndpoint, new[] { Protocol.V20.OPIdentifierServiceTypeURI }), + this.servicePriority, + this.uriPriority); + Assert.AreSame(Protocol.V20, se.Protocol); + se = IdentifierDiscoveryResult.CreateForClaimedIdentifier(this.claimedId, this.localId, new ProviderEndpointDescription(this.providerEndpoint, this.v11TypeUris), this.servicePriority, this.uriPriority); + Assert.AreSame(Protocol.V11, se.Protocol); + } + + [TestCase] + public void EqualsTests() { + IdentifierDiscoveryResult se = IdentifierDiscoveryResult.CreateForClaimedIdentifier(this.claimedId, this.localId, new ProviderEndpointDescription(this.providerEndpoint, this.v20TypeUris), this.servicePriority, this.uriPriority); + IdentifierDiscoveryResult se2 = IdentifierDiscoveryResult.CreateForClaimedIdentifier(this.claimedId, this.localId, new ProviderEndpointDescription(this.providerEndpoint, this.v20TypeUris), (int?)null, (int?)null); + Assert.AreEqual(se2, se); + Assert.AreNotEqual(se, null); + Assert.AreNotEqual(null, se); + + IdentifierDiscoveryResult se3 = IdentifierDiscoveryResult.CreateForClaimedIdentifier(new UriIdentifier(this.claimedId + "a"), this.localId, new ProviderEndpointDescription(this.providerEndpoint, this.v20TypeUris), this.servicePriority, this.uriPriority); + Assert.AreNotEqual(se, se3); + se3 = IdentifierDiscoveryResult.CreateForClaimedIdentifier(this.claimedId, this.localId, new ProviderEndpointDescription(new Uri(this.providerEndpoint.AbsoluteUri + "a"), this.v20TypeUris), this.servicePriority, this.uriPriority); + Assert.AreNotEqual(se, se3); + se3 = IdentifierDiscoveryResult.CreateForClaimedIdentifier(this.claimedId, this.localId + "a", new ProviderEndpointDescription(this.providerEndpoint, this.v20TypeUris), this.servicePriority, this.uriPriority); + Assert.AreNotEqual(se, se3); + se3 = IdentifierDiscoveryResult.CreateForClaimedIdentifier(this.claimedId, this.localId, new ProviderEndpointDescription(this.providerEndpoint, this.v11TypeUris), this.servicePriority, this.uriPriority); + Assert.AreNotEqual(se, se3); + + // make sure that Collection<T>.Contains works as desired. + var list = new List<IdentifierDiscoveryResult>(); + list.Add(se); + Assert.IsTrue(list.Contains(se2)); + } + + [TestCase] + public void GetFriendlyIdentifierForDisplay() { + Uri providerEndpoint = new Uri("http://someprovider"); + Identifier localId = "someuser"; + string[] serviceTypeUris = new string[] { + Protocol.V20.ClaimedIdentifierServiceTypeURI, + }; + IdentifierDiscoveryResult se; + + // strip of protocol, port, query and fragment + se = IdentifierDiscoveryResult.CreateForClaimedIdentifier( + "http://someprovider.somedomain.com:79/someuser?query#frag", + localId, + new ProviderEndpointDescription(providerEndpoint, serviceTypeUris), + null, + null); + Assert.AreEqual("someprovider.somedomain.com/someuser", se.FriendlyIdentifierForDisplay); + + // unescape characters + Uri foreignUri = new Uri("http://server崎/村"); + se = IdentifierDiscoveryResult.CreateForClaimedIdentifier(foreignUri, localId, new ProviderEndpointDescription(providerEndpoint, serviceTypeUris), null, null); + Assert.AreEqual("server崎/村", se.FriendlyIdentifierForDisplay); + + // restore user supplied identifier to XRIs + se = IdentifierDiscoveryResult.CreateForClaimedIdentifier( + new XriIdentifier("=!9B72.7DD1.50A9.5CCD"), + new XriIdentifier("=Arnott崎村"), + localId, + new ProviderEndpointDescription(providerEndpoint, serviceTypeUris), + null, + null); + Assert.AreEqual("=Arnott崎村", se.FriendlyIdentifierForDisplay); + + // If UserSuppliedIdentifier is the same as the ClaimedIdentifier, don't display it twice... + se = IdentifierDiscoveryResult.CreateForClaimedIdentifier( + new XriIdentifier("=!9B72.7DD1.50A9.5CCD"), + new XriIdentifier("=!9B72.7DD1.50A9.5CCD"), + localId, + new ProviderEndpointDescription(providerEndpoint, serviceTypeUris), + null, + null); + Assert.AreEqual("=!9B72.7DD1.50A9.5CCD", se.FriendlyIdentifierForDisplay); + } + + [TestCase] + public void IsTypeUriPresent() { + IdentifierDiscoveryResult se = IdentifierDiscoveryResult.CreateForClaimedIdentifier(this.claimedXri, this.userSuppliedXri, this.localId, new ProviderEndpointDescription(this.providerEndpoint, this.v20TypeUris), this.servicePriority, this.uriPriority); + Assert.IsTrue(se.IsTypeUriPresent(Protocol.Default.ClaimedIdentifierServiceTypeURI)); + Assert.IsFalse(se.IsTypeUriPresent("http://someother")); + } + + [TestCase, ExpectedException(typeof(ArgumentException))] + public void IsTypeUriPresentNull() { + IdentifierDiscoveryResult se = IdentifierDiscoveryResult.CreateForClaimedIdentifier(this.claimedXri, this.userSuppliedXri, this.localId, new ProviderEndpointDescription(this.providerEndpoint, this.v20TypeUris), this.servicePriority, this.uriPriority); + se.IsTypeUriPresent(null); + } + + [TestCase, ExpectedException(typeof(ArgumentException))] + public void IsTypeUriPresentEmpty() { + IdentifierDiscoveryResult se = IdentifierDiscoveryResult.CreateForClaimedIdentifier(this.claimedXri, this.userSuppliedXri, this.localId, new ProviderEndpointDescription(this.providerEndpoint, this.v20TypeUris), this.servicePriority, this.uriPriority); + se.IsTypeUriPresent(string.Empty); + } + + [TestCase, ExpectedException(typeof(ArgumentNullException))] + public void IsExtensionSupportedNullType() { + var se = IdentifierDiscoveryResult.CreateForProviderIdentifier(OPUri, new ProviderEndpointDescription(OPUri, this.v20TypeUris), null, null); + se.IsExtensionSupported((Type)null); + } + + [TestCase, ExpectedException(typeof(ArgumentException))] + public void IsTypeUriPresentNullString() { + var se = IdentifierDiscoveryResult.CreateForProviderIdentifier(OPUri, new ProviderEndpointDescription(OPUri, this.v20TypeUris), null, null); + se.IsTypeUriPresent((string)null); + } + + [TestCase, ExpectedException(typeof(ArgumentException))] + public void IsTypeUriPresentEmptyString() { + var se = IdentifierDiscoveryResult.CreateForProviderIdentifier(OPUri, new ProviderEndpointDescription(OPUri, this.v20TypeUris), null, null); + se.IsTypeUriPresent(string.Empty); + } + + [TestCase, ExpectedException(typeof(ArgumentNullException))] + public void IsExtensionSupportedNullExtension() { + var se = IdentifierDiscoveryResult.CreateForProviderIdentifier(OPUri, new ProviderEndpointDescription(OPUri, this.v20TypeUris), null, null); + se.IsExtensionSupported((IOpenIdMessageExtension)null); + } + + [TestCase] + public void IsExtensionSupported() { + var se = IdentifierDiscoveryResult.CreateForProviderIdentifier(OPUri, new ProviderEndpointDescription(OPUri, this.v20TypeUris), null, null); + Assert.IsFalse(se.IsExtensionSupported<ClaimsRequest>()); + Assert.IsFalse(se.IsExtensionSupported(new ClaimsRequest())); + Assert.IsFalse(se.IsTypeUriPresent("http://someextension/typeuri")); + + se = IdentifierDiscoveryResult.CreateForProviderIdentifier( + OPUri, + new ProviderEndpointDescription(OPUri, new[] { Protocol.V20.ClaimedIdentifierServiceTypeURI, "http://someextension", Constants.sreg_ns }), + null, + null); + Assert.IsTrue(se.IsExtensionSupported<ClaimsRequest>()); + Assert.IsTrue(se.IsExtensionSupported(new ClaimsRequest())); + Assert.IsTrue(se.IsTypeUriPresent("http://someextension")); + } + } +} diff --git a/src/DotNetOpenAuth.Test/OpenId/RelyingParty/NegativeAuthenticationResponseTests.cs b/src/DotNetOpenAuth.Test/OpenId/RelyingParty/NegativeAuthenticationResponseTests.cs index acf537e..dbb4a42 100644 --- a/src/DotNetOpenAuth.Test/OpenId/RelyingParty/NegativeAuthenticationResponseTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/RelyingParty/NegativeAuthenticationResponseTests.cs @@ -13,16 +13,16 @@ namespace DotNetOpenAuth.Test.OpenId.RelyingParty { using DotNetOpenAuth.OpenId.Extensions.SimpleRegistration; using DotNetOpenAuth.OpenId.Messages; using DotNetOpenAuth.OpenId.RelyingParty; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; - [TestClass] + [TestFixture] public class NegativeAuthenticationResponseTests : OpenIdTestBase { private const string UserSuppliedIdentifier = "=arnott"; private Protocol protocol; private NegativeAssertionResponse responseMessage; private NegativeAuthenticationResponse response; - [TestInitialize] + [SetUp] public override void SetUp() { base.SetUp(); @@ -32,7 +32,7 @@ namespace DotNetOpenAuth.Test.OpenId.RelyingParty { this.response = new NegativeAuthenticationResponse(this.responseMessage); } - [TestMethod, ExpectedException(typeof(ArgumentNullException))] + [TestCase, ExpectedException(typeof(ArgumentNullException))] public void CtorNull() { new NegativeAuthenticationResponse(null); } @@ -40,7 +40,7 @@ namespace DotNetOpenAuth.Test.OpenId.RelyingParty { /// <summary> /// Verifies that immediate/setup modes are correctly detected. /// </summary> - [TestMethod] + [TestCase] public void ImmediateVsSetupModes() { this.responseMessage = new NegativeAssertionResponse(this.protocol.Version, RPUri, this.protocol.Args.Mode.cancel); this.response = new NegativeAuthenticationResponse(this.responseMessage); @@ -55,17 +55,17 @@ namespace DotNetOpenAuth.Test.OpenId.RelyingParty { this.responseMessage.ExtraData[AuthenticationRequest.UserSuppliedIdentifierParameterName] = UserSuppliedIdentifier; this.response = new NegativeAuthenticationResponse(this.responseMessage); Assert.AreEqual(AuthenticationStatus.SetupRequired, this.response.Status); - Assert.AreEqual<string>(UserSuppliedIdentifier, this.response.UserSuppliedIdentifier); + Assert.AreEqual(UserSuppliedIdentifier, (string)this.response.UserSuppliedIdentifier); } - [TestMethod] + [TestCase] public void CommonProperties() { Assert.IsNull(this.response.Exception); Assert.IsNull(this.response.ClaimedIdentifier); Assert.IsNull(this.response.FriendlyIdentifierForDisplay); } - [TestMethod] + [TestCase] public void CommonMethods() { Assert.IsNull(this.response.GetExtension<ClaimsRequest>()); Assert.IsNull(this.response.GetExtension(typeof(ClaimsRequest))); diff --git a/src/DotNetOpenAuth.Test/OpenId/RelyingParty/OpenIdRelyingPartyTests.cs b/src/DotNetOpenAuth.Test/OpenId/RelyingParty/OpenIdRelyingPartyTests.cs index f6a57e7..b0ec395 100644 --- a/src/DotNetOpenAuth.Test/OpenId/RelyingParty/OpenIdRelyingPartyTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/RelyingParty/OpenIdRelyingPartyTests.cs @@ -12,40 +12,40 @@ namespace DotNetOpenAuth.Test.OpenId.RelyingParty { using DotNetOpenAuth.OpenId.Extensions; using DotNetOpenAuth.OpenId.Messages; using DotNetOpenAuth.OpenId.RelyingParty; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; - [TestClass] + [TestFixture] public class OpenIdRelyingPartyTests : OpenIdTestBase { - [TestInitialize] + [SetUp] public override void SetUp() { base.SetUp(); } - [TestMethod] + [TestCase] public void CreateRequestDumbMode() { - var rp = new OpenIdRelyingParty(null); + var rp = this.CreateRelyingParty(true); Identifier id = this.GetMockIdentifier(ProtocolVersion.V20); var authReq = rp.CreateRequest(id, RPRealmUri, RPUri); CheckIdRequest requestMessage = (CheckIdRequest)authReq.RedirectingResponse.OriginalMessage; Assert.IsNull(requestMessage.AssociationHandle); } - [TestMethod, ExpectedException(typeof(ArgumentNullException))] + [TestCase, ExpectedException(typeof(ArgumentNullException))] public void SecuritySettingsSetNull() { var rp = new OpenIdRelyingParty(new StandardRelyingPartyApplicationStore()); rp.SecuritySettings = null; } - [TestMethod] + [TestCase] public void ExtensionFactories() { var rp = new OpenIdRelyingParty(null); var factories = rp.ExtensionFactories; Assert.IsNotNull(factories); Assert.AreEqual(1, factories.Count); - Assert.IsInstanceOfType(factories[0], typeof(StandardOpenIdExtensionFactory)); + Assert.IsInstanceOf<StandardOpenIdExtensionFactory>(factories[0]); } - [TestMethod] + [TestCase] public void CreateRequest() { var rp = this.CreateRelyingParty(); StoreAssociation(rp, OPUri, HmacShaAssociation.Create("somehandle", new byte[20], TimeSpan.FromDays(1))); @@ -54,7 +54,7 @@ namespace DotNetOpenAuth.Test.OpenId.RelyingParty { Assert.IsNotNull(req); } - [TestMethod] + [TestCase] public void CreateRequests() { var rp = this.CreateRelyingParty(); StoreAssociation(rp, OPUri, HmacShaAssociation.Create("somehandle", new byte[20], TimeSpan.FromDays(1))); @@ -63,7 +63,7 @@ namespace DotNetOpenAuth.Test.OpenId.RelyingParty { Assert.AreEqual(1, requests.Count()); } - [TestMethod] + [TestCase] public void CreateRequestsWithEndpointFilter() { var rp = this.CreateRelyingParty(); StoreAssociation(rp, OPUri, HmacShaAssociation.Create("somehandle", new byte[20], TimeSpan.FromDays(1))); @@ -78,7 +78,7 @@ namespace DotNetOpenAuth.Test.OpenId.RelyingParty { Assert.AreEqual(0, requests.Count()); } - [TestMethod, ExpectedException(typeof(ProtocolException))] + [TestCase, ExpectedException(typeof(ProtocolException))] public void CreateRequestOnNonOpenID() { Uri nonOpenId = new Uri("http://www.microsoft.com/"); var rp = this.CreateRelyingParty(); @@ -86,7 +86,7 @@ namespace DotNetOpenAuth.Test.OpenId.RelyingParty { rp.CreateRequest(nonOpenId, RPRealmUri, RPUri); } - [TestMethod] + [TestCase] public void CreateRequestsOnNonOpenID() { Uri nonOpenId = new Uri("http://www.microsoft.com/"); var rp = this.CreateRelyingParty(); @@ -99,7 +99,7 @@ namespace DotNetOpenAuth.Test.OpenId.RelyingParty { /// Verifies that incoming positive assertions throw errors if they come from /// OPs that are not approved by <see cref="OpenIdRelyingParty.EndpointFilter"/>. /// </summary> - [TestMethod] + [TestCase] public void AssertionWithEndpointFilter() { var coordinator = new OpenIdCoordinator( rp => { diff --git a/src/DotNetOpenAuth.Test/OpenId/RelyingParty/OpenIdTextBoxTests.cs b/src/DotNetOpenAuth.Test/OpenId/RelyingParty/OpenIdTextBoxTests.cs index 67255e3..2c70e0f 100644 --- a/src/DotNetOpenAuth.Test/OpenId/RelyingParty/OpenIdTextBoxTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/RelyingParty/OpenIdTextBoxTests.cs @@ -6,14 +6,14 @@ namespace DotNetOpenAuth.Test.OpenId.RelyingParty { using DotNetOpenAuth.OpenId.RelyingParty; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; - [TestClass] + [TestFixture] public class OpenIdTextBoxTests : OpenIdTestBase { /// <summary> /// Verifies that the Text and Identifier properties interact correctly. /// </summary> - [TestMethod] + [TestCase] public void IdentifierTextInteraction() { var box = new OpenIdTextBox(); Assert.AreEqual(string.Empty, box.Text); diff --git a/src/DotNetOpenAuth.Test/OpenId/RelyingParty/PositiveAnonymousResponseTests.cs b/src/DotNetOpenAuth.Test/OpenId/RelyingParty/PositiveAnonymousResponseTests.cs index 1418513..b0586a6 100644 --- a/src/DotNetOpenAuth.Test/OpenId/RelyingParty/PositiveAnonymousResponseTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/RelyingParty/PositiveAnonymousResponseTests.cs @@ -10,14 +10,14 @@ namespace DotNetOpenAuth.Test.OpenId.RelyingParty { using DotNetOpenAuth.OpenId.Extensions.SimpleRegistration; using DotNetOpenAuth.OpenId.Messages; using DotNetOpenAuth.OpenId.RelyingParty; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; - [TestClass] + [TestFixture] public class PositiveAnonymousResponseTests : OpenIdTestBase { private readonly Realm realm = new Realm("http://localhost/rp.aspx"); private readonly Uri returnTo = new Uri("http://localhost/rp.aspx"); - [TestInitialize] + [SetUp] public override void SetUp() { base.SetUp(); } @@ -25,7 +25,7 @@ namespace DotNetOpenAuth.Test.OpenId.RelyingParty { /// <summary> /// Verifies that the Status property returns the correct value. /// </summary> - [TestMethod] + [TestCase] public void CtorAndProperties() { var responseMessage = new IndirectSignedResponse(Protocol.V20.Version, this.returnTo); var ext = new ClaimsResponse(); @@ -43,7 +43,7 @@ namespace DotNetOpenAuth.Test.OpenId.RelyingParty { /// <summary> /// Verifies the Provider property. /// </summary> - [TestMethod] + [TestCase] public void ProviderTest() { var responseMessage = new IndirectSignedResponse(Protocol.V20.Version, this.returnTo); responseMessage.ProviderEndpoint = OPUri; diff --git a/src/DotNetOpenAuth.Test/OpenId/RelyingParty/PositiveAuthenticationResponseSnapshotTests.cs b/src/DotNetOpenAuth.Test/OpenId/RelyingParty/PositiveAuthenticationResponseSnapshotTests.cs new file mode 100644 index 0000000..e069c44 --- /dev/null +++ b/src/DotNetOpenAuth.Test/OpenId/RelyingParty/PositiveAuthenticationResponseSnapshotTests.cs @@ -0,0 +1,39 @@ +//----------------------------------------------------------------------- +// <copyright file="PositiveAuthenticationResponseSnapshotTests.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.Test.OpenId.RelyingParty { + using System.Collections.Generic; + using System.IO; + using System.Runtime.Serialization; + using System.Runtime.Serialization.Formatters.Binary; + using DotNetOpenAuth.OpenId; + using DotNetOpenAuth.OpenId.Messages; + using DotNetOpenAuth.OpenId.RelyingParty; + using Microsoft.VisualStudio.TestTools.UnitTesting; + using Moq; + + [TestClass] + public class PositiveAuthenticationResponseSnapshotTests : OpenIdTestBase { + /// <summary> + /// Verifies that the PositiveAuthenticationResponseSnapshot is serializable, + /// as required by the <see cref="OpenIdRelyingPartyAjaxControlBase"/> class. + /// </summary> + [TestMethod] + public void Serializable() { + var response = new Mock<IAuthenticationResponse>(MockBehavior.Strict); + response.Setup(o => o.ClaimedIdentifier).Returns(VanityUri); + response.Setup(o => o.FriendlyIdentifierForDisplay).Returns(VanityUri.AbsoluteUri); + response.Setup(o => o.Status).Returns(AuthenticationStatus.Authenticated); + response.Setup(o => o.Provider).Returns(new ProviderEndpointDescription(OPUri, Protocol.Default.Version)); + response.Setup(o => o.GetUntrustedCallbackArguments()).Returns(new Dictionary<string, string>()); + response.Setup(o => o.GetCallbackArguments()).Returns(new Dictionary<string, string>()); + var snapshot = new PositiveAuthenticationResponseSnapshot(response.Object); + MemoryStream ms = new MemoryStream(); + IFormatter formatter = new BinaryFormatter(); + formatter.Serialize(ms, snapshot); + } + } +} diff --git a/src/DotNetOpenAuth.Test/OpenId/RelyingParty/PositiveAuthenticationResponseTests.cs b/src/DotNetOpenAuth.Test/OpenId/RelyingParty/PositiveAuthenticationResponseTests.cs index 701bcae..25b0607 100644 --- a/src/DotNetOpenAuth.Test/OpenId/RelyingParty/PositiveAuthenticationResponseTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/RelyingParty/PositiveAuthenticationResponseTests.cs @@ -12,14 +12,15 @@ namespace DotNetOpenAuth.Test.OpenId.RelyingParty { using DotNetOpenAuth.OpenId.Extensions.SimpleRegistration; using DotNetOpenAuth.OpenId.Messages; using DotNetOpenAuth.OpenId.RelyingParty; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using DotNetOpenAuth.Test.Mocks; + using NUnit.Framework; - [TestClass] + [TestFixture] public class PositiveAuthenticationResponseTests : OpenIdTestBase { private readonly Realm realm = new Realm("http://localhost/rp.aspx"); private readonly Uri returnTo = new Uri("http://localhost/rp.aspx"); - [TestInitialize] + [SetUp] public override void SetUp() { base.SetUp(); } @@ -27,7 +28,7 @@ namespace DotNetOpenAuth.Test.OpenId.RelyingParty { /// <summary> /// Verifies good, positive assertions are accepted. /// </summary> - [TestMethod] + [TestCase] public void Valid() { PositiveAssertionResponse assertion = this.GetPositiveAssertion(); ClaimsResponse extension = new ClaimsResponse(); @@ -37,8 +38,8 @@ namespace DotNetOpenAuth.Test.OpenId.RelyingParty { var authResponseAccessor = PositiveAuthenticationResponse_Accessor.AttachShadow(authResponse); Assert.AreEqual(AuthenticationStatus.Authenticated, authResponse.Status); Assert.IsNull(authResponse.Exception); - Assert.AreEqual<string>(assertion.ClaimedIdentifier, authResponse.ClaimedIdentifier); - Assert.AreEqual<string>(authResponse.Endpoint.FriendlyIdentifierForDisplay, authResponse.FriendlyIdentifierForDisplay); + Assert.AreEqual((string)assertion.ClaimedIdentifier, (string)authResponse.ClaimedIdentifier); + Assert.AreEqual(authResponse.Endpoint.FriendlyIdentifierForDisplay, authResponse.FriendlyIdentifierForDisplay); Assert.AreSame(extension, authResponse.GetUntrustedExtension(typeof(ClaimsResponse))); Assert.AreSame(extension, authResponse.GetUntrustedExtension<ClaimsResponse>()); Assert.IsNull(authResponse.GetCallbackArgument("a")); @@ -46,11 +47,37 @@ namespace DotNetOpenAuth.Test.OpenId.RelyingParty { } /// <summary> + /// Verifies that discovery verification of a positive assertion can match a dual identifier. + /// </summary> + [TestCase] + public void DualIdentifierMatchesInAssertionVerification() { + PositiveAssertionResponse assertion = this.GetPositiveAssertion(true); + ClaimsResponse extension = new ClaimsResponse(); + assertion.Extensions.Add(extension); + var rp = CreateRelyingParty(); + rp.SecuritySettings.AllowDualPurposeIdentifiers = true; + new PositiveAuthenticationResponse(assertion, rp); // this will throw if it fails to find a match + } + + /// <summary> + /// Verifies that discovery verification of a positive assertion cannot match a dual identifier + /// if the default settings are in place. + /// </summary> + [TestCase, ExpectedException(typeof(ProtocolException))] + public void DualIdentifierNoMatchInAssertionVerificationByDefault() { + PositiveAssertionResponse assertion = this.GetPositiveAssertion(true); + ClaimsResponse extension = new ClaimsResponse(); + assertion.Extensions.Add(extension); + var rp = CreateRelyingParty(); + new PositiveAuthenticationResponse(assertion, rp); // this will throw if it fails to find a match + } + + /// <summary> /// Verifies that the RP rejects signed solicited assertions by an OP that /// makes up a claimed Id that was not part of the original request, and /// that the OP has no authority to assert positively regarding. /// </summary> - [TestMethod, ExpectedException(typeof(ProtocolException))] + [TestCase, ExpectedException(typeof(ProtocolException))] public void SpoofedClaimedIdDetectionSolicited() { PositiveAssertionResponse assertion = this.GetPositiveAssertion(); assertion.ProviderEndpoint = new Uri("http://rogueOP"); @@ -63,7 +90,7 @@ namespace DotNetOpenAuth.Test.OpenId.RelyingParty { /// Verifies that the RP rejects positive assertions with HTTP Claimed /// Cdentifiers when RequireSsl is set to true. /// </summary> - [TestMethod, ExpectedException(typeof(ProtocolException))] + [TestCase, ExpectedException(typeof(ProtocolException))] public void InsecureIdentifiersRejectedWithRequireSsl() { PositiveAssertionResponse assertion = this.GetPositiveAssertion(); var rp = CreateRelyingParty(); @@ -71,7 +98,7 @@ namespace DotNetOpenAuth.Test.OpenId.RelyingParty { var authResponse = new PositiveAuthenticationResponse(assertion, rp); } - [TestMethod] + [TestCase] public void GetCallbackArguments() { PositiveAssertionResponse assertion = this.GetPositiveAssertion(); var rp = CreateRelyingParty(); @@ -94,10 +121,34 @@ namespace DotNetOpenAuth.Test.OpenId.RelyingParty { Assert.IsNull(authResponse.GetCallbackArgument("a")); } + /// <summary> + /// Verifies that certain problematic claimed identifiers pass through to the RP response correctly. + /// </summary> + [TestCase] + public void ProblematicClaimedId() { + var providerEndpoint = new ProviderEndpointDescription(OpenIdTestBase.OPUri, Protocol.Default.Version); + string claimed_id = BaseMockUri + "a./b."; + var se = IdentifierDiscoveryResult.CreateForClaimedIdentifier(claimed_id, claimed_id, providerEndpoint, null, null); + UriIdentifier identityUri = (UriIdentifier)se.ClaimedIdentifier; + var mockId = new MockIdentifier(identityUri, this.MockResponder, new IdentifierDiscoveryResult[] { se }); + + var positiveAssertion = this.GetPositiveAssertion(); + positiveAssertion.ClaimedIdentifier = mockId; + positiveAssertion.LocalIdentifier = mockId; + var rp = CreateRelyingParty(); + var authResponse = new PositiveAuthenticationResponse(positiveAssertion, rp); + Assert.AreEqual(AuthenticationStatus.Authenticated, authResponse.Status); + Assert.AreEqual(claimed_id, authResponse.ClaimedIdentifier.ToString()); + } + private PositiveAssertionResponse GetPositiveAssertion() { + return this.GetPositiveAssertion(false); + } + + private PositiveAssertionResponse GetPositiveAssertion(bool dualIdentifier) { Protocol protocol = Protocol.Default; PositiveAssertionResponse assertion = new PositiveAssertionResponse(protocol.Version, this.returnTo); - assertion.ClaimedIdentifier = this.GetMockIdentifier(protocol.ProtocolVersion, false); + assertion.ClaimedIdentifier = dualIdentifier ? this.GetMockDualIdentifier() : this.GetMockIdentifier(protocol.ProtocolVersion, false); assertion.LocalIdentifier = OPLocalIdentifiers[0]; assertion.ReturnTo = this.returnTo; assertion.ProviderEndpoint = OPUri; diff --git a/src/DotNetOpenAuth.Test/OpenId/RelyingParty/RelyingPartySecuritySettingsTests.cs b/src/DotNetOpenAuth.Test/OpenId/RelyingParty/RelyingPartySecuritySettingsTests.cs index 851939e..2f6d218 100644 --- a/src/DotNetOpenAuth.Test/OpenId/RelyingParty/RelyingPartySecuritySettingsTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/RelyingParty/RelyingPartySecuritySettingsTests.cs @@ -10,20 +10,20 @@ namespace DotNetOpenAuth.Test.OpenId.RelyingParty { using System.Linq; using System.Text; using DotNetOpenAuth.OpenId.RelyingParty; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; - [TestClass] + [TestFixture] public class RelyingPartySecuritySettingsTests : OpenIdTestBase { private RelyingPartySecuritySettings settings; - [TestInitialize] + [SetUp] public override void SetUp() { base.SetUp(); this.settings = new RelyingPartySecuritySettings(); } - [TestMethod] + [TestCase] public void Defaults() { Assert.IsFalse(this.settings.RejectUnsolicitedAssertions); Assert.IsFalse(this.settings.RequireSsl, "Default should be to not require SSL."); @@ -33,7 +33,7 @@ namespace DotNetOpenAuth.Test.OpenId.RelyingParty { /// Verifies that the <see cref="RelyingPartySecuritySettings.RequireSsl"/> property /// getter/setter are implemented correctly. /// </summary> - [TestMethod] + [TestCase] public void RequireSsl() { this.settings.RequireSsl = true; Assert.IsTrue(this.settings.RequireSsl); @@ -45,7 +45,7 @@ namespace DotNetOpenAuth.Test.OpenId.RelyingParty { /// Verifies that the <see cref="RelyingPartySecuritySettings.RequireDirectedIdentity"/> /// property getter/setter are implemented correctly. /// </summary> - [TestMethod] + [TestCase] public void RequireDirectedIdentity() { this.settings.RequireDirectedIdentity = true; Assert.IsTrue(this.settings.RequireDirectedIdentity); @@ -57,7 +57,7 @@ namespace DotNetOpenAuth.Test.OpenId.RelyingParty { /// Verifies that the <see cref="RelyingPartySecuritySettings.RequireAssociation"/> /// property getter/setter are implemented correctly. /// </summary> - [TestMethod] + [TestCase] public void RequireAssociation() { this.settings.RequireAssociation = true; Assert.IsTrue(this.settings.RequireAssociation); diff --git a/src/DotNetOpenAuth.Test/OpenId/RelyingParty/ServiceEndpointTests.cs b/src/DotNetOpenAuth.Test/OpenId/RelyingParty/ServiceEndpointTests.cs deleted file mode 100644 index ff15aa3..0000000 --- a/src/DotNetOpenAuth.Test/OpenId/RelyingParty/ServiceEndpointTests.cs +++ /dev/null @@ -1,195 +0,0 @@ -//----------------------------------------------------------------------- -// <copyright file="ServiceEndpointTests.cs" company="Andrew Arnott"> -// Copyright (c) Andrew Arnott. All rights reserved. -// </copyright> -//----------------------------------------------------------------------- - -namespace DotNetOpenAuth.Test.OpenId.RelyingParty { - using System; - using System.Collections.Generic; - using System.Diagnostics; - using System.IO; - using System.Text; - using DotNetOpenAuth.Messaging; - using DotNetOpenAuth.OpenId; - using DotNetOpenAuth.OpenId.Extensions.SimpleRegistration; - using DotNetOpenAuth.OpenId.Messages; - using DotNetOpenAuth.OpenId.RelyingParty; - using DotNetOpenAuth.Test.Messaging; - using Microsoft.VisualStudio.TestTools.UnitTesting; - - [TestClass] - public class ServiceEndpointTests : OpenIdTestBase { - private UriIdentifier claimedId = new UriIdentifier("http://claimedid.justatest.com"); - private XriIdentifier claimedXri = new XriIdentifier("=!9B72.7DD1.50A9.5CCD"); - private XriIdentifier userSuppliedXri = new XriIdentifier("=Arnot"); - private Uri providerEndpoint = new Uri("http://someprovider.com"); - private Identifier localId = "http://localid.someprovider.com"; - private string[] v20TypeUris = { Protocol.V20.ClaimedIdentifierServiceTypeURI }; - private string[] v11TypeUris = { Protocol.V11.ClaimedIdentifierServiceTypeURI }; - private int servicePriority = 10; - private int uriPriority = 10; - - [TestMethod] - public void Ctor() { - ServiceEndpoint se = ServiceEndpoint.CreateForClaimedIdentifier(this.claimedId, this.localId, new ProviderEndpointDescription(this.providerEndpoint, this.v20TypeUris), this.servicePriority, this.uriPriority); - Assert.AreEqual(this.claimedId, se.ClaimedIdentifier); - Assert.AreSame(this.providerEndpoint, se.ProviderEndpoint); - Assert.AreSame(this.localId, se.ProviderLocalIdentifier); - CollectionAssert<string>.AreEquivalent(this.v20TypeUris, se.ProviderSupportedServiceTypeUris); - Assert.AreEqual(this.servicePriority, ((IXrdsProviderEndpoint)se).ServicePriority); - } - - [TestMethod] - public void CtorImpliedLocalIdentifier() { - ServiceEndpoint se = ServiceEndpoint.CreateForClaimedIdentifier(this.claimedId, null, new ProviderEndpointDescription(this.providerEndpoint, this.v20TypeUris), this.servicePriority, this.uriPriority); - Assert.AreEqual(this.claimedId, se.ClaimedIdentifier); - Assert.AreSame(this.providerEndpoint, se.ProviderEndpoint); - Assert.AreSame(this.claimedId, se.ProviderLocalIdentifier); - CollectionAssert<string>.AreEquivalent(this.v20TypeUris, se.ProviderSupportedServiceTypeUris); - } - - [TestMethod] - public void ProtocolDetection() { - ServiceEndpoint se = ServiceEndpoint.CreateForClaimedIdentifier(this.claimedId, this.localId, new ProviderEndpointDescription(this.providerEndpoint, this.v20TypeUris), this.servicePriority, this.uriPriority); - Assert.AreSame(Protocol.V20, se.Protocol); - se = ServiceEndpoint.CreateForClaimedIdentifier( - this.claimedId, - this.localId, - new ProviderEndpointDescription(this.providerEndpoint, new[] { Protocol.V20.OPIdentifierServiceTypeURI }), - this.servicePriority, - this.uriPriority); - Assert.AreSame(Protocol.V20, se.Protocol); - se = ServiceEndpoint.CreateForClaimedIdentifier(this.claimedId, this.localId, new ProviderEndpointDescription(this.providerEndpoint, this.v11TypeUris), this.servicePriority, this.uriPriority); - Assert.AreSame(Protocol.V11, se.Protocol); - } - - [TestMethod, ExpectedException(typeof(ProtocolException))] - public void ProtocolDetectionWithoutClues() { - ServiceEndpoint se = ServiceEndpoint.CreateForClaimedIdentifier( - this.claimedId, - this.localId, - new ProviderEndpointDescription(this.providerEndpoint, new[] { Protocol.V20.HtmlDiscoveryLocalIdKey }), // random type URI irrelevant to detection - this.servicePriority, - this.uriPriority); - } - - [TestMethod] - public void SerializationWithUri() { - ServiceEndpoint se = ServiceEndpoint.CreateForClaimedIdentifier(this.claimedId, this.localId, new ProviderEndpointDescription(this.providerEndpoint, this.v20TypeUris), this.servicePriority, this.uriPriority); - StringBuilder sb = new StringBuilder(); - using (StringWriter sw = new StringWriter(sb)) { - se.Serialize(sw); - } - using (StringReader sr = new StringReader(sb.ToString())) { - ServiceEndpoint se2 = ServiceEndpoint.Deserialize(sr); - Assert.AreEqual(se, se2); - Assert.AreEqual(se.Protocol.Version, se2.Protocol.Version, "Particularly interested in this, since type URIs are not serialized but version info is."); - Assert.AreEqual(se.UserSuppliedIdentifier, se2.UserSuppliedIdentifier); - Assert.AreEqual(se.FriendlyIdentifierForDisplay, se2.FriendlyIdentifierForDisplay); - } - } - - [TestMethod] - public void SerializationWithXri() { - ServiceEndpoint se = ServiceEndpoint.CreateForClaimedIdentifier(this.claimedXri, this.userSuppliedXri, this.localId, new ProviderEndpointDescription(this.providerEndpoint, this.v20TypeUris), this.servicePriority, this.uriPriority); - StringBuilder sb = new StringBuilder(); - using (StringWriter sw = new StringWriter(sb)) { - se.Serialize(sw); - } - using (StringReader sr = new StringReader(sb.ToString())) { - ServiceEndpoint se2 = ServiceEndpoint.Deserialize(sr); - Assert.AreEqual(se, se2); - Assert.AreEqual(se.Protocol.Version, se2.Protocol.Version, "Particularly interested in this, since type URIs are not serialized but version info is."); - Assert.AreEqual(se.UserSuppliedIdentifier, se2.UserSuppliedIdentifier); - Assert.AreEqual(se.FriendlyIdentifierForDisplay, se2.FriendlyIdentifierForDisplay); - } - } - - [TestMethod] - public void EqualsTests() { - ServiceEndpoint se = ServiceEndpoint.CreateForClaimedIdentifier(this.claimedId, this.localId, new ProviderEndpointDescription(this.providerEndpoint, this.v20TypeUris), this.servicePriority, this.uriPriority); - ServiceEndpoint se2 = ServiceEndpoint.CreateForClaimedIdentifier(this.claimedId, this.localId, new ProviderEndpointDescription(this.providerEndpoint, this.v20TypeUris), (int?)null, (int?)null); - Assert.AreEqual(se2, se); - Assert.AreNotEqual(se, null); - Assert.AreNotEqual(null, se); - - ServiceEndpoint se3 = ServiceEndpoint.CreateForClaimedIdentifier(new UriIdentifier(this.claimedId + "a"), this.localId, new ProviderEndpointDescription(this.providerEndpoint, this.v20TypeUris), this.servicePriority, this.uriPriority); - Assert.AreNotEqual(se, se3); - se3 = ServiceEndpoint.CreateForClaimedIdentifier(this.claimedId, this.localId, new ProviderEndpointDescription(new Uri(this.providerEndpoint.AbsoluteUri + "a"), this.v20TypeUris), this.servicePriority, this.uriPriority); - Assert.AreNotEqual(se, se3); - se3 = ServiceEndpoint.CreateForClaimedIdentifier(this.claimedId, this.localId + "a", new ProviderEndpointDescription(this.providerEndpoint, this.v20TypeUris), this.servicePriority, this.uriPriority); - Assert.AreNotEqual(se, se3); - se3 = ServiceEndpoint.CreateForClaimedIdentifier(this.claimedId, this.localId, new ProviderEndpointDescription(this.providerEndpoint, this.v11TypeUris), this.servicePriority, this.uriPriority); - Assert.AreNotEqual(se, se3); - - // make sure that Collection<T>.Contains works as desired. - List<ServiceEndpoint> list = new List<ServiceEndpoint>(); - list.Add(se); - Assert.IsTrue(list.Contains(se2)); - } - - [TestMethod] - public void FriendlyIdentifierForDisplay() { - Uri providerEndpoint = new Uri("http://someprovider"); - Identifier localId = "someuser"; - string[] serviceTypeUris = new string[] { - Protocol.V20.ClaimedIdentifierServiceTypeURI, - }; - ServiceEndpoint se; - - // strip of protocol, port, query and fragment - se = ServiceEndpoint.CreateForClaimedIdentifier( - "http://someprovider.somedomain.com:79/someuser?query#frag", - localId, - new ProviderEndpointDescription(providerEndpoint, serviceTypeUris), - null, - null); - Assert.AreEqual("someprovider.somedomain.com/someuser", se.FriendlyIdentifierForDisplay); - - // unescape characters - Uri foreignUri = new Uri("http://server崎/村"); - se = ServiceEndpoint.CreateForClaimedIdentifier(foreignUri, localId, new ProviderEndpointDescription(providerEndpoint, serviceTypeUris), null, null); - Assert.AreEqual("server崎/村", se.FriendlyIdentifierForDisplay); - - // restore user supplied identifier to XRIs - se = ServiceEndpoint.CreateForClaimedIdentifier( - new XriIdentifier("=!9B72.7DD1.50A9.5CCD"), - new XriIdentifier("=Arnott崎村"), - localId, - new ProviderEndpointDescription(providerEndpoint, serviceTypeUris), - null, - null); - Assert.AreEqual("=Arnott崎村", se.FriendlyIdentifierForDisplay); - - // If UserSuppliedIdentifier is the same as the ClaimedIdentifier, don't display it twice... - se = ServiceEndpoint.CreateForClaimedIdentifier( - new XriIdentifier("=!9B72.7DD1.50A9.5CCD"), - new XriIdentifier("=!9B72.7DD1.50A9.5CCD"), - localId, - new ProviderEndpointDescription(providerEndpoint, serviceTypeUris), - null, - null); - Assert.AreEqual("=!9B72.7DD1.50A9.5CCD", se.FriendlyIdentifierForDisplay); - } - - [TestMethod] - public void IsTypeUriPresent() { - ServiceEndpoint se = ServiceEndpoint.CreateForClaimedIdentifier(this.claimedXri, this.userSuppliedXri, this.localId, new ProviderEndpointDescription(this.providerEndpoint, this.v20TypeUris), this.servicePriority, this.uriPriority); - Assert.IsTrue(se.IsTypeUriPresent(Protocol.Default.ClaimedIdentifierServiceTypeURI)); - Assert.IsFalse(se.IsTypeUriPresent("http://someother")); - } - - [TestMethod, ExpectedException(typeof(ArgumentException))] - public void IsTypeUriPresentNull() { - ServiceEndpoint se = ServiceEndpoint.CreateForClaimedIdentifier(this.claimedXri, this.userSuppliedXri, this.localId, new ProviderEndpointDescription(this.providerEndpoint, this.v20TypeUris), this.servicePriority, this.uriPriority); - se.IsTypeUriPresent(null); - } - - [TestMethod, ExpectedException(typeof(ArgumentException))] - public void IsTypeUriPresentEmpty() { - ServiceEndpoint se = ServiceEndpoint.CreateForClaimedIdentifier(this.claimedXri, this.userSuppliedXri, this.localId, new ProviderEndpointDescription(this.providerEndpoint, this.v20TypeUris), this.servicePriority, this.uriPriority); - se.IsTypeUriPresent(string.Empty); - } - } -} diff --git a/src/DotNetOpenAuth.Test/OpenId/UriIdentifierTests.cs b/src/DotNetOpenAuth.Test/OpenId/UriIdentifierTests.cs index 5a5182f..5b015ff 100644 --- a/src/DotNetOpenAuth.Test/OpenId/UriIdentifierTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/UriIdentifierTests.cs @@ -13,40 +13,40 @@ namespace DotNetOpenAuth.Test.OpenId { using DotNetOpenAuth.OpenId; using DotNetOpenAuth.OpenId.Extensions.SimpleRegistration; using DotNetOpenAuth.OpenId.RelyingParty; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; - [TestClass] + [TestFixture] public class UriIdentifierTests : OpenIdTestBase { private string goodUri = "http://blog.nerdbank.net/"; private string relativeUri = "host/path"; private string badUri = "som%-)830w8vf/?.<>,ewackedURI"; - [TestInitialize] + [SetUp] public override void SetUp() { base.SetUp(); } - [TestMethod, ExpectedException(typeof(ArgumentNullException))] + [TestCase, ExpectedException(typeof(ArgumentNullException))] public void CtorNullUri() { new UriIdentifier((Uri)null); } - [TestMethod, ExpectedException(typeof(ArgumentException))] + [TestCase, ExpectedException(typeof(ArgumentException))] public void CtorNullString() { new UriIdentifier((string)null); } - [TestMethod, ExpectedException(typeof(ArgumentException))] + [TestCase, ExpectedException(typeof(ArgumentException))] public void CtorBlank() { new UriIdentifier(string.Empty); } - [TestMethod, ExpectedException(typeof(UriFormatException))] + [TestCase, ExpectedException(typeof(UriFormatException))] public void CtorBadUri() { new UriIdentifier(this.badUri); } - [TestMethod] + [TestCase] public void CtorGoodUri() { var uri = new UriIdentifier(this.goodUri); Assert.AreEqual(new Uri(this.goodUri), uri.Uri); @@ -54,33 +54,33 @@ namespace DotNetOpenAuth.Test.OpenId { Assert.IsFalse(uri.IsDiscoverySecureEndToEnd); } - [TestMethod] + [TestCase] public void CtorStringNoSchemeSecure() { var uri = new UriIdentifier("host/path", true); Assert.AreEqual("https://host/path", uri.Uri.AbsoluteUri); Assert.IsTrue(uri.IsDiscoverySecureEndToEnd); } - [TestMethod] + [TestCase] public void CtorStringHttpsSchemeSecure() { var uri = new UriIdentifier("https://host/path", true); Assert.AreEqual("https://host/path", uri.Uri.AbsoluteUri); Assert.IsTrue(uri.IsDiscoverySecureEndToEnd); } - [TestMethod, ExpectedException(typeof(ArgumentException))] + [TestCase, ExpectedException(typeof(ArgumentException))] public void CtorStringHttpSchemeSecure() { new UriIdentifier("http://host/path", true); } - [TestMethod] + [TestCase] public void CtorUriHttpsSchemeSecure() { var uri = new UriIdentifier(new Uri("https://host/path"), true); Assert.AreEqual("https://host/path", uri.Uri.AbsoluteUri); Assert.IsTrue(uri.IsDiscoverySecureEndToEnd); } - [TestMethod, ExpectedException(typeof(ArgumentException))] + [TestCase, ExpectedException(typeof(ArgumentException))] public void CtorUriHttpSchemeSecure() { new UriIdentifier(new Uri("http://host/path"), true); } @@ -93,44 +93,73 @@ namespace DotNetOpenAuth.Test.OpenId { /// they should NOT be stripped from claimed identifiers. So the UriIdentifier /// class, which serves both identifier types, must not do the stripping. /// </remarks> - [TestMethod] + [TestCase] public void DoesNotStripFragment() { Uri original = new Uri("http://a/b#c"); UriIdentifier identifier = new UriIdentifier(original); Assert.AreEqual(original.Fragment, identifier.Uri.Fragment); } - [TestMethod] + [TestCase] public void IsValid() { Assert.IsTrue(UriIdentifier.IsValidUri(this.goodUri)); Assert.IsFalse(UriIdentifier.IsValidUri(this.badUri)); Assert.IsTrue(UriIdentifier.IsValidUri(this.relativeUri), "URL lacking http:// prefix should have worked anyway."); } - [TestMethod] + [TestCase] public void TrimFragment() { Identifier noFragment = UriIdentifier.Parse("http://a/b"); Identifier fragment = UriIdentifier.Parse("http://a/b#c"); Assert.AreSame(noFragment, noFragment.TrimFragment()); - Assert.AreEqual(noFragment, fragment.TrimFragment()); + Assert.AreEqual(noFragment.ToString(), fragment.TrimFragment().ToString()); + + // Try the problematic ones + TestAsFullAndPartialTrust(fullTrust => { + Identifier noFrag = UriIdentifier.Parse("http://a/b./c"); + Identifier frag = UriIdentifier.Parse("http://a/b./c#d"); + Assert.AreSame(noFrag, noFrag.TrimFragment()); + Assert.AreEqual(noFrag.ToString(), frag.TrimFragment().ToString()); + }); } - [TestMethod] + [TestCase] public void ToStringTest() { Assert.AreEqual(this.goodUri, new UriIdentifier(this.goodUri).ToString()); + TestAsFullAndPartialTrust(fullTrust => { + Assert.AreEqual("http://abc/D./e.?Qq#Ff", new UriIdentifier("HTTP://ABC/D./e.?Qq#Ff").ToString()); + Assert.AreEqual("http://abc/D./e.?Qq", new UriIdentifier("HTTP://ABC/D./e.?Qq").ToString()); + Assert.AreEqual("http://abc/D./e.#Ff", new UriIdentifier("HTTP://ABC/D./e.#Ff").ToString()); + Assert.AreEqual("http://abc/", new UriIdentifier("HTTP://ABC").ToString()); + Assert.AreEqual("http://abc/?q", new UriIdentifier("HTTP://ABC?q").ToString()); + Assert.AreEqual("http://abc/#f", new UriIdentifier("HTTP://ABC#f").ToString()); + }); } - [TestMethod] + [TestCase] public void EqualsTest() { - Assert.AreEqual(new UriIdentifier(this.goodUri), new UriIdentifier(this.goodUri)); - // This next test is an interesting side-effect of passing off to Uri.Equals. But it's probably ok. - Assert.AreEqual(new UriIdentifier(this.goodUri), new UriIdentifier(this.goodUri + "#frag")); - Assert.AreNotEqual(new UriIdentifier(this.goodUri), new UriIdentifier(this.goodUri + "a")); - Assert.AreNotEqual(null, new UriIdentifier(this.goodUri)); - Assert.AreEqual(this.goodUri, new UriIdentifier(this.goodUri)); - } - - [TestMethod] + TestAsFullAndPartialTrust(fulltrust => { + Assert.AreEqual(new UriIdentifier(this.goodUri), new UriIdentifier(this.goodUri)); + // This next test is an interesting side-effect of passing off to Uri.Equals. But it's probably ok. + Assert.AreEqual(new UriIdentifier(this.goodUri), new UriIdentifier(this.goodUri + "#frag")); + Assert.AreEqual(new UriIdentifier("http://a/b./c."), new UriIdentifier("http://a/b./c.#frag")); + Assert.AreNotEqual(new UriIdentifier(this.goodUri), new UriIdentifier(this.goodUri + "a")); + Assert.AreNotEqual(null, new UriIdentifier(this.goodUri)); + Assert.IsTrue(new UriIdentifier(this.goodUri).Equals(this.goodUri)); + + Assert.AreEqual(Identifier.Parse("HTTP://WWW.FOO.COM/abc", true), Identifier.Parse("http://www.foo.com/abc", true)); + Assert.AreEqual(Identifier.Parse("HTTP://WWW.FOO.COM/abc", true), Identifier.Parse("http://www.foo.com/abc", false)); + Assert.AreEqual(Identifier.Parse("HTTP://WWW.FOO.COM/abc", false), Identifier.Parse("http://www.foo.com/abc", false)); + Assert.AreNotEqual(Identifier.Parse("http://www.foo.com/abc", true), Identifier.Parse("http://www.foo.com/ABC", true)); + Assert.AreNotEqual(Identifier.Parse("http://www.foo.com/abc", true), Identifier.Parse("http://www.foo.com/ABC", false)); + Assert.AreNotEqual(Identifier.Parse("http://www.foo.com/abc", false), Identifier.Parse("http://www.foo.com/ABC", false)); + + Assert.AreNotEqual(Identifier.Parse("http://a/b./c."), Identifier.Parse("http://a/b/c.")); + Assert.AreEqual(Identifier.Parse("http://a/b./c."), Identifier.Parse("http://a/b./c.")); + }); + } + + [TestCase] public void UnicodeTest() { string unicodeUrl = "http://nerdbank.org/opaffirmative/崎村.aspx"; Assert.IsTrue(UriIdentifier.IsValidUri(unicodeUrl)); @@ -140,63 +169,7 @@ namespace DotNetOpenAuth.Test.OpenId { Assert.AreEqual(Uri.EscapeUriString(unicodeUrl), id.ToString()); } - [TestMethod] - public void HtmlDiscover_11() { - this.DiscoverHtml("html10prov", ProtocolVersion.V11, null, "http://a/b"); - this.DiscoverHtml("html10both", ProtocolVersion.V11, "http://c/d", "http://a/b"); - this.FailDiscoverHtml("html10del"); - - // Verify that HTML discovery generates the 1.x endpoints when appropriate - this.DiscoverHtml("html2010", ProtocolVersion.V11, "http://g/h", "http://e/f"); - this.DiscoverHtml("html1020", ProtocolVersion.V11, "http://g/h", "http://e/f"); - this.DiscoverHtml("html2010combinedA", ProtocolVersion.V11, "http://c/d", "http://a/b"); - this.DiscoverHtml("html2010combinedB", ProtocolVersion.V11, "http://c/d", "http://a/b"); - this.DiscoverHtml("html2010combinedC", ProtocolVersion.V11, "http://c/d", "http://a/b"); - } - - [TestMethod] - public void HtmlDiscover_20() { - this.DiscoverHtml("html20prov", ProtocolVersion.V20, null, "http://a/b"); - this.DiscoverHtml("html20both", ProtocolVersion.V20, "http://c/d", "http://a/b"); - this.FailDiscoverHtml("html20del"); - this.DiscoverHtml("html2010", ProtocolVersion.V20, "http://c/d", "http://a/b"); - this.DiscoverHtml("html1020", ProtocolVersion.V20, "http://c/d", "http://a/b"); - this.DiscoverHtml("html2010combinedA", ProtocolVersion.V20, "http://c/d", "http://a/b"); - this.DiscoverHtml("html2010combinedB", ProtocolVersion.V20, "http://c/d", "http://a/b"); - this.DiscoverHtml("html2010combinedC", ProtocolVersion.V20, "http://c/d", "http://a/b"); - this.FailDiscoverHtml("html20relative"); - } - - [TestMethod] - public void XrdsDiscoveryFromHead() { - this.MockResponder.RegisterMockResponse(new Uri("http://localhost/xrds1020.xml"), "application/xrds+xml", LoadEmbeddedFile("/Discovery/xrdsdiscovery/xrds1020.xml")); - this.DiscoverXrds("XrdsReferencedInHead.html", ProtocolVersion.V10, null, "http://a/b"); - } - - [TestMethod] - public void XrdsDiscoveryFromHttpHeader() { - WebHeaderCollection headers = new WebHeaderCollection(); - headers.Add("X-XRDS-Location", new Uri("http://localhost/xrds1020.xml").AbsoluteUri); - this.MockResponder.RegisterMockResponse(new Uri("http://localhost/xrds1020.xml"), "application/xrds+xml", LoadEmbeddedFile("/Discovery/xrdsdiscovery/xrds1020.xml")); - this.DiscoverXrds("XrdsReferencedInHttpHeader.html", ProtocolVersion.V10, null, "http://a/b", headers); - } - - [TestMethod] - public void XrdsDirectDiscovery_10() { - this.FailDiscoverXrds("xrds-irrelevant"); - this.DiscoverXrds("xrds10", ProtocolVersion.V10, null, "http://a/b"); - this.DiscoverXrds("xrds11", ProtocolVersion.V11, null, "http://a/b"); - this.DiscoverXrds("xrds1020", ProtocolVersion.V10, null, "http://a/b"); - } - - [TestMethod] - public void XrdsDirectDiscovery_20() { - this.DiscoverXrds("xrds20", ProtocolVersion.V20, null, "http://a/b"); - this.DiscoverXrds("xrds2010a", ProtocolVersion.V20, null, "http://a/b"); - this.DiscoverXrds("xrds2010b", ProtocolVersion.V20, null, "http://a/b"); - } - - [TestMethod] + [TestCase] public void NormalizeCase() { // only the host name can be normalized in casing safely. Identifier id = "http://HOST:80/PaTH?KeY=VaLUE#fRag"; @@ -206,36 +179,66 @@ namespace DotNetOpenAuth.Test.OpenId { Assert.AreEqual("https://host:80/PaTH?KeY=VaLUE#fRag", id.ToString()); } - [TestMethod] + /// <summary> + /// Verifies that URIs that contain base64 encoded path segments (such as Yahoo) are properly preserved. + /// </summary> + /// <remarks> + /// Yahoo includes a base64 encoded part as their last path segment, + /// which may end with a period. The default .NET Uri parser trims off + /// trailing periods, which breaks OpenID unless special precautions are taken. + /// </remarks> + [TestCase] + public void TrailingPeriodsNotTrimmed() { + TestAsFullAndPartialTrust(fullTrust => { + string claimedIdentifier = "https://me.yahoo.com/a/AsDf.#asdf"; + Identifier id = claimedIdentifier; + Assert.AreEqual(claimedIdentifier, id.OriginalString); + Assert.AreEqual(claimedIdentifier, id.ToString()); + + UriIdentifier idUri = new UriIdentifier(claimedIdentifier); + Assert.AreEqual(claimedIdentifier, idUri.OriginalString); + Assert.AreEqual(claimedIdentifier, idUri.ToString()); + if (fullTrust) { + Assert.AreEqual(claimedIdentifier, idUri.Uri.AbsoluteUri); + } + Assert.AreEqual(Uri.UriSchemeHttps, idUri.Uri.Scheme); // in case custom scheme tricks are played, this must still match + Assert.AreEqual("https://me.yahoo.com/a/AsDf.", idUri.TrimFragment().ToString()); + Assert.AreEqual("https://me.yahoo.com/a/AsDf.", idUri.TrimFragment().OriginalString); + Assert.AreEqual(id.ToString(), new UriIdentifier((Uri)idUri).ToString(), "Round tripping UriIdentifier->Uri->UriIdentifier failed."); + + idUri = new UriIdentifier(new Uri(claimedIdentifier)); + Assert.AreEqual(claimedIdentifier, idUri.OriginalString); + Assert.AreEqual(claimedIdentifier, idUri.ToString()); + if (fullTrust) { + Assert.AreEqual(claimedIdentifier, idUri.Uri.AbsoluteUri); + } + Assert.AreEqual(Uri.UriSchemeHttps, idUri.Uri.Scheme); // in case custom scheme tricks are played, this must still match + Assert.AreEqual("https://me.yahoo.com/a/AsDf.", idUri.TrimFragment().ToString()); + Assert.AreEqual("https://me.yahoo.com/a/AsDf.", idUri.TrimFragment().OriginalString); + Assert.AreEqual(id.ToString(), new UriIdentifier((Uri)idUri).ToString(), "Round tripping UriIdentifier->Uri->UriIdentifier failed."); + + claimedIdentifier = "https://me.yahoo.com:443/a/AsDf.#asdf"; + id = claimedIdentifier; + Assert.AreEqual(claimedIdentifier, id.OriginalString); + Assert.AreEqual("https://me.yahoo.com/a/AsDf.#asdf", id.ToString()); + }); + } + + [TestCase] public void HttpSchemePrepended() { UriIdentifier id = new UriIdentifier("www.yahoo.com"); Assert.AreEqual("http://www.yahoo.com/", id.ToString()); Assert.IsTrue(id.SchemeImplicitlyPrepended); } - ////[TestMethod, Ignore("The spec says http:// must be prepended in this case, but that just creates an invalid URI. Our UntrustedWebRequest will stop disallowed schemes.")] + ////[TestCase, Ignore("The spec says http:// must be prepended in this case, but that just creates an invalid URI. Our UntrustedWebRequest will stop disallowed schemes.")] public void CtorDisallowedScheme() { UriIdentifier id = new UriIdentifier(new Uri("ftp://host/path")); Assert.AreEqual("http://ftp://host/path", id.ToString()); Assert.IsTrue(id.SchemeImplicitlyPrepended); } - [TestMethod] - public void DiscoveryWithRedirects() { - Identifier claimedId = this.GetMockIdentifier(ProtocolVersion.V20, false); - - // Add a couple of chained redirect pages that lead to the claimedId. - Uri userSuppliedUri = new Uri("https://localhost/someSecurePage"); - Uri insecureMidpointUri = new Uri("http://localhost/insecureStop"); - this.MockResponder.RegisterMockRedirect(userSuppliedUri, insecureMidpointUri); - this.MockResponder.RegisterMockRedirect(insecureMidpointUri, new Uri(claimedId.ToString())); - - // don't require secure SSL discovery for this test. - Identifier userSuppliedIdentifier = new UriIdentifier(userSuppliedUri, false); - Assert.AreEqual(1, userSuppliedIdentifier.Discover(this.RequestHandler).Count()); - } - - [TestMethod] + [TestCase] public void TryRequireSslAdjustsIdentifier() { Identifier secureId; // Try Parse and ctor without explicit scheme @@ -256,180 +259,53 @@ namespace DotNetOpenAuth.Test.OpenId { Assert.IsFalse(id.TryRequireSsl(out secureId)); Assert.IsTrue(secureId.IsDiscoverySecureEndToEnd, "Although the TryRequireSsl failed, the created identifier should retain the Ssl status."); Assert.AreEqual("http://www.yahoo.com/", secureId.ToString()); - Assert.AreEqual(0, secureId.Discover(this.RequestHandler).Count(), "Since TryRequireSsl failed, the created Identifier should never discover anything."); + Assert.AreEqual(0, Discover(secureId).Count(), "Since TryRequireSsl failed, the created Identifier should never discover anything."); id = new UriIdentifier("http://www.yahoo.com"); Assert.IsFalse(id.TryRequireSsl(out secureId)); Assert.IsTrue(secureId.IsDiscoverySecureEndToEnd); Assert.AreEqual("http://www.yahoo.com/", secureId.ToString()); - Assert.AreEqual(0, secureId.Discover(this.RequestHandler).Count()); - } - - [TestMethod] - public void DiscoverRequireSslWithSecureRedirects() { - Identifier claimedId = this.GetMockIdentifier(ProtocolVersion.V20, true); - - // Add a couple of chained redirect pages that lead to the claimedId. - // All redirects should be secure. - Uri userSuppliedUri = new Uri("https://localhost/someSecurePage"); - Uri secureMidpointUri = new Uri("https://localhost/secureStop"); - this.MockResponder.RegisterMockRedirect(userSuppliedUri, secureMidpointUri); - this.MockResponder.RegisterMockRedirect(secureMidpointUri, new Uri(claimedId.ToString())); - - Identifier userSuppliedIdentifier = new UriIdentifier(userSuppliedUri, true); - Assert.AreEqual(1, userSuppliedIdentifier.Discover(this.RequestHandler).Count()); - } - - [TestMethod, ExpectedException(typeof(ProtocolException))] - public void DiscoverRequireSslWithInsecureRedirect() { - Identifier claimedId = this.GetMockIdentifier(ProtocolVersion.V20, true); - - // Add a couple of chained redirect pages that lead to the claimedId. - // Include an insecure HTTP jump in those redirects to verify that - // the ultimate endpoint is never found as a result of high security profile. - Uri userSuppliedUri = new Uri("https://localhost/someSecurePage"); - Uri insecureMidpointUri = new Uri("http://localhost/insecureStop"); - this.MockResponder.RegisterMockRedirect(userSuppliedUri, insecureMidpointUri); - this.MockResponder.RegisterMockRedirect(insecureMidpointUri, new Uri(claimedId.ToString())); - - Identifier userSuppliedIdentifier = new UriIdentifier(userSuppliedUri, true); - userSuppliedIdentifier.Discover(this.RequestHandler); + Assert.AreEqual(0, Discover(secureId).Count()); } - [TestMethod] - public void DiscoveryRequireSslWithInsecureXrdsInSecureHtmlHead() { - var insecureXrdsSource = this.GetMockIdentifier(ProtocolVersion.V20, false); - Uri secureClaimedUri = new Uri("https://localhost/secureId"); - - string html = string.Format("<html><head><meta http-equiv='X-XRDS-Location' content='{0}'/></head><body></body></html>", insecureXrdsSource); - this.MockResponder.RegisterMockResponse(secureClaimedUri, "text/html", html); - - Identifier userSuppliedIdentifier = new UriIdentifier(secureClaimedUri, true); - Assert.AreEqual(0, userSuppliedIdentifier.Discover(this.RequestHandler).Count()); - } - - [TestMethod] - public void DiscoveryRequireSslWithInsecureXrdsInSecureHttpHeader() { - var insecureXrdsSource = this.GetMockIdentifier(ProtocolVersion.V20, false); - - string html = "<html><head></head><body></body></html>"; - WebHeaderCollection headers = new WebHeaderCollection { - { "X-XRDS-Location", insecureXrdsSource } - }; - this.MockResponder.RegisterMockResponse(VanityUriSsl, VanityUriSsl, "text/html", headers, html); - - Identifier userSuppliedIdentifier = new UriIdentifier(VanityUriSsl, true); - Assert.AreEqual(0, userSuppliedIdentifier.Discover(this.RequestHandler).Count()); - } - - [TestMethod] - public void DiscoveryRequireSslWithInsecureXrdsButSecureLinkTags() { - var insecureXrdsSource = this.GetMockIdentifier(ProtocolVersion.V20, false); - string html = string.Format( - @" - <html><head> - <meta http-equiv='X-XRDS-Location' content='{0}'/> <!-- this one will be insecure and ignored --> - <link rel='openid2.provider' href='{1}' /> - <link rel='openid2.local_id' href='{2}' /> - </head><body></body></html>", - HttpUtility.HtmlEncode(insecureXrdsSource), - HttpUtility.HtmlEncode(OPUriSsl.AbsoluteUri), - HttpUtility.HtmlEncode(OPLocalIdentifiersSsl[1].AbsoluteUri)); - this.MockResponder.RegisterMockResponse(VanityUriSsl, "text/html", html); - - Identifier userSuppliedIdentifier = new UriIdentifier(VanityUriSsl, true); - - // We verify that the XRDS was ignored and the LINK tags were used - // because the XRDS OP-LocalIdentifier uses different local identifiers. - Assert.AreEqual(OPLocalIdentifiersSsl[1], userSuppliedIdentifier.Discover(this.RequestHandler).Single().ProviderLocalIdentifier); - } - - [TestMethod] - public void DiscoveryRequiresSslIgnoresInsecureEndpointsInXrds() { - var insecureEndpoint = GetServiceEndpoint(0, ProtocolVersion.V20, 10, false); - var secureEndpoint = GetServiceEndpoint(1, ProtocolVersion.V20, 20, true); - UriIdentifier secureClaimedId = new UriIdentifier(VanityUriSsl, true); - this.MockResponder.RegisterMockXrdsResponse(secureClaimedId, new ServiceEndpoint[] { insecureEndpoint, secureEndpoint }); - Assert.AreEqual(secureEndpoint.ProviderLocalIdentifier, secureClaimedId.Discover(this.RequestHandler).Single().ProviderLocalIdentifier); - } - - private void Discover(string url, ProtocolVersion version, Identifier expectedLocalId, string providerEndpoint, bool expectSreg, bool useRedirect) { - this.Discover(url, version, expectedLocalId, providerEndpoint, expectSreg, useRedirect, null); - } - - private void Discover(string url, ProtocolVersion version, Identifier expectedLocalId, string providerEndpoint, bool expectSreg, bool useRedirect, WebHeaderCollection headers) { - Protocol protocol = Protocol.Lookup(version); - Uri baseUrl = new Uri("http://localhost/"); - UriIdentifier claimedId = new Uri(baseUrl, url); - UriIdentifier userSuppliedIdentifier = new Uri(baseUrl, "Discovery/htmldiscovery/redirect.aspx?target=" + url); - if (expectedLocalId == null) { - expectedLocalId = claimedId; - } - Identifier idToDiscover = useRedirect ? userSuppliedIdentifier : claimedId; - - string contentType; - if (url.EndsWith("html")) { - contentType = "text/html"; - } else if (url.EndsWith("xml")) { - contentType = "application/xrds+xml"; - } else { - throw new InvalidOperationException(); - } - this.MockResponder.RegisterMockResponse(new Uri(idToDiscover), claimedId, contentType, headers ?? new WebHeaderCollection(), LoadEmbeddedFile(url)); - - ServiceEndpoint expected = ServiceEndpoint.CreateForClaimedIdentifier( - claimedId, - expectedLocalId, - new ProviderEndpointDescription(new Uri(providerEndpoint), new string[] { protocol.ClaimedIdentifierServiceTypeURI }), // services aren't checked by Equals - null, - null); - - ServiceEndpoint se = idToDiscover.Discover(this.RequestHandler).FirstOrDefault(ep => ep.Equals(expected)); - Assert.IsNotNull(se, url + " failed to be discovered."); - - // Do extra checking of service type URIs, which aren't included in - // the ServiceEndpoint.Equals method. - Assert.AreEqual(expectSreg ? 2 : 1, se.ProviderSupportedServiceTypeUris.Count); - Assert.IsTrue(se.ProviderSupportedServiceTypeUris.Contains(protocol.ClaimedIdentifierServiceTypeURI)); - Assert.AreEqual(expectSreg, se.IsExtensionSupported<ClaimsRequest>()); - } - - private void DiscoverXrds(string page, ProtocolVersion version, Identifier expectedLocalId, string providerEndpoint) { - this.DiscoverXrds(page, version, expectedLocalId, providerEndpoint, null); + /// <summary> + /// Verifies that unicode hostnames are handled. + /// </summary> + [TestCase] + public void UnicodeHostSupport() { + var id = new UriIdentifier("http://server崎/村"); + Assert.AreEqual("server崎", id.Uri.Host); } - private void DiscoverXrds(string page, ProtocolVersion version, Identifier expectedLocalId, string providerEndpoint, WebHeaderCollection headers) { - if (!page.Contains(".")) { - page += ".xml"; + /// <summary> + /// Verifies SimpleUri behavior + /// </summary> + [TestCase] + public void SimpleUri() { + Assert.AreEqual("http://abc/D./e.?Qq#Ff", new UriIdentifier.SimpleUri("HTTP://ABC/D./e.?Qq#Ff").ToString()); + Assert.AreEqual("http://abc/D./e.?Qq", new UriIdentifier.SimpleUri("HTTP://ABC/D./e.?Qq").ToString()); + Assert.AreEqual("http://abc/D./e.#Ff", new UriIdentifier.SimpleUri("HTTP://ABC/D./e.#Ff").ToString()); + Assert.AreEqual("http://abc/", new UriIdentifier.SimpleUri("HTTP://ABC/").ToString()); + Assert.AreEqual("http://abc/", new UriIdentifier.SimpleUri("HTTP://ABC").ToString()); + Assert.AreEqual("http://abc/?q", new UriIdentifier.SimpleUri("HTTP://ABC?q").ToString()); + Assert.AreEqual("http://abc/#f", new UriIdentifier.SimpleUri("HTTP://ABC#f").ToString()); + + Assert.AreEqual("http://abc/a//b", new UriIdentifier.SimpleUri("http://abc/a//b").ToString()); + Assert.AreEqual("http://abc/a%2Fb/c", new UriIdentifier.SimpleUri("http://abc/a%2fb/c").ToString()); + Assert.AreEqual("http://abc/A/c", new UriIdentifier.SimpleUri("http://abc/%41/c").ToString()); + } + + private static void TestAsFullAndPartialTrust(Action<bool> action) { + // Test a bunch of interesting URLs both with scheme substitution on and off. + Assert.IsTrue(UriIdentifier_Accessor.schemeSubstitution, "Expected scheme substitution to be working."); + action(true); + + UriIdentifier_Accessor.schemeSubstitution = false; + try { + action(false); + } finally { + UriIdentifier_Accessor.schemeSubstitution = true; } - this.Discover("/Discovery/xrdsdiscovery/" + page, version, expectedLocalId, providerEndpoint, true, false, headers); - this.Discover("/Discovery/xrdsdiscovery/" + page, version, expectedLocalId, providerEndpoint, true, true, headers); - } - - private void DiscoverHtml(string page, ProtocolVersion version, Identifier expectedLocalId, string providerEndpoint, bool useRedirect) { - this.Discover("/Discovery/htmldiscovery/" + page, version, expectedLocalId, providerEndpoint, false, useRedirect); - } - - private void DiscoverHtml(string scenario, ProtocolVersion version, Identifier expectedLocalId, string providerEndpoint) { - string page = scenario + ".html"; - this.DiscoverHtml(page, version, expectedLocalId, providerEndpoint, false); - this.DiscoverHtml(page, version, expectedLocalId, providerEndpoint, true); - } - - private void FailDiscover(string url) { - UriIdentifier userSuppliedId = new Uri(new Uri("http://localhost"), url); - - this.MockResponder.RegisterMockResponse(new Uri(userSuppliedId), userSuppliedId, "text/html", LoadEmbeddedFile(url)); - - Assert.AreEqual(0, userSuppliedId.Discover(this.RequestHandler).Count()); // ... but that no endpoint info is discoverable - } - - private void FailDiscoverHtml(string scenario) { - this.FailDiscover("/Discovery/htmldiscovery/" + scenario + ".html"); - } - - private void FailDiscoverXrds(string scenario) { - this.FailDiscover("/Discovery/xrdsdiscovery/" + scenario + ".xml"); } } } diff --git a/src/DotNetOpenAuth.Test/OpenId/XriIdentifierTests.cs b/src/DotNetOpenAuth.Test/OpenId/XriIdentifierTests.cs index 46427bb..0c80821 100644 --- a/src/DotNetOpenAuth.Test/OpenId/XriIdentifierTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/XriIdentifierTests.cs @@ -10,34 +10,34 @@ namespace DotNetOpenAuth.Test.OpenId { using System.Linq; using DotNetOpenAuth.OpenId; using DotNetOpenAuth.OpenId.RelyingParty; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; - [TestClass] + [TestFixture] public class XriIdentifierTests : OpenIdTestBase { private string goodXri = "=Andrew*Arnott"; private string badXri = "some\\wacky%^&*()non-XRI"; - [TestInitialize] + [SetUp] public override void SetUp() { base.SetUp(); } - [TestMethod, ExpectedException(typeof(ArgumentException))] + [TestCase, ExpectedException(typeof(ArgumentException))] public void CtorNull() { new XriIdentifier(null); } - [TestMethod, ExpectedException(typeof(ArgumentException))] + [TestCase, ExpectedException(typeof(ArgumentException))] public void CtorBlank() { new XriIdentifier(string.Empty); } - [TestMethod, ExpectedException(typeof(FormatException))] + [TestCase, ExpectedException(typeof(FormatException))] public void CtorBadXri() { new XriIdentifier(this.badXri); } - [TestMethod] + [TestCase] public void CtorGoodXri() { var xri = new XriIdentifier(this.goodXri); Assert.AreEqual(this.goodXri, xri.OriginalXri); @@ -45,7 +45,7 @@ namespace DotNetOpenAuth.Test.OpenId { Assert.IsFalse(xri.IsDiscoverySecureEndToEnd); } - [TestMethod] + [TestCase] public void CtorGoodXriSecure() { var xri = new XriIdentifier(this.goodXri, true); Assert.AreEqual(this.goodXri, xri.OriginalXri); @@ -53,7 +53,7 @@ namespace DotNetOpenAuth.Test.OpenId { Assert.IsTrue(xri.IsDiscoverySecureEndToEnd); } - [TestMethod] + [TestCase] public void IsValid() { Assert.IsTrue(XriIdentifier.IsValidXri(this.goodXri)); Assert.IsFalse(XriIdentifier.IsValidXri(this.badXri)); @@ -62,412 +62,36 @@ namespace DotNetOpenAuth.Test.OpenId { /// <summary> /// Verifies 2.0 spec section 7.2#1 /// </summary> - [TestMethod] + [TestCase] public void StripXriScheme() { var xri = new XriIdentifier("xri://" + this.goodXri); Assert.AreEqual("xri://" + this.goodXri, xri.OriginalXri); Assert.AreEqual(this.goodXri, xri.CanonicalXri); } - [TestMethod] + [TestCase] public void TrimFragment() { Identifier xri = new XriIdentifier(this.goodXri); Assert.AreSame(xri, xri.TrimFragment()); } - [TestMethod] + [TestCase] public void ToStringTest() { Assert.AreEqual(this.goodXri, new XriIdentifier(this.goodXri).ToString()); } - [TestMethod] + [TestCase] public void EqualsTest() { Assert.AreEqual(new XriIdentifier(this.goodXri), new XriIdentifier(this.goodXri)); Assert.AreNotEqual(new XriIdentifier(this.goodXri), new XriIdentifier(this.goodXri + "a")); Assert.AreNotEqual(null, new XriIdentifier(this.goodXri)); - Assert.AreEqual(this.goodXri, new XriIdentifier(this.goodXri)); + Assert.IsTrue(new XriIdentifier(this.goodXri).Equals(this.goodXri)); } - [TestMethod] - public void Discover() { - string xrds = @"<?xml version='1.0' encoding='UTF-8'?> -<XRD version='2.0' xmlns='xri://$xrd*($v*2.0)'> - <Query>*Arnott</Query> - <Status ceid='off' cid='verified' code='100'/> - <Expires>2008-07-14T02:03:24.000Z</Expires> - <ProviderID>xri://=</ProviderID> - <LocalID>!9b72.7dd1.50a9.5ccd</LocalID> - <CanonicalID>=!9B72.7DD1.50A9.5CCD</CanonicalID> - - <Service priority='10'> - <ProviderID>xri://!!1008</ProviderID> - <Type select='true'>xri://+i-service*(+contact)*($v*1.0)</Type> - <Type match='default' select='false'/> - <Path select='true'>(+contact)</Path> - <Path match='null' select='false'/> - <URI append='qxri' priority='1'>http://1id.com/contact/</URI> - - </Service> - <Service priority='10'> - <ProviderID>xri://!!1008</ProviderID> - <Type select='true'>xri://+i-service*(+forwarding)*($v*1.0)</Type> - <Type match='null' select='false'/> - <URI append='qxri' priority='1'>http://1id.com/</URI> - </Service> - - <Service priority='10'> - <ProviderID>xri://!!1008</ProviderID> - <Type select='true'>http://openid.net/signon/1.0</Type> - <URI append='none' priority='10'>http://1id.com/sso</URI> - </Service> -</XRD>"; - Dictionary<string, string> mocks = new Dictionary<string, string> { - { "https://xri.net/=Arnott?_xrd_r=application/xrd%2Bxml;sep=false", xrds }, - { "https://xri.net/=!9B72.7DD1.50A9.5CCD?_xrd_r=application/xrd%2Bxml;sep=false", xrds }, - }; - this.MockResponder.RegisterMockXrdsResponses(mocks); - - string expectedCanonicalId = "=!9B72.7DD1.50A9.5CCD"; - ServiceEndpoint se = this.VerifyCanonicalId("=Arnott", expectedCanonicalId); - Assert.AreEqual(Protocol.V10, se.Protocol); - Assert.AreEqual("http://1id.com/sso", se.ProviderEndpoint.ToString()); - Assert.AreEqual(se.ClaimedIdentifier, se.ProviderLocalIdentifier); - Assert.AreEqual("=Arnott", se.FriendlyIdentifierForDisplay); - } - - [TestMethod] - public void DiscoverCommunityInameCanonicalIDs() { - string llliResponse = @"<?xml version='1.0' encoding='UTF-8'?> -<XRD version='2.0' xmlns='xri://$xrd*($v*2.0)'> - <Query>*llli</Query> - <Status ceid='off' cid='verified' code='100'/> - <Expires>2008-07-14T02:21:06.000Z</Expires> - <ProviderID>xri://@</ProviderID> - <LocalID>!72cd.a072.157e.a9c6</LocalID> - <CanonicalID>@!72CD.A072.157E.A9C6</CanonicalID> - <Service priority='10'> - <ProviderID>xri://!!1003!103</ProviderID> - <Type select='true'>http://openid.net/signon/1.0</Type> - <URI append='none' priority='1'>https://login.llli.org/server/</URI> - </Service> - <Service priority='1'> - <ProviderID>xri://!!1003!103</ProviderID> - <Type match='null' select='false'/> - <Type select='true'>xri://+i-service*(+forwarding)*($v*1.0)</Type> - <Path match='default'/> - <Path>(+index)</Path> - <URI append='qxri' priority='1'>http://linksafe-forward.ezibroker.net/forwarding/</URI> - </Service> - <Service priority='10'> - <ProviderID>xri://!!1003!103</ProviderID> - <Type select='true'>xri://$res*auth*($v*2.0)</Type> - <MediaType>application/xrds+xml;trust=none</MediaType> - <URI priority='10'>http://resolve.ezibroker.net/resolve/@llli/</URI> - </Service> - <Service priority='10'> - <ProviderID>xri://!!1003!103</ProviderID> - <Type select='true'>xri://+i-service*(+contact)*($v*1.0)</Type> - <Type match='null'/> - <Path select='true'>(+contact)</Path> - <Path match='null'/> - <URI append='authority' priority='1'>http://linksafe-contact.ezibroker.net/contact/</URI> - </Service> -</XRD> -"; - string llliAreaResponse = @"<?xml version='1.0' encoding='UTF-8'?> -<XRD xmlns='xri://$xrd*($v*2.0)'> - <Query>*area</Query> - <Status cid='verified' code='100'>SUCCESS</Status> - <ServerStatus code='100'>SUCCESS</ServerStatus> - <Expires>2008-07-15T01:21:07.000Z</Expires> - <ProviderID>xri://!!1003</ProviderID> - <LocalID>0000.0000.3B9A.CA0C</LocalID> - <CanonicalID>@!72CD.A072.157E.A9C6!0000.0000.3B9A.CA0C</CanonicalID> - <Service> - <ProviderID>xri://!!1003!103</ProviderID> - <Type select='true'>http://openid.net/signon/1.0</Type> - <URI append='none' priority='1'>https://login.llli.org/server/</URI> - </Service> - <Service> - <ProviderID>xri://!!1003!103</ProviderID> - <Type select='true'>xri://+i-service*(+contact)*($v*1.0)</Type> - <Type match='null'/> - <Path select='true'>(+contact)</Path> - <Path match='null'/> - <URI append='authority' priority='1'>http://linksafe-contact.ezibroker.net/contact/</URI> - </Service> - <Service priority='1'> - <ProviderID>xri://!!1003!103</ProviderID> - <Type select='true'>xri://+i-service*(+forwarding)*($v*1.0)</Type> - <Type match='null' select='false'/> - <Path>(+index)</Path> - <Path match='default'/> - <URI append='qxri' priority='1'>http://linksafe-forward.ezibroker.net/forwarding/</URI> - </Service> - <Service> - <ProviderID>xri://!!1003!103</ProviderID> - <Type select='true'>xri://$res*auth*($v*2.0)</Type> - <MediaType>application/xrds+xml;trust=none</MediaType> - <URI>http://resolve.ezibroker.net/resolve/@llli*area/</URI> - </Service> -</XRD>"; - string llliAreaCanadaUnattachedResponse = @"<?xml version='1.0' encoding='UTF-8'?> -<XRD xmlns='xri://$xrd*($v*2.0)'> - <Query>*canada.unattached</Query> - <Status cid='verified' code='100'>SUCCESS</Status> - <ServerStatus code='100'>SUCCESS</ServerStatus> - <Expires>2008-07-15T01:21:08.000Z</Expires> - <ProviderID>xri://!!1003</ProviderID> - <LocalID>0000.0000.3B9A.CA41</LocalID> - <CanonicalID>@!72CD.A072.157E.A9C6!0000.0000.3B9A.CA0C!0000.0000.3B9A.CA41</CanonicalID> - <Service> - <ProviderID>xri://!!1003!103</ProviderID> - <Type select='true'>http://openid.net/signon/1.0</Type> - <URI append='none' priority='1'>https://login.llli.org/server/</URI> - </Service> - <Service> - <ProviderID>xri://!!1003!103</ProviderID> - <Type select='true'>xri://+i-service*(+contact)*($v*1.0)</Type> - <Type match='null'/> - <Path select='true'>(+contact)</Path> - <Path match='null'/> - <URI append='authority' priority='1'>http://linksafe-contact.ezibroker.net/contact/</URI> - </Service> - <Service priority='1'> - <ProviderID>xri://!!1003!103</ProviderID> - <Type select='true'>xri://+i-service*(+forwarding)*($v*1.0)</Type> - <Type match='null' select='false'/> - <Path>(+index)</Path> - <Path match='default'/> - <URI append='qxri' priority='1'>http://linksafe-forward.ezibroker.net/forwarding/</URI> - </Service> - <Service> - <ProviderID>xri://!!1003!103</ProviderID> - <Type select='true'>xri://$res*auth*($v*2.0)</Type> - <MediaType>application/xrds+xml;trust=none</MediaType> - <URI>http://resolve.ezibroker.net/resolve/@llli*area*canada.unattached/</URI> - </Service> -</XRD>"; - string llliAreaCanadaUnattachedAdaResponse = @"<?xml version='1.0' encoding='UTF-8'?> -<XRD xmlns='xri://$xrd*($v*2.0)'> - <Query>*ada</Query> - <Status cid='verified' code='100'>SUCCESS</Status> - <ServerStatus code='100'>SUCCESS</ServerStatus> - <Expires>2008-07-15T01:21:10.000Z</Expires> - <ProviderID>xri://!!1003</ProviderID> - <LocalID>0000.0000.3B9A.CA01</LocalID> - <CanonicalID>@!72CD.A072.157E.A9C6!0000.0000.3B9A.CA0C!0000.0000.3B9A.CA41!0000.0000.3B9A.CA01</CanonicalID> - <Service> - <ProviderID>xri://!!1003!103</ProviderID> - <Type select='true'>http://openid.net/signon/1.0</Type> - <URI append='none' priority='1'>https://login.llli.org/server/</URI> - </Service> - <Service> - <ProviderID>xri://!!1003!103</ProviderID> - <Type select='true'>xri://+i-service*(+contact)*($v*1.0)</Type> - <Type match='null'/> - <Path select='true'>(+contact)</Path> - <Path match='null'/> - <URI append='authority' priority='1'>http://linksafe-contact.ezibroker.net/contact/</URI> - </Service> - <Service priority='1'> - <ProviderID>xri://!!1003!103</ProviderID> - <Type select='true'>xri://+i-service*(+forwarding)*($v*1.0)</Type> - <Type match='null' select='false'/> - <Path>(+index)</Path> - <Path match='default'/> - <URI append='qxri' priority='1'>http://linksafe-forward.ezibroker.net/forwarding/</URI> - </Service> -</XRD>"; - string webResponse = @"<?xml version='1.0' encoding='UTF-8'?> -<XRD version='2.0' xmlns='xri://$xrd*($v*2.0)'> - <Query>*Web</Query> - <Status ceid='off' cid='verified' code='100'/> - <Expires>2008-07-14T02:21:12.000Z</Expires> - <ProviderID>xri://=</ProviderID> - <LocalID>!91f2.8153.f600.ae24</LocalID> - <CanonicalID>=!91F2.8153.F600.AE24</CanonicalID> - <Service priority='10'> - <Type select='true'>xri://+i-service*(+locator)*($v*1.0)</Type> - <Path select='true'>(+locator)</Path> - <MediaType match='default' select='false'/> - <URI append='qxri'>http://locator.fullxri.com/locator/</URI> - </Service> - <Service priority='10'> - <ProviderID>xri://=web</ProviderID> - <Type select='true'>xri://$res*auth*($v*2.0)</Type> - <Type select='true'>xri://$res*auth*($v*2.0)</Type> - <MediaType select='true'>application/xrds+xml</MediaType> - <URI append='qxri' priority='1'>https://resolve.freexri.com/ns/=web/</URI> - <URI append='qxri' priority='2'>http://resolve.freexri.com/ns/=web/</URI> - </Service> - <Service priority='10'> - <Type select='true'>http://openid.net/signon/1.0</Type> - <Type select='true'>http://specs.openid.net/auth/2.0/signon</Type> - <Path select='true'>(+login)</Path> - <Path match='default' select='false'/> - <MediaType match='default' select='false'/> - <URI append='none' priority='2'>http://authn.fullxri.com/authentication/</URI> - <URI append='none' priority='1'>https://authn.fullxri.com/authentication/</URI> - </Service> - <Service priority='10'> - <Type select='true'>xri://+i-service*(+contact)*($v*1.0)</Type> - <Type match='null' select='false'/> - <Path select='true'>(+contact)</Path> - <Path match='null' select='false'/> - <MediaType match='default' select='false'/> - <URI append='qxri'>http://contact.fullxri.com/contact/</URI> - </Service> - <KeyInfo xmlns='http://www.w3.org/2000/09/xmldsig#'> - <X509Data> - <X509Certificate> -MIIExzCCA6+gAwIBAgIJAM+MlFr0Sth6MA0GCSqGSIb3DQEBBQUAMIGdMR8wHQYD -VQQDExZTdXBlcnZpbGxhaW46IFRoZSBSb290MQswCQYDVQQGEwJVUzERMA8GA1UE -CBMITmV3IFlvcmsxDzANBgNVBAcTBkdvdGhhbTEgMB4GA1UEChMXU3VwZXJ2aWxs -YWluIFVuaXZlcnNpdHkxJzAlBgkqhkiG9w0BCQEWGHBlbmd1aW5Ac3VwZXJ2aWxs -YWluLmVkdTAeFw0wNjA4MTcxOTU5NTNaFw0xMTA4MTYxOTU5NTNaMIGdMR8wHQYD -VQQDExZTdXBlcnZpbGxhaW46IFRoZSBSb290MQswCQYDVQQGEwJVUzERMA8GA1UE -CBMITmV3IFlvcmsxDzANBgNVBAcTBkdvdGhhbTEgMB4GA1UEChMXU3VwZXJ2aWxs -YWluIFVuaXZlcnNpdHkxJzAlBgkqhkiG9w0BCQEWGHBlbmd1aW5Ac3VwZXJ2aWxs -YWluLmVkdTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAL6uFqas4dK6 -A2wTZL0viRQNJrPyFnFBDSZGib/2ijhgzed/vvmZIBM9sFpwahcuR5hvyKUe37/c -/RSZXoNDi/eiNOx4qb0l9UB6bd8qvc4V1PnLE7L+ZYcmwrvTKm4x8qXMgEv1wca2 -FPsreHNPdLiTUZ8v0tDTWi3Mgi7y47VTzJaTkcfmO1nL6xAtln5sLdH0PbMM3LAp -T1d3nwI3VdbhqqZ+6+OKEuC8gk5iH4lfrbr6C9bYS6vzIKrotHpZ3N2aIC3NMjJD -PMw/mfCuADfRNlHXgZW+0zyUkwGTMDea8qgsoAMWJGdeTIw8I1I3RhnbgLzdsNQl -b/1ZXx1uJRUCAwEAAaOCAQYwggECMB0GA1UdDgQWBBQe+xSjYTrlfraJARjMxscb -j36jvDCB0gYDVR0jBIHKMIHHgBQe+xSjYTrlfraJARjMxscbj36jvKGBo6SBoDCB -nTEfMB0GA1UEAxMWU3VwZXJ2aWxsYWluOiBUaGUgUm9vdDELMAkGA1UEBhMCVVMx -ETAPBgNVBAgTCE5ldyBZb3JrMQ8wDQYDVQQHEwZHb3RoYW0xIDAeBgNVBAoTF1N1 -cGVydmlsbGFpbiBVbml2ZXJzaXR5MScwJQYJKoZIhvcNAQkBFhhwZW5ndWluQHN1 -cGVydmlsbGFpbi5lZHWCCQDPjJRa9ErYejAMBgNVHRMEBTADAQH/MA0GCSqGSIb3 -DQEBBQUAA4IBAQC4SPBDGYAxfbXd8N5OvG0drM7a5hjXfcCZpiILlPSRpxp79yh7 -I5vVWxBxUfolwbei7PTBVy7CE27SUbSICeqWjcDCfjNjiZk6mLS80rm/TdLrHSyM -+Ujlw9MGcBGaLI+sdziDUMtTQDpeAyQTaGVbh1mx5874Hlo1VXqGYNo0RwR+iLfs -x48VuO6GbWVyxtktkE2ypz1KLWiyI056YynydRvuBCBHeRqGUixPlH9CrmeSCP2S -sfbiKnMOGXjIYbvbsTAMdW2iqg6IWa/fgxhvZoAXChM9bkhisJQc0qD0J5TJQwgr -uEyb50RJ7DWmXctSC0b3eymZ2lSXxAWNOsNy - </X509Certificate> - </X509Data> - </KeyInfo> -</XRD>"; - this.MockResponder.RegisterMockXrdsResponses(new Dictionary<string, string> { - { "https://xri.net/@llli?_xrd_r=application/xrd%2Bxml;sep=false", llliResponse }, - { "https://xri.net/@llli*area?_xrd_r=application/xrd%2Bxml;sep=false", llliAreaResponse }, - { "https://xri.net/@llli*area*canada.unattached?_xrd_r=application/xrd%2Bxml;sep=false", llliAreaCanadaUnattachedResponse }, - { "https://xri.net/@llli*area*canada.unattached*ada?_xrd_r=application/xrd%2Bxml;sep=false", llliAreaCanadaUnattachedAdaResponse }, - { "https://xri.net/=Web?_xrd_r=application/xrd%2Bxml;sep=false", webResponse }, - }); - this.VerifyCanonicalId("@llli", "@!72CD.A072.157E.A9C6"); - this.VerifyCanonicalId("@llli*area", "@!72CD.A072.157E.A9C6!0000.0000.3B9A.CA0C"); - this.VerifyCanonicalId("@llli*area*canada.unattached", "@!72CD.A072.157E.A9C6!0000.0000.3B9A.CA0C!0000.0000.3B9A.CA41"); - this.VerifyCanonicalId("@llli*area*canada.unattached*ada", "@!72CD.A072.157E.A9C6!0000.0000.3B9A.CA0C!0000.0000.3B9A.CA41!0000.0000.3B9A.CA01"); - this.VerifyCanonicalId("=Web", "=!91F2.8153.F600.AE24"); - } - - [TestMethod] - public void DiscoveryCommunityInameDelegateWithoutCanonicalID() { - this.MockResponder.RegisterMockXrdsResponses(new Dictionary<string, string> { - { "https://xri.net/=Web*andrew.arnott?_xrd_r=application/xrd%2Bxml;sep=false", @"<?xml version='1.0' encoding='UTF-8'?> -<XRD xmlns='xri://$xrd*($v*2.0)'> - <Query>*andrew.arnott</Query> - <Status cid='absent' code='100'>Success</Status> - <ServerStatus code='100'>Success</ServerStatus> - <Expires>2008-07-14T03:30:59.722Z</Expires> - <ProviderID>=!91F2.8153.F600.AE24</ProviderID> - <Service> - <Type select='true'>http://openid.net/signon/1.0</Type> - <Path select='true'>(+login)</Path> - <Path match='default'/> - <MediaType match='default'/> - <URI append='none' priority='2'>http://www.myopenid.com/server</URI> - <openid:Delegate xmlns:openid='http://openid.net/xmlns/1.0'>http://blog.nerdbank.net</openid:Delegate> - </Service> - <Service> - <ProviderID>@!7F6F.F50.A4E4.1133</ProviderID> - <Type select='true'>xri://+i-service*(+contact)*($v*1.0)</Type> - <Type match='null'/> - <Path select='true'>(+contact)</Path> - <Path match='null'/> - <MediaType match='default'/> - <URI append='qxri'>http://contact.freexri.com/contact/</URI> - </Service> - <Service> - <ProviderID>@!7F6F.F50.A4E4.1133</ProviderID> - <Type select='true'>xri://+i-service*(+forwarding)*($v*1.0)</Type> - <Path select='true'>(+index)</Path> - <Path match='default'/> - <MediaType match='default'/> - <URI append='qxri'>http://forwarding.freexri.com/forwarding/</URI> - </Service> - <Service> - <ProviderID>@!7F6F.F50.A4E4.1133</ProviderID> - <Type select='true'>http://openid.net/signon/1.0</Type> - <Path select='true'>(+login)</Path> - <Path match='default'/> - <MediaType match='default'/> - <URI append='none' priority='2'>http://authn.freexri.com/authentication/</URI> - <URI append='none' priority='1'>https://authn.freexri.com/authentication/</URI> - </Service> - <ServedBy>OpenXRI</ServedBy> -</XRD>" }, - { "https://xri.net/@id*andrewarnott?_xrd_r=application/xrd%2Bxml;sep=false", @"<?xml version='1.0' encoding='UTF-8'?> -<XRD xmlns='xri://$xrd*($v*2.0)'> - <Query>*andrewarnott</Query> - <Status cid='absent' code='100'>Success</Status> - <ServerStatus code='100'>Success</ServerStatus> - <Expires>2008-07-14T03:31:00.466Z</Expires> - <ProviderID>@!B1E8.C27B.E41C.25C3</ProviderID> - <Service> - <Type select='true'>http://openid.net/signon/1.0</Type> - <Path select='true'>(+login)</Path> - <Path match='default'/> - <MediaType match='default'/> - <URI append='none' priority='2'>http://www.myopenid.com/server</URI> - <openid:Delegate xmlns:openid='http://openid.net/xmlns/1.0'>http://blog.nerdbank.net</openid:Delegate> - </Service> - <Service> - <ProviderID>@!7F6F.F50.A4E4.1133</ProviderID> - <Type select='true'>xri://+i-service*(+contact)*($v*1.0)</Type> - <Type match='null'/> - <Path select='true'>(+contact)</Path> - <Path match='null'/> - <MediaType match='default'/> - <URI append='qxri'>http://contact.freexri.com/contact/</URI> - </Service> - <Service> - <ProviderID>@!7F6F.F50.A4E4.1133</ProviderID> - <Type select='true'>xri://+i-service*(+forwarding)*($v*1.0)</Type> - <Path select='true'>(+index)</Path> - <Path match='default'/> - <MediaType match='default'/> - <URI append='qxri'>http://forwarding.freexri.com/forwarding/</URI> - </Service> - <ServedBy>OpenXRI</ServedBy> -</XRD>" }, - }); - // Consistent with spec section 7.3.2.3, we do not permit - // delegation on XRI discovery when there is no CanonicalID present. - this.VerifyCanonicalId("=Web*andrew.arnott", null); - this.VerifyCanonicalId("@id*andrewarnott", null); - } - - [TestMethod, Ignore] // XRI parsing and normalization is not implemented (yet). + [TestCase, Ignore("XRI parsing and normalization is not implemented (yet).")] public void NormalizeCase() { Identifier id = "=!9B72.7dd1.50a9.5ccd"; Assert.AreEqual("=!9B72.7DD1.50A9.5CCD", id.ToString()); } - - private ServiceEndpoint VerifyCanonicalId(Identifier iname, string expectedClaimedIdentifier) { - ServiceEndpoint se = iname.Discover(this.RequestHandler).FirstOrDefault(); - if (expectedClaimedIdentifier != null) { - Assert.IsNotNull(se); - Assert.AreEqual(expectedClaimedIdentifier, se.ClaimedIdentifier.ToString(), "i-name {0} discovery resulted in unexpected CanonicalId", iname); - Assert.IsTrue(se.ProviderSupportedServiceTypeUris.Count > 0); - } else { - Assert.IsNull(se); - } - return se; - } } } diff --git a/src/DotNetOpenAuth.Test/Test References/DotNetOpenAuth.accessor b/src/DotNetOpenAuth.Test/Test References/DotNetOpenAuth.accessor deleted file mode 100644 index 35adf51..0000000 --- a/src/DotNetOpenAuth.Test/Test References/DotNetOpenAuth.accessor +++ /dev/null @@ -1 +0,0 @@ -DotNetOpenAuth.dll diff --git a/src/DotNetOpenAuth.Test/TestBase.cs b/src/DotNetOpenAuth.Test/TestBase.cs index c6508f6..8aeca2d 100644 --- a/src/DotNetOpenAuth.Test/TestBase.cs +++ b/src/DotNetOpenAuth.Test/TestBase.cs @@ -5,38 +5,43 @@ //----------------------------------------------------------------------- namespace DotNetOpenAuth.Test { + using System; using System.IO; using System.Reflection; using System.Web; using DotNetOpenAuth.Messaging.Reflection; using DotNetOpenAuth.OAuth.Messages; using log4net; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; /// <summary> /// The base class that all test classes inherit from. /// </summary> public class TestBase { - /// <summary> - /// The full path to the directory that contains the test ASP.NET site. - /// </summary> - internal static readonly string TestWebDirectory = Path.GetFullPath(Path.Combine(Directory.GetCurrentDirectory(), @"..\..\..\..\src\DotNetOpenAuth.TestWeb")); - private MessageDescriptionCollection messageDescriptions = new MessageDescriptionCollection(); /// <summary> - /// Gets or sets the test context which provides - /// information about and functionality for the current test run. - /// </summary> - public TestContext TestContext { get; set; } - - /// <summary> /// Gets the logger that tests should use. /// </summary> internal static ILog TestLogger { get { return TestUtilities.TestLogger; } } + /// <summary> + /// Gets the full path to the directory that contains the test ASP.NET site. + /// </summary> + internal string TestWebDirectory { + get { + // System.IO.Path.GetDirectoryName(new System.Uri(basePath).LocalPath) + string basePath = Path.GetDirectoryName(new Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath); + string relativePath = @"src\DotNetOpenAuth.TestWeb"; + for (int i = 0; !Directory.Exists(Path.Combine(basePath, relativePath)) && i < 4; i++) { + relativePath = "..\\" + relativePath; + } + return Path.GetFullPath(relativePath); + } + } + internal MessageDescriptionCollection MessageDescriptions { get { return this.messageDescriptions; } } @@ -44,7 +49,7 @@ namespace DotNetOpenAuth.Test { /// <summary> /// The TestInitialize method for the test cases. /// </summary> - [TestInitialize] + [SetUp] public virtual void SetUp() { log4net.Config.XmlConfigurator.Configure(Assembly.GetExecutingAssembly().GetManifestResourceStream("DotNetOpenAuth.Test.Logging.config")); MessageBase.LowSecurityMode = true; @@ -55,7 +60,7 @@ namespace DotNetOpenAuth.Test { /// <summary> /// The TestCleanup method for the test cases. /// </summary> - [TestCleanup] + [TearDown] public virtual void Cleanup() { log4net.LogManager.Shutdown(); } diff --git a/src/DotNetOpenAuth.Test/UriUtilTests.cs b/src/DotNetOpenAuth.Test/UriUtilTests.cs index 29e740d..a2cf1a2 100644 --- a/src/DotNetOpenAuth.Test/UriUtilTests.cs +++ b/src/DotNetOpenAuth.Test/UriUtilTests.cs @@ -9,11 +9,11 @@ namespace DotNetOpenAuth.Test { using System.Collections.Generic; using System.Linq; using System.Text; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; - [TestClass] + [TestFixture] public class UriUtilTests { - [TestMethod] + [TestCase] public void QueryStringContainPrefixedParametersNull() { Assert.IsFalse(UriUtil.QueryStringContainPrefixedParameters(null, "prefix.")); } diff --git a/src/DotNetOpenAuth.Test/UtilTests.cs b/src/DotNetOpenAuth.Test/UtilTests.cs index 5ea4d0c..0930e8d 100644 --- a/src/DotNetOpenAuth.Test/UtilTests.cs +++ b/src/DotNetOpenAuth.Test/UtilTests.cs @@ -9,14 +9,14 @@ namespace DotNetOpenAuth.Test { using System.Collections.Generic; using System.Linq; using System.Text; - using Microsoft.VisualStudio.TestTools.UnitTesting; + using NUnit.Framework; - [TestClass] + [TestFixture] public class UtilTests { /// <summary> /// Verifies ToStringDeferred generates a reasonable string for an empty, multi-line list. /// </summary> - [TestMethod] + [TestCase] public void ToStringDeferredEmptyMultiLine() { Assert.AreEqual("[]", Util.ToStringDeferred(Enumerable.Empty<string>(), true).ToString()); } |