diff options
Diffstat (limited to 'src/DotNetOAuth.Test')
18 files changed, 923 insertions, 0 deletions
diff --git a/src/DotNetOAuth.Test/.gitignore b/src/DotNetOAuth.Test/.gitignore new file mode 100644 index 0000000..58b701f --- /dev/null +++ b/src/DotNetOAuth.Test/.gitignore @@ -0,0 +1 @@ +StyleCop.Cache diff --git a/src/DotNetOAuth.Test/DotNetOAuth.Test.csproj b/src/DotNetOAuth.Test/DotNetOAuth.Test.csproj new file mode 100644 index 0000000..8f28791 --- /dev/null +++ b/src/DotNetOAuth.Test/DotNetOAuth.Test.csproj @@ -0,0 +1,87 @@ +<Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+ <PropertyGroup>
+ <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
+ <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
+ <ProductVersion>9.0.30729</ProductVersion>
+ <SchemaVersion>2.0</SchemaVersion>
+ <ProjectGuid>{4376ECC9-C346-4A99-B13C-FA93C0FBD2C9}</ProjectGuid>
+ <OutputType>Library</OutputType>
+ <AppDesignerFolder>Properties</AppDesignerFolder>
+ <RootNamespace>DotNetOAuth.Test</RootNamespace>
+ <AssemblyName>DotNetOAuth.Test</AssemblyName>
+ <TargetFrameworkVersion>v3.5</TargetFrameworkVersion>
+ <FileAlignment>512</FileAlignment>
+ <ProjectTypeGuids>{3AC096D0-A1C2-E12C-1390-A8335801FDAB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
+ </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>
+ </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>
+ </PropertyGroup>
+ <PropertyGroup Condition=" '$(Sign)' == 'true' ">
+ <SignAssembly>true</SignAssembly>
+ <AssemblyOriginatorKeyFile>..\official-build-key.pfx</AssemblyOriginatorKeyFile>
+ </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.VisualStudio.QualityTools.UnitTestFramework, Version=9.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL" />
+ <Reference Include="System" />
+ <Reference Include="System.Core">
+ <RequiredTargetFramework>3.5</RequiredTargetFramework>
+ </Reference>
+ <Reference Include="System.Data" />
+ <Reference Include="System.Data.DataSetExtensions">
+ <RequiredTargetFramework>3.5</RequiredTargetFramework>
+ </Reference>
+ <Reference Include="System.Runtime.Serialization">
+ <RequiredTargetFramework>3.0</RequiredTargetFramework>
+ </Reference>
+ <Reference Include="System.Web" />
+ <Reference Include="System.Xml" />
+ <Reference Include="System.Xml.Linq">
+ <RequiredTargetFramework>3.5</RequiredTargetFramework>
+ </Reference>
+ </ItemGroup>
+ <ItemGroup>
+ <Compile Include="MessagingUtilitiesTest.cs" />
+ <Compile Include="Messaging\ChannelTests.cs" />
+ <Compile Include="Messaging\DictionaryXmlReaderTests.cs" />
+ <Compile Include="Mocks\TestDirectedMessage.cs" />
+ <Compile Include="Mocks\TestBadChannel.cs" />
+ <Compile Include="OAuthChannelTests.cs" />
+ <Compile Include="Messaging\MessageSerializerTests.cs" />
+ <Compile Include="Mocks\TestChannel.cs" />
+ <Compile Include="Mocks\TestMessage.cs" />
+ <Compile Include="Mocks\TestMessageTypeProvider.cs" />
+ <Compile Include="Properties\AssemblyInfo.cs" />
+ <Compile Include="Messaging\ResponseTest.cs" />
+ <Compile Include="ServiceProviderTest.cs" />
+ <Compile Include="TestBase.cs" />
+ </ItemGroup>
+ <ItemGroup>
+ <ProjectReference Include="..\DotNetOAuth\DotNetOAuth.csproj">
+ <Project>{3191B653-F76D-4C1A-9A5A-347BC3AAAAB7}</Project>
+ <Name>DotNetOAuth</Name>
+ </ProjectReference>
+ </ItemGroup>
+ <ItemGroup>
+ <EmbeddedResource Include="Logging.config" />
+ </ItemGroup>
+ <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
+ <Import Project="..\..\tools\DotNetOAuth.Versioning.targets" />
+</Project>
\ No newline at end of file diff --git a/src/DotNetOAuth.Test/Logging.config b/src/DotNetOAuth.Test/Logging.config new file mode 100644 index 0000000..a1d675b --- /dev/null +++ b/src/DotNetOAuth.Test/Logging.config @@ -0,0 +1,33 @@ +<?xml version="1.0" encoding="utf-8" ?>
+<log4net>
+ <appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
+ <file value="Testing.log" />
+ <appendToFile value="true" />
+ <rollingStyle value="Size" />
+ <maxSizeRollBackups value="10" />
+ <maximumFileSize value="1024KB" />
+ <staticLogFileName value="true" />
+ <layout type="log4net.Layout.PatternLayout">
+ <conversionPattern value="%date [%thread] %-5level %logger - %message%newline" />
+ </layout>
+ </appender>
+ <appender name="TraceAppender" type="log4net.Appender.TraceAppender">
+ <immediateFlush value="true" />
+ <layout type="log4net.Layout.PatternLayout">
+ <conversionPattern value="%-5level - %message%newline" />
+ </layout>
+ </appender>
+ <!-- Setup the root category, add the appenders and set the default level -->
+ <root>
+ <level value="Info" />
+ <!--<appender-ref ref="RollingFileAppender" />-->
+ <appender-ref ref="TraceAppender" />
+ </root>
+ <!-- Specify the level for some specific categories -->
+ <logger name="DotNetOpenId">
+ <level value="Off" />
+ </logger>
+ <logger name="DotNetOpenId.Test">
+ <level value="Info" />
+ </logger>
+</log4net>
diff --git a/src/DotNetOAuth.Test/Messaging/ChannelTests.cs b/src/DotNetOAuth.Test/Messaging/ChannelTests.cs new file mode 100644 index 0000000..a2909c4 --- /dev/null +++ b/src/DotNetOAuth.Test/Messaging/ChannelTests.cs @@ -0,0 +1,107 @@ +//-----------------------------------------------------------------------
+// <copyright file="ChannelTests.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOAuth.Test.Messaging {
+ using System;
+ using System.Collections.Generic;
+ using System.IO;
+ using System.Net;
+ using DotNetOAuth.Messaging;
+ using DotNetOAuth.Test.Mocks;
+ using Microsoft.VisualStudio.TestTools.UnitTesting;
+
+ [TestClass]
+ public class ChannelTests : TestBase {
+ private Channel channel;
+
+ [TestInitialize]
+ public override void SetUp() {
+ base.SetUp();
+
+ this.channel = new TestChannel();
+ }
+
+ [TestMethod, ExpectedException(typeof(ArgumentNullException))]
+ public void CtorNull() {
+ // This bad channel is deliberately constructed to pass null to
+ // its protected base class' constructor.
+ new TestBadChannel();
+ }
+
+ [TestMethod]
+ public void DequeueIndirectOrResponseMessageReturnsNull() {
+ Assert.IsNull(this.channel.DequeueIndirectOrResponseMessage());
+ }
+
+ [TestMethod]
+ public void ReadFromRequestQueryString() {
+ this.ParameterizedReceiveTest("GET");
+ }
+
+ [TestMethod]
+ public void ReadFromRequestForm() {
+ this.ParameterizedReceiveTest("POST");
+ }
+
+ [TestMethod]
+ public void SendIndirectMessage() {
+ IProtocolMessage message = new TestDirectedMessage {
+ Age = 15,
+ Name = "Andrew",
+ Location = new Uri("http://host/path"),
+ Recipient = new Uri("http://provider/path"),
+ };
+ this.channel.Send(message);
+ Response response = this.channel.DequeueIndirectOrResponseMessage();
+ Assert.AreEqual(HttpStatusCode.Redirect, response.Status);
+ StringAssert.StartsWith(response.Headers[HttpResponseHeader.Location], "http://provider/path");
+ StringAssert.Contains(response.Headers[HttpResponseHeader.Location], "age=15");
+ StringAssert.Contains(response.Headers[HttpResponseHeader.Location], "Name=Andrew");
+ StringAssert.Contains(response.Headers[HttpResponseHeader.Location], "Location=http%3a%2f%2fhost%2fpath");
+ }
+
+ private static HttpRequestInfo CreateHttpRequest(string method, IDictionary<string, string> fields) {
+ string query = MessagingUtilities.CreateQueryString(fields);
+ UriBuilder requestUri = new UriBuilder("http://localhost/path");
+ WebHeaderCollection headers = new WebHeaderCollection();
+ MemoryStream ms = new MemoryStream();
+ if (method == "POST") {
+ headers.Add(HttpRequestHeader.ContentType, "application/x-www-form-urlencoded");
+ StreamWriter sw = new StreamWriter(ms);
+ sw.Write(query);
+ sw.Flush();
+ ms.Position = 0;
+ } else if (method == "GET") {
+ requestUri.Query = query;
+ } else {
+ throw new ArgumentOutOfRangeException("method", method, "Expected POST or GET");
+ }
+ HttpRequestInfo request = new HttpRequestInfo {
+ HttpMethod = method,
+ Url = requestUri.Uri,
+ Headers = headers,
+ InputStream = ms,
+ };
+
+ return request;
+ }
+
+ private void ParameterizedReceiveTest(string method) {
+ var fields = new Dictionary<string, string> {
+ { "age", "15" },
+ { "Name", "Andrew" },
+ { "Location", "http://hostb/pathB" },
+ };
+ IProtocolMessage requestMessage = this.channel.ReadFromRequest(CreateHttpRequest(method, fields));
+ Assert.IsNotNull(requestMessage);
+ Assert.IsInstanceOfType(requestMessage, typeof(TestMessage));
+ TestMessage testMessage = (TestMessage)requestMessage;
+ Assert.AreEqual(15, testMessage.Age);
+ Assert.AreEqual("Andrew", testMessage.Name);
+ Assert.AreEqual("http://hostb/pathB", testMessage.Location.AbsoluteUri);
+ }
+ }
+}
diff --git a/src/DotNetOAuth.Test/Messaging/DictionaryXmlReaderTests.cs b/src/DotNetOAuth.Test/Messaging/DictionaryXmlReaderTests.cs new file mode 100644 index 0000000..3dc3238 --- /dev/null +++ b/src/DotNetOAuth.Test/Messaging/DictionaryXmlReaderTests.cs @@ -0,0 +1,26 @@ +//-----------------------------------------------------------------------
+// <copyright file="DictionaryXmlReaderTests.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOAuth.Test.Messaging {
+ using System;
+ using System.Collections.Generic;
+ using System.Xml.Linq;
+ using DotNetOAuth.Messaging;
+ using Microsoft.VisualStudio.TestTools.UnitTesting;
+
+ [TestClass]
+ public class DictionaryXmlReaderTests : TestBase {
+ [TestMethod, ExpectedException(typeof(ArgumentNullException))]
+ public void CreateWithNullRootElement() {
+ DictionaryXmlReader.Create(null, new Dictionary<string, string>());
+ }
+
+ [TestMethod, ExpectedException(typeof(ArgumentNullException))]
+ public void CreateWithNullFields() {
+ DictionaryXmlReader.Create(XName.Get("name", "ns"), null);
+ }
+ }
+}
diff --git a/src/DotNetOAuth.Test/Messaging/MessageSerializerTests.cs b/src/DotNetOAuth.Test/Messaging/MessageSerializerTests.cs new file mode 100644 index 0000000..5cb5375 --- /dev/null +++ b/src/DotNetOAuth.Test/Messaging/MessageSerializerTests.cs @@ -0,0 +1,142 @@ +//-----------------------------------------------------------------------
+// <copyright file="MessageSerializerTests.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOAuth.Test.Messaging {
+ using System;
+ using System.Collections.Generic;
+ using DotNetOAuth.Messaging;
+ using Microsoft.VisualStudio.TestTools.UnitTesting;
+
+ /// <summary>
+ /// Tests for the <see cref="MessageSerializer"/> class.
+ /// </summary>
+ [TestClass()]
+ public class MessageSerializerTests : TestBase {
+ [TestMethod, ExpectedException(typeof(ArgumentNullException))]
+ public void SerializeNull() {
+ var serializer = MessageSerializer.Get(typeof(Mocks.TestMessage));
+ serializer.Serialize(null);
+ }
+
+ [TestMethod, ExpectedException(typeof(ArgumentNullException))]
+ public void SerializeNullFields() {
+ var serializer = MessageSerializer.Get(typeof(Mocks.TestMessage));
+ serializer.Serialize(null, new Mocks.TestMessage());
+ }
+
+ [TestMethod, ExpectedException(typeof(ArgumentNullException))]
+ public void SerializeNullMessage() {
+ var serializer = MessageSerializer.Get(typeof(Mocks.TestMessage));
+ serializer.Serialize(new Dictionary<string, string>(), null);
+ }
+
+ [TestMethod, ExpectedException(typeof(ArgumentException))]
+ public void GetInvalidMessageType() {
+ MessageSerializer.Get(typeof(string));
+ }
+
+ [TestMethod, ExpectedException(typeof(ArgumentNullException))]
+ public void GetNullType() {
+ MessageSerializer.Get(null);
+ }
+
+ [TestMethod]
+ public void GetReturnsSameSerializerTwice() {
+ Assert.AreSame(MessageSerializer.Get(typeof(Mocks.TestMessage)), MessageSerializer.Get(typeof(Mocks.TestMessage)));
+ }
+
+ [TestMethod, ExpectedException(typeof(ProtocolException))]
+ public void SerializeInvalidMessage() {
+ var serializer = MessageSerializer.Get(typeof(Mocks.TestMessage));
+ Dictionary<string, string> fields = new Dictionary<string, string>(StringComparer.Ordinal);
+ Mocks.TestMessage message = new Mocks.TestMessage();
+ message.EmptyMember = "invalidvalue";
+ serializer.Serialize(message);
+ }
+
+ [TestMethod()]
+ public void SerializeTest() {
+ var serializer = MessageSerializer.Get(typeof(Mocks.TestMessage));
+ var message = new Mocks.TestMessage { Age = 15, Name = "Andrew", Location = new Uri("http://localhost") };
+ IDictionary<string, string> actual = serializer.Serialize(message);
+ Assert.AreEqual(3, actual.Count);
+
+ // Test case sensitivity of generated dictionary
+ Assert.IsFalse(actual.ContainsKey("Age"));
+ Assert.IsTrue(actual.ContainsKey("age"));
+
+ // Test contents of dictionary
+ Assert.AreEqual("15", actual["age"]);
+ Assert.AreEqual("Andrew", actual["Name"]);
+ Assert.AreEqual("http://localhost/", actual["Location"]);
+ Assert.IsFalse(actual.ContainsKey("EmptyMember"));
+ }
+
+ [TestMethod]
+ public void SerializeToExistingDictionary() {
+ var serializer = MessageSerializer.Get(typeof(Mocks.TestMessage));
+ var message = new Mocks.TestMessage { Age = 15, Name = "Andrew" };
+ var fields = new Dictionary<string, string>();
+ fields["someExtraField"] = "someValue";
+ serializer.Serialize(fields, message);
+ Assert.AreEqual(3, fields.Count);
+ Assert.AreEqual("15", fields["age"]);
+ Assert.AreEqual("Andrew", fields["Name"]);
+ Assert.AreEqual("someValue", fields["someExtraField"]);
+ }
+
+ [TestMethod, ExpectedException(typeof(ArgumentNullException))]
+ public void DeserializeNull() {
+ var serializer = MessageSerializer.Get(typeof(Mocks.TestMessage));
+ serializer.Deserialize(null);
+ }
+
+ [TestMethod()]
+ public void DeserializeSimple() {
+ var serializer = MessageSerializer.Get(typeof(Mocks.TestMessage));
+ Dictionary<string, string> fields = new Dictionary<string, string>(StringComparer.Ordinal);
+ // We deliberately do this OUT of alphabetical order (caps would go first),
+ // since DataContractSerializer demands things to be IN alphabetical order.
+ fields["age"] = "15";
+ fields["Name"] = "Andrew";
+ var actual = (Mocks.TestMessage)serializer.Deserialize(fields);
+ Assert.AreEqual(15, actual.Age);
+ Assert.AreEqual("Andrew", actual.Name);
+ Assert.IsNull(actual.EmptyMember);
+ }
+
+ [TestMethod]
+ public void DeserializeWithExtraFields() {
+ var serializer = MessageSerializer.Get(typeof(Mocks.TestMessage));
+ Dictionary<string, string> fields = new Dictionary<string, string>(StringComparer.Ordinal);
+ fields["age"] = "15";
+ fields["Name"] = "Andrew";
+ // Add some field that is not recognized by the class. This simulates a querystring with
+ // more parameters than are actually interesting to the protocol message.
+ fields["someExtraField"] = "asdf";
+ var actual = (Mocks.TestMessage)serializer.Deserialize(fields);
+ Assert.AreEqual(15, actual.Age);
+ Assert.AreEqual("Andrew", actual.Name);
+ Assert.IsNull(actual.EmptyMember);
+ }
+
+ [TestMethod, ExpectedException(typeof(ProtocolException))]
+ public void DeserializeEmpty() {
+ var serializer = MessageSerializer.Get(typeof(Mocks.TestMessage));
+ var fields = new Dictionary<string, string>(StringComparer.Ordinal);
+ serializer.Deserialize(fields);
+ }
+
+ [TestMethod, ExpectedException(typeof(ProtocolException))]
+ public void DeserializeInvalidMessage() {
+ var serializer = MessageSerializer.Get(typeof(Mocks.TestMessage));
+ Dictionary<string, string> fields = new Dictionary<string, string>(StringComparer.Ordinal);
+ // Set an disallowed value.
+ fields["age"] = "-1";
+ serializer.Deserialize(fields);
+ }
+ }
+}
diff --git a/src/DotNetOAuth.Test/Messaging/ResponseTest.cs b/src/DotNetOAuth.Test/Messaging/ResponseTest.cs new file mode 100644 index 0000000..c1c7dff --- /dev/null +++ b/src/DotNetOAuth.Test/Messaging/ResponseTest.cs @@ -0,0 +1,19 @@ +//-----------------------------------------------------------------------
+// <copyright file="ResponseTest.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOAuth.Test.Messaging {
+ using System;
+ using DotNetOAuth.Messaging;
+ using Microsoft.VisualStudio.TestTools.UnitTesting;
+
+ [TestClass]
+ public class ResponseTest : TestBase {
+ [TestMethod, ExpectedException(typeof(InvalidOperationException))]
+ public void SendWithoutAspNetContext() {
+ new Response().Send();
+ }
+ }
+}
diff --git a/src/DotNetOAuth.Test/MessagingUtilitiesTest.cs b/src/DotNetOAuth.Test/MessagingUtilitiesTest.cs new file mode 100644 index 0000000..cc3e552 --- /dev/null +++ b/src/DotNetOAuth.Test/MessagingUtilitiesTest.cs @@ -0,0 +1,99 @@ +//-----------------------------------------------------------------------
+// <copyright file="MessagingUtilitiesTest.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOAuth.Test
+{
+ using System;
+ using System.Collections.Generic;
+ using System.Collections.Specialized;
+ using System.IO;
+ using System.Net;
+ using System.Web;
+ using DotNetOAuth.Messaging;
+ using Microsoft.VisualStudio.TestTools.UnitTesting;
+
+ [TestClass]
+ public class MessagingUtilitiesTest : TestBase {
+ [TestMethod]
+ public void CreateQueryString() {
+ var args = new Dictionary<string, string>();
+ args.Add("a", "b");
+ args.Add("c/d", "e/f");
+ Assert.AreEqual("a=b&c%2fd=e%2ff", MessagingUtilities.CreateQueryString(args));
+ }
+
+ [TestMethod]
+ public void CreateQueryStringEmptyCollection() {
+ Assert.AreEqual(0, MessagingUtilities.CreateQueryString(new Dictionary<string, string>()).Length);
+ }
+
+ [TestMethod, ExpectedException(typeof(ArgumentNullException))]
+ public void CreateQueryStringNullDictionary() {
+ MessagingUtilities.CreateQueryString(null);
+ }
+
+ [TestMethod]
+ public void AppendQueryArgs() {
+ UriBuilder uri = new UriBuilder("http://baseline.org/page");
+ var args = new Dictionary<string, string>();
+ args.Add("a", "b");
+ args.Add("c/d", "e/f");
+ MessagingUtilities.AppendQueryArgs(uri, args);
+ Assert.AreEqual("http://baseline.org/page?a=b&c%2fd=e%2ff", uri.Uri.AbsoluteUri);
+ args.Clear();
+ args.Add("g", "h");
+ MessagingUtilities.AppendQueryArgs(uri, args);
+ Assert.AreEqual("http://baseline.org/page?a=b&c%2fd=e%2ff&g=h", uri.Uri.AbsoluteUri);
+ }
+
+ [TestMethod, ExpectedException(typeof(ArgumentNullException))]
+ public void AppendQueryArgsNullUriBuilder() {
+ MessagingUtilities.AppendQueryArgs(null, new Dictionary<string, string>());
+ }
+
+ [TestMethod]
+ public void AppendQueryArgsNullDictionary() {
+ MessagingUtilities.AppendQueryArgs(new UriBuilder(), null);
+ }
+
+ [TestMethod]
+ public void ToDictionary() {
+ NameValueCollection nvc = new NameValueCollection();
+ nvc["a"] = "b";
+ nvc["c"] = "d";
+ Dictionary<string, string> actual = MessagingUtilities.ToDictionary(nvc);
+ Assert.AreEqual(nvc.Count, actual.Count);
+ Assert.AreEqual(nvc["a"], actual["a"]);
+ Assert.AreEqual(nvc["c"], actual["c"]);
+ }
+
+ [TestMethod]
+ public void ToDictionaryNull() {
+ Assert.IsNull(MessagingUtilities.ToDictionary(null));
+ }
+
+ [TestMethod, ExpectedException(typeof(ArgumentNullException))]
+ public void ApplyHeadersToResponseNullResponse() {
+ MessagingUtilities.ApplyHeadersToResponse(new WebHeaderCollection(), null);
+ }
+
+ [TestMethod, ExpectedException(typeof(ArgumentNullException))]
+ public void ApplyHeadersToResponseNullHeaders() {
+ MessagingUtilities.ApplyHeadersToResponse(null, new HttpResponse(new StringWriter()));
+ }
+
+ [TestMethod]
+ public void ApplyHeadersToResponse() {
+ var headers = new WebHeaderCollection();
+ headers[HttpResponseHeader.ContentType] = "application/binary";
+
+ var response = new HttpResponse(new StringWriter());
+ MessagingUtilities.ApplyHeadersToResponse(headers, response);
+
+ Assert.AreEqual(headers[HttpResponseHeader.ContentType], response.ContentType);
+ }
+ }
+}
diff --git a/src/DotNetOAuth.Test/Mocks/TestBadChannel.cs b/src/DotNetOAuth.Test/Mocks/TestBadChannel.cs new file mode 100644 index 0000000..20fe03a --- /dev/null +++ b/src/DotNetOAuth.Test/Mocks/TestBadChannel.cs @@ -0,0 +1,42 @@ +//-----------------------------------------------------------------------
+// <copyright file="TestBadChannel.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOAuth.Test.Mocks {
+ using System;
+ using System.Collections.Generic;
+ using System.Linq;
+ using System.Text;
+ using DotNetOAuth.Messaging;
+
+ /// <summary>
+ /// A Channel derived type that passes null to the protected constructor.
+ /// </summary>
+ internal class TestBadChannel : Channel {
+ internal TestBadChannel()
+ : base(null) {
+ }
+
+ protected internal override IProtocolMessage Request(IDirectedProtocolMessage request) {
+ throw new NotImplementedException();
+ }
+
+ protected internal override IProtocolMessage ReadFromResponse(System.IO.Stream responseStream) {
+ throw new NotImplementedException();
+ }
+
+ protected override void SendDirectMessageResponse(IProtocolMessage response) {
+ throw new NotImplementedException();
+ }
+
+ protected override void ReportErrorToUser(ProtocolException exception) {
+ throw new NotImplementedException();
+ }
+
+ protected override void ReportErrorAsDirectResponse(ProtocolException exception) {
+ throw new NotImplementedException();
+ }
+ }
+}
diff --git a/src/DotNetOAuth.Test/Mocks/TestChannel.cs b/src/DotNetOAuth.Test/Mocks/TestChannel.cs new file mode 100644 index 0000000..1920a38 --- /dev/null +++ b/src/DotNetOAuth.Test/Mocks/TestChannel.cs @@ -0,0 +1,39 @@ +//-----------------------------------------------------------------------
+// <copyright file="TestChannel.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOAuth.Test.Mocks {
+ using System;
+ using System.Collections.Generic;
+ using System.Linq;
+ using System.Text;
+ using DotNetOAuth.Messaging;
+
+ internal class TestChannel : Channel {
+ internal TestChannel()
+ : base(new TestMessageTypeProvider()) {
+ }
+
+ protected internal override IProtocolMessage Request(IDirectedProtocolMessage request) {
+ throw new NotImplementedException();
+ }
+
+ protected internal override IProtocolMessage ReadFromResponse(System.IO.Stream responseStream) {
+ throw new NotImplementedException();
+ }
+
+ protected override void SendDirectMessageResponse(IProtocolMessage response) {
+ throw new NotImplementedException();
+ }
+
+ protected override void ReportErrorToUser(ProtocolException exception) {
+ throw new NotImplementedException();
+ }
+
+ protected override void ReportErrorAsDirectResponse(ProtocolException exception) {
+ throw new NotImplementedException();
+ }
+ }
+}
diff --git a/src/DotNetOAuth.Test/Mocks/TestDirectedMessage.cs b/src/DotNetOAuth.Test/Mocks/TestDirectedMessage.cs new file mode 100644 index 0000000..6972624 --- /dev/null +++ b/src/DotNetOAuth.Test/Mocks/TestDirectedMessage.cs @@ -0,0 +1,47 @@ +//-----------------------------------------------------------------------
+// <copyright file="TestDirectedMessage.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOAuth.Test.Mocks {
+ using System;
+ using System.Runtime.Serialization;
+ using DotNetOAuth.Messaging;
+
+ [DataContract(Namespace = Protocol.DataContractNamespaceV10)]
+ internal class TestDirectedMessage : IDirectedProtocolMessage {
+ [DataMember(Name = "age", IsRequired = true)]
+ public int Age { get; set; }
+ [DataMember]
+ public string Name { get; set; }
+ [DataMember]
+ public string EmptyMember { get; set; }
+ [DataMember]
+ public Uri Location { get; set; }
+
+ #region IDirectedProtocolMessage Members
+
+ public Uri Recipient { get; internal set; }
+
+ #endregion
+
+ #region IProtocolMessage Members
+
+ Protocol IProtocolMessage.Protocol {
+ get { return Protocol.V10; }
+ }
+
+ MessageTransport IProtocolMessage.Transport {
+ get { return MessageTransport.Direct; }
+ }
+
+ void IProtocolMessage.EnsureValidMessage() {
+ if (this.EmptyMember != null || this.Age < 0) {
+ throw new ProtocolException();
+ }
+ }
+
+ #endregion
+ }
+}
diff --git a/src/DotNetOAuth.Test/Mocks/TestMessage.cs b/src/DotNetOAuth.Test/Mocks/TestMessage.cs new file mode 100644 index 0000000..8c47717 --- /dev/null +++ b/src/DotNetOAuth.Test/Mocks/TestMessage.cs @@ -0,0 +1,41 @@ +//-----------------------------------------------------------------------
+// <copyright file="TestMessage.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOAuth.Test.Mocks {
+ using System;
+ using System.Runtime.Serialization;
+ using DotNetOAuth.Messaging;
+
+ [DataContract(Namespace = Protocol.DataContractNamespaceV10)]
+ internal class TestMessage : IProtocolMessage {
+ [DataMember(Name = "age", IsRequired = true)]
+ public int Age { get; set; }
+ [DataMember]
+ public string Name { get; set; }
+ [DataMember]
+ public string EmptyMember { get; set; }
+ [DataMember]
+ public Uri Location { get; set; }
+
+ #region IProtocolMessage Members
+
+ Protocol IProtocolMessage.Protocol {
+ get { return Protocol.V10; }
+ }
+
+ MessageTransport IProtocolMessage.Transport {
+ get { return MessageTransport.Direct; }
+ }
+
+ void IProtocolMessage.EnsureValidMessage() {
+ if (this.EmptyMember != null || this.Age < 0) {
+ throw new ProtocolException();
+ }
+ }
+
+ #endregion
+ }
+}
diff --git a/src/DotNetOAuth.Test/Mocks/TestMessageTypeProvider.cs b/src/DotNetOAuth.Test/Mocks/TestMessageTypeProvider.cs new file mode 100644 index 0000000..647a09f --- /dev/null +++ b/src/DotNetOAuth.Test/Mocks/TestMessageTypeProvider.cs @@ -0,0 +1,31 @@ +//-----------------------------------------------------------------------
+// <copyright file="TestMessageTypeProvider.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOAuth.Test.Mocks {
+ using System;
+ using System.Collections.Generic;
+ using System.Linq;
+ using System.Text;
+ using DotNetOAuth.Messaging;
+
+ internal class TestMessageTypeProvider : IMessageTypeProvider {
+ #region IMessageTypeProvider Members
+
+ public Type GetRequestMessageType(IDictionary<string, string> fields) {
+ if (fields.ContainsKey("age")) {
+ return typeof(TestMessage);
+ } else {
+ return null;
+ }
+ }
+
+ public Type GetResponseMessageType(IProtocolMessage request, IDictionary<string, string> fields) {
+ return this.GetRequestMessageType(fields);
+ }
+
+ #endregion
+ }
+}
diff --git a/src/DotNetOAuth.Test/OAuthChannelTests.cs b/src/DotNetOAuth.Test/OAuthChannelTests.cs new file mode 100644 index 0000000..1099dc6 --- /dev/null +++ b/src/DotNetOAuth.Test/OAuthChannelTests.cs @@ -0,0 +1,49 @@ +//-----------------------------------------------------------------------
+// <copyright file="OAuthChannelTests.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOAuth.Test {
+ using System;
+ using System.Collections.Generic;
+ using System.Text;
+ using DotNetOAuth.Messaging;
+ using Microsoft.VisualStudio.TestTools.UnitTesting;
+
+ [TestClass]
+ public class OAuthChannelTests : TestBase {
+ private Channel channel;
+
+ [TestInitialize]
+ public override void SetUp() {
+ base.SetUp();
+
+ this.channel = new OAuthChannel();
+ }
+
+ [TestMethod, Ignore]
+ public void ReadFromRequestAuthorization() {
+ }
+
+ internal static string CreateAuthorizationHeader(IDictionary<string, string> fields) {
+ if (fields == null) {
+ throw new ArgumentNullException("fields");
+ }
+
+ StringBuilder authorization = new StringBuilder();
+ authorization.Append("OAuth ");
+ foreach (var pair in fields) {
+ string key = Uri.EscapeDataString(pair.Key);
+ string value = Uri.EscapeDataString(pair.Value);
+ authorization.Append(key);
+ authorization.Append("=\"");
+ authorization.Append(value);
+ authorization.Append("\",");
+ }
+ authorization.Length--; // remove trailing comma
+
+ return authorization.ToString();
+ }
+ }
+}
diff --git a/src/DotNetOAuth.Test/Properties/AssemblyInfo.cs b/src/DotNetOAuth.Test/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..2495cc7 --- /dev/null +++ b/src/DotNetOAuth.Test/Properties/AssemblyInfo.cs @@ -0,0 +1,29 @@ +//-----------------------------------------------------------------------
+// <copyright file="AssemblyInfo.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+using System.Reflection;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+
+// General Information about an assembly is controlled through the following
+// set of attributes. Change these attribute values to modify the information
+// associated with an assembly.
+[assembly: AssemblyTitle("DotNetOAuth.Test")]
+[assembly: AssemblyDescription("")]
+[assembly: AssemblyConfiguration("")]
+[assembly: AssemblyCompany("")]
+[assembly: AssemblyProduct("DotNetOAuth.Test")]
+[assembly: AssemblyCopyright("Copyright © 2008")]
+[assembly: AssemblyTrademark("")]
+[assembly: AssemblyCulture("")]
+
+// Setting ComVisible to false makes the types in this assembly not visible
+// to COM componenets. If you need to access a type in this assembly from
+// COM, set the ComVisible attribute to true on that type.
+[assembly: ComVisible(false)]
+
+// The following GUID is for the ID of the typelib if this project is exposed to COM
+[assembly: Guid("aef0bb13-b79c-4854-a69a-de58b8feb5d1")]
diff --git a/src/DotNetOAuth.Test/ServiceProviderTest.cs b/src/DotNetOAuth.Test/ServiceProviderTest.cs new file mode 100644 index 0000000..d4bced7 --- /dev/null +++ b/src/DotNetOAuth.Test/ServiceProviderTest.cs @@ -0,0 +1,65 @@ +//-----------------------------------------------------------------------
+// <copyright file="ServiceProviderTest.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOAuth.Test {
+ using System;
+ using Microsoft.VisualStudio.TestTools.UnitTesting;
+
+ /// <summary>
+ /// Tests for the <see cref="ServiceProvider"/> class.
+ /// </summary>
+ [TestClass]
+ public class ServiceProviderTest : TestBase {
+ /// <summary>
+ /// A test for UserAuthorizationUri
+ /// </summary>
+ [TestMethod]
+ public void UserAuthorizationUriTest() {
+ ServiceProvider target = new ServiceProvider();
+ Uri expected = new Uri("http://localhost/authorization");
+ Uri actual;
+ target.UserAuthorizationUri = expected;
+ actual = target.UserAuthorizationUri;
+ Assert.AreEqual(expected, actual);
+ }
+
+ /// <summary>
+ /// A test for RequestTokenUri
+ /// </summary>
+ [TestMethod()]
+ public void RequestTokenUriTest() {
+ ServiceProvider target = new ServiceProvider();
+ Uri expected = new Uri("http://localhost/requesttoken");
+ Uri actual;
+ target.RequestTokenUri = expected;
+ actual = target.RequestTokenUri;
+ Assert.AreEqual(expected, actual);
+ }
+
+ /// <summary>
+ /// 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))]
+ public void RequestTokenUriWithOAuthParametersTest() {
+ ServiceProvider target = new ServiceProvider();
+ target.RequestTokenUri = new Uri("http://localhost/requesttoken?oauth_token=something");
+ }
+
+ /// <summary>
+ /// A test for AccessTokenUri
+ /// </summary>
+ [TestMethod()]
+ public void AccessTokenUriTest() {
+ ServiceProvider target = new ServiceProvider();
+ Uri expected = new Uri("http://localhost/accesstoken");
+ Uri actual;
+ target.AccessTokenUri = expected;
+ actual = target.AccessTokenUri;
+ Assert.AreEqual(expected, actual);
+ }
+ }
+}
diff --git a/src/DotNetOAuth.Test/Settings.StyleCop b/src/DotNetOAuth.Test/Settings.StyleCop new file mode 100644 index 0000000..100fae5 --- /dev/null +++ b/src/DotNetOAuth.Test/Settings.StyleCop @@ -0,0 +1,24 @@ +<StyleCopSettings Version="4.3">
+ <Analyzers>
+ <Analyzer AnalyzerId="Microsoft.StyleCop.CSharp.DocumentationRules">
+ <Rules>
+ <Rule Name="ElementsMustBeDocumented">
+ <RuleSettings>
+ <BooleanProperty Name="Enabled">False</BooleanProperty>
+ </RuleSettings>
+ </Rule>
+ </Rules>
+ <AnalyzerSettings />
+ </Analyzer>
+ <Analyzer AnalyzerId="Microsoft.StyleCop.CSharp.LayoutRules">
+ <Rules>
+ <Rule Name="SingleLineCommentMustBePrecededByBlankLine">
+ <RuleSettings>
+ <BooleanProperty Name="Enabled">False</BooleanProperty>
+ </RuleSettings>
+ </Rule>
+ </Rules>
+ <AnalyzerSettings />
+ </Analyzer>
+ </Analyzers>
+</StyleCopSettings>
\ No newline at end of file diff --git a/src/DotNetOAuth.Test/TestBase.cs b/src/DotNetOAuth.Test/TestBase.cs new file mode 100644 index 0000000..e41b01c --- /dev/null +++ b/src/DotNetOAuth.Test/TestBase.cs @@ -0,0 +1,42 @@ +//-----------------------------------------------------------------------
+// <copyright file="TestBase.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+namespace DotNetOAuth.Test {
+ using System.Reflection;
+ using log4net;
+ using Microsoft.VisualStudio.TestTools.UnitTesting;
+
+ /// <summary>
+ /// The base class that all test classes inherit from.
+ /// </summary>
+ public class TestBase {
+ /// <summary>
+ /// The logger that tests should use.
+ /// </summary>
+ internal static readonly ILog Logger = LogManager.GetLogger("DotNetOAuth.Test");
+
+ /// <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>
+ /// The TestInitialize method for the test cases.
+ /// </summary>
+ [TestInitialize]
+ public virtual void SetUp() {
+ log4net.Config.XmlConfigurator.Configure(Assembly.GetExecutingAssembly().GetManifestResourceStream("DotNetOAuth.Test.Logging.config"));
+ }
+
+ /// <summary>
+ /// The TestCleanup method for the test cases.
+ /// </summary>
+ [TestCleanup]
+ public virtual void Cleanup() {
+ log4net.LogManager.Shutdown();
+ }
+ }
+}
|