Retire stackforge/openstack-sdk-dotnet
This commit is contained in:
parent
244434ba1b
commit
79fcb23e9b
63
.gitattributes
vendored
63
.gitattributes
vendored
@ -1,63 +0,0 @@
|
||||
###############################################################################
|
||||
# Set default behavior to automatically normalize line endings.
|
||||
###############################################################################
|
||||
* text=auto
|
||||
|
||||
###############################################################################
|
||||
# Set default behavior for command prompt diff.
|
||||
#
|
||||
# This is need for earlier builds of msysgit that does not have it on by
|
||||
# default for csharp files.
|
||||
# Note: This is only used by command line
|
||||
###############################################################################
|
||||
#*.cs diff=csharp
|
||||
|
||||
###############################################################################
|
||||
# Set the merge driver for project and solution files
|
||||
#
|
||||
# Merging from the command prompt will add diff markers to the files if there
|
||||
# are conflicts (Merging from VS is not affected by the settings below, in VS
|
||||
# the diff markers are never inserted). Diff markers may cause the following
|
||||
# file extensions to fail to load in VS. An alternative would be to treat
|
||||
# these files as binary and thus will always conflict and require user
|
||||
# intervention with every merge. To do so, just uncomment the entries below
|
||||
###############################################################################
|
||||
#*.sln merge=binary
|
||||
#*.csproj merge=binary
|
||||
#*.vbproj merge=binary
|
||||
#*.vcxproj merge=binary
|
||||
#*.vcproj merge=binary
|
||||
#*.dbproj merge=binary
|
||||
#*.fsproj merge=binary
|
||||
#*.lsproj merge=binary
|
||||
#*.wixproj merge=binary
|
||||
#*.modelproj merge=binary
|
||||
#*.sqlproj merge=binary
|
||||
#*.wwaproj merge=binary
|
||||
|
||||
###############################################################################
|
||||
# behavior for image files
|
||||
#
|
||||
# image files are treated as binary by default.
|
||||
###############################################################################
|
||||
#*.jpg binary
|
||||
#*.png binary
|
||||
#*.gif binary
|
||||
|
||||
###############################################################################
|
||||
# diff behavior for common document formats
|
||||
#
|
||||
# Convert binary document formats to text before diffing them. This feature
|
||||
# is only available from the command line. Turn it on by uncommenting the
|
||||
# entries below.
|
||||
###############################################################################
|
||||
#*.doc diff=astextplain
|
||||
#*.DOC diff=astextplain
|
||||
#*.docx diff=astextplain
|
||||
#*.DOCX diff=astextplain
|
||||
#*.dot diff=astextplain
|
||||
#*.DOT diff=astextplain
|
||||
#*.pdf diff=astextplain
|
||||
#*.PDF diff=astextplain
|
||||
#*.rtf diff=astextplain
|
||||
#*.RTF diff=astextplain
|
9
.gitignore
vendored
9
.gitignore
vendored
@ -1,9 +0,0 @@
|
||||
################################################################################
|
||||
# This .gitignore file was automatically created by Microsoft(R) Visual Studio.
|
||||
################################################################################
|
||||
|
||||
*.user
|
||||
*.suo
|
||||
packages/
|
||||
obj/
|
||||
bin/
|
@ -1,4 +0,0 @@
|
||||
[gerrit]
|
||||
host=review.openstack.org
|
||||
port=29418
|
||||
project=stackforge/openstack-sdk-dotnet.git
|
13
CHANGELOG.md
13
CHANGELOG.md
@ -1,13 +0,0 @@
|
||||
# Release Notes
|
||||
|
||||
This changelog contains the relevant feature additions and bug fixes. To obtain a complete diff between versions you can got to https://github.com/stackforge/openstack-sdk-dotnet/compare/XXX...XXX where the XXX values are two different tagged versions of the library. For example, https://github.com/stackforge/openstack-sdk-dotnet/compare/v0.9.0...v0.9.1
|
||||
|
||||
* v0.9.1 (2014-05-30)
|
||||
|
||||
* Includes bug fixes for DevStack compatibility.
|
||||
|
||||
* v0.9.0 (2014-05-12)
|
||||
|
||||
* Initial release of the SDK.
|
||||
* Includes basic support for authentication.
|
||||
* Includes basic support for working with storage containers, objects and folders.
|
@ -1,32 +0,0 @@
|
||||
// /* ============================================================================
|
||||
// Copyright 2014 Hewlett Packard
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ============================================================================ */
|
||||
|
||||
using System.Reflection;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
// Version information for an assembly consists of the following four values:
|
||||
//
|
||||
// Major Version
|
||||
// Minor Version
|
||||
// Build Number
|
||||
// Revision
|
||||
//
|
||||
// You can specify all the values or you can default the Build and Revision Numbers
|
||||
// by using the '*' as shown below:
|
||||
// [assembly: AssemblyVersion("1.0.*")]
|
||||
[assembly: AssemblyVersion("0.9.1.0")]
|
||||
[assembly: AssemblyFileVersion("0.9.1.0")]
|
@ -1 +0,0 @@
|
||||
This is where we would put things like fixcop and stylcop related stuff or any custom build targets that we would want to bring in... basically anything that is related to building the solution.
|
@ -1,6 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8" ?>
|
||||
<configuration>
|
||||
<startup>
|
||||
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
|
||||
</startup>
|
||||
</configuration>
|
@ -1,79 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
||||
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
|
||||
<PropertyGroup>
|
||||
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
|
||||
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
|
||||
<ProjectGuid>{83B16A76-A3DF-42E5-95A6-5BBE41FC7854}</ProjectGuid>
|
||||
<OutputType>Exe</OutputType>
|
||||
<AppDesignerFolder>Properties</AppDesignerFolder>
|
||||
<RootNamespace>CustomServiceClientExample</RootNamespace>
|
||||
<AssemblyName>CustomServiceClientExample</AssemblyName>
|
||||
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
|
||||
<FileAlignment>512</FileAlignment>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
|
||||
<PlatformTarget>AnyCPU</PlatformTarget>
|
||||
<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' ">
|
||||
<PlatformTarget>AnyCPU</PlatformTarget>
|
||||
<DebugType>pdbonly</DebugType>
|
||||
<Optimize>true</Optimize>
|
||||
<OutputPath>bin\Release\</OutputPath>
|
||||
<DefineConstants>TRACE</DefineConstants>
|
||||
<ErrorReport>prompt</ErrorReport>
|
||||
<WarningLevel>4</WarningLevel>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<Reference Include="Newtonsoft.Json">
|
||||
<HintPath>..\..\Bin\Debug\Newtonsoft.Json.dll</HintPath>
|
||||
</Reference>
|
||||
<Reference Include="OpenStack, Version=0.9.0.0, Culture=neutral, processorArchitecture=MSIL">
|
||||
<SpecificVersion>False</SpecificVersion>
|
||||
<HintPath>..\..\Bin\net45\Debug\OpenStack.dll</HintPath>
|
||||
</Reference>
|
||||
<Reference Include="System" />
|
||||
<Reference Include="System.Core" />
|
||||
<Reference Include="System.Net.Http" />
|
||||
<Reference Include="System.Xml.Linq" />
|
||||
<Reference Include="System.Data.DataSetExtensions" />
|
||||
<Reference Include="Microsoft.CSharp" />
|
||||
<Reference Include="System.Data" />
|
||||
<Reference Include="System.Xml" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<Compile Include="EchoPocoClient.cs" />
|
||||
<Compile Include="EchoPocoClientFactory.cs" />
|
||||
<Compile Include="EchoResponse.cs" />
|
||||
<Compile Include="EchoRestClient.cs" />
|
||||
<Compile Include="EchoRestClientFactory.cs" />
|
||||
<Compile Include="EchoServiceClient.cs" />
|
||||
<Compile Include="EchoServiceClientDefinition.cs" />
|
||||
<Compile Include="EchoServiceRegistrar.cs" />
|
||||
<Compile Include="IEchoPocoClient.cs" />
|
||||
<Compile Include="IEchoPocoClientFactory.cs" />
|
||||
<Compile Include="IEchoRestClient.cs" />
|
||||
<Compile Include="IEchoRestClientFactory.cs" />
|
||||
<Compile Include="IEchoServiceClient.cs" />
|
||||
<Compile Include="Program.cs" />
|
||||
<Compile Include="Properties\AssemblyInfo.cs" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<None Include="App.config" />
|
||||
</ItemGroup>
|
||||
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
|
||||
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
|
||||
Other similar extension points exist, see Microsoft.Common.targets.
|
||||
<Target Name="BeforeBuild">
|
||||
</Target>
|
||||
<Target Name="AfterBuild">
|
||||
</Target>
|
||||
-->
|
||||
</Project>
|
@ -1,41 +0,0 @@
|
||||
// /* ============================================================================
|
||||
// Copyright 2014 Hewlett Packard
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ============================================================================ */
|
||||
|
||||
using System.Threading.Tasks;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using OpenStack.Common.ServiceLocation;
|
||||
|
||||
namespace CustomServiceClientExample
|
||||
{
|
||||
internal class EchoPocoClient : IEchoPocoClient
|
||||
{
|
||||
internal IServiceLocator ServiceLocator;
|
||||
|
||||
public EchoPocoClient(IServiceLocator serviceLocator)
|
||||
{
|
||||
this.ServiceLocator = serviceLocator;
|
||||
}
|
||||
|
||||
public async Task<EchoResponse> Echo(string message)
|
||||
{
|
||||
var restClient = this.ServiceLocator.Locate<IEchoRestClientFactory>().Create(this.ServiceLocator);
|
||||
var resp = await restClient.Echo(message);
|
||||
var payload = await resp.ReadContentAsStringAsync();
|
||||
var obj = JObject.Parse(payload);
|
||||
return new EchoResponse((string)obj["args"]["m"], (string)obj["url"]);
|
||||
}
|
||||
}
|
||||
}
|
@ -1,28 +0,0 @@
|
||||
// /* ============================================================================
|
||||
// Copyright 2014 Hewlett Packard
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ============================================================================ */
|
||||
|
||||
using OpenStack.Common.ServiceLocation;
|
||||
|
||||
namespace CustomServiceClientExample
|
||||
{
|
||||
internal class EchoPocoClientFactory : IEchoPocoClientFactory
|
||||
{
|
||||
public IEchoPocoClient Create(IServiceLocator serviceLocator)
|
||||
{
|
||||
return new EchoPocoClient(serviceLocator);
|
||||
}
|
||||
}
|
||||
}
|
@ -1,31 +0,0 @@
|
||||
// /* ============================================================================
|
||||
// Copyright 2014 Hewlett Packard
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ============================================================================ */
|
||||
|
||||
namespace CustomServiceClientExample
|
||||
{
|
||||
public class EchoResponse
|
||||
{
|
||||
public string Message { get; private set; }
|
||||
|
||||
public string Url { get; private set; }
|
||||
|
||||
public EchoResponse(string message, string url)
|
||||
{
|
||||
this.Message = message;
|
||||
this.Url = url;
|
||||
}
|
||||
}
|
||||
}
|
@ -1,45 +0,0 @@
|
||||
// /* ============================================================================
|
||||
// Copyright 2014 Hewlett Packard
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ============================================================================ */
|
||||
|
||||
using System;
|
||||
using System.Net.Http;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using OpenStack.Common.Http;
|
||||
using OpenStack.Common.ServiceLocation;
|
||||
|
||||
namespace CustomServiceClientExample
|
||||
{
|
||||
internal class EchoRestClient : IEchoRestClient
|
||||
{
|
||||
internal const string serviceEndpoint = "http://httpbin.org/get";
|
||||
|
||||
internal IServiceLocator ServiceLocator;
|
||||
|
||||
public EchoRestClient(IServiceLocator serviceLocator)
|
||||
{
|
||||
this.ServiceLocator = serviceLocator;
|
||||
}
|
||||
|
||||
public async Task<IHttpResponseAbstraction> Echo(string message)
|
||||
{
|
||||
var client = this.ServiceLocator.Locate<IHttpAbstractionClientFactory>().Create(CancellationToken.None);
|
||||
client.Method = HttpMethod.Get;
|
||||
client.Uri = new Uri(serviceEndpoint + "?m=" + message);
|
||||
return await client.SendAsync();
|
||||
}
|
||||
}
|
||||
}
|
@ -1,28 +0,0 @@
|
||||
// /* ============================================================================
|
||||
// Copyright 2014 Hewlett Packard
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ============================================================================ */
|
||||
|
||||
using OpenStack.Common.ServiceLocation;
|
||||
|
||||
namespace CustomServiceClientExample
|
||||
{
|
||||
internal class EchoRestClientFactory : IEchoRestClientFactory
|
||||
{
|
||||
public IEchoRestClient Create(IServiceLocator serviceLocator)
|
||||
{
|
||||
return new EchoRestClient(serviceLocator);
|
||||
}
|
||||
}
|
||||
}
|
@ -1,39 +0,0 @@
|
||||
// /* ============================================================================
|
||||
// Copyright 2014 Hewlett Packard
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ============================================================================ */
|
||||
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using OpenStack.Common.ServiceLocation;
|
||||
using OpenStack.Identity;
|
||||
|
||||
namespace CustomServiceClientExample
|
||||
{
|
||||
internal class EchoServiceClient : IEchoServiceClient
|
||||
{
|
||||
internal IServiceLocator ServiceLocator;
|
||||
|
||||
public EchoServiceClient(ICredential credential, CancellationToken token, IServiceLocator serviceLocator)
|
||||
{
|
||||
this.ServiceLocator = serviceLocator;
|
||||
}
|
||||
|
||||
public async Task<EchoResponse> Echo(string message)
|
||||
{
|
||||
var pocoClient = this.ServiceLocator.Locate<IEchoPocoClientFactory>().Create(this.ServiceLocator);
|
||||
return await pocoClient.Echo(message);
|
||||
}
|
||||
}
|
||||
}
|
@ -1,49 +0,0 @@
|
||||
// /* ============================================================================
|
||||
// Copyright 2014 Hewlett Packard
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ============================================================================ */
|
||||
|
||||
using System.Collections.Generic;
|
||||
using System.Threading;
|
||||
using OpenStack;
|
||||
using OpenStack.Common.ServiceLocation;
|
||||
using OpenStack.Identity;
|
||||
|
||||
namespace CustomServiceClientExample
|
||||
{
|
||||
internal class EchoServiceClientDefinition : IOpenStackServiceClientDefinition
|
||||
{
|
||||
public string Name { get; private set; }
|
||||
|
||||
public EchoServiceClientDefinition()
|
||||
{
|
||||
this.Name = typeof(EchoServiceClient).Name;
|
||||
}
|
||||
|
||||
public IOpenStackServiceClient Create(ICredential credential, string serviceName, CancellationToken cancellationToken, IServiceLocator serviceLocator)
|
||||
{
|
||||
return new EchoServiceClient(credential, cancellationToken, serviceLocator);
|
||||
}
|
||||
|
||||
public IEnumerable<string> ListSupportedVersions()
|
||||
{
|
||||
return new List<string>();
|
||||
}
|
||||
|
||||
public bool IsSupported(ICredential credential, string serviceName)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
@ -1,32 +0,0 @@
|
||||
// /* ============================================================================
|
||||
// Copyright 2014 Hewlett Packard
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ============================================================================ */
|
||||
|
||||
using OpenStack;
|
||||
using OpenStack.Common.ServiceLocation;
|
||||
|
||||
namespace CustomServiceClientExample
|
||||
{
|
||||
public class EchoServiceRegistrar : IServiceLocationRegistrar
|
||||
{
|
||||
public void Register(IServiceLocationManager manager, IServiceLocator locator)
|
||||
{
|
||||
manager.RegisterServiceInstance(typeof(IEchoPocoClientFactory), new EchoPocoClientFactory());
|
||||
manager.RegisterServiceInstance(typeof(IEchoRestClientFactory), new EchoRestClientFactory());
|
||||
var serviceManager = locator.Locate<IOpenStackServiceClientManager>();
|
||||
serviceManager.RegisterServiceClient<EchoServiceClient>(new EchoServiceClientDefinition());
|
||||
}
|
||||
}
|
||||
}
|
@ -1,25 +0,0 @@
|
||||
// /* ============================================================================
|
||||
// Copyright 2014 Hewlett Packard
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ============================================================================ */
|
||||
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace CustomServiceClientExample
|
||||
{
|
||||
public interface IEchoPocoClient
|
||||
{
|
||||
Task<EchoResponse> Echo(string message);
|
||||
}
|
||||
}
|
@ -1,25 +0,0 @@
|
||||
// /* ============================================================================
|
||||
// Copyright 2014 Hewlett Packard
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ============================================================================ */
|
||||
|
||||
using OpenStack.Common.ServiceLocation;
|
||||
|
||||
namespace CustomServiceClientExample
|
||||
{
|
||||
public interface IEchoPocoClientFactory
|
||||
{
|
||||
IEchoPocoClient Create(IServiceLocator serviceLocator);
|
||||
}
|
||||
}
|
@ -1,26 +0,0 @@
|
||||
// /* ============================================================================
|
||||
// Copyright 2014 Hewlett Packard
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ============================================================================ */
|
||||
|
||||
using System.Threading.Tasks;
|
||||
using OpenStack.Common.Http;
|
||||
|
||||
namespace CustomServiceClientExample
|
||||
{
|
||||
public interface IEchoRestClient
|
||||
{
|
||||
Task<IHttpResponseAbstraction> Echo(string message);
|
||||
}
|
||||
}
|
@ -1,25 +0,0 @@
|
||||
// /* ============================================================================
|
||||
// Copyright 2014 Hewlett Packard
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ============================================================================ */
|
||||
|
||||
using OpenStack.Common.ServiceLocation;
|
||||
|
||||
namespace CustomServiceClientExample
|
||||
{
|
||||
public interface IEchoRestClientFactory
|
||||
{
|
||||
IEchoRestClient Create(IServiceLocator serviceLocator);
|
||||
}
|
||||
}
|
@ -1,26 +0,0 @@
|
||||
// /* ============================================================================
|
||||
// Copyright 2014 Hewlett Packard
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ============================================================================ */
|
||||
|
||||
using System.Threading.Tasks;
|
||||
using OpenStack;
|
||||
|
||||
namespace CustomServiceClientExample
|
||||
{
|
||||
public interface IEchoServiceClient : IOpenStackServiceClient
|
||||
{
|
||||
Task<EchoResponse> Echo(string message);
|
||||
}
|
||||
}
|
@ -1,55 +0,0 @@
|
||||
// /* ============================================================================
|
||||
// Copyright 2014 Hewlett Packard
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ============================================================================ */
|
||||
|
||||
using System;
|
||||
using System.Threading.Tasks;
|
||||
using OpenStack;
|
||||
using OpenStack.Identity;
|
||||
|
||||
namespace CustomServiceClientExample
|
||||
{
|
||||
class Program
|
||||
{
|
||||
static void Main(string[] args)
|
||||
{
|
||||
var authUri = new Uri("https://region.identity.host.com:12345/v2.0/tokens");
|
||||
var userName = "user name";
|
||||
var password = "password";
|
||||
var tenantId = "XXXXXXXXXXXXXX-Project";
|
||||
var echoMessage = "Hello world!";
|
||||
|
||||
Console.WriteLine("Calling remote service to echo the following message: '{0}'", echoMessage);
|
||||
|
||||
var echoMessageTask = EchoMessage(echoMessage, authUri, userName, password, tenantId);
|
||||
echoMessageTask.Wait();
|
||||
|
||||
Console.WriteLine("Response from remote service: '{0}'", echoMessageTask.Result);
|
||||
Console.ReadLine();
|
||||
}
|
||||
|
||||
public static async Task<string> EchoMessage(string message, Uri authUri, string userName, string password, string tenantId)
|
||||
{
|
||||
var credential = new OpenStackCredential(authUri, userName, password, tenantId);
|
||||
var client = OpenStackClientFactory.CreateClient(credential);
|
||||
|
||||
await client.Connect();
|
||||
|
||||
var echoServiceClient = client.CreateServiceClient<EchoServiceClient>();
|
||||
var resp = await echoServiceClient.Echo(message);
|
||||
return resp.Message;
|
||||
}
|
||||
}
|
||||
}
|
@ -1,36 +0,0 @@
|
||||
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("CustomServiceClientExample")]
|
||||
[assembly: AssemblyDescription("")]
|
||||
[assembly: AssemblyConfiguration("")]
|
||||
[assembly: AssemblyCompany("Microsoft")]
|
||||
[assembly: AssemblyProduct("CustomServiceClientExample")]
|
||||
[assembly: AssemblyCopyright("Copyright © Microsoft 2014")]
|
||||
[assembly: AssemblyTrademark("")]
|
||||
[assembly: AssemblyCulture("")]
|
||||
|
||||
// Setting ComVisible to false makes the types in this assembly not visible
|
||||
// to COM components. 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("4cc5544b-fdb5-43ef-8108-9ed8e995d114")]
|
||||
|
||||
// Version information for an assembly consists of the following four values:
|
||||
//
|
||||
// Major Version
|
||||
// Minor Version
|
||||
// Build Number
|
||||
// Revision
|
||||
//
|
||||
// You can specify all the values or you can default the Build and Revision Numbers
|
||||
// by using the '*' as shown below:
|
||||
// [assembly: AssemblyVersion("1.0.*")]
|
||||
[assembly: AssemblyVersion("1.0.0.0")]
|
||||
[assembly: AssemblyFileVersion("1.0.0.0")]
|
@ -1,28 +0,0 @@
|
||||
|
||||
Microsoft Visual Studio Solution File, Format Version 12.00
|
||||
# Visual Studio 2013
|
||||
VisualStudioVersion = 12.0.30110.0
|
||||
MinimumVisualStudioVersion = 10.0.40219.1
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SimpleStorageExample", "SimpleStorageExample\SimpleStorageExample.csproj", "{A8BB096A-9E6F-4D84-B091-F1FCF4DDCBDC}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CustomServiceClientExample", "CustomServiceClientExample\CustomServiceClientExample.csproj", "{83B16A76-A3DF-42E5-95A6-5BBE41FC7854}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|Any CPU = Debug|Any CPU
|
||||
Release|Any CPU = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(ProjectConfigurationPlatforms) = postSolution
|
||||
{A8BB096A-9E6F-4D84-B091-F1FCF4DDCBDC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{A8BB096A-9E6F-4D84-B091-F1FCF4DDCBDC}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{A8BB096A-9E6F-4D84-B091-F1FCF4DDCBDC}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{A8BB096A-9E6F-4D84-B091-F1FCF4DDCBDC}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{83B16A76-A3DF-42E5-95A6-5BBE41FC7854}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{83B16A76-A3DF-42E5-95A6-5BBE41FC7854}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{83B16A76-A3DF-42E5-95A6-5BBE41FC7854}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{83B16A76-A3DF-42E5-95A6-5BBE41FC7854}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
EndGlobalSection
|
||||
EndGlobal
|
@ -1,6 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8" ?>
|
||||
<configuration>
|
||||
<startup>
|
||||
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
|
||||
</startup>
|
||||
</configuration>
|
@ -1,71 +0,0 @@
|
||||
// /* ============================================================================
|
||||
// Copyright 2014 Hewlett Packard
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ============================================================================ */
|
||||
|
||||
using System;
|
||||
using OpenStack;
|
||||
using OpenStack.Identity;
|
||||
using OpenStack.Storage;
|
||||
|
||||
namespace SimpleStorageExample
|
||||
{
|
||||
class Program
|
||||
{
|
||||
static void Main(string[] args)
|
||||
{
|
||||
//enter your user name, password, tenant Id, and the authorization endpoint
|
||||
//for the instance of OpenStack that you want to connect to.
|
||||
var authUri = new Uri("https://region.identity.host.com:12345/v2.0/tokens");
|
||||
var userName = "user name";
|
||||
var password = "password";
|
||||
var tenantId = "tenant Id"; // e.g. XXXXXXXXXXXXX-Project
|
||||
|
||||
//Construct an OpenStackCredential object that will be used to authenticate.
|
||||
//The credential will also be useful later as it contains a reference to the service catalog, and access token.
|
||||
var credential = new OpenStackCredential(authUri, userName, password, tenantId);
|
||||
|
||||
//Create a new OpenStackClient object using the credentials you just created.
|
||||
var client = OpenStackClientFactory.CreateClient(credential);
|
||||
|
||||
//Connect the client to OpenStack. This will authenticate you, as well as construct the service catalog,
|
||||
//and retrieve the access token that will be used in future calls to OpenStack services.
|
||||
var connectTask = client.Connect();
|
||||
|
||||
//Console applications can't do async, so we need to wait on the task,
|
||||
//in other contexts you can use the wait keyword.
|
||||
connectTask.Wait();
|
||||
|
||||
//Once the OpenStackClient has been connected, you can request a service client from it.
|
||||
//The service client will be created with the credentials that you have already specified,
|
||||
//and do not need any additional information for you to interact with them.
|
||||
var storageClient = client.CreateServiceClient<IStorageServiceClient>();
|
||||
|
||||
//Once we have the storage service client, we can ask it for the details of the current storage account.
|
||||
var getAccountTask = storageClient.GetStorageAccount();
|
||||
getAccountTask.Wait();
|
||||
var account = getAccountTask.Result;
|
||||
|
||||
//Here we will write out the name of the account, and print out the names of each storage container in the account.
|
||||
Console.WriteLine("Connected to storage account '{0}'", account.Name);
|
||||
Console.WriteLine("Storage account '{0}' has the following containers:", account.Name);
|
||||
foreach (var container in account.Containers)
|
||||
{
|
||||
Console.WriteLine("\t{0}",container.Name);
|
||||
}
|
||||
Console.WriteLine(string.Empty);
|
||||
Console.ReadLine();
|
||||
}
|
||||
}
|
||||
}
|
@ -1,36 +0,0 @@
|
||||
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("SimpleStorageExample")]
|
||||
[assembly: AssemblyDescription("")]
|
||||
[assembly: AssemblyConfiguration("")]
|
||||
[assembly: AssemblyCompany("Microsoft")]
|
||||
[assembly: AssemblyProduct("SimpleStorageExample")]
|
||||
[assembly: AssemblyCopyright("Copyright © Microsoft 2014")]
|
||||
[assembly: AssemblyTrademark("")]
|
||||
[assembly: AssemblyCulture("")]
|
||||
|
||||
// Setting ComVisible to false makes the types in this assembly not visible
|
||||
// to COM components. 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("095db9ea-9103-4a27-b7ec-e91bd1e0817c")]
|
||||
|
||||
// Version information for an assembly consists of the following four values:
|
||||
//
|
||||
// Major Version
|
||||
// Minor Version
|
||||
// Build Number
|
||||
// Revision
|
||||
//
|
||||
// You can specify all the values or you can default the Build and Revision Numbers
|
||||
// by using the '*' as shown below:
|
||||
// [assembly: AssemblyVersion("1.0.*")]
|
||||
[assembly: AssemblyVersion("1.0.0.0")]
|
||||
[assembly: AssemblyFileVersion("1.0.0.0")]
|
@ -1,65 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
||||
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
|
||||
<PropertyGroup>
|
||||
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
|
||||
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
|
||||
<ProjectGuid>{A8BB096A-9E6F-4D84-B091-F1FCF4DDCBDC}</ProjectGuid>
|
||||
<OutputType>Exe</OutputType>
|
||||
<AppDesignerFolder>Properties</AppDesignerFolder>
|
||||
<RootNamespace>SimpleStorageExample</RootNamespace>
|
||||
<AssemblyName>SimpleStorageExample</AssemblyName>
|
||||
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
|
||||
<FileAlignment>512</FileAlignment>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
|
||||
<PlatformTarget>AnyCPU</PlatformTarget>
|
||||
<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' ">
|
||||
<PlatformTarget>AnyCPU</PlatformTarget>
|
||||
<DebugType>pdbonly</DebugType>
|
||||
<Optimize>true</Optimize>
|
||||
<OutputPath>bin\Release\</OutputPath>
|
||||
<DefineConstants>TRACE</DefineConstants>
|
||||
<ErrorReport>prompt</ErrorReport>
|
||||
<WarningLevel>4</WarningLevel>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<Reference Include="Newtonsoft.Json">
|
||||
<HintPath>..\..\Bin\net45\Debug\Newtonsoft.Json.dll</HintPath>
|
||||
</Reference>
|
||||
<Reference Include="OpenStack, Version=0.9.0.0, Culture=neutral, processorArchitecture=MSIL">
|
||||
<SpecificVersion>False</SpecificVersion>
|
||||
<HintPath>..\..\Bin\net45\Debug\OpenStack.dll</HintPath>
|
||||
</Reference>
|
||||
<Reference Include="System" />
|
||||
<Reference Include="System.Core" />
|
||||
<Reference Include="System.Xml.Linq" />
|
||||
<Reference Include="System.Data.DataSetExtensions" />
|
||||
<Reference Include="Microsoft.CSharp" />
|
||||
<Reference Include="System.Data" />
|
||||
<Reference Include="System.Xml" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<Compile Include="Program.cs" />
|
||||
<Compile Include="Properties\AssemblyInfo.cs" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<None Include="App.config" />
|
||||
</ItemGroup>
|
||||
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
|
||||
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
|
||||
Other similar extension points exist, see Microsoft.Common.targets.
|
||||
<Target Name="BeforeBuild">
|
||||
</Target>
|
||||
<Target Name="AfterBuild">
|
||||
</Target>
|
||||
-->
|
||||
</Project>
|
1
OpenStack/Externals/readme.txt
vendored
1
OpenStack/Externals/readme.txt
vendored
@ -1 +0,0 @@
|
||||
This is a folder to bring in any non-NuGet external dependencies...
|
@ -1,383 +0,0 @@
|
||||
// /* ============================================================================
|
||||
// Copyright 2014 Hewlett Packard
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ============================================================================ */
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
using OpenStack.Compute;
|
||||
|
||||
namespace OpenStack.Test.Compute
|
||||
{
|
||||
[TestClass]
|
||||
public class ComputeFlavorPayloadConverterTests
|
||||
{
|
||||
internal string CreateFlavorJsonFixtrue(string name, string id, string ram, string disk, string vcpus,
|
||||
string permaUri, string publicUri)
|
||||
{
|
||||
var ComputeFlavorJsonResponseFixture = @"{{
|
||||
""flavor"" : {{
|
||||
""name"": ""{0}"",
|
||||
""links"": [
|
||||
{{
|
||||
""href"": ""{1}"",
|
||||
""rel"": ""self""
|
||||
}},
|
||||
{{
|
||||
""href"": ""{2}"",
|
||||
""rel"": ""bookmark""
|
||||
}}
|
||||
],
|
||||
""ram"": {3},
|
||||
""vcpus"": {4},
|
||||
""disk"": {5},
|
||||
""id"": ""{6}""
|
||||
}}
|
||||
}}";
|
||||
|
||||
return string.Format(ComputeFlavorJsonResponseFixture, name, publicUri, permaUri, ram, vcpus, disk, id);
|
||||
}
|
||||
|
||||
internal string CreateFlavorSummaryJsonFixtrue(string name, string id, string permaUri, string publicUri)
|
||||
{
|
||||
var computeFlavorSummaryJsonResponseFixture = @"{{
|
||||
""id"": ""{0}"",
|
||||
""links"": [
|
||||
{{
|
||||
""href"": ""{1}"",
|
||||
""rel"": ""self""
|
||||
}},
|
||||
{{
|
||||
""href"": ""{2}"",
|
||||
""rel"": ""bookmark""
|
||||
}}
|
||||
],
|
||||
""name"": ""{3}""
|
||||
}}";
|
||||
|
||||
return string.Format(computeFlavorSummaryJsonResponseFixture, id, publicUri, permaUri, name);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanConvertJsonPayloadToFlavor()
|
||||
{
|
||||
var flavorName = "m1.tiny";
|
||||
var flavorId = "1";
|
||||
var flavorPublicUri = "http://www.server.com/v2/flavors/1";
|
||||
var flavorPermUri = "http://www.server.com/flavors/1";
|
||||
var flavorRam = "512";
|
||||
var flavorDisk = "10";
|
||||
var flavorVcpus = "2";
|
||||
|
||||
var computeFlavorJsonResponseFixture = CreateFlavorJsonFixtrue(flavorName, flavorId, flavorRam, flavorDisk,
|
||||
flavorVcpus, flavorPermUri, flavorPublicUri);
|
||||
|
||||
var converter = new ComputeFlavorPayloadConverter();
|
||||
var flavor = converter.ConvertFlavor(computeFlavorJsonResponseFixture);
|
||||
Assert.IsNotNull(flavor);
|
||||
Assert.AreEqual(flavorName, flavor.Name);
|
||||
Assert.AreEqual(flavorId, flavor.Id);
|
||||
Assert.AreEqual(flavorRam, flavor.Ram);
|
||||
Assert.AreEqual(flavorVcpus, flavor.Vcpus);
|
||||
Assert.AreEqual(flavorDisk, flavor.Disk);
|
||||
Assert.AreEqual(new Uri(flavorPermUri), flavor.PermanentUri);
|
||||
Assert.AreEqual(new Uri(flavorPublicUri), flavor.PublicUri);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanConvertJsonPayloadMissingRamToFlavor()
|
||||
{
|
||||
var missingFixture = @"{
|
||||
""flavor"": {
|
||||
""name"": ""m1.tiny"",
|
||||
""id"": ""1"",
|
||||
""links"": [
|
||||
{
|
||||
""href"": ""http://someuri.com/v2/flavors/1"",
|
||||
""rel"": ""self""
|
||||
},
|
||||
{
|
||||
""href"": ""http://someuri.com/flavors/1"",
|
||||
""rel"": ""bookmark""
|
||||
}
|
||||
],
|
||||
""vcpus"": 2,
|
||||
""disk"": 10
|
||||
}
|
||||
}";
|
||||
|
||||
var converter = new ComputeFlavorPayloadConverter();
|
||||
var flavor = converter.ConvertFlavor(missingFixture);
|
||||
Assert.IsNotNull(flavor);
|
||||
Assert.AreEqual("m1.tiny", flavor.Name);
|
||||
Assert.AreEqual("1", flavor.Id);
|
||||
Assert.AreEqual("2", flavor.Vcpus);
|
||||
Assert.AreEqual("10", flavor.Disk);
|
||||
Assert.AreEqual(new Uri("http://someuri.com/flavors/1"), flavor.PermanentUri);
|
||||
Assert.AreEqual(new Uri("http://someuri.com/v2/flavors/1"), flavor.PublicUri);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanConvertJsonPayloadMissingVcpusToFlavor()
|
||||
{
|
||||
var missingFixture = @"{
|
||||
""flavor"": {
|
||||
""name"": ""m1.tiny"",
|
||||
""id"": ""1"",
|
||||
""links"": [
|
||||
{
|
||||
""href"": ""http://someuri.com/v2/flavors/1"",
|
||||
""rel"": ""self""
|
||||
},
|
||||
{
|
||||
""href"": ""http://someuri.com/flavors/1"",
|
||||
""rel"": ""bookmark""
|
||||
}
|
||||
],
|
||||
""ram"": 512,
|
||||
""disk"": 10
|
||||
}
|
||||
}";
|
||||
|
||||
var converter = new ComputeFlavorPayloadConverter();
|
||||
var flavor = converter.ConvertFlavor(missingFixture);
|
||||
Assert.IsNotNull(flavor);
|
||||
Assert.AreEqual("m1.tiny", flavor.Name);
|
||||
Assert.AreEqual("1", flavor.Id);
|
||||
Assert.AreEqual("512", flavor.Ram);
|
||||
Assert.AreEqual("10", flavor.Disk);
|
||||
Assert.AreEqual(new Uri("http://someuri.com/flavors/1"), flavor.PermanentUri);
|
||||
Assert.AreEqual(new Uri("http://someuri.com/v2/flavors/1"), flavor.PublicUri);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanConvertJsonPayloadMissingDiskToFlavor()
|
||||
{
|
||||
var missingFixture = @"{
|
||||
""flavor"": {
|
||||
""name"": ""m1.tiny"",
|
||||
""id"": ""1"",
|
||||
""links"": [
|
||||
{
|
||||
""href"": ""http://someuri.com/v2/flavors/1"",
|
||||
""rel"": ""self""
|
||||
},
|
||||
{
|
||||
""href"": ""http://someuri.com/flavors/1"",
|
||||
""rel"": ""bookmark""
|
||||
}
|
||||
],
|
||||
""ram"": 512,
|
||||
""vcpus"": 2
|
||||
}
|
||||
}";
|
||||
|
||||
var converter = new ComputeFlavorPayloadConverter();
|
||||
var flavor = converter.ConvertFlavor(missingFixture);
|
||||
Assert.IsNotNull(flavor);
|
||||
Assert.AreEqual("m1.tiny", flavor.Name);
|
||||
Assert.AreEqual("1", flavor.Id);
|
||||
Assert.AreEqual("512", flavor.Ram);
|
||||
Assert.AreEqual("2", flavor.Vcpus);
|
||||
Assert.AreEqual(new Uri("http://someuri.com/flavors/1"), flavor.PermanentUri);
|
||||
Assert.AreEqual(new Uri("http://someuri.com/v2/flavors/1"), flavor.PublicUri);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(FormatException))]
|
||||
public void CannotConvertJsonPayloadMissingIdToFlavor()
|
||||
{
|
||||
var missingIdFixture = @"{
|
||||
""flavor"" : {
|
||||
""name"": ""m1.tiny"",
|
||||
""links"": [
|
||||
{
|
||||
""href"": ""http://someuri.com/v2/flavors/1"",
|
||||
""rel"": ""self""
|
||||
},
|
||||
{
|
||||
""href"": ""http://someuri.com/flavors/1"",
|
||||
""rel"": ""bookmark""
|
||||
}
|
||||
],
|
||||
""ram"": 512,
|
||||
""vcpus"": 2,
|
||||
""disk"": 10
|
||||
}
|
||||
}";
|
||||
|
||||
var converter = new ComputeFlavorPayloadConverter();
|
||||
converter.ConvertFlavor(missingIdFixture);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(FormatException))]
|
||||
public void CannotConvertJsonPayloadMissingNameToFlavor()
|
||||
{
|
||||
var missingTokenFixture = @"{
|
||||
""flavor"": {
|
||||
""name"" : ""m1.tiny"",
|
||||
""links"": [
|
||||
{
|
||||
""href"": ""http://someuri.com/v2/flavors/1"",
|
||||
""rel"": ""self""
|
||||
},
|
||||
{
|
||||
""href"": ""http://someuri.com/flavors/1"",
|
||||
""rel"": ""bookmark""
|
||||
}
|
||||
],
|
||||
""ram"": 512,
|
||||
""vcpus"": 2,
|
||||
""disk"": 10
|
||||
}
|
||||
}";
|
||||
|
||||
var converter = new ComputeFlavorPayloadConverter();
|
||||
converter.ConvertFlavor(missingTokenFixture);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(FormatException))]
|
||||
public void CannotConvertJsonPayloadEmptyObjectToFlavor()
|
||||
{
|
||||
var emptyObjectFixture = @"{ }";
|
||||
|
||||
var converter = new ComputeFlavorPayloadConverter();
|
||||
converter.ConvertFlavor(emptyObjectFixture);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(FormatException))]
|
||||
public void CannotConvertInvalidJsonToFlavor()
|
||||
{
|
||||
var badJsonFixture = @"{ NOT JSON";
|
||||
|
||||
var converter = new ComputeFlavorPayloadConverter();
|
||||
converter.ConvertFlavor(badJsonFixture);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(FormatException))]
|
||||
public void CannotConvertNonObjectJsonToFlavor()
|
||||
{
|
||||
var nonObjectJson = @"[]";
|
||||
|
||||
var converter = new ComputeFlavorPayloadConverter();
|
||||
converter.ConvertFlavor(nonObjectJson);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanParseValidFlavorsJsonPayloadWithMultipleFlavors()
|
||||
{
|
||||
var validMultipleFlavorsJsonFixture = @"{{ ""flavors"": [ {0} ] }}";
|
||||
var firstFlavor = CreateFlavorSummaryJsonFixtrue("m1.tiny", "1", "http://server.com/flavors/1",
|
||||
"http://server.com/v2/flavors/1");
|
||||
var secondFlavor = CreateFlavorSummaryJsonFixtrue("m1.small", "2", "http://server.com/flavors/2",
|
||||
"http://server.com/v2/flavors/2");
|
||||
|
||||
var validMultipleFlavorsJson = string.Format(validMultipleFlavorsJsonFixture,
|
||||
string.Join(",", new List<string>() {firstFlavor, secondFlavor}));
|
||||
|
||||
var converter = new ComputeFlavorPayloadConverter();
|
||||
var flavors = converter.ConvertFlavors(validMultipleFlavorsJson).ToList();
|
||||
|
||||
Assert.AreEqual(2, flavors.Count());
|
||||
var flv1 =
|
||||
flavors.First(o => string.Equals(o.Name, "m1.tiny", StringComparison.InvariantCultureIgnoreCase));
|
||||
var flv2 =
|
||||
flavors.First(o => string.Equals(o.Name, "m1.small", StringComparison.InvariantCultureIgnoreCase));
|
||||
Assert.IsNotNull(flv1);
|
||||
Assert.IsNotNull(flv2);
|
||||
|
||||
Assert.AreEqual("1", flv1.Id);
|
||||
Assert.AreEqual(new Uri("http://server.com/flavors/1"), flv1.PermanentUri);
|
||||
Assert.AreEqual(new Uri("http://server.com/v2/flavors/1"), flv1.PublicUri);
|
||||
|
||||
Assert.AreEqual("2", flv2.Id);
|
||||
Assert.AreEqual(new Uri("http://server.com/flavors/2"), flv2.PermanentUri);
|
||||
Assert.AreEqual(new Uri("http://server.com/v2/flavors/2"), flv2.PublicUri);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanConvertValidFlavorsJsonPayloadWithSingleFlavor()
|
||||
{
|
||||
var validFlavorsJsonFixture = @"{{ ""flavors"": [ {0} ] }}";
|
||||
var firstFlavor = CreateFlavorSummaryJsonFixtrue("m1.tiny", "1", "http://server.com/flavors/1",
|
||||
"http://server.com/v2/flavors/1");
|
||||
var validMultipleFlavorsJson = string.Format(validFlavorsJsonFixture, firstFlavor);
|
||||
|
||||
var converter = new ComputeFlavorPayloadConverter();
|
||||
var flavors = converter.ConvertFlavors(validMultipleFlavorsJson).ToList();
|
||||
|
||||
Assert.AreEqual(1, flavors.Count());
|
||||
var flv1 =
|
||||
flavors.First(o => string.Equals(o.Name, "m1.tiny", StringComparison.InvariantCultureIgnoreCase));
|
||||
|
||||
Assert.IsNotNull(flv1);
|
||||
|
||||
Assert.AreEqual("1", flv1.Id);
|
||||
Assert.AreEqual(new Uri("http://server.com/flavors/1"), flv1.PermanentUri);
|
||||
Assert.AreEqual(new Uri("http://server.com/v2/flavors/1"), flv1.PublicUri);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanParseValidFlavorsPayloadWithEmptyJsonArray()
|
||||
{
|
||||
var emptyJsonArray = @"{ ""flavors"": [ ] }";
|
||||
|
||||
var converter = new ComputeFlavorPayloadConverter();
|
||||
var containers = converter.ConvertFlavors(emptyJsonArray).ToList();
|
||||
|
||||
Assert.AreEqual(0, containers.Count());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanParseAnEmptyFlavorsPayload()
|
||||
{
|
||||
var payload = string.Empty;
|
||||
|
||||
var converter = new ComputeFlavorPayloadConverter();
|
||||
var containers = converter.ConvertFlavors(payload).ToList();
|
||||
|
||||
Assert.AreEqual(0, containers.Count());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(ArgumentNullException))]
|
||||
public void CannotParseANullFlavorsPayload()
|
||||
{
|
||||
var converter = new ComputeFlavorPayloadConverter();
|
||||
converter.ConvertFlavors(null);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(FormatException))]
|
||||
public void CannotParseInvalidFlavorsJsonPayload()
|
||||
{
|
||||
var converter = new ComputeFlavorPayloadConverter();
|
||||
converter.ConvertFlavors("[ { \"SomeAtrib\" }]");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(FormatException))]
|
||||
public void CannotParseInvalidFlavorsPayload()
|
||||
{
|
||||
var converter = new ComputeFlavorPayloadConverter();
|
||||
converter.ConvertFlavors("NOT JSON");
|
||||
}
|
||||
}
|
||||
}
|
@ -1,640 +0,0 @@
|
||||
// /* ============================================================================
|
||||
// Copyright 2014 Hewlett Packard
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ============================================================================ */
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
using OpenStack.Compute;
|
||||
|
||||
namespace OpenStack.Test.Compute
|
||||
{
|
||||
[TestClass]
|
||||
public class ComputeImagePayloadConverterTests
|
||||
{
|
||||
internal string CreateImageJsonFixtrue(string name, string id, string permaUri, string publicUri, string status, string minDisk, string minRam, string progress, string created, string updated)
|
||||
{
|
||||
var ComputeFlavorJsonResponseFixture = @"{{
|
||||
""image"" : {{
|
||||
""name"": ""{0}"",
|
||||
""status"": ""{1}"",
|
||||
""updated"": ""{2}"",
|
||||
""created"": ""{3}"",
|
||||
""minDisk"": {4},
|
||||
""progress"": {5},
|
||||
""minRam"": {6},
|
||||
""links"": [
|
||||
{{
|
||||
""href"": ""{7}"",
|
||||
""rel"": ""self""
|
||||
}},
|
||||
{{
|
||||
""href"": ""{8}"",
|
||||
""rel"": ""bookmark""
|
||||
}}
|
||||
],
|
||||
""metadata"": {{
|
||||
""kernel_id"": ""nokernel"",
|
||||
""ramdisk_id"": ""98765""
|
||||
}},
|
||||
""id"": ""{9}""
|
||||
}}
|
||||
}}";
|
||||
|
||||
return string.Format(ComputeFlavorJsonResponseFixture, name, status, updated, created, minDisk, progress, minRam, publicUri, permaUri, id);
|
||||
}
|
||||
|
||||
internal string CreateImageSummaryJsonFixtrue(string name, string id, string permaUri, string publicUri)
|
||||
{
|
||||
var computeImageSummaryJsonResponseFixture = @"{{
|
||||
""id"": ""{0}"",
|
||||
""links"": [
|
||||
{{
|
||||
""href"": ""{1}"",
|
||||
""rel"": ""self""
|
||||
}},
|
||||
{{
|
||||
""href"": ""{2}"",
|
||||
""rel"": ""bookmark""
|
||||
}}
|
||||
],
|
||||
""name"": ""{3}""
|
||||
}}";
|
||||
|
||||
return string.Format(computeImageSummaryJsonResponseFixture, id, publicUri, permaUri, name);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanConvertJsonPayloadToImage()
|
||||
{
|
||||
var imageName = "myimage";
|
||||
var imageId = "12345";
|
||||
var imagePublicUri = "http://www.server.com/v2/images/12345";
|
||||
var imagePermUri = "http://www.server.com/images/12345";
|
||||
var minRam = 512;
|
||||
var minDisk = 10;
|
||||
var progress = 100;
|
||||
var status = "ACTIVE";
|
||||
|
||||
var lastUpdate = DateTime.UtcNow.Subtract(TimeSpan.FromMinutes(10));
|
||||
var createdDate = DateTime.UtcNow.Subtract(TimeSpan.FromMinutes(100));
|
||||
var created = createdDate.ToLongTimeString();
|
||||
var updated = lastUpdate.ToLongTimeString();
|
||||
|
||||
var computeFlavorJsonResponseFixture = CreateImageJsonFixtrue(imageName, imageId, imagePermUri, imagePublicUri,
|
||||
status, minDisk.ToString(), minRam.ToString(), progress.ToString(), created,updated);
|
||||
|
||||
var converter = new ComputeImagePayloadConverter();
|
||||
var image = converter.ConvertImage(computeFlavorJsonResponseFixture);
|
||||
Assert.IsNotNull(image);
|
||||
Assert.AreEqual(imageName, image.Name);
|
||||
Assert.AreEqual(imageId, image.Id);
|
||||
Assert.AreEqual(minRam, image.MinimumRamSize);
|
||||
Assert.AreEqual(progress, image.UploadProgress);
|
||||
Assert.AreEqual(minDisk, image.MinimumDiskSize);
|
||||
Assert.AreEqual(status, image.Status);
|
||||
Assert.AreEqual(lastUpdate.ToLongTimeString(), image.LastUpdated.ToLongTimeString());
|
||||
Assert.AreEqual(createdDate.ToLongTimeString(), image.CreateDate.ToLongTimeString());
|
||||
Assert.AreEqual(new Uri(imagePermUri), image.PermanentUri);
|
||||
Assert.AreEqual(new Uri(imagePublicUri), image.PublicUri);
|
||||
Assert.AreEqual(2, image.Metadata.Count);
|
||||
Assert.AreEqual("nokernel",image.Metadata["kernel_id"]);
|
||||
Assert.AreEqual("98765",image.Metadata["ramdisk_id"]);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanConvertJsonPayloadMissingMinRamToImage()
|
||||
{
|
||||
var created = DateTime.Parse("2014-05-30T16:56:32Z").ToUniversalTime();
|
||||
var updated = DateTime.Parse("2014-06-30T16:56:32Z").ToUniversalTime();
|
||||
var missingFixture = @"{
|
||||
""image"" : {
|
||||
""name"": ""image1"",
|
||||
""status"": ""ACTIVE"",
|
||||
""updated"": ""2014-06-30T16:56:32Z"",
|
||||
""created"": ""2014-05-30T16:56:32Z"",
|
||||
""minDisk"": 10,
|
||||
""progress"": 100,
|
||||
""links"": [
|
||||
{
|
||||
""href"": ""http://someuri.com/v2/images/12345"",
|
||||
""rel"": ""self""
|
||||
},
|
||||
{
|
||||
""href"": ""http://someuri.com/images/12345"",
|
||||
""rel"": ""bookmark""
|
||||
}
|
||||
],
|
||||
""id"": ""12345""
|
||||
}
|
||||
}";
|
||||
|
||||
var converter = new ComputeImagePayloadConverter();
|
||||
var image = converter.ConvertImage(missingFixture);
|
||||
Assert.IsNotNull(image);
|
||||
Assert.AreEqual("image1", image.Name);
|
||||
Assert.AreEqual("ACTIVE", image.Status);
|
||||
Assert.AreEqual("12345", image.Id);
|
||||
Assert.AreEqual(0, image.MinimumRamSize);
|
||||
Assert.AreEqual(10, image.MinimumDiskSize);
|
||||
Assert.AreEqual(100, image.UploadProgress);
|
||||
Assert.AreEqual(created.ToLongTimeString(), image.CreateDate.ToLongTimeString());
|
||||
Assert.AreEqual(updated.ToLongTimeString(), image.LastUpdated.ToLongTimeString());
|
||||
Assert.AreEqual(new Uri("http://someuri.com/images/12345"), image.PermanentUri);
|
||||
Assert.AreEqual(new Uri("http://someuri.com/v2/images/12345"), image.PublicUri);
|
||||
}
|
||||
|
||||
public void CanConvertJsonPayloadMissingMetadataToImage()
|
||||
{
|
||||
var created = DateTime.Parse("2014-05-30T16:56:32Z").ToUniversalTime();
|
||||
var updated = DateTime.Parse("2014-06-30T16:56:32Z").ToUniversalTime();
|
||||
var missingFixture = @"{
|
||||
""image"" : {
|
||||
""name"": ""image1"",
|
||||
""status"": ""ACTIVE"",
|
||||
""updated"": ""2014-06-30T16:56:32Z"",
|
||||
""created"": ""2014-05-30T16:56:32Z"",
|
||||
""minDisk"": 10,
|
||||
""minRam"": 512,
|
||||
""progress"": 100,
|
||||
""links"": [
|
||||
{
|
||||
""href"": ""http://someuri.com/v2/images/12345"",
|
||||
""rel"": ""self""
|
||||
},
|
||||
{
|
||||
""href"": ""http://someuri.com/images/12345"",
|
||||
""rel"": ""bookmark""
|
||||
}
|
||||
],
|
||||
""id"": ""12345""
|
||||
}
|
||||
}";
|
||||
|
||||
var converter = new ComputeImagePayloadConverter();
|
||||
var image = converter.ConvertImage(missingFixture);
|
||||
Assert.IsNotNull(image);
|
||||
Assert.AreEqual("image1", image.Name);
|
||||
Assert.AreEqual("ACTIVE", image.Status);
|
||||
Assert.AreEqual("12345", image.Id);
|
||||
Assert.AreEqual(512, image.MinimumRamSize);
|
||||
Assert.AreEqual(10, image.MinimumDiskSize);
|
||||
Assert.AreEqual(100, image.UploadProgress);
|
||||
Assert.AreEqual(created.ToLongTimeString(), image.CreateDate.ToLongTimeString());
|
||||
Assert.AreEqual(updated.ToLongTimeString(), image.LastUpdated.ToLongTimeString());
|
||||
Assert.AreEqual(new Uri("http://someuri.com/images/12345"), image.PermanentUri);
|
||||
Assert.AreEqual(new Uri("http://someuri.com/v2/images/12345"), image.PublicUri);
|
||||
Assert.AreEqual(0, image.Metadata.Count);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(FormatException))]
|
||||
public void CannotConvertJsonPayloadWithBadMetadataToImage()
|
||||
{
|
||||
var created = DateTime.Parse("2014-05-30T16:56:32Z").ToUniversalTime();
|
||||
var updated = DateTime.Parse("2014-06-30T16:56:32Z").ToUniversalTime();
|
||||
var missingFixture = @"{
|
||||
""image"" : {
|
||||
""name"": ""image1"",
|
||||
""status"": ""ACTIVE"",
|
||||
""updated"": ""2014-06-30T16:56:32Z"",
|
||||
""created"": ""2014-05-30T16:56:32Z"",
|
||||
""minDisk"": 10,
|
||||
""minRam"": 512,
|
||||
""progress"": 100,
|
||||
""links"": [
|
||||
{
|
||||
""href"": ""http://someuri.com/v2/images/12345"",
|
||||
""rel"": ""self""
|
||||
},
|
||||
{
|
||||
""href"": ""http://someuri.com/images/12345"",
|
||||
""rel"": ""bookmark""
|
||||
}
|
||||
],
|
||||
""metadata"": {
|
||||
""kernel_id"": { ""NotExpectyed"" : ""SomeBadValue"" },
|
||||
""ramdisk_id"": ""98765""
|
||||
},
|
||||
""id"": ""12345""
|
||||
}
|
||||
}";
|
||||
|
||||
var converter = new ComputeImagePayloadConverter();
|
||||
converter.ConvertImage(missingFixture);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanConvertJsonPayloadMissingMinDiskToImage()
|
||||
{
|
||||
var created = DateTime.Parse("2014-05-30T16:56:32Z").ToUniversalTime();
|
||||
var updated = DateTime.Parse("2014-06-30T16:56:32Z").ToUniversalTime();
|
||||
var missingFixture = @"{
|
||||
""image"" : {
|
||||
""name"": ""image1"",
|
||||
""status"": ""ACTIVE"",
|
||||
""updated"": ""2014-06-30T16:56:32Z"",
|
||||
""created"": ""2014-05-30T16:56:32Z"",
|
||||
""progress"": 100,
|
||||
""minRam"": 512,
|
||||
""links"": [
|
||||
{
|
||||
""href"": ""http://someuri.com/v2/images/12345"",
|
||||
""rel"": ""self""
|
||||
},
|
||||
{
|
||||
""href"": ""http://someuri.com/images/12345"",
|
||||
""rel"": ""bookmark""
|
||||
}
|
||||
],
|
||||
""id"": ""12345""
|
||||
}
|
||||
}";
|
||||
|
||||
var converter = new ComputeImagePayloadConverter();
|
||||
var image = converter.ConvertImage(missingFixture);
|
||||
Assert.IsNotNull(image);
|
||||
Assert.AreEqual("image1", image.Name);
|
||||
Assert.AreEqual("ACTIVE", image.Status);
|
||||
Assert.AreEqual("12345", image.Id);
|
||||
Assert.AreEqual(512, image.MinimumRamSize);
|
||||
Assert.AreEqual(0, image.MinimumDiskSize);
|
||||
Assert.AreEqual(100, image.UploadProgress);
|
||||
Assert.AreEqual(created.ToLongTimeString(), image.CreateDate.ToLongTimeString());
|
||||
Assert.AreEqual(updated.ToLongTimeString(), image.LastUpdated.ToLongTimeString());
|
||||
Assert.AreEqual(new Uri("http://someuri.com/images/12345"), image.PermanentUri);
|
||||
Assert.AreEqual(new Uri("http://someuri.com/v2/images/12345"), image.PublicUri);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanConvertJsonPayloadMissingStatusToImage()
|
||||
{
|
||||
var created = DateTime.Parse("2014-05-30T16:56:32Z").ToUniversalTime();
|
||||
var updated = DateTime.Parse("2014-06-30T16:56:32Z").ToUniversalTime();
|
||||
var missingFixture = @"{
|
||||
""image"" : {
|
||||
""name"": ""image1"",
|
||||
""updated"": ""2014-06-30T16:56:32Z"",
|
||||
""created"": ""2014-05-30T16:56:32Z"",
|
||||
""minDisk"": 10,
|
||||
""progress"": 100,
|
||||
""minRam"": 512,
|
||||
""links"": [
|
||||
{
|
||||
""href"": ""http://someuri.com/v2/images/12345"",
|
||||
""rel"": ""self""
|
||||
},
|
||||
{
|
||||
""href"": ""http://someuri.com/images/12345"",
|
||||
""rel"": ""bookmark""
|
||||
}
|
||||
],
|
||||
""id"": ""12345""
|
||||
}
|
||||
}";
|
||||
|
||||
var converter = new ComputeImagePayloadConverter();
|
||||
var image = converter.ConvertImage(missingFixture);
|
||||
Assert.IsNotNull(image);
|
||||
Assert.AreEqual("image1", image.Name);
|
||||
Assert.AreEqual(string.Empty, image.Status);
|
||||
Assert.AreEqual("12345", image.Id);
|
||||
Assert.AreEqual(512, image.MinimumRamSize);
|
||||
Assert.AreEqual(10, image.MinimumDiskSize);
|
||||
Assert.AreEqual(100, image.UploadProgress);
|
||||
Assert.AreEqual(created.ToLongTimeString(), image.CreateDate.ToLongTimeString());
|
||||
Assert.AreEqual(updated.ToLongTimeString(), image.LastUpdated.ToLongTimeString());
|
||||
Assert.AreEqual(new Uri("http://someuri.com/images/12345"), image.PermanentUri);
|
||||
Assert.AreEqual(new Uri("http://someuri.com/v2/images/12345"), image.PublicUri);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanConvertJsonPayloadMissingUpdateDateToImage()
|
||||
{
|
||||
var created = DateTime.Parse("2014-05-30T16:56:32Z").ToUniversalTime();
|
||||
var updated = DateTime.MinValue;
|
||||
var missingFixture = @"{
|
||||
""image"" : {
|
||||
""name"": ""image1"",
|
||||
""status"": ""ACTIVE"",
|
||||
""created"": ""2014-05-30T16:56:32Z"",
|
||||
""minDisk"": 10,
|
||||
""progress"": 100,
|
||||
""minRam"": 512,
|
||||
""links"": [
|
||||
{
|
||||
""href"": ""http://someuri.com/v2/images/12345"",
|
||||
""rel"": ""self""
|
||||
},
|
||||
{
|
||||
""href"": ""http://someuri.com/images/12345"",
|
||||
""rel"": ""bookmark""
|
||||
}
|
||||
],
|
||||
""id"": ""12345""
|
||||
}
|
||||
}";
|
||||
|
||||
var converter = new ComputeImagePayloadConverter();
|
||||
var image = converter.ConvertImage(missingFixture);
|
||||
Assert.IsNotNull(image);
|
||||
Assert.AreEqual("image1", image.Name);
|
||||
Assert.AreEqual("ACTIVE", image.Status);
|
||||
Assert.AreEqual("12345", image.Id);
|
||||
Assert.AreEqual(512, image.MinimumRamSize);
|
||||
Assert.AreEqual(10, image.MinimumDiskSize);
|
||||
Assert.AreEqual(100, image.UploadProgress);
|
||||
Assert.AreEqual(created.ToLongTimeString(), image.CreateDate.ToLongTimeString());
|
||||
Assert.AreEqual(updated.ToLongTimeString(), image.LastUpdated.ToLongTimeString());
|
||||
Assert.AreEqual(new Uri("http://someuri.com/images/12345"), image.PermanentUri);
|
||||
Assert.AreEqual(new Uri("http://someuri.com/v2/images/12345"), image.PublicUri);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanConvertJsonPayloadMissinCreatedDateToImage()
|
||||
{
|
||||
var created = DateTime.MinValue;
|
||||
var updated = DateTime.Parse("2014-06-30T16:56:32Z").ToUniversalTime();
|
||||
var missingFixture = @"{
|
||||
""image"" : {
|
||||
""name"": ""image1"",
|
||||
""status"": ""ACTIVE"",
|
||||
""updated"": ""2014-06-30T16:56:32Z"",
|
||||
""minDisk"": 10,
|
||||
""progress"": 100,
|
||||
""minRam"": 512,
|
||||
""links"": [
|
||||
{
|
||||
""href"": ""http://someuri.com/v2/images/12345"",
|
||||
""rel"": ""self""
|
||||
},
|
||||
{
|
||||
""href"": ""http://someuri.com/images/12345"",
|
||||
""rel"": ""bookmark""
|
||||
}
|
||||
],
|
||||
""id"": ""12345""
|
||||
}
|
||||
}";
|
||||
|
||||
var converter = new ComputeImagePayloadConverter();
|
||||
var image = converter.ConvertImage(missingFixture);
|
||||
Assert.IsNotNull(image);
|
||||
Assert.AreEqual("image1", image.Name);
|
||||
Assert.AreEqual("ACTIVE", image.Status);
|
||||
Assert.AreEqual("12345", image.Id);
|
||||
Assert.AreEqual(512, image.MinimumRamSize);
|
||||
Assert.AreEqual(10, image.MinimumDiskSize);
|
||||
Assert.AreEqual(100, image.UploadProgress);
|
||||
Assert.AreEqual(created.ToLongTimeString(), image.CreateDate.ToLongTimeString());
|
||||
Assert.AreEqual(updated.ToLongTimeString(), image.LastUpdated.ToLongTimeString());
|
||||
Assert.AreEqual(new Uri("http://someuri.com/images/12345"), image.PermanentUri);
|
||||
Assert.AreEqual(new Uri("http://someuri.com/v2/images/12345"), image.PublicUri);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanConvertJsonPayloadMissingProgressToImage()
|
||||
{
|
||||
var created = DateTime.Parse("2014-05-30T16:56:32Z").ToUniversalTime();
|
||||
var updated = DateTime.Parse("2014-06-30T16:56:32Z").ToUniversalTime();
|
||||
var missingFixture = @"{
|
||||
""image"" : {
|
||||
""name"": ""image1"",
|
||||
""status"": ""ACTIVE"",
|
||||
""updated"": ""2014-06-30T16:56:32Z"",
|
||||
""created"": ""2014-05-30T16:56:32Z"",
|
||||
""minDisk"": 10,
|
||||
""minRam"": 512,
|
||||
""links"": [
|
||||
{
|
||||
""href"": ""http://someuri.com/v2/images/12345"",
|
||||
""rel"": ""self""
|
||||
},
|
||||
{
|
||||
""href"": ""http://someuri.com/images/12345"",
|
||||
""rel"": ""bookmark""
|
||||
}
|
||||
],
|
||||
""id"": ""12345""
|
||||
}
|
||||
}";
|
||||
|
||||
var converter = new ComputeImagePayloadConverter();
|
||||
var image = converter.ConvertImage(missingFixture);
|
||||
Assert.IsNotNull(image);
|
||||
Assert.AreEqual("image1", image.Name);
|
||||
Assert.AreEqual("ACTIVE", image.Status);
|
||||
Assert.AreEqual("12345", image.Id);
|
||||
Assert.AreEqual(512, image.MinimumRamSize);
|
||||
Assert.AreEqual(10, image.MinimumDiskSize);
|
||||
Assert.AreEqual(0, image.UploadProgress);
|
||||
Assert.AreEqual(created, image.CreateDate);
|
||||
Assert.AreEqual(updated, image.LastUpdated);
|
||||
Assert.AreEqual(new Uri("http://someuri.com/images/12345"), image.PermanentUri);
|
||||
Assert.AreEqual(new Uri("http://someuri.com/v2/images/12345"), image.PublicUri);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(FormatException))]
|
||||
public void CannotConvertJsonPayloadMissingIdToImage()
|
||||
{
|
||||
var missingFixture = @"{
|
||||
""image"" : {
|
||||
""name"": ""image1"",
|
||||
""status"": ""ACTIVE"",
|
||||
""updated"": ""2014-06-30T16:56:32Z"",
|
||||
""created"": ""2014-05-30T16:56:32Z"",
|
||||
""minDisk"": 10,
|
||||
""progress"": 100,
|
||||
""minRam"": 512,
|
||||
""links"": [
|
||||
{
|
||||
""href"": ""http://someuri.com/v2/images/12345"",
|
||||
""rel"": ""self""
|
||||
},
|
||||
{
|
||||
""href"": ""http://someuri.com/images/12345"",
|
||||
""rel"": ""bookmark""
|
||||
}
|
||||
]
|
||||
}
|
||||
}";
|
||||
|
||||
var converter = new ComputeImagePayloadConverter();
|
||||
converter.ConvertImage(missingFixture);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(FormatException))]
|
||||
public void CannotConvertJsonPayloadMissingNameToImage()
|
||||
{
|
||||
var missingFixture = @"{
|
||||
""image"" : {
|
||||
""status"": ""ACTIVE"",
|
||||
""updated"": ""2014-06-30T16:56:32Z"",
|
||||
""created"": ""2014-05-30T16:56:32Z"",
|
||||
""minDisk"": 10,
|
||||
""progress"": 100,
|
||||
""minRam"": 512,
|
||||
""links"": [
|
||||
{
|
||||
""href"": ""http://someuri.com/v2/images/12345"",
|
||||
""rel"": ""self""
|
||||
},
|
||||
{
|
||||
""href"": ""http://someuri.com/images/12345"",
|
||||
""rel"": ""bookmark""
|
||||
}
|
||||
],
|
||||
""id"": ""12345""
|
||||
}
|
||||
}";
|
||||
|
||||
var converter = new ComputeImagePayloadConverter();
|
||||
converter.ConvertImage(missingFixture);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(FormatException))]
|
||||
public void CannotConvertJsonPayloadEmptyObjectToImage()
|
||||
{
|
||||
var emptyObjectFixture = @"{ }";
|
||||
|
||||
var converter = new ComputeImagePayloadConverter();
|
||||
converter.ConvertImage(emptyObjectFixture);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(FormatException))]
|
||||
public void CannotConvertInvalidJsonToImage()
|
||||
{
|
||||
var badJsonFixture = @"{ NOT JSON";
|
||||
|
||||
var converter = new ComputeImagePayloadConverter();
|
||||
converter.ConvertImage(badJsonFixture);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(FormatException))]
|
||||
public void CannotConvertNonObjectJsonToImage()
|
||||
{
|
||||
var nonObjectJson = @"[]";
|
||||
|
||||
var converter = new ComputeImagePayloadConverter();
|
||||
converter.ConvertImage(nonObjectJson);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanParseValidFlavorsJsonPayloadWithMultipleFlavors()
|
||||
{
|
||||
var validMultipleImagesJsonFixture = @"{{ ""images"": [ {0} ] }}";
|
||||
var firstImage = CreateImageSummaryJsonFixtrue("image1", "12345", "http://server.com/images/12345",
|
||||
"http://server.com/v2/images/12345");
|
||||
var secondImage = CreateImageSummaryJsonFixtrue("image2", "23456", "http://server.com/images/23456",
|
||||
"http://server.com/v2/images/23456");
|
||||
|
||||
var validMultipleImagesJson = string.Format(validMultipleImagesJsonFixture,
|
||||
string.Join(",", new List<string>() { firstImage, secondImage }));
|
||||
|
||||
var converter = new ComputeImagePayloadConverter();
|
||||
var images = converter.ConvertImages(validMultipleImagesJson).ToList();
|
||||
|
||||
Assert.AreEqual(2, images.Count());
|
||||
var img1 =
|
||||
images.First(o => string.Equals(o.Name, "image1", StringComparison.InvariantCultureIgnoreCase));
|
||||
var img2 =
|
||||
images.First(o => string.Equals(o.Name, "image2", StringComparison.InvariantCultureIgnoreCase));
|
||||
Assert.IsNotNull(img1);
|
||||
Assert.IsNotNull(img2);
|
||||
|
||||
Assert.AreEqual("12345", img1.Id);
|
||||
Assert.AreEqual(new Uri("http://server.com/images/12345"), img1.PermanentUri);
|
||||
Assert.AreEqual(new Uri("http://server.com/v2/images/12345"), img1.PublicUri);
|
||||
|
||||
Assert.AreEqual("23456", img2.Id);
|
||||
Assert.AreEqual(new Uri("http://server.com/images/23456"), img2.PermanentUri);
|
||||
Assert.AreEqual(new Uri("http://server.com/v2/images/23456"), img2.PublicUri);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanConvertValidFlavorsJsonPayloadWithSingleFlavor()
|
||||
{
|
||||
var validImagesJsonFixture = @"{{ ""images"": [ {0} ] }}";
|
||||
var firstImage = CreateImageSummaryJsonFixtrue("image1", "12345", "http://server.com/images/12345",
|
||||
"http://server.com/v2/images/12345");
|
||||
var validImagesJson = string.Format(validImagesJsonFixture, firstImage);
|
||||
|
||||
var converter = new ComputeImagePayloadConverter();
|
||||
var images = converter.ConvertImages(validImagesJson).ToList();
|
||||
|
||||
Assert.AreEqual(1, images.Count());
|
||||
var img1 =
|
||||
images.First(o => string.Equals(o.Name, "image1", StringComparison.InvariantCultureIgnoreCase));
|
||||
|
||||
Assert.IsNotNull(img1);
|
||||
|
||||
Assert.AreEqual("12345", img1.Id);
|
||||
Assert.AreEqual(new Uri("http://server.com/images/12345"), img1.PermanentUri);
|
||||
Assert.AreEqual(new Uri("http://server.com/v2/images/12345"), img1.PublicUri);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanParseValidImagesPayloadWithEmptyJsonArray()
|
||||
{
|
||||
var emptyJsonArray = @"{ ""images"": [ ] }";
|
||||
|
||||
var converter = new ComputeImagePayloadConverter();
|
||||
var containers = converter.ConvertImages(emptyJsonArray).ToList();
|
||||
|
||||
Assert.AreEqual(0, containers.Count());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanParseAnEmptyImagesPayload()
|
||||
{
|
||||
var payload = string.Empty;
|
||||
|
||||
var converter = new ComputeImagePayloadConverter();
|
||||
var containers = converter.ConvertImages(payload).ToList();
|
||||
|
||||
Assert.AreEqual(0, containers.Count());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(ArgumentNullException))]
|
||||
public void CannotParseANullImagesPayload()
|
||||
{
|
||||
var converter = new ComputeImagePayloadConverter();
|
||||
converter.ConvertImages(null);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(FormatException))]
|
||||
public void CannotParseInvalidImagesJsonPayload()
|
||||
{
|
||||
var converter = new ComputeImagePayloadConverter();
|
||||
converter.ConvertImages("[ { \"SomeAtrib\" }]");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(FormatException))]
|
||||
public void CannotParseInvalidImagesPayload()
|
||||
{
|
||||
var converter = new ComputeImagePayloadConverter();
|
||||
converter.ConvertImages("NOT JSON");
|
||||
}
|
||||
}
|
||||
}
|
@ -1,131 +0,0 @@
|
||||
// /* ============================================================================
|
||||
// Copyright 2014 Hewlett Packard
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ============================================================================ */
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using OpenStack.Compute;
|
||||
|
||||
namespace OpenStack.Test.Compute
|
||||
{
|
||||
[TestClass]
|
||||
public class ComputeItemMetadataPayloadConverterTests
|
||||
{
|
||||
[TestMethod]
|
||||
public void CanConvertJsonPayloadToMetadata()
|
||||
{
|
||||
var metadataPayload = @"{
|
||||
""metadata"": {
|
||||
""item1"": ""value1"",
|
||||
""item2"": ""value2""
|
||||
}
|
||||
}";
|
||||
|
||||
var converter = new ComputeItemMetadataPayloadConverter();
|
||||
var metadata = converter.Convert(metadataPayload);
|
||||
|
||||
Assert.AreEqual(2, metadata.Count);
|
||||
Assert.IsTrue(metadata.ContainsKey("item1"));
|
||||
Assert.AreEqual("value1",metadata["item1"]);
|
||||
Assert.IsTrue(metadata.ContainsKey("item2"));
|
||||
Assert.AreEqual("value2", metadata["item2"]);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(FormatException))]
|
||||
public void CannotConvertJsonPayloadEmptyObjectToMetadata()
|
||||
{
|
||||
var emptyObjectFixture = @"{ }";
|
||||
|
||||
var converter = new ComputeItemMetadataPayloadConverter();
|
||||
converter.Convert(emptyObjectFixture);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(FormatException))]
|
||||
public void CannotConvertNonObjectJsonToMetadata()
|
||||
{
|
||||
var nonObjectJson = @"[]";
|
||||
|
||||
var converter = new ComputeItemMetadataPayloadConverter();
|
||||
converter.Convert(nonObjectJson);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(FormatException))]
|
||||
public void CannotConvertInvalidJsonToMetadata()
|
||||
{
|
||||
var badJsonFixture = @"{ NOT JSON";
|
||||
|
||||
var converter = new ComputeItemMetadataPayloadConverter();
|
||||
converter.Convert(badJsonFixture);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanConvertEmptyMetadataToJson()
|
||||
{
|
||||
var metadata = new Dictionary<string, string>();
|
||||
|
||||
var converter = new ComputeItemMetadataPayloadConverter();
|
||||
var payload = converter.Convert(metadata);
|
||||
|
||||
var jsonObj = JObject.Parse(payload);
|
||||
var metadataToken = jsonObj["metadata"];
|
||||
Assert.IsNotNull(metadataToken);
|
||||
Assert.AreEqual(0, metadataToken.Children().Count());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanConvertSingleMetadataToJson()
|
||||
{
|
||||
var metadata = new Dictionary<string, string>() { { "item1", "value1" } };
|
||||
|
||||
var converter = new ComputeItemMetadataPayloadConverter();
|
||||
var payload = converter.Convert(metadata);
|
||||
|
||||
var jsonObj = JObject.Parse(payload);
|
||||
var metadataToken = jsonObj["metadata"];
|
||||
Assert.IsNotNull(metadataToken);
|
||||
Assert.AreEqual("value1", metadataToken["item1"]);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanConvertMultipleMetadataToJson()
|
||||
{
|
||||
var metadata = new Dictionary<string, string>() {{"item1", "value1"}, {"item2", "value2"}};
|
||||
|
||||
var converter = new ComputeItemMetadataPayloadConverter();
|
||||
var payload = converter.Convert(metadata);
|
||||
|
||||
var jsonObj = JObject.Parse(payload);
|
||||
var metadataToken = jsonObj["metadata"];
|
||||
Assert.IsNotNull(metadataToken);
|
||||
Assert.AreEqual("value1", metadataToken["item1"]);
|
||||
Assert.AreEqual("value2", metadataToken["item2"]);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(ArgumentNullException))]
|
||||
public void CannotConvertNullMetadataToJson()
|
||||
{
|
||||
IDictionary<string, string> metadata = null;
|
||||
var converter = new ComputeItemMetadataPayloadConverter();
|
||||
converter.Convert(metadata);
|
||||
}
|
||||
}
|
||||
}
|
@ -1,232 +0,0 @@
|
||||
// /* ============================================================================
|
||||
// Copyright 2014 Hewlett Packard
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ============================================================================ */
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
using OpenStack.Compute;
|
||||
|
||||
namespace OpenStack.Test.Compute
|
||||
{
|
||||
[TestClass]
|
||||
public class ComputeKeyPairPayloadConverterTests
|
||||
{
|
||||
internal string CreateKeyPairJsonFixtrue(string name, string publickKey, string fingerprint)
|
||||
{
|
||||
var ComputeKeyPairJsonResponseFixture = @"{{
|
||||
""keypair"": {{
|
||||
""public_key"": ""{1}"",
|
||||
""name"": ""{0}"",
|
||||
""fingerprint"": ""{2}""
|
||||
}}
|
||||
}}";
|
||||
|
||||
return string.Format(ComputeKeyPairJsonResponseFixture, name, publickKey, fingerprint);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanConvertJsonPayloadToKeyPair()
|
||||
{
|
||||
var keyName = "Key1";
|
||||
var publicKey = "12345";
|
||||
var fingerprint = "abcdef";
|
||||
|
||||
var computeFlavorJsonResponseFixture = CreateKeyPairJsonFixtrue(keyName, publicKey, fingerprint);
|
||||
|
||||
var converter = new ComputeKeyPairPayloadConverter();
|
||||
var keyPair = converter.Convert(computeFlavorJsonResponseFixture);
|
||||
Assert.IsNotNull(keyPair);
|
||||
Assert.AreEqual(keyName, keyPair.Name);
|
||||
Assert.AreEqual(publicKey, keyPair.PublicKey);
|
||||
Assert.AreEqual(fingerprint, keyPair.Fingerprint);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanConvertJsonPayloadMissingPublicKey()
|
||||
{
|
||||
var missingFixture = @"{
|
||||
""keypair"": {
|
||||
""name"": ""Key1"",
|
||||
""fingerprint"": ""ABCDEF""
|
||||
}
|
||||
}";
|
||||
|
||||
var converter = new ComputeKeyPairPayloadConverter();
|
||||
var keyPair = converter.Convert(missingFixture);
|
||||
Assert.IsNotNull(keyPair);
|
||||
Assert.AreEqual("Key1", keyPair.Name);
|
||||
Assert.AreEqual(string.Empty, keyPair.PublicKey);
|
||||
Assert.AreEqual("ABCDEF", keyPair.Fingerprint);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanConvertJsonPayloadMissingFingerprint()
|
||||
{
|
||||
var missingFixture = @"{
|
||||
""keypair"": {
|
||||
""public_key"": ""12345"",
|
||||
""name"": ""Key1""
|
||||
}
|
||||
}";
|
||||
|
||||
var converter = new ComputeKeyPairPayloadConverter();
|
||||
var keyPair = converter.Convert(missingFixture);
|
||||
Assert.IsNotNull(keyPair);
|
||||
Assert.AreEqual("Key1", keyPair.Name);
|
||||
Assert.AreEqual("12345", keyPair.PublicKey);
|
||||
Assert.AreEqual(string.Empty, keyPair.Fingerprint);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(FormatException))]
|
||||
public void CannotConvertJsonPayloadMissingName()
|
||||
{
|
||||
var missingFixture = @"{
|
||||
""keypair"": {
|
||||
""public_key"": ""12345"",
|
||||
""fingerprint"": ""ABCDEF""
|
||||
}
|
||||
}";
|
||||
|
||||
var converter = new ComputeKeyPairPayloadConverter();
|
||||
converter.Convert(missingFixture);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(FormatException))]
|
||||
public void CannotConvertJsonPayloadEmptyObjectToKeyPair()
|
||||
{
|
||||
var emptyObjectFixture = @"{ }";
|
||||
|
||||
var converter = new ComputeKeyPairPayloadConverter();
|
||||
converter.ConvertKeyPairs(emptyObjectFixture);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(FormatException))]
|
||||
public void CannotConvertInvalidJsonToKeyPair()
|
||||
{
|
||||
var badJsonFixture = @"{ NOT JSON";
|
||||
|
||||
var converter = new ComputeKeyPairPayloadConverter();
|
||||
converter.ConvertKeyPairs(badJsonFixture);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(FormatException))]
|
||||
public void CannotConvertNonObjectJsonToKeyPair()
|
||||
{
|
||||
var nonObjectJson = @"[]";
|
||||
|
||||
var converter = new ComputeKeyPairPayloadConverter();
|
||||
converter.ConvertKeyPairs(nonObjectJson);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanParseValidJsonPayloadWithMultipleKeyPairs()
|
||||
{
|
||||
var validMultipleKeyPairsJsonFixture = @"{{ ""keypairs"": [ {0} ] }}";
|
||||
var firstKey = CreateKeyPairJsonFixtrue("Key1", "12345", "abcdef");
|
||||
var secondKey = CreateKeyPairJsonFixtrue("Key2", "54321", "fedcba");
|
||||
|
||||
var validMultipleKeyPairsJson = string.Format(validMultipleKeyPairsJsonFixture,
|
||||
string.Join(",", new List<string>() {firstKey, secondKey}));
|
||||
|
||||
var converter = new ComputeKeyPairPayloadConverter();
|
||||
var pairs = converter.ConvertKeyPairs(validMultipleKeyPairsJson).ToList();
|
||||
|
||||
Assert.AreEqual(2, pairs.Count());
|
||||
var key1 =
|
||||
pairs.First(o => string.Equals(o.Name, "Key1", StringComparison.InvariantCultureIgnoreCase));
|
||||
var key2 =
|
||||
pairs.First(o => string.Equals(o.Name, "Key2", StringComparison.InvariantCultureIgnoreCase));
|
||||
Assert.IsNotNull(key1);
|
||||
Assert.IsNotNull(key2);
|
||||
|
||||
Assert.AreEqual("12345", key1.PublicKey);
|
||||
Assert.AreEqual("abcdef", key1.Fingerprint);
|
||||
|
||||
Assert.AreEqual("54321", key2.PublicKey);
|
||||
Assert.AreEqual("fedcba", key2.Fingerprint);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanConvertValidJsonPayloadWithSingleKeyPair()
|
||||
{
|
||||
var validKeyPairsJsonFixture = @"{{ ""keypairs"": [ {0} ] }}";
|
||||
var firstKey = CreateKeyPairJsonFixtrue("Key1", "12345", "abcdef");
|
||||
|
||||
var validKeyPairsJson = string.Format(validKeyPairsJsonFixture, firstKey);
|
||||
|
||||
var converter = new ComputeKeyPairPayloadConverter();
|
||||
var pairs = converter.ConvertKeyPairs(validKeyPairsJson).ToList();
|
||||
|
||||
Assert.AreEqual(1, pairs.Count());
|
||||
var key1 = pairs.First(o => string.Equals(o.Name, "Key1", StringComparison.InvariantCultureIgnoreCase));
|
||||
Assert.IsNotNull(key1);
|
||||
|
||||
Assert.AreEqual("12345", key1.PublicKey);
|
||||
Assert.AreEqual("abcdef", key1.Fingerprint);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanParseValidKeyPairsPayloadWithEmptyJsonArray()
|
||||
{
|
||||
var emptyJsonArray = @"{ ""keypairs"": [ ] }";
|
||||
|
||||
var converter = new ComputeKeyPairPayloadConverter();
|
||||
var containers = converter.ConvertKeyPairs(emptyJsonArray).ToList();
|
||||
|
||||
Assert.AreEqual(0, containers.Count());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanParseAnEmptyKeyPairsPayload()
|
||||
{
|
||||
var payload = string.Empty;
|
||||
|
||||
var converter = new ComputeKeyPairPayloadConverter();
|
||||
var containers = converter.ConvertKeyPairs(payload).ToList();
|
||||
|
||||
Assert.AreEqual(0, containers.Count());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(ArgumentNullException))]
|
||||
public void CannotParseANullKeyPairsPayload()
|
||||
{
|
||||
var converter = new ComputeKeyPairPayloadConverter();
|
||||
converter.ConvertKeyPairs(null);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(FormatException))]
|
||||
public void CannotParseInvalidKeyPairsJsonPayload()
|
||||
{
|
||||
var converter = new ComputeKeyPairPayloadConverter();
|
||||
converter.ConvertKeyPairs("[ { \"SomeAtrib\" }]");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(FormatException))]
|
||||
public void CannotParseInvalidKeyPairsPayload()
|
||||
{
|
||||
var converter = new ComputeKeyPairPayloadConverter();
|
||||
converter.ConvertKeyPairs("NOT JSON");
|
||||
}
|
||||
}
|
||||
}
|
@ -1,733 +0,0 @@
|
||||
// /* ============================================================================
|
||||
// Copyright 2014 Hewlett Packard
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ============================================================================ */
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Mime;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using OpenStack.Common;
|
||||
using OpenStack.Common.Http;
|
||||
using OpenStack.Compute;
|
||||
|
||||
namespace OpenStack.Test.Compute
|
||||
{
|
||||
public class ComputeRestSimulator : RestSimulator
|
||||
{
|
||||
internal ICollection<ComputeFlavor> Flavors { get; private set; }
|
||||
|
||||
internal ICollection<ComputeImage> Images { get; private set; }
|
||||
|
||||
internal ICollection<ComputeServer> Servers { get; private set; }
|
||||
|
||||
internal ICollection<ComputeKeyPair> KeyPairs { get; private set; }
|
||||
|
||||
public ComputeRestSimulator() : base()
|
||||
{
|
||||
this.Flavors = new List<ComputeFlavor>();
|
||||
this.Images = new List<ComputeImage>();
|
||||
this.Servers = new List<ComputeServer>();
|
||||
this.KeyPairs = new List<ComputeKeyPair>();
|
||||
}
|
||||
|
||||
public ComputeRestSimulator(CancellationToken token) : this()
|
||||
{
|
||||
}
|
||||
|
||||
protected override IHttpResponseAbstraction HandleGet()
|
||||
{
|
||||
if (this.Uri.Segments.Count() >= 4)
|
||||
{
|
||||
switch (this.Uri.Segments[3].TrimEnd('/').ToLower())
|
||||
{
|
||||
case "flavors":
|
||||
return HandleGetFlavor();
|
||||
case "images":
|
||||
return HandleGetImage();
|
||||
case "servers":
|
||||
return HandleGetServer();
|
||||
case "os-keypairs":
|
||||
return HandleGetKeyPairs();
|
||||
}
|
||||
}
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
internal IHttpResponseAbstraction HandleGetFlavor()
|
||||
{
|
||||
Stream flavorContent;
|
||||
switch (this.Uri.Segments.Count())
|
||||
{
|
||||
case 5:
|
||||
//flavor id given, list single flavor
|
||||
var flavorId = this.Uri.Segments[4].TrimEnd('/');
|
||||
var flavor =
|
||||
this.Flavors.FirstOrDefault(
|
||||
f => string.Equals(f.Id, flavorId, StringComparison.OrdinalIgnoreCase));
|
||||
if (flavor == null)
|
||||
{
|
||||
return TestHelper.CreateResponse(HttpStatusCode.NotFound);
|
||||
}
|
||||
|
||||
flavorContent = TestHelper.CreateStream(GenerateFlavorPayload(flavor));
|
||||
break;
|
||||
case 4:
|
||||
//no flavor id given, list all flavors
|
||||
flavorContent = TestHelper.CreateStream(GenerateItemsPayload(this.Flavors, "flavors"));
|
||||
break;
|
||||
default:
|
||||
//Unknown Uri format
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
return TestHelper.CreateResponse(HttpStatusCode.OK, new Dictionary<string, string>(), flavorContent);
|
||||
}
|
||||
|
||||
internal IHttpResponseAbstraction HandleGetKeyPairs()
|
||||
{
|
||||
Stream keyPairContent;
|
||||
switch (this.Uri.Segments.Count())
|
||||
{
|
||||
case 5:
|
||||
var keyPairName = this.Uri.Segments[4].TrimEnd('/');
|
||||
var pair =
|
||||
this.KeyPairs.FirstOrDefault(
|
||||
kp => string.Equals(kp.Name, keyPairName, StringComparison.OrdinalIgnoreCase));
|
||||
if (pair == null)
|
||||
{
|
||||
return TestHelper.CreateResponse(HttpStatusCode.NotFound);
|
||||
}
|
||||
|
||||
keyPairContent = TestHelper.CreateStream(GenerateKeyPairPayload(pair));
|
||||
break;
|
||||
case 4:
|
||||
keyPairContent = TestHelper.CreateStream(GenerateKeyPairsPayload(this.KeyPairs));
|
||||
break;
|
||||
default:
|
||||
//Unknown Uri format
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
return TestHelper.CreateResponse(HttpStatusCode.OK, new Dictionary<string, string>(), keyPairContent);
|
||||
}
|
||||
|
||||
internal IHttpResponseAbstraction HandleGetImage()
|
||||
{
|
||||
Stream imageContent;
|
||||
switch (this.Uri.Segments.Count())
|
||||
{
|
||||
case 5:
|
||||
//image id given, list single image
|
||||
var imageId = this.Uri.Segments[4].TrimEnd('/');
|
||||
if (imageId.ToLower() == "detail")
|
||||
{
|
||||
imageContent = TestHelper.CreateStream(GenerateItemsPayload(this.Images, "images"));
|
||||
}
|
||||
else
|
||||
{
|
||||
var image =
|
||||
this.Images.FirstOrDefault(
|
||||
f => string.Equals(f.Id, imageId, StringComparison.OrdinalIgnoreCase));
|
||||
if (image == null)
|
||||
{
|
||||
return TestHelper.CreateResponse(HttpStatusCode.NotFound);
|
||||
}
|
||||
|
||||
imageContent = TestHelper.CreateStream(GenerateImagePayload(image));
|
||||
}
|
||||
break;
|
||||
case 6:
|
||||
if (this.Uri.Segments[5].TrimEnd('/').ToLower() != "metadata")
|
||||
{
|
||||
return TestHelper.CreateResponse(HttpStatusCode.NotFound);
|
||||
}
|
||||
var imgId = this.Uri.Segments[4].TrimEnd('/');
|
||||
var img =
|
||||
this.Images.FirstOrDefault(
|
||||
i => string.Equals(i.Id, imgId, StringComparison.OrdinalIgnoreCase));
|
||||
if (img == null)
|
||||
{
|
||||
return TestHelper.CreateResponse(HttpStatusCode.NotFound);
|
||||
}
|
||||
imageContent = TestHelper.CreateStream(GenerateMetadataPayload(img.Metadata));
|
||||
break;
|
||||
default:
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
return TestHelper.CreateResponse(HttpStatusCode.OK, new Dictionary<string, string>(), imageContent);
|
||||
}
|
||||
|
||||
internal IHttpResponseAbstraction HandleGetServer()
|
||||
{
|
||||
Stream serverContent;
|
||||
|
||||
if (this.Uri.Segments.Count() < 5)
|
||||
{
|
||||
if (this.Uri.Segments.Count() == 4)
|
||||
{
|
||||
serverContent = TestHelper.CreateStream(GenerateItemsPayload(this.Flavors, "servers"));
|
||||
return TestHelper.CreateResponse(HttpStatusCode.OK, new Dictionary<string, string>(), serverContent);
|
||||
}
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
var srvId = this.Uri.Segments[4].TrimEnd('/');
|
||||
var srv =
|
||||
this.Servers.FirstOrDefault(
|
||||
s => string.Equals(s.Id, srvId, StringComparison.OrdinalIgnoreCase));
|
||||
if (srv == null)
|
||||
{
|
||||
return TestHelper.CreateResponse(HttpStatusCode.NotFound);
|
||||
}
|
||||
|
||||
|
||||
switch (this.Uri.Segments.Count())
|
||||
{
|
||||
case 6:
|
||||
if (this.Uri.Segments[5].TrimEnd('/').ToLower() != "metadata")
|
||||
{
|
||||
return TestHelper.CreateResponse(HttpStatusCode.NotFound);
|
||||
}
|
||||
|
||||
serverContent = TestHelper.CreateStream(GenerateMetadataPayload(srv.Metadata));
|
||||
break;
|
||||
case 5:
|
||||
//server id given, list single server
|
||||
serverContent = TestHelper.CreateStream(GenerateServerPayload(srv));
|
||||
break;
|
||||
default:
|
||||
//Unknown Uri format
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
return TestHelper.CreateResponse(HttpStatusCode.OK, new Dictionary<string, string>(), serverContent);
|
||||
}
|
||||
|
||||
protected override IHttpResponseAbstraction HandlePost()
|
||||
{
|
||||
if (this.Uri.Segments.Count() >= 4)
|
||||
{
|
||||
switch (this.Uri.Segments[3].TrimEnd('/').ToLower())
|
||||
{
|
||||
case "servers":
|
||||
return HandlePostServer();
|
||||
case "images":
|
||||
return HandlePostImage();
|
||||
}
|
||||
}
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
protected override IHttpResponseAbstraction HandlePut()
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
internal IHttpResponseAbstraction HandlePostImage()
|
||||
{
|
||||
switch (this.Uri.Segments.Count())
|
||||
{
|
||||
case 6:
|
||||
if (this.Uri.Segments[5].TrimEnd('/').ToLower() != "metadata")
|
||||
{
|
||||
return TestHelper.CreateResponse(HttpStatusCode.NotFound);
|
||||
}
|
||||
var imgId = this.Uri.Segments[4].TrimEnd('/');
|
||||
var img =
|
||||
this.Images.FirstOrDefault(
|
||||
i => string.Equals(i.Id, imgId, StringComparison.OrdinalIgnoreCase));
|
||||
if (img == null)
|
||||
{
|
||||
return TestHelper.CreateResponse(HttpStatusCode.NotFound);
|
||||
}
|
||||
|
||||
ParseAndStoreMetadata(img, GetPayload(this.Content));
|
||||
break;
|
||||
default:
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
return TestHelper.CreateResponse(HttpStatusCode.OK, new Dictionary<string, string>());
|
||||
}
|
||||
|
||||
internal IHttpResponseAbstraction HandlePostServer()
|
||||
{
|
||||
switch (this.Uri.Segments.Count())
|
||||
{
|
||||
case 4:
|
||||
return HandlePostNewServer();
|
||||
case 6:
|
||||
var srvId = this.Uri.Segments[4].TrimEnd('/');
|
||||
var action = this.Uri.Segments[5].TrimEnd('/').ToLower();
|
||||
switch (action)
|
||||
{
|
||||
case "metadata":
|
||||
return HandlePostServerMetadata(srvId);
|
||||
case "action":
|
||||
return HandlePostServerAction(srvId);
|
||||
default:
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
default:
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
}
|
||||
|
||||
internal IHttpResponseAbstraction HandlePostServerAction(string serverId)
|
||||
{
|
||||
this.Content.Position = 0;
|
||||
var reqBody = TestHelper.GetStringFromStream(this.Content);
|
||||
var body = JObject.Parse(reqBody);
|
||||
if (body["addFloatingIp"] != null && body["addFloatingIp"]["address"] != null)
|
||||
{
|
||||
return TestHelper.CreateResponse(HttpStatusCode.Accepted, new Dictionary<string, string>());
|
||||
}
|
||||
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
internal IHttpResponseAbstraction HandlePostServerMetadata(string serverId)
|
||||
{
|
||||
var srv =
|
||||
this.Servers.FirstOrDefault(
|
||||
s => string.Equals(s.Id, serverId, StringComparison.OrdinalIgnoreCase));
|
||||
if (srv == null)
|
||||
{
|
||||
return TestHelper.CreateResponse(HttpStatusCode.NotFound);
|
||||
}
|
||||
|
||||
ParseAndStoreMetadata(srv, GetPayload(this.Content));
|
||||
return TestHelper.CreateResponse(HttpStatusCode.OK, new Dictionary<string, string>());
|
||||
}
|
||||
|
||||
internal IHttpResponseAbstraction HandlePostNewServer()
|
||||
{
|
||||
var payload = TestHelper.GetStringFromStream(this.Content);
|
||||
var obj = JObject.Parse(payload);
|
||||
var name = (string)obj["server"]["name"];
|
||||
var srv = new ComputeServer(Guid.NewGuid().ToString(), name, "12345", new Uri("http://test.com"), new Uri("http://test.com"), new Dictionary<string, string>());
|
||||
this.Servers.Add(srv);
|
||||
var responsePayload = GenerateCreateServeResponse(srv);
|
||||
|
||||
return TestHelper.CreateResponse(HttpStatusCode.Accepted, new Dictionary<string, string>(), responsePayload.ConvertToStream());
|
||||
}
|
||||
|
||||
protected override IHttpResponseAbstraction HandleDelete()
|
||||
{
|
||||
if (this.Uri.Segments.Count() >= 4)
|
||||
{
|
||||
switch (this.Uri.Segments[3].TrimEnd('/').ToLower())
|
||||
{
|
||||
case "images":
|
||||
return HandleDeleteImages();
|
||||
case "flavors":
|
||||
return HandleDeleteFlavors();
|
||||
case "servers":
|
||||
return HandleDeleteServers();
|
||||
}
|
||||
}
|
||||
return TestHelper.CreateResponse(HttpStatusCode.NotFound);
|
||||
}
|
||||
|
||||
private IHttpResponseAbstraction HandleDeleteImages()
|
||||
{
|
||||
if (this.Uri.Segments.Count() < 5)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
var imageId = this.Uri.Segments[4].TrimEnd('/');
|
||||
var image = this.Images.FirstOrDefault(i => i.Id == imageId);
|
||||
if (image == null)
|
||||
{
|
||||
return TestHelper.CreateResponse(HttpStatusCode.NotFound);
|
||||
}
|
||||
|
||||
switch (this.Uri.Segments.Count())
|
||||
{
|
||||
case 5:
|
||||
this.Images.Remove(image);
|
||||
return TestHelper.CreateResponse(HttpStatusCode.OK);
|
||||
case 7:
|
||||
var key = this.Uri.Segments[6].TrimEnd('/');
|
||||
if (!image.Metadata.ContainsKey(key))
|
||||
{
|
||||
return TestHelper.CreateResponse(HttpStatusCode.NotFound);
|
||||
}
|
||||
image.Metadata.Remove(key);
|
||||
return TestHelper.CreateResponse(HttpStatusCode.OK);
|
||||
default:
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
}
|
||||
|
||||
private IHttpResponseAbstraction HandleDeleteFlavors()
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
private IHttpResponseAbstraction HandleDeleteServers()
|
||||
{
|
||||
if (this.Uri.Segments.Count() < 5)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
var srvId = this.Uri.Segments[4].TrimEnd('/');
|
||||
var srv = this.Servers.FirstOrDefault(s => s.Id == srvId);
|
||||
if (srv == null)
|
||||
{
|
||||
return TestHelper.CreateResponse(HttpStatusCode.NotFound);
|
||||
}
|
||||
|
||||
switch (this.Uri.Segments.Count())
|
||||
{
|
||||
case 5:
|
||||
this.Servers.Remove(srv);
|
||||
return TestHelper.CreateResponse(HttpStatusCode.OK);
|
||||
case 7:
|
||||
var key = this.Uri.Segments[6].TrimEnd('/');
|
||||
if (!srv.Metadata.ContainsKey(key))
|
||||
{
|
||||
return TestHelper.CreateResponse(HttpStatusCode.NotFound);
|
||||
}
|
||||
srv.Metadata.Remove(key);
|
||||
return TestHelper.CreateResponse(HttpStatusCode.OK);
|
||||
default:
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
}
|
||||
|
||||
protected override IHttpResponseAbstraction HandleHead()
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
protected override IHttpResponseAbstraction HandleCopy()
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
private string GetPayload(Stream input)
|
||||
{
|
||||
using (var sr = new StreamReader(input))
|
||||
{
|
||||
return sr.ReadToEnd();
|
||||
}
|
||||
}
|
||||
|
||||
private string GenerateItemsPayload(IEnumerable<ComputeItem> items, string collectionName )
|
||||
{
|
||||
var payload = new StringBuilder();
|
||||
payload.Append(string.Format("{{ \"{0}\": [",collectionName));
|
||||
var first = true;
|
||||
foreach (var item in items)
|
||||
{
|
||||
if (!first)
|
||||
{
|
||||
payload.Append(",");
|
||||
}
|
||||
|
||||
payload.Append("{");
|
||||
payload.Append(string.Format("\"id\": \"{0}\",", item.Id));
|
||||
payload.Append("\"links\": [");
|
||||
payload.Append("{");
|
||||
payload.Append(string.Format("\"href\": \"{0}\",", item.PublicUri.AbsoluteUri));
|
||||
payload.Append("\"rel\": \"self\"");
|
||||
payload.Append("},{");
|
||||
payload.Append(string.Format("\"href\": \"{0}\",", item.PermanentUri.AbsoluteUri));
|
||||
payload.Append("\"rel\": \"bookmark\"");
|
||||
payload.Append("}");
|
||||
payload.Append("],");
|
||||
payload.Append(string.Format("\"name\": \"{0}\"", item.Name));
|
||||
payload.Append("}");
|
||||
first = false;
|
||||
}
|
||||
payload.Append("] }");
|
||||
return payload.ToString();
|
||||
}
|
||||
|
||||
private string GenerateKeyPairPayload(ComputeKeyPair keyPair)
|
||||
{
|
||||
var payloadFixture = @"{{
|
||||
""keypair"": {{
|
||||
""public_key"": ""{1}"",
|
||||
""name"": ""{0}"",
|
||||
""fingerprint"": ""{2}""
|
||||
}}
|
||||
}}";
|
||||
return string.Format(payloadFixture, keyPair.Name, keyPair.PublicKey, keyPair.Fingerprint);
|
||||
}
|
||||
|
||||
private string GenerateKeyPairsPayload(IEnumerable<ComputeKeyPair> keyPairs)
|
||||
{
|
||||
var payload = new StringBuilder();
|
||||
payload.Append("{ \"keypairs\": [");
|
||||
var first = true;
|
||||
foreach (var keyPair in keyPairs)
|
||||
{
|
||||
if (!first)
|
||||
{
|
||||
payload.Append(",");
|
||||
}
|
||||
payload.Append(GenerateKeyPairPayload(keyPair));
|
||||
first = false;
|
||||
}
|
||||
|
||||
payload.Append("] }");
|
||||
return payload.ToString();
|
||||
}
|
||||
|
||||
private string GenerateFlavorPayload(ComputeFlavor flavor)
|
||||
{
|
||||
var payloadFixture = @"{{
|
||||
""flavor"" : {{
|
||||
""name"": ""{0}"",
|
||||
""links"": [
|
||||
{{
|
||||
""href"": ""{1}"",
|
||||
""rel"": ""self""
|
||||
}},
|
||||
{{
|
||||
""href"": ""{2}"",
|
||||
""rel"": ""bookmark""
|
||||
}}
|
||||
],
|
||||
""ram"": {3},
|
||||
""vcpus"": {4},
|
||||
""disk"": {5},
|
||||
""id"": ""{6}""
|
||||
}}
|
||||
}}";
|
||||
return string.Format(payloadFixture, flavor.Name, flavor.PublicUri.AbsoluteUri,
|
||||
flavor.PermanentUri.AbsoluteUri, flavor.Ram, flavor.Vcpus, flavor.Disk, flavor.Id);
|
||||
}
|
||||
|
||||
private string GenerateImagePayload(ComputeImage image)
|
||||
{
|
||||
var payloadFixture = @"{{
|
||||
""image"" : {{
|
||||
""name"": ""{0}"",
|
||||
""status"": ""{1}"",
|
||||
""updated"": ""{2}"",
|
||||
""created"": ""{3}"",
|
||||
""minDisk"": {4},
|
||||
""progress"": {5},
|
||||
""minRam"": {6},
|
||||
""links"": [
|
||||
{{
|
||||
""href"": ""{7}"",
|
||||
""rel"": ""self""
|
||||
}},
|
||||
{{
|
||||
""href"": ""{8}"",
|
||||
""rel"": ""bookmark""
|
||||
}}
|
||||
],
|
||||
""id"": ""{9}""
|
||||
}}
|
||||
}}";
|
||||
|
||||
return string.Format(payloadFixture, image.Name, image.Status, image.CreateDate, image.LastUpdated,
|
||||
image.MinimumDiskSize, image.UploadProgress, image.MinimumRamSize, image.PublicUri.AbsoluteUri,
|
||||
image.PermanentUri.AbsoluteUri, image.Id);
|
||||
}
|
||||
|
||||
internal string GenerateCreateServeResponse(ComputeServer server)
|
||||
{
|
||||
var payloadFixture = @"{{
|
||||
""server"": {{
|
||||
""security_groups"": [
|
||||
{{
|
||||
""name"": ""default""
|
||||
}},
|
||||
{{
|
||||
""name"": ""MyGroup""
|
||||
}}
|
||||
],
|
||||
""OS-DCF:diskConfig"": ""MANUAL"",
|
||||
""id"": ""{0}"",
|
||||
""links"": [
|
||||
{{
|
||||
""href"": ""{2}"",
|
||||
""rel"": ""self""
|
||||
}},
|
||||
{{
|
||||
""href"": ""{3}"",
|
||||
""rel"": ""bookmark""
|
||||
}}
|
||||
],
|
||||
""adminPass"": ""{1}""
|
||||
}}
|
||||
}}";
|
||||
|
||||
return string.Format(payloadFixture, server.Id, server.AdminPassword,
|
||||
server.PublicUri.AbsoluteUri, server.PermanentUri.AbsoluteUri);
|
||||
}
|
||||
|
||||
private string GenerateServerPayload(ComputeServer server)
|
||||
{
|
||||
var payloadFixture = @"{{
|
||||
""server"": {{
|
||||
""status"": ""{2}"",
|
||||
""updated"": ""2014-06-11T18:04:46Z"",
|
||||
""hostId"": ""bd5417ccb076908f6e0d639c37c053b0b6b9681db3464d19908dd4d9"",
|
||||
""addresses"": {{
|
||||
""private"": [
|
||||
{{
|
||||
""OS-EXT-IPS-MAC:mac_addr"": ""fa:16:3e:34:da:44"",
|
||||
""version"": 4,
|
||||
""addr"": ""10.0.0.2"",
|
||||
""OS-EXT-IPS:type"": ""fixed""
|
||||
}},
|
||||
{{
|
||||
""OS-EXT-IPS-MAC:mac_addr"": ""fa:16:3e:34:da:44"",
|
||||
""version"": 4,
|
||||
""addr"": ""172.24.4.3"",
|
||||
""OS-EXT-IPS:type"": ""floating""
|
||||
}}
|
||||
]
|
||||
}},
|
||||
""links"": [
|
||||
{{
|
||||
""href"": ""{4}"",
|
||||
""rel"": ""self""
|
||||
}},
|
||||
{{
|
||||
""href"": ""{5}"",
|
||||
""rel"": ""bookmark""
|
||||
}}
|
||||
],
|
||||
""key_name"": null,
|
||||
""image"": {{
|
||||
""id"": ""c650e788-3c46-4efc-bfa6-1d94a14d6405"",
|
||||
""links"": [
|
||||
{{
|
||||
""href"": ""http://15.125.87.81:8774/ffe683d1060449d09dac0bf9d7a371cd/images/c650e788-3c46-4efc-bfa6-1d94a14d6405"",
|
||||
""rel"": ""bookmark""
|
||||
}}
|
||||
]
|
||||
}},
|
||||
""OS-EXT-STS:task_state"": null,
|
||||
""OS-EXT-STS:vm_state"": ""active"",
|
||||
""OS-SRV-USG:launched_at"": ""2014-06-11T18:04:45.000000"",
|
||||
""flavor"": {{
|
||||
""id"": ""1"",
|
||||
""links"": [
|
||||
{{
|
||||
""href"": ""http://15.125.87.81:8774/ffe683d1060449d09dac0bf9d7a371cd/flavors/1"",
|
||||
""rel"": ""bookmark""
|
||||
}}
|
||||
]
|
||||
}},
|
||||
""id"": ""{0}"",
|
||||
""security_groups"": [
|
||||
{{
|
||||
""name"": ""MyGroup""
|
||||
}},
|
||||
{{
|
||||
""name"": ""default""
|
||||
}}
|
||||
],
|
||||
""OS-SRV-USG:terminated_at"": null,
|
||||
""OS-EXT-AZ:availability_zone"": ""nova"",
|
||||
""user_id"": ""70d48d344b494a1cbe8adbf7c02be7b5"",
|
||||
""name"": ""{1}"",
|
||||
""created"": ""2014-06-11T18:04:25Z"",
|
||||
""tenant_id"": ""ffe683d1060449d09dac0bf9d7a371cd"",
|
||||
""OS-DCF:diskConfig"": ""AUTO"",
|
||||
""os-extended-volumes:volumes_attached"": [],
|
||||
""accessIPv4"": """",
|
||||
""accessIPv6"": """",
|
||||
""progress"": {3},
|
||||
""OS-EXT-STS:power_state"": 1,
|
||||
""config_drive"": """",
|
||||
""metadata"": {{}}
|
||||
}}
|
||||
}}";
|
||||
return string.Format(payloadFixture, server.Id, server.Name, server.Status, server.Progress, server.PublicUri.AbsoluteUri, server.PermanentUri.AbsoluteUri);
|
||||
}
|
||||
|
||||
private string GenerateMetadataPayload(IDictionary<string, string> metadata)
|
||||
{
|
||||
var payload = new StringBuilder();
|
||||
payload.Append("{ \"metadata\" : {");
|
||||
var isFirst = true;
|
||||
|
||||
foreach (var item in metadata)
|
||||
{
|
||||
if (!isFirst)
|
||||
{
|
||||
payload.Append(",");
|
||||
}
|
||||
|
||||
payload.AppendFormat("\"{0}\":\"{1}\"", item.Key, item.Value);
|
||||
isFirst = false;
|
||||
}
|
||||
|
||||
payload.Append("}}");
|
||||
return payload.ToString();
|
||||
}
|
||||
|
||||
private void ParseAndStoreMetadata(MetadataComputeItem item, string payload)
|
||||
{
|
||||
var jObj = JObject.Parse(payload);
|
||||
var metaToken = jObj["metadata"];
|
||||
var metdata = JsonConvert.DeserializeObject<Dictionary<string, string>>(metaToken.ToString());
|
||||
item.Metadata = metdata;
|
||||
}
|
||||
}
|
||||
|
||||
public class ComputeRestSimulatorFactory : IHttpAbstractionClientFactory
|
||||
{
|
||||
internal ComputeRestSimulator Simulator = null;
|
||||
|
||||
public ComputeRestSimulatorFactory(ComputeRestSimulator simulator)
|
||||
{
|
||||
this.Simulator = simulator;
|
||||
}
|
||||
|
||||
public IHttpAbstractionClient Create()
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public IHttpAbstractionClient Create(CancellationToken token)
|
||||
{
|
||||
if (this.Simulator != null)
|
||||
{
|
||||
this.Simulator.Headers.Clear();
|
||||
}
|
||||
return this.Simulator ?? new ComputeRestSimulator(token);
|
||||
}
|
||||
|
||||
public IHttpAbstractionClient Create(TimeSpan timeout)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public IHttpAbstractionClient Create(TimeSpan timeout, CancellationToken token)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
}
|
||||
}
|
@ -1,756 +0,0 @@
|
||||
// /* ============================================================================
|
||||
// Copyright 2014 Hewlett Packard
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ============================================================================ */
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
using OpenStack.Compute;
|
||||
|
||||
namespace OpenStack.Test.Compute
|
||||
{
|
||||
[TestClass]
|
||||
public class ComputeServerPayloadConverterTests
|
||||
{
|
||||
internal string CreateServerJsonFixtrue(string name, string id, string status, int progress, string publicUri, string permUri)
|
||||
{
|
||||
var payloadFixture = @"{{
|
||||
""server"": {{
|
||||
""status"": ""{2}"",
|
||||
""updated"": ""2014-06-11T18:04:46Z"",
|
||||
""hostId"": ""bd5417ccb076908f6e0d639c37c053b0b6b9681db3464d19908dd4d9"",
|
||||
""addresses"": {{
|
||||
""private"": [
|
||||
{{
|
||||
""OS-EXT-IPS-MAC:mac_addr"": ""fa:16:3e:34:da:44"",
|
||||
""version"": 4,
|
||||
""addr"": ""10.0.0.2"",
|
||||
""OS-EXT-IPS:type"": ""fixed""
|
||||
}},
|
||||
{{
|
||||
""OS-EXT-IPS-MAC:mac_addr"": ""fa:16:3e:34:da:44"",
|
||||
""version"": 4,
|
||||
""addr"": ""172.24.4.3"",
|
||||
""OS-EXT-IPS:type"": ""floating""
|
||||
}}
|
||||
]
|
||||
}},
|
||||
""links"": [
|
||||
{{
|
||||
""href"": ""{4}"",
|
||||
""rel"": ""self""
|
||||
}},
|
||||
{{
|
||||
""href"": ""{5}"",
|
||||
""rel"": ""bookmark""
|
||||
}}
|
||||
],
|
||||
""key_name"": null,
|
||||
""image"": {{
|
||||
""id"": ""c650e788-3c46-4efc-bfa6-1d94a14d6405"",
|
||||
""links"": [
|
||||
{{
|
||||
""href"": ""http://15.125.87.81:8774/ffe683d1060449d09dac0bf9d7a371cd/images/c650e788-3c46-4efc-bfa6-1d94a14d6405"",
|
||||
""rel"": ""bookmark""
|
||||
}}
|
||||
]
|
||||
}},
|
||||
""OS-EXT-STS:task_state"": null,
|
||||
""OS-EXT-STS:vm_state"": ""active"",
|
||||
""OS-SRV-USG:launched_at"": ""2014-06-11T18:04:45.000000"",
|
||||
""flavor"": {{
|
||||
""id"": ""1"",
|
||||
""links"": [
|
||||
{{
|
||||
""href"": ""http://15.125.87.81:8774/ffe683d1060449d09dac0bf9d7a371cd/flavors/1"",
|
||||
""rel"": ""bookmark""
|
||||
}}
|
||||
]
|
||||
}},
|
||||
""id"": ""{0}"",
|
||||
""security_groups"": [
|
||||
{{
|
||||
""name"": ""MyGroup""
|
||||
}},
|
||||
{{
|
||||
""name"": ""default""
|
||||
}}
|
||||
],
|
||||
""OS-SRV-USG:terminated_at"": null,
|
||||
""OS-EXT-AZ:availability_zone"": ""nova"",
|
||||
""user_id"": ""70d48d344b494a1cbe8adbf7c02be7b5"",
|
||||
""name"": ""{1}"",
|
||||
""created"": ""2014-06-11T18:04:25Z"",
|
||||
""tenant_id"": ""ffe683d1060449d09dac0bf9d7a371cd"",
|
||||
""OS-DCF:diskConfig"": ""AUTO"",
|
||||
""os-extended-volumes:volumes_attached"": [],
|
||||
""accessIPv4"": """",
|
||||
""accessIPv6"": """",
|
||||
""progress"": {3},
|
||||
""OS-EXT-STS:power_state"": 1,
|
||||
""config_drive"": """",
|
||||
""metadata"": {{}}
|
||||
}}
|
||||
}}";
|
||||
return string.Format(payloadFixture, id, name, status, progress, publicUri, permUri);
|
||||
}
|
||||
|
||||
internal string CreateServerRequstSummaryJsonFixtrue(string id, string permaUri, string publicUri, string adminPass)
|
||||
{
|
||||
var computeServerSummaryJsonResponseFixture = @"{{
|
||||
""server"": {{
|
||||
""security_groups"": [
|
||||
{{
|
||||
""name"": ""default""
|
||||
}},
|
||||
{{
|
||||
""name"": ""MyGroup""
|
||||
}}
|
||||
],
|
||||
""OS-DCF:diskConfig"": ""MANUAL"",
|
||||
""id"": ""{0}"",
|
||||
""links"": [
|
||||
{{
|
||||
""href"": ""{1}"",
|
||||
""rel"": ""self""
|
||||
}},
|
||||
{{
|
||||
""href"": ""{2}"",
|
||||
""rel"": ""bookmark""
|
||||
}}
|
||||
],
|
||||
""adminPass"": ""{3}""
|
||||
}}
|
||||
}}";
|
||||
|
||||
return string.Format(computeServerSummaryJsonResponseFixture, id, publicUri, permaUri, adminPass);
|
||||
}
|
||||
|
||||
internal string CreateServersSummaryJsonFixtrue(string name, string id, string permaUri, string publicUri)
|
||||
{
|
||||
var computeServerSummaryJsonResponseFixture = @"{{
|
||||
""id"": ""{0}"",
|
||||
""links"": [
|
||||
{{
|
||||
""href"": ""{1}"",
|
||||
""rel"": ""self""
|
||||
}},
|
||||
{{
|
||||
""href"": ""{2}"",
|
||||
""rel"": ""bookmark""
|
||||
}}
|
||||
],
|
||||
""name"": ""{3}""
|
||||
}}";
|
||||
|
||||
return string.Format(computeServerSummaryJsonResponseFixture, id, publicUri, permaUri, name);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanConvertJsonPayloadToServer()
|
||||
{
|
||||
var serverPublicUri = "http://www.server.com/v2/servers/1";
|
||||
var serverPermUri = "http://www.server.com/servers/1";
|
||||
var serverId = "12345";
|
||||
var serverName = "testServer";
|
||||
var serverProgress = 0;
|
||||
var serverState = "ACTIVE";
|
||||
|
||||
var computeServerFixture = CreateServerJsonFixtrue(serverName, serverId, serverState, serverProgress, serverPublicUri, serverPermUri);
|
||||
|
||||
var converter = new ComputeServerPayloadConverter();
|
||||
var server = converter.Convert(computeServerFixture);
|
||||
|
||||
Assert.IsNotNull(server);
|
||||
Assert.AreEqual(serverId, server.Id);
|
||||
Assert.AreEqual(serverName, server.Name);
|
||||
Assert.AreEqual(serverState.ToLower(), server.Status.ToString().ToLower());
|
||||
Assert.AreEqual(serverProgress, server.Progress);
|
||||
Assert.AreEqual(new Uri(serverPermUri), server.PermanentUri);
|
||||
Assert.AreEqual(new Uri(serverPublicUri), server.PublicUri);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(FormatException))]
|
||||
public void CannotConvertJsonPayloadMissingIdToServer()
|
||||
{
|
||||
var serverPublicUri = "http://www.server.com/v2/servers/1";
|
||||
var serverPermUri = "http://www.server.com/servers/1";
|
||||
var serverName = "testServer";
|
||||
var serverProgress = 0;
|
||||
var serverState = "ACTIVE";
|
||||
|
||||
var payloadFixture = @"{{
|
||||
""server"": {{
|
||||
""status"": ""{1}"",
|
||||
""updated"": ""2014-06-11T18:04:46Z"",
|
||||
""links"": [
|
||||
{{
|
||||
""href"": ""{3}"",
|
||||
""rel"": ""self""
|
||||
}},
|
||||
{{
|
||||
""href"": ""{4}"",
|
||||
""rel"": ""bookmark""
|
||||
}}
|
||||
],
|
||||
""name"": ""{0}"",
|
||||
""created"": ""2014-06-11T18:04:25Z"",
|
||||
""progress"": {2}
|
||||
}}
|
||||
}}";
|
||||
|
||||
var missingFixture = string.Format(payloadFixture, serverName, serverState, serverProgress, serverPublicUri, serverPermUri);
|
||||
|
||||
var converter = new ComputeServerPayloadConverter();
|
||||
converter.Convert(missingFixture);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(FormatException))]
|
||||
public void CannotConvertJsonPayloadMissingpublicUriToServer()
|
||||
{
|
||||
var serverPermUri = "http://www.server.com/servers/1";
|
||||
var serverId = "12345";
|
||||
var serverName = "testServer";
|
||||
var serverProgress = 0;
|
||||
var serverState = "ACTIVE";
|
||||
|
||||
var payloadFixture = @"{{
|
||||
""server"": {{
|
||||
""status"": ""{2}"",
|
||||
""updated"": ""2014-06-11T18:04:46Z"",
|
||||
""links"": [
|
||||
{{
|
||||
""rel"": ""self""
|
||||
}},
|
||||
{{
|
||||
""href"": ""{4}"",
|
||||
""rel"": ""bookmark""
|
||||
}}
|
||||
],
|
||||
""id"": ""{0}"",
|
||||
""name"": ""{1}"",
|
||||
""created"": ""2014-06-11T18:04:25Z"",
|
||||
""progress"": {3}
|
||||
}}
|
||||
}}";
|
||||
|
||||
var missingFixture = string.Format(payloadFixture, serverId, serverName, serverState, serverProgress, serverPermUri);
|
||||
|
||||
var converter = new ComputeServerPayloadConverter();
|
||||
converter.Convert(missingFixture);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(FormatException))]
|
||||
public void CannotConvertJsonPayloadMissingPermUriToServer()
|
||||
{
|
||||
var serverPublicUri = "http://www.server.com/v2/servers/1";
|
||||
var serverId = "12345";
|
||||
var serverName = "testServer";
|
||||
var serverProgress = 0;
|
||||
var serverState = "ACTIVE";
|
||||
|
||||
var payloadFixture = @"{{
|
||||
""server"": {{
|
||||
""status"": ""{2}"",
|
||||
""updated"": ""2014-06-11T18:04:46Z"",
|
||||
""links"": [
|
||||
{{
|
||||
""href"": ""{4}"",
|
||||
""rel"": ""self""
|
||||
}},
|
||||
{{
|
||||
""rel"": ""bookmark""
|
||||
}}
|
||||
],
|
||||
""id"": ""{0}"",
|
||||
""name"": ""{1}"",
|
||||
""created"": ""2014-06-11T18:04:25Z"",
|
||||
""progress"": {3}
|
||||
}}
|
||||
}}";
|
||||
|
||||
var missingFixture = string.Format(payloadFixture, serverId, serverName, serverState, serverProgress, serverPublicUri);
|
||||
|
||||
var converter = new ComputeServerPayloadConverter();
|
||||
converter.Convert(missingFixture);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(FormatException))]
|
||||
public void CannotConvertJsonPayloadMissingStatusToServer()
|
||||
{
|
||||
var serverPublicUri = "http://www.server.com/v2/servers/1";
|
||||
var serverPermUri = "http://www.server.com/servers/1";
|
||||
var serverId = "12345";
|
||||
var serverName = "testServer";
|
||||
var serverProgress = 0;
|
||||
|
||||
var payloadFixture = @"{{
|
||||
""server"": {{
|
||||
""updated"": ""2014-06-11T18:04:46Z"",
|
||||
""links"": [
|
||||
{{
|
||||
""href"": ""{3}"",
|
||||
""rel"": ""self""
|
||||
}},
|
||||
{{
|
||||
""href"": ""{4}"",
|
||||
""rel"": ""bookmark""
|
||||
}}
|
||||
],
|
||||
""id"": ""{0}"",
|
||||
""name"": ""{1}"",
|
||||
""created"": ""2014-06-11T18:04:25Z"",
|
||||
""progress"": {2}
|
||||
}}
|
||||
}}";
|
||||
|
||||
var missingFixture = string.Format(payloadFixture, serverId, serverName, serverProgress, serverPublicUri, serverPermUri);
|
||||
|
||||
var converter = new ComputeServerPayloadConverter();
|
||||
converter.Convert(missingFixture);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(FormatException))]
|
||||
public void CannotConvertJsonPayloadMissingNameToServer()
|
||||
{
|
||||
var serverPublicUri = "http://www.server.com/v2/servers/1";
|
||||
var serverPermUri = "http://www.server.com/servers/1";
|
||||
var serverId = "12345";
|
||||
var serverProgress = 0;
|
||||
var serverState = "ACTIVE";
|
||||
|
||||
var payloadFixture = @"{{
|
||||
""server"": {{
|
||||
""status"": ""{1}"",
|
||||
""updated"": ""2014-06-11T18:04:46Z"",
|
||||
""links"": [
|
||||
{{
|
||||
""href"": ""{3}"",
|
||||
""rel"": ""self""
|
||||
}},
|
||||
{{
|
||||
""href"": ""{4}"",
|
||||
""rel"": ""bookmark""
|
||||
}}
|
||||
],
|
||||
""id"": ""{0}"",
|
||||
""created"": ""2014-06-11T18:04:25Z"",
|
||||
""progress"": {2}
|
||||
}}
|
||||
}}";
|
||||
|
||||
var missingFixture = string.Format(payloadFixture, serverId, serverState, serverProgress, serverPublicUri, serverPermUri);
|
||||
|
||||
var converter = new ComputeServerPayloadConverter();
|
||||
converter.Convert(missingFixture);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanConvertJsonPayloadMissingProgressToServer()
|
||||
{
|
||||
var serverPublicUri = "http://www.server.com/v2/servers/1";
|
||||
var serverPermUri = "http://www.server.com/servers/1";
|
||||
var serverId = "12345";
|
||||
var serverName = "testServer";
|
||||
var serverState = "ACTIVE";
|
||||
|
||||
var payloadFixture = @"{{
|
||||
""server"": {{
|
||||
""status"": ""{2}"",
|
||||
""updated"": ""2014-06-11T18:04:46Z"",
|
||||
""links"": [
|
||||
{{
|
||||
""href"": ""{3}"",
|
||||
""rel"": ""self""
|
||||
}},
|
||||
{{
|
||||
""href"": ""{4}"",
|
||||
""rel"": ""bookmark""
|
||||
}}
|
||||
],
|
||||
""id"": ""{0}"",
|
||||
""name"": ""{1}"",
|
||||
""created"": ""2014-06-11T18:04:25Z""
|
||||
}}
|
||||
}}";
|
||||
|
||||
var missingFixture = string.Format(payloadFixture, serverId, serverName, serverState, serverPublicUri, serverPermUri);
|
||||
|
||||
var converter = new ComputeServerPayloadConverter();
|
||||
var server = converter.Convert(missingFixture);
|
||||
|
||||
Assert.IsNotNull(server);
|
||||
Assert.AreEqual(serverId, server.Id);
|
||||
Assert.AreEqual(serverName, server.Name);
|
||||
Assert.AreEqual(serverState.ToLower(), server.Status.ToString().ToLower());
|
||||
Assert.AreEqual(0, server.Progress);
|
||||
Assert.AreEqual(new Uri(serverPermUri), server.PermanentUri);
|
||||
Assert.AreEqual(new Uri(serverPublicUri), server.PublicUri);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(FormatException))]
|
||||
public void CannotConvertServerJsonPayloadEmptyObjectToServer()
|
||||
{
|
||||
var emptyObjectFixture = @"{ }";
|
||||
|
||||
var converter = new ComputeServerPayloadConverter();
|
||||
converter.Convert(emptyObjectFixture);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(FormatException))]
|
||||
public void CannotConvertInvalidServerJsonToServer()
|
||||
{
|
||||
var badJsonFixture = @"{ NOT JSON";
|
||||
|
||||
var converter = new ComputeServerPayloadConverter();
|
||||
converter.Convert(badJsonFixture);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(FormatException))]
|
||||
public void CannotConvertNonObjectServerJsonToServer()
|
||||
{
|
||||
var nonObjectJson = @"[]";
|
||||
|
||||
var converter = new ComputeServerPayloadConverter();
|
||||
converter.Convert(nonObjectJson);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(ArgumentNullException))]
|
||||
public void CannotConvertNullJsonToServer()
|
||||
{
|
||||
var converter = new ComputeServerPayloadConverter();
|
||||
converter.Convert(null);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(ArgumentException))]
|
||||
public void CannotConvertEmptyStringJsonToServer()
|
||||
{
|
||||
var converter = new ComputeServerPayloadConverter();
|
||||
converter.Convert(string.Empty);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanConvertSummaryJsonPayloadToServer()
|
||||
{
|
||||
|
||||
var serverId = "1";
|
||||
var serverPublicUri = "http://www.server.com/v2/servers/1";
|
||||
var serverPermUri = "http://www.server.com/servers/1";
|
||||
var serverAdminPass = "ABCDE";
|
||||
|
||||
var computeServerFixture = CreateServerRequstSummaryJsonFixtrue(serverId, serverPermUri, serverPublicUri, serverAdminPass);
|
||||
|
||||
var converter = new ComputeServerPayloadConverter();
|
||||
var server = converter.ConvertSummary(computeServerFixture);
|
||||
|
||||
Assert.IsNotNull(server);
|
||||
Assert.AreEqual(serverId, server.Id);
|
||||
Assert.AreEqual(serverAdminPass, server.AdminPassword);
|
||||
Assert.AreEqual(new Uri(serverPermUri), server.PermanentUri);
|
||||
Assert.AreEqual(new Uri(serverPublicUri), server.PublicUri);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(FormatException))]
|
||||
public void CannotConvertSummaryJsonPayloadMissingIdToServer()
|
||||
{
|
||||
var serverPublicUri = "http://www.server.com/v2/servers/1";
|
||||
var serverPermUri = "http://www.server.com/servers/1";
|
||||
var serverAdminPass = "ABCDE";
|
||||
|
||||
var computeServerSummaryJsonResponseFixture = @"{{
|
||||
""server"": {{
|
||||
""security_groups"": [
|
||||
{{
|
||||
""name"": ""default""
|
||||
}},
|
||||
{{
|
||||
""name"": ""MyGroup""
|
||||
}}
|
||||
],
|
||||
""OS-DCF:diskConfig"": ""MANUAL"",
|
||||
""links"": [
|
||||
{{
|
||||
""href"": ""{1}"",
|
||||
""rel"": ""self""
|
||||
}},
|
||||
{{
|
||||
""href"": ""{0}"",
|
||||
""rel"": ""bookmark""
|
||||
}}
|
||||
],
|
||||
""adminPass"": ""{2}""
|
||||
}}
|
||||
}}";
|
||||
|
||||
var missingFixture = string.Format(computeServerSummaryJsonResponseFixture, serverPermUri, serverPublicUri, serverAdminPass);
|
||||
|
||||
var converter = new ComputeServerPayloadConverter();
|
||||
converter.ConvertSummary(missingFixture);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(FormatException))]
|
||||
public void CannotConvertSummaryJsonPayloadMissingpublicUriToServer()
|
||||
{
|
||||
var serverId = "1";
|
||||
var serverPermUri = "http://www.server.com/servers/1";
|
||||
var serverAdminPass = "ABCDE";
|
||||
|
||||
var computeServerSummaryJsonResponseFixture = @"{{
|
||||
""server"": {{
|
||||
""security_groups"": [
|
||||
{{
|
||||
""name"": ""default""
|
||||
}},
|
||||
{{
|
||||
""name"": ""MyGroup""
|
||||
}}
|
||||
],
|
||||
""OS-DCF:diskConfig"": ""MANUAL"",
|
||||
""id"": ""{0}"",
|
||||
""links"": [
|
||||
{{
|
||||
""href"": ""{1}"",
|
||||
""rel"": ""bookmark""
|
||||
}}
|
||||
],
|
||||
""adminPass"": ""{2}""
|
||||
}}
|
||||
}}";
|
||||
|
||||
var missingFixture = string.Format(computeServerSummaryJsonResponseFixture, serverId, serverPermUri, serverAdminPass);
|
||||
|
||||
var converter = new ComputeServerPayloadConverter();
|
||||
converter.ConvertSummary(missingFixture);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(FormatException))]
|
||||
public void CannotConvertSummaryJsonPayloadMissingPermUriToServer()
|
||||
{
|
||||
var serverId = "1";
|
||||
var serverPublicUri = "http://www.server.com/v2/servers/1";
|
||||
var serverAdminPass = "ABCDE";
|
||||
|
||||
var computeServerSummaryJsonResponseFixture = @"{{
|
||||
""server"": {{
|
||||
""security_groups"": [
|
||||
{{
|
||||
""name"": ""default""
|
||||
}},
|
||||
{{
|
||||
""name"": ""MyGroup""
|
||||
}}
|
||||
],
|
||||
""OS-DCF:diskConfig"": ""MANUAL"",
|
||||
""id"": ""{0}"",
|
||||
""links"": [
|
||||
{{
|
||||
""href"": ""{1}"",
|
||||
""rel"": ""self""
|
||||
}}
|
||||
],
|
||||
""adminPass"": ""{2}""
|
||||
}}
|
||||
}}";
|
||||
|
||||
var missingFixture = string.Format(computeServerSummaryJsonResponseFixture, serverId, serverPublicUri, serverAdminPass);
|
||||
|
||||
var converter = new ComputeServerPayloadConverter();
|
||||
converter.ConvertSummary(missingFixture);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(FormatException))]
|
||||
public void CannotConvertSummaryJsonPayloadMissingAdminPasswordToServer()
|
||||
{
|
||||
var serverId = "1";
|
||||
var serverPublicUri = "http://www.server.com/v2/servers/1";
|
||||
var serverPermUri = "http://www.server.com/servers/1";
|
||||
|
||||
var computeServerSummaryJsonResponseFixture = @"{{
|
||||
""server"": {{
|
||||
""security_groups"": [
|
||||
{{
|
||||
""name"": ""default""
|
||||
}},
|
||||
{{
|
||||
""name"": ""MyGroup""
|
||||
}}
|
||||
],
|
||||
""OS-DCF:diskConfig"": ""MANUAL"",
|
||||
""id"": ""{0}"",
|
||||
""links"": [
|
||||
{{
|
||||
""href"": ""{1}"",
|
||||
""rel"": ""self""
|
||||
}},
|
||||
{{
|
||||
""href"": ""{2}"",
|
||||
""rel"": ""bookmark""
|
||||
}}
|
||||
]
|
||||
}}
|
||||
}}";
|
||||
|
||||
var missingFixture = string.Format(computeServerSummaryJsonResponseFixture, serverId, serverPermUri, serverPublicUri);
|
||||
|
||||
var converter = new ComputeServerPayloadConverter();
|
||||
converter.ConvertSummary(missingFixture);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(FormatException))]
|
||||
public void CannotConvertJsonPayloadEmptyObjectToServer()
|
||||
{
|
||||
var emptyObjectFixture = @"{ }";
|
||||
|
||||
var converter = new ComputeServerPayloadConverter();
|
||||
converter.ConvertSummary(emptyObjectFixture);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(FormatException))]
|
||||
public void CannotConvertInvalidJsonToServer()
|
||||
{
|
||||
var badJsonFixture = @"{ NOT JSON";
|
||||
|
||||
var converter = new ComputeServerPayloadConverter();
|
||||
converter.ConvertSummary(badJsonFixture);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(FormatException))]
|
||||
public void CannotConvertNonObjectJsonToServer()
|
||||
{
|
||||
var nonObjectJson = @"[]";
|
||||
|
||||
var converter = new ComputeServerPayloadConverter();
|
||||
converter.ConvertSummary(nonObjectJson);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanParseValidServersJsonPayloadWithMultipleFlavors()
|
||||
{
|
||||
var validMultipleServersJsonFixture = @"{{ ""servers"": [ {0} ] }}";
|
||||
var firstServer = CreateServersSummaryJsonFixtrue("srv1", "1", "http://server.com/servers/1",
|
||||
"http://server.com/v2/servers/1");
|
||||
var secondServer = CreateServersSummaryJsonFixtrue("srv2", "2", "http://server.com/servers/2",
|
||||
"http://server.com/v2/servers/2");
|
||||
|
||||
var validMultipleServersJson = string.Format(validMultipleServersJsonFixture,
|
||||
string.Join(",", new List<string>() { firstServer, secondServer }));
|
||||
|
||||
var converter = new ComputeServerPayloadConverter();
|
||||
var servers = converter.ConvertServers(validMultipleServersJson).ToList();
|
||||
|
||||
Assert.AreEqual(2, servers.Count());
|
||||
var srv1 =
|
||||
servers.First(o => string.Equals(o.Name, "srv1", StringComparison.InvariantCultureIgnoreCase));
|
||||
var srv2 =
|
||||
servers.First(o => string.Equals(o.Name, "srv2", StringComparison.InvariantCultureIgnoreCase));
|
||||
Assert.IsNotNull(srv1);
|
||||
Assert.IsNotNull(srv2);
|
||||
|
||||
Assert.AreEqual("1", srv1.Id);
|
||||
Assert.AreEqual(new Uri("http://server.com/servers/1"), srv1.PermanentUri);
|
||||
Assert.AreEqual(new Uri("http://server.com/v2/servers/1"), srv1.PublicUri);
|
||||
|
||||
Assert.AreEqual("2", srv2.Id);
|
||||
Assert.AreEqual(new Uri("http://server.com/servers/2"), srv2.PermanentUri);
|
||||
Assert.AreEqual(new Uri("http://server.com/v2/servers/2"), srv2.PublicUri);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanConvertValidServersJsonPayloadWithSingleFlavor()
|
||||
{
|
||||
var validFlavorsJsonFixture = @"{{ ""servers"": [ {0} ] }}";
|
||||
var firstServer = CreateServersSummaryJsonFixtrue("myserver", "1", "http://server.com/servers/1",
|
||||
"http://server.com/v2/servers/1");
|
||||
var validSingleServerPayload = string.Format(validFlavorsJsonFixture, firstServer);
|
||||
|
||||
var converter = new ComputeServerPayloadConverter();
|
||||
var servers = converter.ConvertServers(validSingleServerPayload).ToList();
|
||||
|
||||
Assert.AreEqual(1, servers.Count());
|
||||
var srv1 =
|
||||
servers.First(o => string.Equals(o.Name, "myserver", StringComparison.InvariantCultureIgnoreCase));
|
||||
|
||||
Assert.IsNotNull(srv1);
|
||||
|
||||
Assert.AreEqual("1", srv1.Id);
|
||||
Assert.AreEqual(new Uri("http://server.com/servers/1"), srv1.PermanentUri);
|
||||
Assert.AreEqual(new Uri("http://server.com/v2/servers/1"), srv1.PublicUri);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanParseValidServersPayloadWithEmptyJsonArray()
|
||||
{
|
||||
var emptyJsonArray = @"{ ""servers"": [ ] }";
|
||||
|
||||
var converter = new ComputeServerPayloadConverter();
|
||||
var containers = converter.ConvertServers(emptyJsonArray).ToList();
|
||||
|
||||
Assert.AreEqual(0, containers.Count());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanParseAnEmptyServersPayload()
|
||||
{
|
||||
var payload = string.Empty;
|
||||
|
||||
var converter = new ComputeServerPayloadConverter();
|
||||
var containers = converter.ConvertServers(payload).ToList();
|
||||
|
||||
Assert.AreEqual(0, containers.Count());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(ArgumentNullException))]
|
||||
public void CannotParseANullServersPayload()
|
||||
{
|
||||
var converter = new ComputeServerPayloadConverter();
|
||||
converter.ConvertServers(null);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(FormatException))]
|
||||
public void CannotParseInvalidServersJsonPayload()
|
||||
{
|
||||
var converter = new ComputeServerPayloadConverter();
|
||||
converter.ConvertServers("[ { \"SomeAtrib\" }]");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(FormatException))]
|
||||
public void CannotParseInvalidServersPayload()
|
||||
{
|
||||
var converter = new ComputeServerPayloadConverter();
|
||||
converter.ConvertServers("NOT JSON");
|
||||
}
|
||||
}
|
||||
}
|
@ -1,773 +0,0 @@
|
||||
// /* ============================================================================
|
||||
// Copyright 2014 Hewlett Packard
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ============================================================================ */
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
using OpenStack.Common.ServiceLocation;
|
||||
using OpenStack.Compute;
|
||||
using OpenStack.Identity;
|
||||
|
||||
namespace OpenStack.Test.Compute
|
||||
{
|
||||
[TestClass]
|
||||
public class ComputeServiceClientTests
|
||||
{
|
||||
internal TestComputeServicePocoClient ServicePocoClient;
|
||||
|
||||
internal string authId = "12345";
|
||||
internal string endpoint = "http://testcomputeendpoint.com/v2/1234567890";
|
||||
internal ServiceLocator ServiceLocator;
|
||||
|
||||
[TestInitialize]
|
||||
public void TestSetup()
|
||||
{
|
||||
this.ServicePocoClient = new TestComputeServicePocoClient();
|
||||
this.ServiceLocator = new ServiceLocator();
|
||||
|
||||
var manager = this.ServiceLocator.Locate<IServiceLocationOverrideManager>();
|
||||
manager.RegisterServiceInstance(typeof(IComputeServicePocoClientFactory), new TestComputeServicePocoClientFactory(this.ServicePocoClient));
|
||||
}
|
||||
|
||||
[TestCleanup]
|
||||
public void TestCleanup()
|
||||
{
|
||||
this.ServicePocoClient = new TestComputeServicePocoClient();
|
||||
this.ServiceLocator = new ServiceLocator();
|
||||
}
|
||||
|
||||
IOpenStackCredential GetValidCreds()
|
||||
{
|
||||
var catalog = new OpenStackServiceCatalog();
|
||||
catalog.Add(new OpenStackServiceDefinition("Nova", "Compute Service",
|
||||
new List<OpenStackServiceEndpoint>()
|
||||
{
|
||||
new OpenStackServiceEndpoint(endpoint, string.Empty, "some version", "some version info", "1,2,3")
|
||||
}));
|
||||
|
||||
var creds = new OpenStackCredential(new Uri(this.endpoint), "SomeUser", "Password", "SomeTenant");
|
||||
creds.SetAccessTokenId(this.authId);
|
||||
creds.SetServiceCatalog(catalog);
|
||||
return creds;
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task CanGetFlavors()
|
||||
{
|
||||
var flv1 = new ComputeFlavor("1", "m1.tiny", "512", "2", "10", new Uri("http://someuri.com/v2/flavors/1"),
|
||||
new Uri("http://someuri.com/flavors/1"), new Dictionary<string, string>());
|
||||
var flv2 = new ComputeFlavor("2", "m1.small", "1024", "4", "100", new Uri("http://someuri.com/v2/flavors/2"),
|
||||
new Uri("http://someuri.com/flavors/2"), new Dictionary<string, string>());
|
||||
var flavors = new List<ComputeFlavor>() {flv1, flv2};
|
||||
|
||||
this.ServicePocoClient.GetFlavorsDelegate = () => Task.Factory.StartNew(() => (IEnumerable<ComputeFlavor>)flavors);
|
||||
|
||||
var client = new ComputeServiceClient(GetValidCreds(), "Nova", CancellationToken.None, this.ServiceLocator);
|
||||
var resp = await client.GetFlavors();
|
||||
Assert.IsNotNull(resp);
|
||||
|
||||
var respFlavors = resp.ToList();
|
||||
Assert.AreEqual(2, respFlavors.Count());
|
||||
Assert.AreEqual(flv1, respFlavors[0]);
|
||||
Assert.AreEqual(flv2, respFlavors[1]);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task CanGetFlavor()
|
||||
{
|
||||
var expectedFlavor = new ComputeFlavor("1", "m1.tiny", "512", "2", "10", new Uri("http://someuri.com/v2/flavors/1"),
|
||||
new Uri("http://someuri.com/flavors/1"), new Dictionary<string, string>());
|
||||
|
||||
this.ServicePocoClient.GetFlavorDelegate = (id) =>
|
||||
{
|
||||
Assert.AreEqual("1", id);
|
||||
return Task.Factory.StartNew(() => expectedFlavor);
|
||||
};
|
||||
|
||||
var client = new ComputeServiceClient(GetValidCreds(), "Nova", CancellationToken.None, this.ServiceLocator);
|
||||
var flavor = await client.GetFlavor("1");
|
||||
|
||||
Assert.IsNotNull(flavor);
|
||||
Assert.AreEqual(expectedFlavor, flavor);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(ArgumentNullException))]
|
||||
public async Task GetFlavorWithNullFlavorIdThrows()
|
||||
{
|
||||
var client = new ComputeServiceClient(GetValidCreds(), "Nova", CancellationToken.None, this.ServiceLocator);
|
||||
await client.GetFlavor(null);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(ArgumentException))]
|
||||
public async Task GetFlavorWithEmptyFlavorIdThrows()
|
||||
{
|
||||
var client = new ComputeServiceClient(GetValidCreds(), "Nova", CancellationToken.None, this.ServiceLocator);
|
||||
await client.GetFlavor(string.Empty);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task CanCreateServer()
|
||||
{
|
||||
var serverName = "MyServer";
|
||||
var imageId = "56789";
|
||||
var keyName = "MyKey";
|
||||
var flavorId = "2";
|
||||
var networkId = "98765";
|
||||
var adminPassword = "ABCDE";
|
||||
var expServer = new ComputeServer("1235", serverName, adminPassword, new Uri("http://someuri.com/v2/servers/12345"),
|
||||
new Uri("http://someuri.com/servers/12345"), new Dictionary<string, string>());
|
||||
|
||||
this.ServicePocoClient.CreateServerDelegate = (name, imgId, flvId, ntwId, key, groups) =>
|
||||
{
|
||||
Assert.AreEqual(serverName, name);
|
||||
Assert.AreEqual(imageId, imgId);
|
||||
Assert.AreEqual(flavorId, flvId);
|
||||
Assert.AreEqual(networkId, ntwId);
|
||||
Assert.AreEqual(keyName, key);
|
||||
Assert.IsTrue(groups.Any(g => g == "default"));
|
||||
return Task.Factory.StartNew(() => expServer);
|
||||
};
|
||||
|
||||
var client = new ComputeServiceClient(GetValidCreds(), "Nova", CancellationToken.None, this.ServiceLocator);
|
||||
var server = await client.CreateServer(serverName, imageId, flavorId, networkId, keyName, new List<string>() { "default" });
|
||||
|
||||
Assert.IsNotNull(server);
|
||||
Assert.AreEqual("1235", server.Id);
|
||||
Assert.AreEqual(adminPassword, server.AdminPassword);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task CanCreateServerWithoutKeyName()
|
||||
{
|
||||
var serverName = "MyServer";
|
||||
var imageId = "56789";
|
||||
var flavorId = "2";
|
||||
var networkId = "98765";
|
||||
var adminPassword = "ABCDE";
|
||||
var expServer = new ComputeServer("1235", serverName, adminPassword, new Uri("http://someuri.com/v2/servers/12345"),
|
||||
new Uri("http://someuri.com/servers/12345"), new Dictionary<string, string>());
|
||||
|
||||
this.ServicePocoClient.CreateServerDelegate = (name, imgId, flvId, ntwId, key, groups) =>
|
||||
{
|
||||
Assert.AreEqual(serverName, name);
|
||||
Assert.AreEqual(imageId, imgId);
|
||||
Assert.AreEqual(flavorId, flvId);
|
||||
Assert.AreEqual(networkId, ntwId);
|
||||
Assert.AreEqual(string.Empty, key);
|
||||
Assert.IsTrue(groups.Any(g => g == "default"));
|
||||
return Task.Factory.StartNew(() => expServer);
|
||||
};
|
||||
|
||||
var client = new ComputeServiceClient(GetValidCreds(), "Nova", CancellationToken.None, this.ServiceLocator);
|
||||
var server = await client.CreateServer(serverName, imageId, flavorId, networkId, new List<string>() { "default" });
|
||||
|
||||
Assert.IsNotNull(server);
|
||||
Assert.AreEqual("1235", server.Id);
|
||||
Assert.AreEqual(adminPassword, server.AdminPassword);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(ArgumentNullException))]
|
||||
public async Task CreateServerWithNullNameThrows()
|
||||
{
|
||||
var client = new ComputeServiceClient(GetValidCreds(), "Nova", CancellationToken.None, this.ServiceLocator);
|
||||
await client.CreateServer(null, "12345", "2", "54321", new List<string>() { "default" });
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(ArgumentException))]
|
||||
public async Task CreateServerWithEmptyNameThrows()
|
||||
{
|
||||
var client = new ComputeServiceClient(GetValidCreds(), "Nova", CancellationToken.None, this.ServiceLocator);
|
||||
await client.CreateServer(string.Empty, "12345", "2", "54321", new List<string>() { "default" });
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(ArgumentNullException))]
|
||||
public async Task CreateServerWithNullImageIdThrows()
|
||||
{
|
||||
var client = new ComputeServiceClient(GetValidCreds(), "Nova", CancellationToken.None, this.ServiceLocator);
|
||||
await client.CreateServer("MyServer", null, "2", "54321", new List<string>() { "default" });
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(ArgumentException))]
|
||||
public async Task CreateServerWithEmptyImageIdThrows()
|
||||
{
|
||||
var client = new ComputeServiceClient(GetValidCreds(), "Nova", CancellationToken.None, this.ServiceLocator);
|
||||
await client.CreateServer("MyServer", string.Empty, "2", "54321", new List<string>() { "default" });
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(ArgumentNullException))]
|
||||
public async Task CreateServerWithNullFlavorIdThrows()
|
||||
{
|
||||
var client = new ComputeServiceClient(GetValidCreds(), "Nova", CancellationToken.None, this.ServiceLocator);
|
||||
await client.CreateServer("MyServer", "12345", null, "54321", new List<string>() { "default" });
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(ArgumentException))]
|
||||
public async Task CreateServerWithEmptyFlavorIdThrows()
|
||||
{
|
||||
var client = new ComputeServiceClient(GetValidCreds(), "Nova", CancellationToken.None, this.ServiceLocator);
|
||||
await client.CreateServer("MyServer", "12345", string.Empty, "54321", new List<string>() { "default" });
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(ArgumentNullException))]
|
||||
public async Task CreateServerWithNullNetworkIdThrows()
|
||||
{
|
||||
var client = new ComputeServiceClient(GetValidCreds(), "Nova", CancellationToken.None, this.ServiceLocator);
|
||||
await client.CreateServer("MyServer", "12345", "2", null, new List<string>() { "default" });
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(ArgumentException))]
|
||||
public async Task CreateServerWithEmptyNetworkIdThrows()
|
||||
{
|
||||
var client = new ComputeServiceClient(GetValidCreds(), "Nova", CancellationToken.None, this.ServiceLocator);
|
||||
await client.CreateServer("MyServer", "12345", "2", string.Empty, new List<string>() { "default" });
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task CanGetServers()
|
||||
{
|
||||
var expServer1 = new ComputeServer("1", "srv1",
|
||||
new Uri("http://testcomputeendpoint.com/v2/1234567890/servers/1"),
|
||||
new Uri("http://testcomputeendpoint.com/1234567890/servers/1"), new Dictionary<string, string>());
|
||||
|
||||
var expServer2 = new ComputeServer("2", "srv2",
|
||||
new Uri("http://testcomputeendpoint.com/v2/1234567890/servers/1"),
|
||||
new Uri("http://testcomputeendpoint.com/1234567890/servers/1"), new Dictionary<string, string>());
|
||||
var servers = new List<ComputeServer>() { expServer1, expServer2 };
|
||||
|
||||
this.ServicePocoClient.GetServersDelegate = () => Task.Factory.StartNew(() => (IEnumerable<ComputeServer>)servers);
|
||||
|
||||
var client = new ComputeServiceClient(GetValidCreds(), "Nova", CancellationToken.None, this.ServiceLocator);
|
||||
var resp = await client.GetServers();
|
||||
Assert.IsNotNull(resp);
|
||||
|
||||
var respFlavors = resp.ToList();
|
||||
Assert.AreEqual(2, respFlavors.Count());
|
||||
Assert.AreEqual(expServer1, respFlavors[0]);
|
||||
Assert.AreEqual(expServer2, respFlavors[1]);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task CanGetServer()
|
||||
{
|
||||
var serverId = "12345";
|
||||
var expServer = new ComputeServer(serverId, "tiny",
|
||||
new Uri("http://testcomputeendpoint.com/v2/1234567890/servers/1"),
|
||||
new Uri("http://testcomputeendpoint.com/1234567890/servers/1"), new Dictionary<string, string>());
|
||||
|
||||
this.ServicePocoClient.GetServerDelegate = (id) =>
|
||||
{
|
||||
Assert.AreEqual(serverId, id);
|
||||
return Task.Factory.StartNew(() => expServer);
|
||||
};
|
||||
|
||||
var client = new ComputeServiceClient(GetValidCreds(), "Nova", CancellationToken.None, this.ServiceLocator);
|
||||
var server = await client.GetServer(serverId);
|
||||
|
||||
Assert.IsNotNull(server);
|
||||
Assert.AreEqual(expServer, server);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(ArgumentNullException))]
|
||||
public async Task GetServerWithNullIdThrows()
|
||||
{
|
||||
var client = new ComputeServiceClient(GetValidCreds(), "Nova", CancellationToken.None, this.ServiceLocator);
|
||||
await client.GetServer(null);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(ArgumentException))]
|
||||
public async Task GetServerWithEmptyIdThrows()
|
||||
{
|
||||
var client = new ComputeServiceClient(GetValidCreds(), "Nova", CancellationToken.None, this.ServiceLocator);
|
||||
await client.GetServer(string.Empty);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task CanDeleteServer()
|
||||
{
|
||||
this.ServicePocoClient.DeleteServerDelegate = async (serverId) =>
|
||||
{
|
||||
await Task.Run(() => Assert.AreEqual(serverId, "12345"));
|
||||
};
|
||||
|
||||
var client = new ComputeServiceClient(GetValidCreds(), "Nova", CancellationToken.None, this.ServiceLocator);
|
||||
await client.DeleteServer("12345");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(ArgumentNullException))]
|
||||
public async Task DeleteServerWithNullServerIdThrows()
|
||||
{
|
||||
var client = new ComputeServiceClient(GetValidCreds(), "Nova", CancellationToken.None, this.ServiceLocator);
|
||||
await client.DeleteServer(null);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(ArgumentException))]
|
||||
public async Task DeleteServerWithEmptyServerIdThrows()
|
||||
{
|
||||
var client = new ComputeServiceClient(GetValidCreds(), "Nova", CancellationToken.None, this.ServiceLocator);
|
||||
await client.DeleteServer(string.Empty);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task CanAssignFloatingIp()
|
||||
{
|
||||
this.ServicePocoClient.AssignFloatingIpDelegate = async (serverId, ipAddress) =>
|
||||
{
|
||||
await Task.Run(() =>
|
||||
{
|
||||
Assert.AreEqual(serverId, "12345");
|
||||
Assert.AreEqual(ipAddress, "172.0.0.1");
|
||||
});
|
||||
};
|
||||
|
||||
var client = new ComputeServiceClient(GetValidCreds(), "Nova", CancellationToken.None, this.ServiceLocator);
|
||||
await client.AssignFloatingIp("12345", "172.0.0.1");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(ArgumentNullException))]
|
||||
public async Task AssignFloatingIpWithNullServerIdThrows()
|
||||
{
|
||||
var client = new ComputeServiceClient(GetValidCreds(), "Nova", CancellationToken.None, this.ServiceLocator);
|
||||
await client.AssignFloatingIp(null, "172.0.0.1");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(ArgumentException))]
|
||||
public async Task AssignFloatingIpWithEmptyServerIdThrows()
|
||||
{
|
||||
var client = new ComputeServiceClient(GetValidCreds(), "Nova", CancellationToken.None, this.ServiceLocator);
|
||||
await client.AssignFloatingIp(string.Empty, "172.0.0.1");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(ArgumentNullException))]
|
||||
public async Task AssignFloatingIpWithNullIpAddressThrows()
|
||||
{
|
||||
var client = new ComputeServiceClient(GetValidCreds(), "Nova", CancellationToken.None, this.ServiceLocator);
|
||||
await client.AssignFloatingIp("12345", null);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(ArgumentException))]
|
||||
public async Task AssignFloatingIpWithEmptyIpAddressThrows()
|
||||
{
|
||||
var client = new ComputeServiceClient(GetValidCreds(), "Nova", CancellationToken.None, this.ServiceLocator);
|
||||
await client.AssignFloatingIp("12345", string.Empty);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task CanGetServerMetadata()
|
||||
{
|
||||
var meta = new Dictionary<string, string>() { { "item1", "value1" } };
|
||||
|
||||
this.ServicePocoClient.GetServerMetadataDelegate = (id) =>
|
||||
{
|
||||
Assert.AreEqual("12345", id);
|
||||
return Task.Factory.StartNew(() => (IDictionary<string, string>)meta);
|
||||
};
|
||||
|
||||
var client = new ComputeServiceClient(GetValidCreds(), "Nova", CancellationToken.None, this.ServiceLocator);
|
||||
var metadata = await client.GetServerMetadata("12345");
|
||||
|
||||
Assert.IsNotNull(metadata);
|
||||
Assert.AreEqual(meta, metadata);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(ArgumentNullException))]
|
||||
public async Task GetServerMetadataWithNullImageIdThrows()
|
||||
{
|
||||
var client = new ComputeServiceClient(GetValidCreds(), "Nova", CancellationToken.None, this.ServiceLocator);
|
||||
await client.GetServerMetadata(null);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(ArgumentException))]
|
||||
public async Task GetServerMetadataWithEmptyImageIdThrows()
|
||||
{
|
||||
var client = new ComputeServiceClient(GetValidCreds(), "Nova", CancellationToken.None, this.ServiceLocator);
|
||||
await client.GetServerMetadata(string.Empty);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task CanDeleteServerMetadata()
|
||||
{
|
||||
this.ServicePocoClient.DeleteServerMetadataDelegate = async (flavorId, key) =>
|
||||
{
|
||||
await Task.Run(() =>
|
||||
{
|
||||
Assert.AreEqual(flavorId, "12345");
|
||||
Assert.AreEqual(key, "item1");
|
||||
});
|
||||
};
|
||||
|
||||
var client = new ComputeServiceClient(GetValidCreds(), "Nova", CancellationToken.None, this.ServiceLocator);
|
||||
await client.DeleteServerMetadata("12345", "item1");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(ArgumentNullException))]
|
||||
public async Task DeleteServerMetadataWithNullImageIdThrows()
|
||||
{
|
||||
var client = new ComputeServiceClient(GetValidCreds(), "Nova", CancellationToken.None, this.ServiceLocator);
|
||||
await client.DeleteServerMetadata(null, "item1");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(ArgumentException))]
|
||||
public async Task DeleteServerMetadataWithEmptyImageIdThrows()
|
||||
{
|
||||
var client = new ComputeServiceClient(GetValidCreds(), "Nova", CancellationToken.None, this.ServiceLocator);
|
||||
await client.DeleteServerMetadata(string.Empty, "item1");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(ArgumentException))]
|
||||
public async Task DeleteServerMetadataWithEmptyKeyThrows()
|
||||
{
|
||||
var client = new ComputeServiceClient(GetValidCreds(), "Nova", CancellationToken.None, this.ServiceLocator);
|
||||
await client.DeleteServerMetadata("12345", string.Empty);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(ArgumentNullException))]
|
||||
public async Task DeleteServerMetadataWithNullKeyThrows()
|
||||
{
|
||||
var client = new ComputeServiceClient(GetValidCreds(), "Nova", CancellationToken.None, this.ServiceLocator);
|
||||
await client.DeleteServerMetadata("12345", null);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task CanUpdateServerMetadata()
|
||||
{
|
||||
var metadata = new Dictionary<string, string>() { { "item1", "value1" } };
|
||||
this.ServicePocoClient.UpdateServerMetadataDelegate = async (flavorId, meta) =>
|
||||
{
|
||||
await Task.Run(() =>
|
||||
{
|
||||
Assert.AreEqual(flavorId, "12345");
|
||||
Assert.AreEqual(metadata, meta);
|
||||
});
|
||||
};
|
||||
|
||||
var client = new ComputeServiceClient(GetValidCreds(), "Nova", CancellationToken.None, this.ServiceLocator);
|
||||
await client.UpdateServerMetadata("12345", metadata);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(ArgumentNullException))]
|
||||
public async Task UpdateServerMetadataWithNullImageIdThrows()
|
||||
{
|
||||
var metadata = new Dictionary<string, string>() { { "item1", "value1" } };
|
||||
var client = new ComputeServiceClient(GetValidCreds(), "Nova", CancellationToken.None, this.ServiceLocator);
|
||||
await client.UpdateServerMetadata(null, metadata);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(ArgumentException))]
|
||||
public async Task UpdateServerMetadataWithEmptyImageIdThrows()
|
||||
{
|
||||
var metadata = new Dictionary<string, string>() { { "item1", "value1" } };
|
||||
var client = new ComputeServiceClient(GetValidCreds(), "Nova", CancellationToken.None, this.ServiceLocator);
|
||||
await client.UpdateServerMetadata(string.Empty, metadata);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(ArgumentNullException))]
|
||||
public async Task UpdateServerMetadataWithNullMetadataThrows()
|
||||
{
|
||||
var client = new ComputeServiceClient(GetValidCreds(), "Nova", CancellationToken.None, this.ServiceLocator);
|
||||
await client.UpdateServerMetadata("12345", null);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task CanGetImages()
|
||||
{
|
||||
var img1 = new ComputeImage("12345", "image1", new Uri("http://someuri.com/v2/images/12345"), new Uri("http://someuri.com/images/12345"), new Dictionary<string, string>(), "active", DateTime.Now, DateTime.Now, 10, 512, 100);
|
||||
var img2 = new ComputeImage("23456", "image2", new Uri("http://someuri.com/v2/images/23456"), new Uri("http://someuri.com/images/23456"), new Dictionary<string, string>(), "active", DateTime.Now, DateTime.Now, 10, 512, 100);
|
||||
var images = new List<ComputeImage>() { img1, img2 };
|
||||
|
||||
this.ServicePocoClient.GetImagesDelegate = () => Task.Factory.StartNew(() => (IEnumerable<ComputeImage>)images);
|
||||
|
||||
var client = new ComputeServiceClient(GetValidCreds(), "Nova", CancellationToken.None, this.ServiceLocator);
|
||||
var resp = await client.GetImages();
|
||||
Assert.IsNotNull(resp);
|
||||
|
||||
var respImage = resp.ToList();
|
||||
Assert.AreEqual(2, respImage.Count());
|
||||
Assert.AreEqual(img1, respImage[0]);
|
||||
Assert.AreEqual(img2, respImage[1]);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task CanGetImage()
|
||||
{
|
||||
var img1 = new ComputeImage("12345", "image1", new Uri("http://someuri.com/v2/images/12345"), new Uri("http://someuri.com/images/12345"), new Dictionary<string, string>(), "active", DateTime.Now, DateTime.Now, 10, 512, 100);
|
||||
|
||||
this.ServicePocoClient.GetImageDelegate = (id) =>
|
||||
{
|
||||
Assert.AreEqual("12345", id);
|
||||
return Task.Factory.StartNew(() => img1);
|
||||
};
|
||||
|
||||
var client = new ComputeServiceClient(GetValidCreds(), "Nova", CancellationToken.None, this.ServiceLocator);
|
||||
var image = await client.GetImage("12345");
|
||||
|
||||
Assert.IsNotNull(image);
|
||||
Assert.AreEqual(img1, image);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(ArgumentNullException))]
|
||||
public async Task GetImageWithNullImageIdThrows()
|
||||
{
|
||||
var client = new ComputeServiceClient(GetValidCreds(), "Nova", CancellationToken.None, this.ServiceLocator);
|
||||
await client.GetImage(null);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(ArgumentException))]
|
||||
public async Task GetImageWithEmptyImageIdThrows()
|
||||
{
|
||||
var client = new ComputeServiceClient(GetValidCreds(), "Nova", CancellationToken.None, this.ServiceLocator);
|
||||
await client.GetImage(string.Empty);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task CanDeleteImage()
|
||||
{
|
||||
this.ServicePocoClient.DeleteImageDelegate = async (imageId) =>
|
||||
{
|
||||
await Task.Run(() => Assert.AreEqual(imageId, "12345"));
|
||||
};
|
||||
|
||||
var client = new ComputeServiceClient(GetValidCreds(), "Nova", CancellationToken.None, this.ServiceLocator);
|
||||
await client.DeleteImage("12345");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(ArgumentNullException))]
|
||||
public async Task DeleteImageWithNullImageIdThrows()
|
||||
{
|
||||
var client = new ComputeServiceClient(GetValidCreds(), "Nova", CancellationToken.None, this.ServiceLocator);
|
||||
await client.DeleteImage(null);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(ArgumentException))]
|
||||
public async Task DeleteImageWithEmptyImageIdThrows()
|
||||
{
|
||||
var client = new ComputeServiceClient(GetValidCreds(), "Nova", CancellationToken.None, this.ServiceLocator);
|
||||
await client.DeleteImage(string.Empty);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task CanGetImageMetadata()
|
||||
{
|
||||
var meta = new Dictionary<string, string>() { { "item1", "value1" } };
|
||||
|
||||
this.ServicePocoClient.GetImageMetadataDelegate = (id) =>
|
||||
{
|
||||
Assert.AreEqual("12345", id);
|
||||
return Task.Factory.StartNew(() => (IDictionary<string, string>)meta);
|
||||
};
|
||||
|
||||
var client = new ComputeServiceClient(GetValidCreds(), "Nova", CancellationToken.None, this.ServiceLocator);
|
||||
var metadata = await client.GetImageMetadata("12345");
|
||||
|
||||
Assert.IsNotNull(metadata);
|
||||
Assert.AreEqual(meta, metadata);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(ArgumentNullException))]
|
||||
public async Task GetImageMetadataWithNullImageIdThrows()
|
||||
{
|
||||
var client = new ComputeServiceClient(GetValidCreds(), "Nova", CancellationToken.None, this.ServiceLocator);
|
||||
await client.GetImageMetadata(null);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(ArgumentException))]
|
||||
public async Task GetImageMetadataWithEmptyImageIdThrows()
|
||||
{
|
||||
var client = new ComputeServiceClient(GetValidCreds(), "Nova", CancellationToken.None, this.ServiceLocator);
|
||||
await client.GetImageMetadata(string.Empty);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task CanDeleteImageMetadata()
|
||||
{
|
||||
this.ServicePocoClient.DeleteImageMetadataDelegate = async (imageId, key) =>
|
||||
{
|
||||
await Task.Run(() =>
|
||||
{
|
||||
Assert.AreEqual(imageId, "12345");
|
||||
Assert.AreEqual(key, "item1");
|
||||
});
|
||||
};
|
||||
|
||||
var client = new ComputeServiceClient(GetValidCreds(), "Nova", CancellationToken.None, this.ServiceLocator);
|
||||
await client.DeleteImageMetadata("12345", "item1");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(ArgumentNullException))]
|
||||
public async Task DeleteImageMetadataWithNullImageIdThrows()
|
||||
{
|
||||
var client = new ComputeServiceClient(GetValidCreds(), "Nova", CancellationToken.None, this.ServiceLocator);
|
||||
await client.DeleteImageMetadata(null, "item1");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(ArgumentException))]
|
||||
public async Task DeleteImageMetadataWithEmptyImageIdThrows()
|
||||
{
|
||||
var client = new ComputeServiceClient(GetValidCreds(), "Nova", CancellationToken.None, this.ServiceLocator);
|
||||
await client.DeleteImageMetadata(string.Empty, "item1");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(ArgumentException))]
|
||||
public async Task DeleteImageMetadataWithEmptyKeyThrows()
|
||||
{
|
||||
var client = new ComputeServiceClient(GetValidCreds(), "Nova", CancellationToken.None, this.ServiceLocator);
|
||||
await client.DeleteImageMetadata("12345", string.Empty);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(ArgumentNullException))]
|
||||
public async Task DeleteImageMetadataWithNullKeyThrows()
|
||||
{
|
||||
var client = new ComputeServiceClient(GetValidCreds(), "Nova", CancellationToken.None, this.ServiceLocator);
|
||||
await client.DeleteImageMetadata("12345", null);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task CanUpdateImageMetadata()
|
||||
{
|
||||
var metadata = new Dictionary<string, string>() { { "item1", "value1" } };
|
||||
this.ServicePocoClient.UpdateImageMetadataDelegate = async (imageId, meta) =>
|
||||
{
|
||||
await Task.Run(() =>
|
||||
{
|
||||
Assert.AreEqual(imageId, "12345");
|
||||
Assert.AreEqual(metadata, meta);
|
||||
});
|
||||
};
|
||||
|
||||
var client = new ComputeServiceClient(GetValidCreds(), "Nova", CancellationToken.None, this.ServiceLocator);
|
||||
await client.UpdateImageMetadata("12345", metadata);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(ArgumentNullException))]
|
||||
public async Task UpdateImageMetadataWithNullImageIdThrows()
|
||||
{
|
||||
var metadata = new Dictionary<string, string>() { { "item1", "value1" } };
|
||||
var client = new ComputeServiceClient(GetValidCreds(), "Nova", CancellationToken.None, this.ServiceLocator);
|
||||
await client.UpdateImageMetadata(null, metadata);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(ArgumentException))]
|
||||
public async Task UpdateImageMetadataWithEmptyImageIdThrows()
|
||||
{
|
||||
var metadata = new Dictionary<string, string>() { { "item1", "value1" } };
|
||||
var client = new ComputeServiceClient(GetValidCreds(), "Nova", CancellationToken.None, this.ServiceLocator);
|
||||
await client.UpdateImageMetadata(string.Empty, metadata);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(ArgumentNullException))]
|
||||
public async Task UpdateImageMetadataWithNullMetadataThrows()
|
||||
{
|
||||
var client = new ComputeServiceClient(GetValidCreds(), "Nova", CancellationToken.None, this.ServiceLocator);
|
||||
await client.UpdateImageMetadata("12345", null);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task CanGetKeyPairs()
|
||||
{
|
||||
var expKeyPair1 = new ComputeKeyPair("1", "ABCDEF","12345");
|
||||
var expKeyPair2 = new ComputeKeyPair("2", "FEDCBA", "54321");
|
||||
var pairs = new List<ComputeKeyPair>() { expKeyPair1, expKeyPair2 };
|
||||
|
||||
this.ServicePocoClient.GetKeyPairsDelegate = () => Task.Factory.StartNew(() => (IEnumerable<ComputeKeyPair>)pairs);
|
||||
|
||||
var client = new ComputeServiceClient(GetValidCreds(), "Nova", CancellationToken.None, this.ServiceLocator);
|
||||
var resp = await client.GetKeyPairs();
|
||||
Assert.IsNotNull(resp);
|
||||
|
||||
var respPairs = resp.ToList();
|
||||
Assert.AreEqual(2, respPairs.Count());
|
||||
Assert.AreEqual(expKeyPair1, respPairs[0]);
|
||||
Assert.AreEqual(expKeyPair2, respPairs[1]);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task CanGetKeyPair()
|
||||
{
|
||||
var keyName = "1";
|
||||
var expKeyPair1 = new ComputeKeyPair(keyName, "ABCDEF", "12345");
|
||||
|
||||
this.ServicePocoClient.GetKeyPairDelegate = (name) =>
|
||||
{
|
||||
Assert.AreEqual(keyName, name);
|
||||
return Task.Factory.StartNew(() => expKeyPair1);
|
||||
};
|
||||
|
||||
var client = new ComputeServiceClient(GetValidCreds(), "Nova", CancellationToken.None, this.ServiceLocator);
|
||||
var keyPair = await client.GetKeyPair(keyName);
|
||||
|
||||
Assert.IsNotNull(keyPair);
|
||||
Assert.AreEqual(expKeyPair1, keyPair);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(ArgumentNullException))]
|
||||
public async Task GetKeyPairWithNullNameThrows()
|
||||
{
|
||||
var client = new ComputeServiceClient(GetValidCreds(), "Nova", CancellationToken.None, this.ServiceLocator);
|
||||
await client.GetKeyPair(null);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(ArgumentException))]
|
||||
public async Task GetKeyPairWithEmptyNameThrows()
|
||||
{
|
||||
var client = new ComputeServiceClient(GetValidCreds(), "Nova", CancellationToken.None, this.ServiceLocator);
|
||||
await client.GetKeyPair(string.Empty);
|
||||
}
|
||||
}
|
||||
}
|
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@ -1,168 +0,0 @@
|
||||
// /* ============================================================================
|
||||
// Copyright 2014 Hewlett Packard
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ============================================================================ */
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading.Tasks;
|
||||
using OpenStack.Common.ServiceLocation;
|
||||
using OpenStack.Compute;
|
||||
|
||||
namespace OpenStack.Test.Compute
|
||||
{
|
||||
public class TestComputeServicePocoClient : IComputeServicePocoClient
|
||||
{
|
||||
public Func<string, Task<ComputeFlavor>> GetFlavorDelegate { get; set; }
|
||||
|
||||
public Func<Task<IEnumerable<ComputeFlavor>>> GetFlavorsDelegate { get; set; }
|
||||
|
||||
public Func<string, Task<ComputeImage>> GetImageDelegate { get; set; }
|
||||
|
||||
public Func<Task<IEnumerable<ComputeImage>>> GetImagesDelegate { get; set; }
|
||||
|
||||
public Func<string, Task> DeleteImageDelegate { get; set; }
|
||||
|
||||
public Func<string, string, string, string, string, IEnumerable<string>, Task<ComputeServer>> CreateServerDelegate { get; set; }
|
||||
|
||||
public Func<string, Task> DeleteServerDelegate { get; set; }
|
||||
|
||||
public Func<string, Task<IDictionary<string,string>>> GetImageMetadataDelegate { get; set; }
|
||||
|
||||
public Func<string, IDictionary<string, string>, Task> UpdateImageMetadataDelegate { get; set; }
|
||||
|
||||
public Func<string, string, Task> DeleteImageMetadataDelegate { get; set; }
|
||||
|
||||
public Func<string, Task<IDictionary<string, string>>> GetServerMetadataDelegate { get; set; }
|
||||
|
||||
public Func<string, IDictionary<string, string>, Task> UpdateServerMetadataDelegate { get; set; }
|
||||
|
||||
public Func<string, string, Task> DeleteServerMetadataDelegate { get; set; }
|
||||
|
||||
public Func<string, string, Task> AssignFloatingIpDelegate { get; set; }
|
||||
|
||||
public Func<string, Task<ComputeServer>> GetServerDelegate { get; set; }
|
||||
|
||||
public Func<Task<IEnumerable<ComputeServer>>> GetServersDelegate { get; set; }
|
||||
|
||||
public Func<string, Task<ComputeKeyPair>> GetKeyPairDelegate { get; set; }
|
||||
|
||||
public Func<Task<IEnumerable<ComputeKeyPair>>> GetKeyPairsDelegate { get; set; }
|
||||
|
||||
public async Task<ComputeFlavor> GetFlavor(string flavorId)
|
||||
{
|
||||
return await this.GetFlavorDelegate(flavorId);
|
||||
}
|
||||
|
||||
public async Task<IDictionary<string, string>> GetServerMetadata(string serverId)
|
||||
{
|
||||
return await this.GetServerMetadataDelegate(serverId);
|
||||
}
|
||||
|
||||
public async Task UpdateServerMetadata(string serverId, IDictionary<string, string> metadata)
|
||||
{
|
||||
await this.UpdateServerMetadataDelegate(serverId, metadata);
|
||||
}
|
||||
|
||||
public async Task DeleteServerMetadata(string serverId, string key)
|
||||
{
|
||||
await this.DeleteServerMetadataDelegate(serverId, key);
|
||||
}
|
||||
|
||||
public async Task<IEnumerable<ComputeKeyPair>> GetKeyPairs()
|
||||
{
|
||||
return await this.GetKeyPairsDelegate();
|
||||
}
|
||||
|
||||
public async Task<ComputeKeyPair> GetKeyPair(string keyPairName)
|
||||
{
|
||||
return await this.GetKeyPairDelegate(keyPairName);
|
||||
}
|
||||
|
||||
public async Task<IEnumerable<ComputeImage>> GetImages()
|
||||
{
|
||||
return await this.GetImagesDelegate();
|
||||
}
|
||||
|
||||
public async Task<ComputeImage> GetImage(string imageId)
|
||||
{
|
||||
return await this.GetImageDelegate(imageId);
|
||||
}
|
||||
|
||||
public async Task DeleteImage(string imageId)
|
||||
{
|
||||
await this.DeleteImageDelegate(imageId);
|
||||
}
|
||||
|
||||
public async Task<ComputeServer> CreateServer(string name, string imageId, string flavorId, string networkId, string keyName, IEnumerable<string> securityGroups)
|
||||
{
|
||||
return await this.CreateServerDelegate(name, imageId, flavorId, networkId, keyName, securityGroups);
|
||||
}
|
||||
|
||||
public async Task DeleteServer(string serverId)
|
||||
{
|
||||
await this.DeleteServerDelegate(serverId);
|
||||
}
|
||||
|
||||
public async Task<IEnumerable<ComputeServer>> GetServers()
|
||||
{
|
||||
return await this.GetServersDelegate();
|
||||
}
|
||||
|
||||
public async Task<ComputeServer> GetServer(string serverId)
|
||||
{
|
||||
return await this.GetServerDelegate(serverId);
|
||||
}
|
||||
|
||||
public async Task AssignFloatingIp(string serverId, string ipAddress)
|
||||
{
|
||||
await this.AssignFloatingIpDelegate(serverId, ipAddress);
|
||||
}
|
||||
|
||||
public async Task<IDictionary<string, string>> GetImageMetadata(string flavorId)
|
||||
{
|
||||
return await this.GetImageMetadataDelegate(flavorId);
|
||||
}
|
||||
|
||||
public async Task UpdateImageMetadata(string flavorId, IDictionary<string, string> metadata)
|
||||
{
|
||||
await this.UpdateImageMetadataDelegate(flavorId, metadata);
|
||||
}
|
||||
|
||||
public async Task DeleteImageMetadata(string flavorId, string key)
|
||||
{
|
||||
await this.DeleteImageMetadataDelegate(flavorId, key);
|
||||
}
|
||||
|
||||
public async Task<IEnumerable<ComputeFlavor>> GetFlavors()
|
||||
{
|
||||
return await this.GetFlavorsDelegate();
|
||||
}
|
||||
}
|
||||
|
||||
public class TestComputeServicePocoClientFactory : IComputeServicePocoClientFactory
|
||||
{
|
||||
internal IComputeServicePocoClient client;
|
||||
|
||||
public TestComputeServicePocoClientFactory(IComputeServicePocoClient client)
|
||||
{
|
||||
this.client = client;
|
||||
}
|
||||
|
||||
public IComputeServicePocoClient Create(ServiceClientContext context, IServiceLocator serviceLocator)
|
||||
{
|
||||
return client;
|
||||
}
|
||||
}
|
||||
}
|
@ -1,147 +0,0 @@
|
||||
// /* ============================================================================
|
||||
// Copyright 2014 Hewlett Packard
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ============================================================================ */
|
||||
|
||||
using System.Collections.Generic;
|
||||
using System.Threading.Tasks;
|
||||
using OpenStack.Common.Http;
|
||||
using OpenStack.Common.ServiceLocation;
|
||||
using OpenStack.Compute;
|
||||
|
||||
namespace OpenStack.Test.Compute
|
||||
{
|
||||
public class TestComputeServiceRestClient : IComputeServiceRestClient
|
||||
{
|
||||
public TestComputeServiceRestClient()
|
||||
{
|
||||
this.Responses = new Queue<IHttpResponseAbstraction>();
|
||||
}
|
||||
|
||||
public Queue<IHttpResponseAbstraction> Responses { get; set; }
|
||||
|
||||
public Task<IHttpResponseAbstraction> GetFlavors()
|
||||
{
|
||||
return Task.Factory.StartNew(() => Responses.Dequeue());
|
||||
}
|
||||
|
||||
public Task<IHttpResponseAbstraction> GetFlavor(string flavorId)
|
||||
{
|
||||
return Task.Factory.StartNew(() => Responses.Dequeue());
|
||||
}
|
||||
|
||||
public Task<IHttpResponseAbstraction> AssignFloatingIp(string serverId, string ipAddress)
|
||||
{
|
||||
return Task.Factory.StartNew(() => Responses.Dequeue());
|
||||
}
|
||||
|
||||
public Task<IHttpResponseAbstraction> GetServerMetadata(string serverId)
|
||||
{
|
||||
return Task.Factory.StartNew(() => Responses.Dequeue());
|
||||
}
|
||||
|
||||
public Task<IHttpResponseAbstraction> UpdateServerMetadata(string serverId, IDictionary<string, string> metadata)
|
||||
{
|
||||
return Task.Factory.StartNew(() => Responses.Dequeue());
|
||||
}
|
||||
|
||||
public Task<IHttpResponseAbstraction> DeleteServerMetadata(string serverId, string key)
|
||||
{
|
||||
return Task.Factory.StartNew(() => Responses.Dequeue());
|
||||
}
|
||||
|
||||
public Task<IHttpResponseAbstraction> GetKeyPairs()
|
||||
{
|
||||
return Task.Factory.StartNew(() => Responses.Dequeue());
|
||||
}
|
||||
|
||||
public Task<IHttpResponseAbstraction> GetKeyPair(string keyPairName)
|
||||
{
|
||||
return Task.Factory.StartNew(() => Responses.Dequeue());
|
||||
}
|
||||
|
||||
public Task<IHttpResponseAbstraction> GetImages()
|
||||
{
|
||||
return Task.Factory.StartNew(() => Responses.Dequeue());
|
||||
}
|
||||
|
||||
public Task<IHttpResponseAbstraction> GetImage(string imageId)
|
||||
{
|
||||
return Task.Factory.StartNew(() => Responses.Dequeue());
|
||||
}
|
||||
|
||||
public Task<IHttpResponseAbstraction> DeleteImage(string imageId)
|
||||
{
|
||||
return Task.Factory.StartNew(() => Responses.Dequeue());
|
||||
}
|
||||
|
||||
public Task<IHttpResponseAbstraction> GetImageMetadata(string imageId)
|
||||
{
|
||||
return Task.Factory.StartNew(() => Responses.Dequeue());
|
||||
}
|
||||
|
||||
public Task<IHttpResponseAbstraction> UpdateImageMetadata(string imageId, IDictionary<string, string> metadata)
|
||||
{
|
||||
return Task.Factory.StartNew(() => Responses.Dequeue());
|
||||
}
|
||||
|
||||
public Task<IHttpResponseAbstraction> DeleteImageMetadata(string imageId, string key)
|
||||
{
|
||||
return Task.Factory.StartNew(() => Responses.Dequeue());
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public Task<IHttpResponseAbstraction> CreateServer(string name, string imageId, string flavorId, string networkId, IEnumerable<string> securityGroups)
|
||||
{
|
||||
return Task.Factory.StartNew(() => Responses.Dequeue());
|
||||
}
|
||||
|
||||
public Task<IHttpResponseAbstraction> CreateServer(string name, string imageId, string flavorId, string networkId, string keyName,
|
||||
IEnumerable<string> securityGroups)
|
||||
{
|
||||
return Task.Factory.StartNew(() => Responses.Dequeue());
|
||||
}
|
||||
|
||||
public Task<IHttpResponseAbstraction> GetServers()
|
||||
{
|
||||
return Task.Factory.StartNew(() => Responses.Dequeue());
|
||||
}
|
||||
|
||||
public Task<IHttpResponseAbstraction> GetServer(string serverId)
|
||||
{
|
||||
return Task.Factory.StartNew(() => Responses.Dequeue());
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public Task<IHttpResponseAbstraction> DeleteServer(string serverId)
|
||||
{
|
||||
return Task.Factory.StartNew(() => Responses.Dequeue());
|
||||
}
|
||||
}
|
||||
|
||||
public class TestComputeServiceRestClientFactory : IComputeServiceRestClientFactory
|
||||
{
|
||||
internal IComputeServiceRestClient Client;
|
||||
|
||||
public TestComputeServiceRestClientFactory(IComputeServiceRestClient client)
|
||||
{
|
||||
this.Client = client;
|
||||
}
|
||||
|
||||
public IComputeServiceRestClient Create(ServiceClientContext context, IServiceLocator serviceLocator)
|
||||
{
|
||||
return Client;
|
||||
}
|
||||
}
|
||||
}
|
@ -1,69 +0,0 @@
|
||||
// /* ============================================================================
|
||||
// Copyright 2014 Hewlett Packard
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ============================================================================ */
|
||||
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Net;
|
||||
using System.Text;
|
||||
using OpenStack.Common.Http;
|
||||
|
||||
namespace OpenStack.Test
|
||||
{
|
||||
public static class TestHelper
|
||||
{
|
||||
public static MemoryStream CreateStream(string input)
|
||||
{
|
||||
byte[] byteArray = Encoding.ASCII.GetBytes(input);
|
||||
return new MemoryStream(byteArray);
|
||||
}
|
||||
|
||||
public static string GetStringFromStream(Stream input)
|
||||
{
|
||||
var reader = new StreamReader(input);
|
||||
return reader.ReadToEnd();
|
||||
}
|
||||
|
||||
public static IHttpResponseAbstraction CreateErrorResponse()
|
||||
{
|
||||
return new HttpResponseAbstraction(null, new HttpHeadersAbstraction(), HttpStatusCode.InternalServerError);
|
||||
}
|
||||
|
||||
public static IHttpResponseAbstraction CreateResponse(HttpStatusCode code)
|
||||
{
|
||||
return new HttpResponseAbstraction(null, new HttpHeadersAbstraction(), code);
|
||||
}
|
||||
|
||||
public static IHttpResponseAbstraction CreateResponse(HttpStatusCode code, IEnumerable<KeyValuePair<string, string>> headers)
|
||||
{
|
||||
var abstractionHeaders = new HttpHeadersAbstraction();
|
||||
foreach (var header in headers)
|
||||
{
|
||||
abstractionHeaders.Add(header.Key, header.Value);
|
||||
}
|
||||
return new HttpResponseAbstraction(null, abstractionHeaders, code);
|
||||
}
|
||||
|
||||
public static IHttpResponseAbstraction CreateResponse(HttpStatusCode code, IEnumerable<KeyValuePair<string, string>> headers, Stream content)
|
||||
{
|
||||
var abstractionHeaders = new HttpHeadersAbstraction();
|
||||
foreach (var header in headers)
|
||||
{
|
||||
abstractionHeaders.Add(header.Key, header.Value);
|
||||
}
|
||||
return new HttpResponseAbstraction(content, abstractionHeaders, code);
|
||||
}
|
||||
}
|
||||
}
|
@ -1,305 +0,0 @@
|
||||
// /* ============================================================================
|
||||
// Copyright 2014 Hewlett Packard
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ============================================================================ */
|
||||
|
||||
using System;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Threading;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
using OpenStack.Common.Http;
|
||||
|
||||
namespace OpenStack.Test.HttpAbstraction
|
||||
{
|
||||
[TestClass]
|
||||
public class HttpAbstractionClientTests
|
||||
{
|
||||
[TestMethod]
|
||||
[TestCategory("Integration")]
|
||||
[TestCategory("LongRunning")]
|
||||
public void CanMakeGetRequest()
|
||||
{
|
||||
using (var client = new HttpAbstractionClientFactory().Create())
|
||||
{
|
||||
client.Uri = new Uri("http://httpbin.org/get");
|
||||
client.Method = HttpMethod.Get;
|
||||
|
||||
var responseTask = client.SendAsync();
|
||||
responseTask.Wait();
|
||||
var response = responseTask.Result;
|
||||
|
||||
Assert.IsNotNull(response);
|
||||
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
|
||||
|
||||
Assert.IsNotNull(response.Content);
|
||||
var content = TestHelper.GetStringFromStream(response.Content);
|
||||
Assert.AreNotEqual(0, content.Length);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory("Integration")]
|
||||
[TestCategory("LongRunning")]
|
||||
public void ResponsesIncludeContentHeaders()
|
||||
{
|
||||
using (var client = new HttpAbstractionClientFactory().Create(new TimeSpan(0, 5, 0), CancellationToken.None))
|
||||
{
|
||||
client.Uri = new Uri("http://httpbin.org/get");
|
||||
client.Method = HttpMethod.Get;
|
||||
|
||||
var responseTask = client.SendAsync();
|
||||
responseTask.Wait();
|
||||
var response = responseTask.Result;
|
||||
|
||||
Assert.IsNotNull(response);
|
||||
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
|
||||
|
||||
Assert.IsTrue(response.Headers.Contains("Content-Length"));
|
||||
Assert.IsTrue(response.Headers.Contains("Content-Type"));
|
||||
|
||||
Assert.IsTrue(int.Parse(response.Headers["Content-Length"].First()) > 100);
|
||||
Assert.AreEqual("application/json", response.Headers["Content-Type"].First());
|
||||
|
||||
Assert.IsNotNull(response.Content);
|
||||
var content = TestHelper.GetStringFromStream(response.Content);
|
||||
Assert.AreNotEqual(0, content.Length);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory("Integration")]
|
||||
[TestCategory("LongRunning")]
|
||||
public void CanMakePutRequest()
|
||||
{
|
||||
using (var client = new HttpAbstractionClientFactory().Create())
|
||||
{
|
||||
using (var content = TestHelper.CreateStream("Test Text"))
|
||||
{
|
||||
client.Uri = new Uri("http://httpbin.org/put");
|
||||
client.Method = HttpMethod.Put;
|
||||
client.Content = content;
|
||||
|
||||
var responseTask = client.SendAsync();
|
||||
responseTask.Wait();
|
||||
var response = responseTask.Result;
|
||||
|
||||
Assert.IsNotNull(response);
|
||||
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
|
||||
|
||||
Assert.IsNotNull(response.Content);
|
||||
|
||||
var stringContent = TestHelper.GetStringFromStream(response.Content);
|
||||
Assert.AreNotEqual(0, stringContent.Length);
|
||||
Assert.IsTrue(stringContent.Contains("\"data\": \"Test Text\""));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory("Integration")]
|
||||
[TestCategory("LongRunning")]
|
||||
public void CanMakePostRequest()
|
||||
{
|
||||
using (var client = new HttpAbstractionClientFactory().Create())
|
||||
{
|
||||
using (var content = TestHelper.CreateStream("Test Text"))
|
||||
{
|
||||
client.Uri = new Uri("http://httpbin.org/post");
|
||||
client.Method = HttpMethod.Post;
|
||||
client.Content = content;
|
||||
|
||||
var responseTask = client.SendAsync();
|
||||
responseTask.Wait();
|
||||
var response = responseTask.Result;
|
||||
|
||||
Assert.IsNotNull(response);
|
||||
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
|
||||
|
||||
var stringContent = TestHelper.GetStringFromStream(response.Content);
|
||||
|
||||
Assert.IsTrue(stringContent.Contains("\"data\": \"Test Text\""));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory("Integration")]
|
||||
[TestCategory("LongRunning")]
|
||||
public void CanMakePostRequestWithNullContent()
|
||||
{
|
||||
using (var client = new HttpAbstractionClientFactory().Create())
|
||||
{
|
||||
client.Uri = new Uri("http://httpbin.org/post");
|
||||
client.Method = HttpMethod.Post;
|
||||
|
||||
var responseTask = client.SendAsync();
|
||||
responseTask.Wait();
|
||||
var response = responseTask.Result;
|
||||
|
||||
Assert.IsNotNull(response);
|
||||
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
|
||||
|
||||
var stringContent = TestHelper.GetStringFromStream(response.Content);
|
||||
|
||||
Assert.IsTrue(stringContent.Contains("\"data\": \"\""));
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory("Integration")]
|
||||
[TestCategory("LongRunning")]
|
||||
public void CanMakeDeleteRequest()
|
||||
{
|
||||
using (var client = new HttpAbstractionClientFactory().Create())
|
||||
{
|
||||
|
||||
client.Uri = new Uri("http://httpbin.org/delete");
|
||||
client.Method = HttpMethod.Delete;
|
||||
|
||||
var responseTask = client.SendAsync();
|
||||
responseTask.Wait();
|
||||
var response = responseTask.Result;
|
||||
|
||||
Assert.IsNotNull(response);
|
||||
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
|
||||
|
||||
Assert.IsNotNull(response.Content);
|
||||
var content = TestHelper.GetStringFromStream(response.Content);
|
||||
Assert.AreNotEqual(0, content.Length);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory("Integration")]
|
||||
[TestCategory("LongRunning")]
|
||||
public void CanMakeMultipleGetRequestsWithSameClient()
|
||||
{
|
||||
using (var client = new HttpAbstractionClientFactory().Create())
|
||||
{
|
||||
|
||||
client.Uri = new Uri("http://httpbin.org/get");
|
||||
client.Method = HttpMethod.Get;
|
||||
|
||||
var responseTask = client.SendAsync();
|
||||
responseTask.Wait();
|
||||
|
||||
responseTask = client.SendAsync();
|
||||
responseTask.Wait();
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory("Integration")]
|
||||
[TestCategory("LongRunning")]
|
||||
public void RequestsHonorsClientSideTimeout()
|
||||
{
|
||||
try
|
||||
{
|
||||
using (var client = new HttpAbstractionClientFactory().Create(TimeSpan.FromMilliseconds(100)))
|
||||
{
|
||||
client.Uri = new Uri("http://httpbin.org/delay/30000");
|
||||
|
||||
var responseTask = client.SendAsync();
|
||||
responseTask.Wait();
|
||||
}
|
||||
}
|
||||
catch (AggregateException ex)
|
||||
{
|
||||
var inner = ex.InnerException;
|
||||
Assert.IsInstanceOfType(inner,typeof(TimeoutException));
|
||||
Assert.IsTrue(inner.Message.Contains("failed to complete in the given timeout period"));
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory("Integration")]
|
||||
[TestCategory("LongRunning")]
|
||||
public void RequestsHonorsCancelationToken()
|
||||
{
|
||||
var token = new CancellationToken(true);
|
||||
var startTime = DateTime.Now;
|
||||
|
||||
try
|
||||
{
|
||||
using (var client = new HttpAbstractionClientFactory().Create(token))
|
||||
{
|
||||
client.Uri = new Uri("http://httpbin.org/delay/30000");
|
||||
client.Timeout = TimeSpan.FromSeconds(31);
|
||||
|
||||
var responseTask = client.SendAsync();
|
||||
responseTask.Wait();
|
||||
}
|
||||
}
|
||||
catch (AggregateException ex)
|
||||
{
|
||||
var inner = ex.InnerException;
|
||||
Assert.IsTrue(DateTime.Now - startTime < TimeSpan.FromSeconds(30));
|
||||
Assert.IsTrue(inner.Message.Contains("was canceled"));
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory("Integration")]
|
||||
[TestCategory("LongRunning")]
|
||||
public void RequestsHandlesHttpErrors()
|
||||
{
|
||||
using (var client = new HttpAbstractionClientFactory().Create())
|
||||
{
|
||||
client.Uri = new Uri("http://httpbin.org/status/404");
|
||||
|
||||
var responseTask = client.SendAsync();
|
||||
responseTask.Wait();
|
||||
var response = responseTask.Result;
|
||||
|
||||
Assert.IsNotNull(response);
|
||||
Assert.AreEqual(HttpStatusCode.NotFound, response.StatusCode);
|
||||
|
||||
var stringContent = TestHelper.GetStringFromStream(response.Content);
|
||||
|
||||
Assert.AreEqual(string.Empty, stringContent);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory("Integration")]
|
||||
[TestCategory("LongRunning")]
|
||||
public void RequestsCanSendHeaders()
|
||||
{
|
||||
using (var client = new HttpAbstractionClientFactory().Create())
|
||||
{
|
||||
client.Uri = new Uri("http://httpbin.org/get");
|
||||
client.Headers.Add("X-Test-Header","TEST");
|
||||
|
||||
//Added in order to force httpbin not to cache the responses from any prior get requests/unit tests.
|
||||
client.Headers.Add("Cache-Control", "max-age=0");
|
||||
|
||||
var responseTask = client.SendAsync();
|
||||
|
||||
responseTask.Wait();
|
||||
var response = responseTask.Result;
|
||||
Assert.IsNotNull(response);
|
||||
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
|
||||
|
||||
Assert.IsNotNull(response.Content);
|
||||
var content = TestHelper.GetStringFromStream(response.Content);
|
||||
Assert.AreNotEqual(0, content.Length);
|
||||
|
||||
Assert.IsTrue(content.Contains("\"X-Test-Header\": \"TEST\""));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
@ -1,85 +0,0 @@
|
||||
// /* ============================================================================
|
||||
// Copyright 2014 Hewlett Packard
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ============================================================================ */
|
||||
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Net.Http;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
using OpenStack.Common.Http;
|
||||
|
||||
namespace OpenStack.Test.HttpAbstraction
|
||||
{
|
||||
[TestClass]
|
||||
public class HttpHeadersAbstractionTests
|
||||
{
|
||||
[TestMethod]
|
||||
public void CanAddHeaders()
|
||||
{
|
||||
var headers = new HttpHeadersAbstraction();
|
||||
headers.Add("Test","Value");
|
||||
Assert.IsTrue(headers.Contains("Test"));
|
||||
Assert.AreEqual("Value",headers["Test"].First());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanAddRangeHeaders()
|
||||
{
|
||||
var headers = new HttpHeadersAbstraction();
|
||||
|
||||
var rspMsg = new HttpResponseMessage();
|
||||
rspMsg.Headers.Add("Test", "Value");
|
||||
|
||||
headers.AddRange(rspMsg.Headers);
|
||||
Assert.IsTrue(headers.Contains("Test"));
|
||||
Assert.AreEqual("Value", headers["Test"].First());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanClearHeaders()
|
||||
{
|
||||
var headers = new HttpHeadersAbstraction();
|
||||
headers.Add("Test", "Value");
|
||||
Assert.IsTrue(headers.Contains("Test"));
|
||||
|
||||
headers.Clear();
|
||||
Assert.AreEqual(0,headers.Count());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanGetValuesHeaders()
|
||||
{
|
||||
var headers = new HttpHeadersAbstraction();
|
||||
var values = new List<string>() {"value1", "value2"};
|
||||
headers.Add("Test", values);
|
||||
Assert.IsTrue(headers.Contains("Test"));
|
||||
Assert.AreEqual(values, headers.GetValues("Test"));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanTryGetValuesHeaders()
|
||||
{
|
||||
var headers = new HttpHeadersAbstraction();
|
||||
var values = new List<string>() { "value1", "value2" };
|
||||
headers.Add("Test", values);
|
||||
|
||||
IEnumerable<string> resValues = new List<string>();
|
||||
Assert.IsTrue(headers.TryGetValue("Test", out resValues));
|
||||
|
||||
Assert.AreEqual(2,resValues.Count());
|
||||
Assert.AreEqual(values, resValues);
|
||||
}
|
||||
}
|
||||
}
|
@ -1,112 +0,0 @@
|
||||
// /* ============================================================================
|
||||
// Copyright 2014 Hewlett Packard
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ============================================================================ */
|
||||
|
||||
using System;
|
||||
using System.Web;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
using OpenStack.Identity;
|
||||
|
||||
namespace OpenStack.Test.Identity
|
||||
{
|
||||
[TestClass]
|
||||
public class AccessTokenPayloadConverterTests
|
||||
{
|
||||
[TestMethod]
|
||||
public void CanConvertJsonPayload()
|
||||
{
|
||||
var AuthJsonResponseFixture = @"{
|
||||
""access"": {
|
||||
""token"": {
|
||||
""expires"": ""2014-03-18T10:59:46.355Z"",
|
||||
""id"": ""HPAuth10_af3d1bfe456d18e8d4793e54922f839fa051d9f60f115aca52c9a44f9e3d96fb"",
|
||||
""tenant"": {
|
||||
""id"": ""10244656540440"",
|
||||
""name"": ""10255892528404-Project""
|
||||
}
|
||||
}
|
||||
}
|
||||
}";
|
||||
|
||||
var expectedToken = "HPAuth10_af3d1bfe456d18e8d4793e54922f839fa051d9f60f115aca52c9a44f9e3d96fb";
|
||||
var converter = new AccessTokenPayloadConverter();
|
||||
var token = converter.Convert(AuthJsonResponseFixture);
|
||||
Assert.IsNotNull(token);
|
||||
Assert.AreEqual(expectedToken, token);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(FormatException))]
|
||||
public void CannotConvertJsonPayloadMissingTokenId()
|
||||
{
|
||||
var missingTokenIdFixture = @"{
|
||||
""access"": {
|
||||
""token"": {
|
||||
""expires"": ""2014-03-18T10:59:46.355Z"",
|
||||
""tenant"": {
|
||||
""id"": ""10244656540440"",
|
||||
""name"": ""10255892528404-Project""
|
||||
}
|
||||
}
|
||||
}
|
||||
}";
|
||||
|
||||
var converter = new AccessTokenPayloadConverter();
|
||||
converter.Convert(missingTokenIdFixture);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(FormatException))]
|
||||
public void CannotConvertJsonPayloadMissingToken()
|
||||
{
|
||||
var missingTokenFixture = @"{
|
||||
""access"": { }
|
||||
}";
|
||||
|
||||
var converter = new AccessTokenPayloadConverter();
|
||||
converter.Convert(missingTokenFixture);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(FormatException))]
|
||||
public void CannotConvertJsonPayloadEmptyObject()
|
||||
{
|
||||
var emptyObjectFixture = @"{ }";
|
||||
|
||||
var converter = new AccessTokenPayloadConverter();
|
||||
converter.Convert(emptyObjectFixture);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(FormatException))]
|
||||
public void CannotConvertInvalidJson()
|
||||
{
|
||||
var badJsonFixture = @"{ NOT JSON";
|
||||
|
||||
var converter = new AccessTokenPayloadConverter();
|
||||
converter.Convert(badJsonFixture);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(FormatException))]
|
||||
public void CannotConvertNonObjectJson()
|
||||
{
|
||||
var nonObjectJson = @"[]";
|
||||
|
||||
var converter = new AccessTokenPayloadConverter();
|
||||
converter.Convert(nonObjectJson);
|
||||
}
|
||||
}
|
||||
}
|
@ -1,200 +0,0 @@
|
||||
// /* ============================================================================
|
||||
// Copyright 2014 Hewlett Packard
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ============================================================================ */
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using OpenStack.Common;
|
||||
using OpenStack.Common.Http;
|
||||
|
||||
namespace OpenStack.Test.Identity
|
||||
{
|
||||
public class IdentityRestServiceSimulator : DisposableClass, IHttpAbstractionClient
|
||||
{
|
||||
#region Authentication Json Response Fixture
|
||||
|
||||
internal string AuthJsonResponseFixture = @"{
|
||||
""access"": {
|
||||
""token"": {
|
||||
""expires"": ""2014-03-18T10:59:46.355Z"",
|
||||
""id"": ""HPAuth10_af3d1bfe456d18e8d4793e54922f839fa051d9f60f115aca52c9a44f9e3d96fb"",
|
||||
""tenant"": {
|
||||
""id"": ""10244656540440"",
|
||||
""name"": ""10255892528404-Project""
|
||||
}
|
||||
},
|
||||
""user"": {
|
||||
""id"": ""10391119133001"",
|
||||
""name"": ""wayne.foley"",
|
||||
""otherAttributes"": {
|
||||
""domainStatus"": ""enabled"",
|
||||
""domainStatusCode"": ""00""
|
||||
},
|
||||
""roles"": [ ]
|
||||
},
|
||||
""serviceCatalog"": [
|
||||
{
|
||||
""name"": ""Networking"",
|
||||
""type"": ""network"",
|
||||
""endpoints"": [
|
||||
{
|
||||
""tenantId"": ""10244656540440"",
|
||||
""publicURL"": ""https://region-a.geo-1.network.hpcloudsvc.com"",
|
||||
""publicURL2"": """",
|
||||
""region"": ""region-a.geo-1"",
|
||||
""versionId"": ""2.0"",
|
||||
""versionInfo"": ""https://region-a.geo-1.network.hpcloudsvc.com"",
|
||||
""versionList"": ""https://region-a.geo-1.network.hpcloudsvc.com""
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
""name"": ""Object Storage"",
|
||||
""type"": ""object-store"",
|
||||
""endpoints"": [
|
||||
{
|
||||
""tenantId"": ""10244656540440"",
|
||||
""publicURL"": ""https://region-a.geo-1.objects.hpcloudsvc.com/v1/10244656540440"",
|
||||
""region"": ""region-a.geo-1"",
|
||||
""versionId"": ""1.0"",
|
||||
""versionInfo"": ""https://region-a.geo-1.objects.hpcloudsvc.com/v1.0/"",
|
||||
""versionList"": ""https://region-a.geo-1.objects.hpcloudsvc.com""
|
||||
},
|
||||
{
|
||||
""tenantId"": ""10244656540440"",
|
||||
""publicURL"": ""https://region-b.geo-1.objects.hpcloudsvc.com:443/v1/10244656540440"",
|
||||
""region"": ""region-b.geo-1"",
|
||||
""versionId"": ""1"",
|
||||
""versionInfo"": ""https://region-b.geo-1.objects.hpcloudsvc.com:443/v1/"",
|
||||
""versionList"": ""https://region-b.geo-1.objects.hpcloudsvc.com:443""
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
""name"": ""Identity"",
|
||||
""type"": ""identity"",
|
||||
""endpoints"": [
|
||||
{
|
||||
""publicURL"": ""https://region-a.geo-1.identity.hpcloudsvc.com:35357/v2.0/"",
|
||||
""region"": ""region-a.geo-1"",
|
||||
""versionId"": ""2.0"",
|
||||
""versionInfo"": ""https://region-a.geo-1.identity.hpcloudsvc.com:35357/v2.0/"",
|
||||
""versionList"": ""https://region-a.geo-1.identity.hpcloudsvc.com:35357""
|
||||
},
|
||||
{
|
||||
""publicURL"": ""https://region-a.geo-1.identity.hpcloudsvc.com:35357/v3/"",
|
||||
""region"": ""region-a.geo-1"",
|
||||
""versionId"": ""3.0"",
|
||||
""versionInfo"": ""https://region-a.geo-1.identity.hpcloudsvc.com:35357/v3/"",
|
||||
""versionList"": ""https://region-a.geo-1.identity.hpcloudsvc.com:35357""
|
||||
},
|
||||
{
|
||||
""publicURL"": ""https://region-b.geo-1.identity.hpcloudsvc.com:35357/v2.0/"",
|
||||
""region"": ""region-b.geo-1"",
|
||||
""versionId"": ""2.0"",
|
||||
""versionInfo"": ""https://region-b.geo-1.identity.hpcloudsvc.com:35357/v2.0/"",
|
||||
""versionList"": ""https://region-b.geo-1.identity.hpcloudsvc.com:35357""
|
||||
},
|
||||
{
|
||||
""publicURL"": ""https://region-b.geo-1.identity.hpcloudsvc.com:35357/v3/"",
|
||||
""region"": ""region-b.geo-1"",
|
||||
""versionId"": ""3.0"",
|
||||
""versionInfo"": ""https://region-b.geo-1.identity.hpcloudsvc.com:35357/v3/"",
|
||||
""versionList"": ""https://region-b.geo-1.identity.hpcloudsvc.com:35357""
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
""name"": ""Compute"",
|
||||
""type"": ""compute"",
|
||||
""endpoints"": [
|
||||
{
|
||||
""tenantId"": ""10244656540440"",
|
||||
""publicURL"": ""https://region-a.geo-1.compute.hpcloudsvc.com/v2/10244656540440"",
|
||||
""region"": ""region-a.geo-1"",
|
||||
""versionId"": ""2"",
|
||||
""versionInfo"": ""https://region-a.geo-1.compute.hpcloudsvc.com/v2/"",
|
||||
""versionList"": ""https://region-a.geo-1.compute.hpcloudsvc.com""
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}";
|
||||
|
||||
|
||||
#endregion
|
||||
|
||||
public HttpMethod Method { get; set; }
|
||||
public Uri Uri { get; set; }
|
||||
public Stream Content { get; set; }
|
||||
public IDictionary<string, string> Headers { get; private set; }
|
||||
public string ContentType { get; set; }
|
||||
public TimeSpan Timeout { get; set; }
|
||||
//public event EventHandler<HttpProgressEventArgs> HttpReceiveProgress;
|
||||
//public event EventHandler<HttpProgressEventArgs> HttpSendProgress;
|
||||
|
||||
public IdentityRestServiceSimulator()
|
||||
{
|
||||
this.Headers = new Dictionary<string, string>();
|
||||
}
|
||||
|
||||
public Task<IHttpResponseAbstraction> SendAsync()
|
||||
{
|
||||
var resp = TestHelper.CreateResponse(HttpStatusCode.OK, new List<KeyValuePair<string, string>>(),
|
||||
this.AuthJsonResponseFixture.ConvertToStream());
|
||||
return Task.Factory.StartNew(() => resp);
|
||||
}
|
||||
}
|
||||
|
||||
public class IdentityRestServiceSimulatorFactory : IHttpAbstractionClientFactory
|
||||
{
|
||||
internal IdentityRestServiceSimulator Simulator;
|
||||
|
||||
public IdentityRestServiceSimulatorFactory(IdentityRestServiceSimulator simulator)
|
||||
{
|
||||
this.Simulator = simulator;
|
||||
}
|
||||
|
||||
public IHttpAbstractionClient Create()
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public IHttpAbstractionClient Create(CancellationToken token)
|
||||
{
|
||||
if (this.Simulator != null)
|
||||
{
|
||||
this.Simulator.Headers.Clear();
|
||||
}
|
||||
return this.Simulator ?? new IdentityRestServiceSimulator();
|
||||
}
|
||||
|
||||
public IHttpAbstractionClient Create(TimeSpan timeout)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public IHttpAbstractionClient Create(TimeSpan timeout, CancellationToken token)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
}
|
||||
}
|
@ -1,52 +0,0 @@
|
||||
using System;
|
||||
using System.Linq;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
using OpenStack.Common;
|
||||
using OpenStack.Identity;
|
||||
|
||||
namespace OpenStack.Test.Identity
|
||||
{
|
||||
[TestClass]
|
||||
public class IdentityServiceClientDefinitionTests
|
||||
{
|
||||
public IOpenStackCredential GetValidCredentials()
|
||||
{
|
||||
var endpoint = new Uri("https://someidentityendpoint:35357/v2.0");
|
||||
var userName = "TestUser";
|
||||
var password = "RandomPassword";
|
||||
var tenantId = "12345";
|
||||
|
||||
return new OpenStackCredential(endpoint, userName, password, tenantId);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanSupportVersion2()
|
||||
{
|
||||
var client = new IdentityServiceClientDefinition();
|
||||
|
||||
Assert.IsTrue(client.IsSupported(GetValidCredentials(), string.Empty));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CannotSupportVersion1()
|
||||
{
|
||||
var endpoint = new Uri("https://someidentityendpoint:35357/v1.0/tokens");
|
||||
var userName = "TestUser";
|
||||
var password = "RandomPassword";
|
||||
var tenantId = "12345";
|
||||
|
||||
var creds = new OpenStackCredential(endpoint, userName, password, tenantId);
|
||||
|
||||
var client = new IdentityServiceClientDefinition();
|
||||
|
||||
Assert.IsFalse(client.IsSupported(creds, string.Empty));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Version2Supported()
|
||||
{
|
||||
var client = new IdentityServiceClientDefinition();
|
||||
Assert.IsTrue(client.ListSupportedVersions().Contains("2.0.0.0"));
|
||||
}
|
||||
}
|
||||
}
|
@ -1,79 +0,0 @@
|
||||
// /* ============================================================================
|
||||
// Copyright 2014 Hewlett Packard
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ============================================================================ */
|
||||
|
||||
using System;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
using OpenStack.Common;
|
||||
using OpenStack.Common.ServiceLocation;
|
||||
using OpenStack.Identity;
|
||||
|
||||
namespace OpenStack.Test.Identity
|
||||
{
|
||||
[TestClass]
|
||||
public class IdentityServiceClientTests
|
||||
{
|
||||
internal TestIdentityServicePocoClient pocoClient;
|
||||
internal IServiceLocator ServiceLocator;
|
||||
|
||||
[TestInitialize]
|
||||
public void TestSetup()
|
||||
{
|
||||
this.ServiceLocator = new ServiceLocator();
|
||||
this.pocoClient = new TestIdentityServicePocoClient();
|
||||
|
||||
var manager = this.ServiceLocator.Locate<IServiceLocationOverrideManager>();
|
||||
manager.RegisterServiceInstance(typeof(IIdentityServicePocoClientFactory), new TestIdentityServicePocoClientFactory(pocoClient));
|
||||
}
|
||||
|
||||
[TestCleanup]
|
||||
public void TestCleanup()
|
||||
{
|
||||
this.pocoClient = new TestIdentityServicePocoClient();
|
||||
this.ServiceLocator = new ServiceLocator();
|
||||
}
|
||||
|
||||
public IOpenStackCredential GetValidCredentials()
|
||||
{
|
||||
var endpoint = new Uri("https://someidentityendpoint:35357/v2.0/tokens");
|
||||
var userName = "TestUser";
|
||||
var password = "RandomPassword";
|
||||
var tenantId = "12345";
|
||||
|
||||
return new OpenStackCredential(endpoint, userName, password, tenantId);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task CanAuthenticate()
|
||||
{
|
||||
var creds = GetValidCredentials();
|
||||
var token = "someToken";
|
||||
|
||||
this.pocoClient.AuthenticationDelegate = () =>
|
||||
{
|
||||
creds.SetAccessTokenId(token);
|
||||
return Task.Factory.StartNew(() => creds);
|
||||
};
|
||||
|
||||
var client = new IdentityServiceClientDefinition().Create(GetValidCredentials(), string.Empty, CancellationToken.None, this.ServiceLocator) as IdentityServiceClient;
|
||||
var resp = await client.Authenticate();
|
||||
|
||||
Assert.AreEqual(creds, resp);
|
||||
Assert.AreEqual(creds,client.Credential);
|
||||
}
|
||||
}
|
||||
}
|
@ -1,342 +0,0 @@
|
||||
// /* ============================================================================
|
||||
// Copyright 2014 Hewlett Packard
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ============================================================================ */
|
||||
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
using OpenStack.Common;
|
||||
using OpenStack.Common.Http;
|
||||
using OpenStack.Common.ServiceLocation;
|
||||
using OpenStack.Identity;
|
||||
|
||||
namespace OpenStack.Test.Identity
|
||||
{
|
||||
[TestClass]
|
||||
public class IdentityServicePocoClientTests
|
||||
{
|
||||
internal TestIdentityServiceRestClient RestClient;
|
||||
internal string defaultRegion = "region-a.geo-1";
|
||||
internal IServiceLocator ServiceLocator;
|
||||
|
||||
[TestInitialize]
|
||||
public void TestSetup()
|
||||
{
|
||||
this.RestClient = new TestIdentityServiceRestClient();
|
||||
this.ServiceLocator = new ServiceLocator();
|
||||
this.ServiceLocator.EnsureAssemblyRegistration(typeof(ServiceLocator).Assembly);
|
||||
|
||||
var manager = this.ServiceLocator.Locate<IServiceLocationOverrideManager>();
|
||||
manager.RegisterServiceInstance(typeof(IIdentityServiceRestClientFactory), new TestIdentityServiceRestClientFactory(RestClient));
|
||||
manager.RegisterServiceInstance(typeof(IOpenStackRegionResolver), new TestOpenStackRegionResolver(defaultRegion));
|
||||
}
|
||||
|
||||
[TestCleanup]
|
||||
public void TestCleanup()
|
||||
{
|
||||
this.RestClient = new TestIdentityServiceRestClient();
|
||||
this.ServiceLocator = new ServiceLocator();
|
||||
}
|
||||
|
||||
public IOpenStackCredential GetValidCredentials()
|
||||
{
|
||||
var endpoint = new Uri("https://auth.someplace.com/authme");
|
||||
var userName = "TestUser";
|
||||
var password = "RandomPassword";
|
||||
var tenantId = "12345";
|
||||
|
||||
return new OpenStackCredential(endpoint, userName, password, tenantId);
|
||||
}
|
||||
|
||||
|
||||
[TestMethod]
|
||||
public async Task CanAuthenticateWithOkResponse()
|
||||
{
|
||||
var creds = GetValidCredentials();
|
||||
|
||||
var expectedToken = "HPAuth10_af3d1bfe456d18e8d4793e54922f839fa051d9f60f115aca52c9a44f9e3d96fb";
|
||||
|
||||
var payload = @"{
|
||||
""access"": {
|
||||
""token"": {
|
||||
""expires"": ""2014-03-18T10:59:46.355Z"",
|
||||
""id"": ""HPAuth10_af3d1bfe456d18e8d4793e54922f839fa051d9f60f115aca52c9a44f9e3d96fb"",
|
||||
""tenant"": {
|
||||
""id"": ""10244656540440"",
|
||||
""name"": ""10255892528404-Project""
|
||||
}
|
||||
},
|
||||
""serviceCatalog"":[{
|
||||
""name"": ""Object Storage"",
|
||||
""type"": ""object-store"",
|
||||
""endpoints"": [
|
||||
{
|
||||
""tenantId"": ""10244656540440"",
|
||||
""publicURL"": ""https://region-a.geo-1.objects.hpcloudsvc.com/v1/10244656540440"",
|
||||
""region"": ""region-a.geo-1"",
|
||||
""versionId"": ""1.0"",
|
||||
""versionInfo"": ""https://region-a.geo-1.objects.hpcloudsvc.com/v1.0/"",
|
||||
""versionList"": ""https://region-a.geo-1.objects.hpcloudsvc.com""
|
||||
},
|
||||
{
|
||||
""tenantId"": ""10244656540440"",
|
||||
""publicURL"": ""https://region-b.geo-1.objects.hpcloudsvc.com:443/v1/10244656540440"",
|
||||
""region"": ""region-b.geo-1"",
|
||||
""versionId"": ""1"",
|
||||
""versionInfo"": ""https://region-b.geo-1.objects.hpcloudsvc.com:443/v1/"",
|
||||
""versionList"": ""https://region-b.geo-1.objects.hpcloudsvc.com:443""
|
||||
}
|
||||
]
|
||||
}]
|
||||
}
|
||||
}";
|
||||
|
||||
var content = TestHelper.CreateStream(payload);
|
||||
|
||||
var restResp = new HttpResponseAbstraction(content, new HttpHeadersAbstraction(), HttpStatusCode.OK);
|
||||
this.RestClient.Response = restResp;
|
||||
|
||||
var client =
|
||||
new IdentityServicePocoClientFactory().Create(creds, "Swift", CancellationToken.None, this.ServiceLocator) as
|
||||
IdentityServicePocoClient;
|
||||
var result = await client.Authenticate();
|
||||
|
||||
Assert.IsNotNull(result);
|
||||
Assert.AreEqual(creds.UserName, result.UserName);
|
||||
Assert.AreEqual(creds.Password, result.Password);
|
||||
Assert.AreEqual(creds.TenantId, result.TenantId);
|
||||
Assert.AreEqual(expectedToken, result.AccessTokenId);
|
||||
Assert.AreEqual(1,result.ServiceCatalog.Count());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task CanAuthenticateWithNonAuthoritativeInfoResponse()
|
||||
{
|
||||
var creds = GetValidCredentials();
|
||||
|
||||
var expectedToken = "HPAuth10_af3d1bfe456d18e8d4793e54922f839fa051d9f60f115aca52c9a44f9e3d96fb";
|
||||
|
||||
var payload = @"{
|
||||
""access"": {
|
||||
""token"": {
|
||||
""expires"": ""2014-03-18T10:59:46.355Z"",
|
||||
""id"": ""HPAuth10_af3d1bfe456d18e8d4793e54922f839fa051d9f60f115aca52c9a44f9e3d96fb"",
|
||||
""tenant"": {
|
||||
""id"": ""10244656540440"",
|
||||
""name"": ""10255892528404-Project""
|
||||
}
|
||||
},
|
||||
""serviceCatalog"":[{
|
||||
""name"": ""Object Storage"",
|
||||
""type"": ""object-store"",
|
||||
""endpoints"": [
|
||||
{
|
||||
""tenantId"": ""10244656540440"",
|
||||
""publicURL"": ""https://region-a.geo-1.objects.hpcloudsvc.com/v1/10244656540440"",
|
||||
""region"": ""region-a.geo-1"",
|
||||
""versionId"": ""1.0"",
|
||||
""versionInfo"": ""https://region-a.geo-1.objects.hpcloudsvc.com/v1.0/"",
|
||||
""versionList"": ""https://region-a.geo-1.objects.hpcloudsvc.com""
|
||||
},
|
||||
{
|
||||
""tenantId"": ""10244656540440"",
|
||||
""publicURL"": ""https://region-b.geo-1.objects.hpcloudsvc.com:443/v1/10244656540440"",
|
||||
""region"": ""region-b.geo-1"",
|
||||
""versionId"": ""1"",
|
||||
""versionInfo"": ""https://region-b.geo-1.objects.hpcloudsvc.com:443/v1/"",
|
||||
""versionList"": ""https://region-b.geo-1.objects.hpcloudsvc.com:443""
|
||||
}
|
||||
]
|
||||
}]
|
||||
}
|
||||
}";
|
||||
|
||||
var content = TestHelper.CreateStream(payload);
|
||||
|
||||
var restResp = new HttpResponseAbstraction(content, new HttpHeadersAbstraction(), HttpStatusCode.NonAuthoritativeInformation);
|
||||
this.RestClient.Response = restResp;
|
||||
|
||||
var client = new IdentityServicePocoClient(creds, "Swift", CancellationToken.None, this.ServiceLocator);
|
||||
var result = await client.Authenticate();
|
||||
|
||||
Assert.IsNotNull(result);
|
||||
Assert.AreEqual(creds.UserName, result.UserName);
|
||||
Assert.AreEqual(creds.Password, result.Password);
|
||||
Assert.AreEqual(creds.TenantId, result.TenantId);
|
||||
Assert.AreEqual(expectedToken, result.AccessTokenId);
|
||||
Assert.AreEqual(1, result.ServiceCatalog.Count());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task AuthenticationDoesNotResolveRegionIfCredRegionSupplied()
|
||||
{
|
||||
var expectedRegion = "Some region";
|
||||
var creds = GetValidCredentials();
|
||||
creds.SetRegion(expectedRegion);
|
||||
var payload = @"{
|
||||
""access"": {
|
||||
""token"": {
|
||||
""expires"": ""2014-03-18T10:59:46.355Z"",
|
||||
""id"": ""HPAuth10_af3d1bfe456d18e8d4793e54922f839fa051d9f60f115aca52c9a44f9e3d96fb"",
|
||||
""tenant"": {
|
||||
""id"": ""10244656540440"",
|
||||
""name"": ""10255892528404-Project""
|
||||
}
|
||||
},
|
||||
""serviceCatalog"":[{
|
||||
""name"": ""Object Storage"",
|
||||
""type"": ""object-store"",
|
||||
""endpoints"": [
|
||||
{
|
||||
""tenantId"": ""10244656540440"",
|
||||
""publicURL"": ""https://region-a.geo-1.objects.hpcloudsvc.com/v1/10244656540440"",
|
||||
""region"": ""region-a.geo-1"",
|
||||
""versionId"": ""1.0"",
|
||||
""versionInfo"": ""https://region-a.geo-1.objects.hpcloudsvc.com/v1.0/"",
|
||||
""versionList"": ""https://region-a.geo-1.objects.hpcloudsvc.com""
|
||||
},
|
||||
{
|
||||
""tenantId"": ""10244656540440"",
|
||||
""publicURL"": ""https://region-b.geo-1.objects.hpcloudsvc.com:443/v1/10244656540440"",
|
||||
""region"": ""region-b.geo-1"",
|
||||
""versionId"": ""1"",
|
||||
""versionInfo"": ""https://region-b.geo-1.objects.hpcloudsvc.com:443/v1/"",
|
||||
""versionList"": ""https://region-b.geo-1.objects.hpcloudsvc.com:443""
|
||||
}
|
||||
]
|
||||
}]
|
||||
}
|
||||
}";
|
||||
|
||||
var content = TestHelper.CreateStream(payload);
|
||||
|
||||
var restResp = new HttpResponseAbstraction(content, new HttpHeadersAbstraction(), HttpStatusCode.NonAuthoritativeInformation);
|
||||
this.RestClient.Response = restResp;
|
||||
|
||||
var client = new IdentityServicePocoClient(creds, "Swift", CancellationToken.None, this.ServiceLocator);
|
||||
var result = await client.Authenticate();
|
||||
|
||||
Assert.AreEqual(expectedRegion, result.Region);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(InvalidOperationException))]
|
||||
public async Task CannotAuthenticateWithUnauthorizedResponse()
|
||||
{
|
||||
var creds = GetValidCredentials();
|
||||
|
||||
var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.Unauthorized);
|
||||
this.RestClient.Response = restResp;
|
||||
|
||||
var client = new IdentityServicePocoClient(creds, "Swift", CancellationToken.None, this.ServiceLocator);
|
||||
await client.Authenticate();
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(InvalidOperationException))]
|
||||
public async Task CannotAuthenticateWithBadRequestResponse()
|
||||
{
|
||||
var creds = GetValidCredentials();
|
||||
|
||||
var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.BadRequest);
|
||||
this.RestClient.Response = restResp;
|
||||
|
||||
var client = new IdentityServicePocoClient(creds, "Swift", CancellationToken.None, this.ServiceLocator);
|
||||
await client.Authenticate();
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(InvalidOperationException))]
|
||||
public async Task CannotAuthenticateWithInternalServerErrorResponse()
|
||||
{
|
||||
var creds = GetValidCredentials();
|
||||
|
||||
var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.InternalServerError);
|
||||
this.RestClient.Response = restResp;
|
||||
|
||||
var client = new IdentityServicePocoClient(creds, "Swift", CancellationToken.None, this.ServiceLocator);
|
||||
await client.Authenticate();
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(InvalidOperationException))]
|
||||
public async Task CannotAuthenticateWithForbiddenResponse()
|
||||
{
|
||||
var creds = GetValidCredentials();
|
||||
|
||||
var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.Forbidden);
|
||||
this.RestClient.Response = restResp;
|
||||
|
||||
var client = new IdentityServicePocoClient(creds, "Swift", CancellationToken.None, this.ServiceLocator);
|
||||
await client.Authenticate();
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(InvalidOperationException))]
|
||||
public async Task CannotAuthenticateWithBadMethodResponse()
|
||||
{
|
||||
var creds = GetValidCredentials();
|
||||
|
||||
var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.MethodNotAllowed);
|
||||
this.RestClient.Response = restResp;
|
||||
|
||||
var client = new IdentityServicePocoClient(creds, "Swift", CancellationToken.None, this.ServiceLocator);
|
||||
await client.Authenticate();
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(InvalidOperationException))]
|
||||
public async Task CannotAuthenticateWithOverLimitResponse()
|
||||
{
|
||||
var creds = GetValidCredentials();
|
||||
|
||||
var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.RequestEntityTooLarge);
|
||||
this.RestClient.Response = restResp;
|
||||
|
||||
var client = new IdentityServicePocoClient(creds, "Swift", CancellationToken.None, this.ServiceLocator);
|
||||
await client.Authenticate();
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(InvalidOperationException))]
|
||||
public async Task CannotAuthenticateWithServiceUnavailableResponse()
|
||||
{
|
||||
var creds = GetValidCredentials();
|
||||
|
||||
var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.ServiceUnavailable);
|
||||
this.RestClient.Response = restResp;
|
||||
|
||||
var client = new IdentityServicePocoClient(creds, "Swift", CancellationToken.None, this.ServiceLocator);
|
||||
await client.Authenticate();
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(InvalidOperationException))]
|
||||
public async Task CannotAuthenticateWithNotFoundResponse()
|
||||
{
|
||||
var creds = GetValidCredentials();
|
||||
|
||||
var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.NotFound);
|
||||
this.RestClient.Response = restResp;
|
||||
|
||||
var client = new IdentityServicePocoClient(creds, "Swift", CancellationToken.None, this.ServiceLocator);
|
||||
await client.Authenticate();
|
||||
}
|
||||
}
|
||||
}
|
@ -1,119 +0,0 @@
|
||||
// /* ============================================================================
|
||||
// Copyright 2014 Hewlett Packard
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ============================================================================ */
|
||||
|
||||
using System;
|
||||
using System.Net.Http;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using OpenStack.Common;
|
||||
using OpenStack.Common.Http;
|
||||
using OpenStack.Common.ServiceLocation;
|
||||
using OpenStack.Identity;
|
||||
|
||||
namespace OpenStack.Test.Identity
|
||||
{
|
||||
[TestClass]
|
||||
public class IdentityServiceRestClientTests
|
||||
{
|
||||
internal IdentityRestServiceSimulator simulator;
|
||||
internal IServiceLocator ServiceLocator;
|
||||
|
||||
[TestInitialize]
|
||||
public void TestSetup()
|
||||
{
|
||||
this.simulator = new IdentityRestServiceSimulator();
|
||||
this.ServiceLocator = new ServiceLocator();
|
||||
|
||||
var manager = this.ServiceLocator.Locate<IServiceLocationOverrideManager>();
|
||||
manager.RegisterServiceInstance(typeof(IHttpAbstractionClientFactory), new IdentityRestServiceSimulatorFactory(simulator));
|
||||
}
|
||||
|
||||
[TestCleanup]
|
||||
public void TestCleanup()
|
||||
{
|
||||
this.simulator = new IdentityRestServiceSimulator();
|
||||
this.ServiceLocator = new ServiceLocator();
|
||||
}
|
||||
|
||||
public IOpenStackCredential GetValidCredentials()
|
||||
{
|
||||
var endpoint = new Uri("https://auth.someplace.com/authme");
|
||||
var userName = "TestUser";
|
||||
var password = "RandomPassword";
|
||||
var tenantId = "12345";
|
||||
|
||||
return new OpenStackCredential(endpoint, userName, password, tenantId);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task AuthenticationMethodAndUriAreValid()
|
||||
{
|
||||
var creds = GetValidCredentials();
|
||||
var client = new IdentityServiceRestClientFactory().Create(creds,CancellationToken.None, this.ServiceLocator);
|
||||
|
||||
await client.Authenticate();
|
||||
var expectedUri = new Uri(string.Format("{0}/tokens", creds.AuthenticationEndpoint));
|
||||
Assert.AreEqual(expectedUri, this.simulator.Uri);
|
||||
Assert.AreEqual(HttpMethod.Post, this.simulator.Method);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task AuthenticateIncludesCorrectHeaders()
|
||||
{
|
||||
var creds = GetValidCredentials();
|
||||
var client = new IdentityServiceRestClient(creds, CancellationToken.None, this.ServiceLocator);
|
||||
|
||||
await client.Authenticate();
|
||||
|
||||
Assert.IsTrue(this.simulator.Headers.ContainsKey("Accept"));
|
||||
Assert.AreEqual("application/json", this.simulator.Headers["Accept"]);
|
||||
Assert.AreEqual("application/json", this.simulator.ContentType);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task AuthenticateIncludesPayload()
|
||||
{
|
||||
var creds = GetValidCredentials();
|
||||
var client = new IdentityServiceRestClient(creds, CancellationToken.None, this.ServiceLocator);
|
||||
|
||||
await client.Authenticate();
|
||||
|
||||
Assert.IsNotNull(this.simulator.Content);
|
||||
|
||||
var content = TestHelper.GetStringFromStream(this.simulator.Content);
|
||||
Assert.IsTrue(content.Length > 0);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void AuthenticationPayloadIsGeneratedCorrectly()
|
||||
{
|
||||
var creds = GetValidCredentials();
|
||||
var payload = IdentityServiceRestClient.CreateAuthenticationJsonPayload(creds);
|
||||
|
||||
var obj = JObject.Parse(payload);
|
||||
var userName = obj["auth"]["passwordCredentials"]["username"];
|
||||
var password = obj["auth"]["passwordCredentials"]["password"];
|
||||
var tenantId = obj["auth"]["tenantName"];
|
||||
|
||||
Assert.AreEqual(creds.UserName, userName);
|
||||
Assert.AreEqual(creds.Password, password);
|
||||
Assert.AreEqual(creds.TenantId, tenantId);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
@ -1,180 +0,0 @@
|
||||
// /* ============================================================================
|
||||
// Copyright 2014 Hewlett Packard
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ============================================================================ */
|
||||
|
||||
using System;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
using OpenStack.Common;
|
||||
using OpenStack.Identity;
|
||||
|
||||
namespace OpenStack.Test.Identity
|
||||
{
|
||||
[TestClass]
|
||||
public class OpenStackCredentialTests
|
||||
{
|
||||
[TestMethod]
|
||||
public void CanCreateAnOpenStackCredential()
|
||||
{
|
||||
var endpoint = new Uri("https://auth.someplace.com/authme");
|
||||
var userName = "TestUser";
|
||||
var password = "RandomPassword";
|
||||
var tenantId = "12345";
|
||||
|
||||
var cred = new OpenStackCredential(endpoint, userName, password, tenantId);
|
||||
|
||||
Assert.IsNotNull(cred);
|
||||
Assert.AreEqual(userName, cred.UserName);
|
||||
Assert.AreEqual(endpoint, cred.AuthenticationEndpoint);
|
||||
Assert.IsNotNull(cred.Password);
|
||||
Assert.AreEqual(tenantId, cred.TenantId);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanSetAcessTokenId()
|
||||
{
|
||||
var endpoint = new Uri("https://auth.someplace.com/authme");
|
||||
var userName = "TestUser";
|
||||
var password = "RandomPassword";
|
||||
var tenantId = "12345";
|
||||
var token = "someToken";
|
||||
|
||||
var cred = new OpenStackCredential(endpoint, userName, password, tenantId);
|
||||
cred.SetAccessTokenId(token);
|
||||
|
||||
Assert.AreEqual(token, cred.AccessTokenId);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(ArgumentNullException))]
|
||||
public void CannotSetAcessTokenIdWithNullToken()
|
||||
{
|
||||
var endpoint = new Uri("https://auth.someplace.com/authme");
|
||||
var userName = "TestUser";
|
||||
var password = "RandomPassword";
|
||||
var tenantId = "12345";
|
||||
|
||||
var cred = new OpenStackCredential(endpoint, userName, password, tenantId);
|
||||
cred.SetAccessTokenId(null);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanSetServiceCatalog()
|
||||
{
|
||||
var endpoint = new Uri("https://auth.someplace.com/authme");
|
||||
var userName = "TestUser";
|
||||
var password = "RandomPassword";
|
||||
var tenantId = "12345";
|
||||
|
||||
var catalog = new OpenStackServiceCatalog();
|
||||
|
||||
var cred = new OpenStackCredential(endpoint, userName, password, tenantId);
|
||||
cred.SetServiceCatalog(catalog);
|
||||
|
||||
Assert.AreEqual(catalog, cred.ServiceCatalog);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(ArgumentNullException))]
|
||||
public void CannotSetServiceCatalogWithNullToken()
|
||||
{
|
||||
var endpoint = new Uri("https://auth.someplace.com/authme");
|
||||
var userName = "TestUser";
|
||||
var password = "RandomPassword";
|
||||
var tenantId = "12345";
|
||||
|
||||
var cred = new OpenStackCredential(endpoint, userName, password, tenantId);
|
||||
cred.SetServiceCatalog(null);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(ArgumentException))]
|
||||
public void CannotSetAcessTokenIdWithEmptyToken()
|
||||
{
|
||||
var endpoint = new Uri("https://auth.someplace.com/authme");
|
||||
var userName = "TestUser";
|
||||
var password = "RandomPassword";
|
||||
var tenantId = "12345";
|
||||
|
||||
var cred = new OpenStackCredential(endpoint, userName, password, tenantId);
|
||||
cred.SetAccessTokenId(string.Empty);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(ArgumentNullException))]
|
||||
public void CannotCreateAnOpenStackCredentialWithNullEndpoint()
|
||||
{
|
||||
var userName = "TestUser";
|
||||
var password = "RandomPassword";
|
||||
var tenantId = "12345";
|
||||
|
||||
var cred = new OpenStackCredential(null, userName, password, tenantId);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(ArgumentNullException))]
|
||||
public void CannotCreateAnOpenStackCredentialWithNullUserName()
|
||||
{
|
||||
var endpoint = new Uri("https://auth.someplace.com/authme");
|
||||
var password = "RandomPassword";
|
||||
var tenantId = "12345";
|
||||
|
||||
var cred = new OpenStackCredential(endpoint, null, password, tenantId);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(ArgumentException))]
|
||||
public void CannotCreateAnOpenStackCredentialWithEmptyUserName()
|
||||
{
|
||||
var endpoint = new Uri("https://auth.someplace.com/authme");
|
||||
var password = "RandomPassword";
|
||||
var tenantId = "12345";
|
||||
|
||||
var cred = new OpenStackCredential(endpoint, string.Empty, password, tenantId);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(ArgumentNullException))]
|
||||
public void CannotCreateAnOpenStackCredentialWithNullPassword()
|
||||
{
|
||||
var endpoint = new Uri("https://auth.someplace.com/authme");
|
||||
var userName = "TestUser";
|
||||
var tenantId = "12345";
|
||||
|
||||
var cred = new OpenStackCredential(endpoint, userName, null, tenantId);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(ArgumentNullException))]
|
||||
public void CannotCreateAnOpenStackCredentialWithNullTenantId()
|
||||
{
|
||||
var endpoint = new Uri("https://auth.someplace.com/authme");
|
||||
var userName = "TestUser";
|
||||
var password = "RandomPassword";
|
||||
|
||||
var cred = new OpenStackCredential(endpoint, userName, password, null);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(ArgumentException))]
|
||||
public void CannotCreateAnOpenStackCredentialWithEmptyTenantId()
|
||||
{
|
||||
var endpoint = new Uri("https://auth.someplace.com/authme");
|
||||
var userName = "TestUser";
|
||||
var password = "RandomPassword";
|
||||
|
||||
var cred = new OpenStackCredential(endpoint, userName, password, string.Empty);
|
||||
}
|
||||
}
|
||||
}
|
@ -1,167 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
using OpenStack.Identity;
|
||||
|
||||
namespace OpenStack.Test.Identity
|
||||
{
|
||||
[TestClass]
|
||||
public class OpenStackRegionResolverTests
|
||||
{
|
||||
[TestMethod]
|
||||
public void CanResolveRegion()
|
||||
{
|
||||
var expectedRegion = "some region";
|
||||
var catalog = new OpenStackServiceCatalog();
|
||||
catalog.Add(new OpenStackServiceDefinition("Test Service", "Test-Service",
|
||||
new List<OpenStackServiceEndpoint>()
|
||||
{
|
||||
new OpenStackServiceEndpoint("http://other.endpoint.org", expectedRegion , "1.0",
|
||||
"http://www.someplace.com", "http://www.someplace.com")
|
||||
}));
|
||||
|
||||
catalog.Add(new OpenStackServiceDefinition("Other Test Service", "Test-Service",
|
||||
new List<OpenStackServiceEndpoint>()
|
||||
{
|
||||
new OpenStackServiceEndpoint("http://other.endpoint.org", "some other region", "1.0",
|
||||
"http://www.someplace.com", "http://www.someplace.com")
|
||||
}));
|
||||
var resolver = new OpenStackRegionResolver();
|
||||
var region = resolver.Resolve(new Uri("http://other.endpoint.org/v2/tokens"), catalog, "Test Service");
|
||||
Assert.AreEqual(expectedRegion, region);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CannotResolveRegionWhenNoEnpointMatches()
|
||||
{
|
||||
var expectedRegion = string.Empty;
|
||||
var catalog = new OpenStackServiceCatalog();
|
||||
catalog.Add(new OpenStackServiceDefinition("Test Service", "Test-Service",
|
||||
new List<OpenStackServiceEndpoint>()
|
||||
{
|
||||
new OpenStackServiceEndpoint("http://other.endpoint.org", "Some Region" , "1.0",
|
||||
"http://www.someplace.com", "http://www.someplace.com")
|
||||
}));
|
||||
|
||||
catalog.Add(new OpenStackServiceDefinition("Other Test Service", "Test-Service",
|
||||
new List<OpenStackServiceEndpoint>()
|
||||
{
|
||||
new OpenStackServiceEndpoint("http://other.endpoint.org", "some other region", "1.0",
|
||||
"http://www.someplace.com", "http://www.someplace.com")
|
||||
}));
|
||||
var resolver = new OpenStackRegionResolver();
|
||||
var region = resolver.Resolve(new Uri("http://nomatching.endpoint.org/v2/tokens"), catalog, "Test Service");
|
||||
Assert.AreEqual(expectedRegion, region);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CannotResolveRegionWhenNoMatchingServices()
|
||||
{
|
||||
var expectedRegion = string.Empty;
|
||||
var catalog = new OpenStackServiceCatalog();
|
||||
catalog.Add(new OpenStackServiceDefinition("Test Service", "Test-Service",
|
||||
new List<OpenStackServiceEndpoint>()
|
||||
{
|
||||
new OpenStackServiceEndpoint("http://other.endpoint.org", "Some Region" , "1.0",
|
||||
"http://www.someplace.com", "http://www.someplace.com")
|
||||
}));
|
||||
|
||||
catalog.Add(new OpenStackServiceDefinition("Other Test Service", "Test-Service",
|
||||
new List<OpenStackServiceEndpoint>()
|
||||
{
|
||||
new OpenStackServiceEndpoint("http://other.endpoint.org", "some other region", "1.0",
|
||||
"http://www.someplace.com", "http://www.someplace.com")
|
||||
}));
|
||||
var resolver = new OpenStackRegionResolver();
|
||||
var region = resolver.Resolve(new Uri("http://nomatching.endpoint.org/v2/tokens"), catalog, "No Matching Service");
|
||||
Assert.AreEqual(expectedRegion, region);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanResolveRegionWhenNoMatchingServicesButMatchingEndpoint()
|
||||
{
|
||||
var expectedRegion = "Some Region";
|
||||
var catalog = new OpenStackServiceCatalog();
|
||||
catalog.Add(new OpenStackServiceDefinition("Test Service", "Test-Service",
|
||||
new List<OpenStackServiceEndpoint>()
|
||||
{
|
||||
new OpenStackServiceEndpoint("http://the.endpoint.org", "Some Region" , "1.0",
|
||||
"http://www.someplace.com", "http://www.someplace.com")
|
||||
}));
|
||||
|
||||
catalog.Add(new OpenStackServiceDefinition("Other Test Service", "Test-Service",
|
||||
new List<OpenStackServiceEndpoint>()
|
||||
{
|
||||
new OpenStackServiceEndpoint("http://other.endpoint.org", "some other region", "1.0",
|
||||
"http://www.someplace.com", "http://www.someplace.com")
|
||||
}));
|
||||
var resolver = new OpenStackRegionResolver();
|
||||
var region = resolver.Resolve(new Uri("http://the.endpoint.org/v2/tokens"), catalog, "No Matching Service");
|
||||
Assert.AreEqual(expectedRegion, region);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CannotResolveRegionWhenMatchingEndpointHasEmptyRegion()
|
||||
{
|
||||
var expectedRegion = string.Empty;
|
||||
var catalog = new OpenStackServiceCatalog();
|
||||
catalog.Add(new OpenStackServiceDefinition("Test Service", "Test-Service",
|
||||
new List<OpenStackServiceEndpoint>()
|
||||
{
|
||||
new OpenStackServiceEndpoint("http://other.endpoint.org", "Some Region" , "1.0",
|
||||
"http://www.someplace.com", "http://www.someplace.com")
|
||||
}));
|
||||
|
||||
catalog[0].Endpoints.First().Region = string.Empty;
|
||||
|
||||
catalog.Add(new OpenStackServiceDefinition("Other Test Service", "Test-Service",
|
||||
new List<OpenStackServiceEndpoint>()
|
||||
{
|
||||
new OpenStackServiceEndpoint("http://other.endpoint.org", "some other region", "1.0",
|
||||
"http://www.someplace.com", "http://www.someplace.com")
|
||||
}));
|
||||
var resolver = new OpenStackRegionResolver();
|
||||
var region = resolver.Resolve(new Uri("http://nomatching.endpoint.org/v2/tokens"), catalog, "Test Service");
|
||||
Assert.AreEqual(expectedRegion, region);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(ArgumentNullException))]
|
||||
public void CannotResolveRegionWithNullCatalog()
|
||||
{
|
||||
var resolver = new OpenStackRegionResolver();
|
||||
resolver.Resolve(new Uri("http://other.endpoint.org/v2/tokens"), null, "Test Service");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(ArgumentNullException))]
|
||||
public void CannotResolveRegionWithNullEndpoint()
|
||||
{
|
||||
var catalog = new OpenStackServiceCatalog();
|
||||
|
||||
var resolver = new OpenStackRegionResolver();
|
||||
resolver.Resolve(null, catalog, "Test Service");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(ArgumentNullException))]
|
||||
public void CannotResolveRegionWithNullServiceName()
|
||||
{
|
||||
var catalog = new OpenStackServiceCatalog();
|
||||
|
||||
var resolver = new OpenStackRegionResolver();
|
||||
resolver.Resolve(new Uri("http://other.endpoint.org/v2/tokens"), catalog, null);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(ArgumentException))]
|
||||
public void CannotResolveRegionWithEmptyServiceName()
|
||||
{
|
||||
var catalog = new OpenStackServiceCatalog();
|
||||
|
||||
var resolver = new OpenStackRegionResolver();
|
||||
resolver.Resolve(new Uri("http://other.endpoint.org/v2/tokens"), catalog, string.Empty);
|
||||
}
|
||||
}
|
||||
}
|
@ -1,190 +0,0 @@
|
||||
// /* ============================================================================
|
||||
// Copyright 2014 Hewlett Packard
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ============================================================================ */
|
||||
|
||||
using System;
|
||||
using System.Linq;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
using OpenStack.Common.ServiceLocation;
|
||||
using OpenStack.Identity;
|
||||
|
||||
namespace OpenStack.Test.Identity
|
||||
{
|
||||
[TestClass]
|
||||
public class OpenStackServiceCatalogPayloadConverterTests
|
||||
{
|
||||
[TestMethod]
|
||||
public void CanConvertJsonPayload()
|
||||
{
|
||||
var expectedName = "Object Storage";
|
||||
var expectedType = "object-store";
|
||||
|
||||
var serviceCatalogPayload = @"{
|
||||
""access"": {
|
||||
|
||||
""serviceCatalog"":[{
|
||||
""name"": ""Object Storage"",
|
||||
""type"": ""object-store"",
|
||||
""endpoints"": [
|
||||
{
|
||||
""tenantId"": ""10244656540440"",
|
||||
""publicURL"": ""https://region-a.geo-1.objects.hpcloudsvc.com/v1/10244656540440"",
|
||||
""region"": ""region-a.geo-1"",
|
||||
""versionId"": ""1.0"",
|
||||
""versionInfo"": ""https://region-a.geo-1.objects.hpcloudsvc.com/v1.0/"",
|
||||
""versionList"": ""https://region-a.geo-1.objects.hpcloudsvc.com""
|
||||
},
|
||||
{
|
||||
""tenantId"": ""10244656540440"",
|
||||
""publicURL"": ""https://region-b.geo-1.objects.hpcloudsvc.com:443/v1/10244656540440"",
|
||||
""region"": ""region-b.geo-1"",
|
||||
""versionId"": ""1"",
|
||||
""versionInfo"": ""https://region-b.geo-1.objects.hpcloudsvc.com:443/v1/"",
|
||||
""versionList"": ""https://region-b.geo-1.objects.hpcloudsvc.com:443""
|
||||
}
|
||||
]
|
||||
}]}}";
|
||||
|
||||
var converter = new OpenStackServiceCatalogPayloadConverter(new ServiceLocator());
|
||||
var serviceDefs = converter.Convert(serviceCatalogPayload).ToList();
|
||||
|
||||
Assert.AreEqual(1, serviceDefs.Count());
|
||||
|
||||
var service = serviceDefs.First(i => i.Name == expectedName);
|
||||
Assert.IsNotNull(service);
|
||||
Assert.AreEqual(expectedName, service.Name);
|
||||
Assert.AreEqual(expectedType, service.Type);
|
||||
Assert.AreEqual(2, service.Endpoints.Count());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanConvertJsonPayloadWithMultipleServiceDefs()
|
||||
{
|
||||
var expectedName1 = "Object Storage";
|
||||
var expectedType1 = "object-store";
|
||||
|
||||
var expectedName2 = "Some Other Service";
|
||||
var expectedType2 = "other-service";
|
||||
|
||||
var serviceCatalogPayload = @"{
|
||||
""access"": {
|
||||
|
||||
""serviceCatalog"":[{
|
||||
""name"": ""Object Storage"",
|
||||
""type"": ""object-store"",
|
||||
""endpoints"": [
|
||||
{
|
||||
""tenantId"": ""10244656540440"",
|
||||
""publicURL"": ""https://region-a.geo-1.objects.hpcloudsvc.com/v1/10244656540440"",
|
||||
""region"": ""region-a.geo-1"",
|
||||
""versionId"": ""1.0"",
|
||||
""versionInfo"": ""https://region-a.geo-1.objects.hpcloudsvc.com/v1.0/"",
|
||||
""versionList"": ""https://region-a.geo-1.objects.hpcloudsvc.com""
|
||||
},
|
||||
{
|
||||
""tenantId"": ""10244656540440"",
|
||||
""publicURL"": ""https://region-b.geo-1.objects.hpcloudsvc.com:443/v1/10244656540440"",
|
||||
""region"": ""region-b.geo-1"",
|
||||
""versionId"": ""1"",
|
||||
""versionInfo"": ""https://region-b.geo-1.objects.hpcloudsvc.com:443/v1/"",
|
||||
""versionList"": ""https://region-b.geo-1.objects.hpcloudsvc.com:443""
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
""name"": ""Some Other Service"",
|
||||
""type"": ""other-service"",
|
||||
""endpoints"": [
|
||||
{
|
||||
""tenantId"": ""10244656540440"",
|
||||
""publicURL"": ""https://region-a.geo-1.objects.hpcloudsvc.com/v1/10244656540440"",
|
||||
""region"": ""region-a.geo-1"",
|
||||
""versionId"": ""1.0"",
|
||||
""versionInfo"": ""https://region-a.geo-1.objects.hpcloudsvc.com/v1.0/"",
|
||||
""versionList"": ""https://region-a.geo-1.objects.hpcloudsvc.com""
|
||||
}
|
||||
]
|
||||
}]}}";
|
||||
|
||||
var converter = new OpenStackServiceCatalogPayloadConverter(new ServiceLocator());
|
||||
var serviceDefs = converter.Convert(serviceCatalogPayload).ToList();
|
||||
|
||||
Assert.AreEqual(2, serviceDefs.Count());
|
||||
|
||||
var service1 = serviceDefs.First(i => i.Name == expectedName1);
|
||||
Assert.IsNotNull(service1);
|
||||
Assert.AreEqual(expectedName1, service1.Name);
|
||||
Assert.AreEqual(expectedType1, service1.Type);
|
||||
Assert.AreEqual(2, service1.Endpoints.Count());
|
||||
|
||||
var service2 = serviceDefs.First(i => i.Name == expectedName2);
|
||||
Assert.IsNotNull(service1);
|
||||
Assert.AreEqual(expectedName2, service2.Name);
|
||||
Assert.AreEqual(expectedType2, service2.Type);
|
||||
Assert.AreEqual(1, service2.Endpoints.Count());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(FormatException))]
|
||||
public void CannotConvertJsonPayloadWithMissingCatalog()
|
||||
{
|
||||
var serviceCatalogPayload = @"{
|
||||
""access"": {
|
||||
|
||||
}}";
|
||||
|
||||
var converter = new OpenStackServiceCatalogPayloadConverter(new ServiceLocator());
|
||||
converter.Convert(serviceCatalogPayload);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(FormatException))]
|
||||
public void CannotConvertJsonPayloadWithEmptyObject()
|
||||
{
|
||||
var serviceDefPayload = @" { }";
|
||||
|
||||
var converter = new OpenStackServiceCatalogPayloadConverter(new ServiceLocator());
|
||||
converter.Convert(serviceDefPayload);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(ArgumentNullException))]
|
||||
public void CannotConvertWithNullJsonPayload()
|
||||
{
|
||||
var converter = new OpenStackServiceCatalogPayloadConverter(new ServiceLocator());
|
||||
converter.Convert(null);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(FormatException))]
|
||||
public void CannotConvertInvalidJsonPayload()
|
||||
{
|
||||
var serviceDefPayload = @" { NOT JSON";
|
||||
|
||||
var converter = new OpenStackServiceCatalogPayloadConverter(new ServiceLocator());
|
||||
converter.Convert(serviceDefPayload);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(FormatException))]
|
||||
public void CannotConvertNonObjectJsonPayload()
|
||||
{
|
||||
var serviceDefPayload = @"[]";
|
||||
|
||||
var converter = new OpenStackServiceCatalogPayloadConverter(new ServiceLocator());
|
||||
converter.Convert(serviceDefPayload);
|
||||
}
|
||||
}
|
||||
}
|
@ -1,203 +0,0 @@
|
||||
// /* ============================================================================
|
||||
// Copyright 2014 Hewlett Packard
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ============================================================================ */
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
using OpenStack.Identity;
|
||||
|
||||
namespace OpenStack.Test.Identity
|
||||
{
|
||||
[TestClass]
|
||||
public class OpenStackServiceCatalogTests
|
||||
{
|
||||
[TestMethod]
|
||||
public void IfAServiceExistsCatalogReturnsTrue()
|
||||
{
|
||||
var expectedEndpoint = new Uri("http://public.endpoint.org");
|
||||
var serviceDef = new OpenStackServiceDefinition("Test Service", "Test-Service",
|
||||
new List<OpenStackServiceEndpoint>()
|
||||
{
|
||||
new OpenStackServiceEndpoint(expectedEndpoint.ToString(), "some region", "1.0",
|
||||
"http://www.someplace.com", "http://www.someplace.com")
|
||||
});
|
||||
var catalog = new OpenStackServiceCatalog { serviceDef };
|
||||
Assert.IsTrue(catalog.Exists("Test Service"));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void IfAServiceDoesNotExistsCatalogReturnsFalse()
|
||||
{
|
||||
var expectedEndpoint = new Uri("http://public.endpoint.org");
|
||||
var serviceDef = new OpenStackServiceDefinition("Test Service", "Test-Service",
|
||||
new List<OpenStackServiceEndpoint>()
|
||||
{
|
||||
new OpenStackServiceEndpoint(expectedEndpoint.ToString(), "some region", "1.0",
|
||||
"http://www.someplace.com", "http://www.someplace.com")
|
||||
});
|
||||
var catalog = new OpenStackServiceCatalog { serviceDef };
|
||||
Assert.IsFalse(catalog.Exists("NOT IN CATALOG"));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanGetServicesInRegion()
|
||||
{
|
||||
var expectedEndpoint = new Uri("http://public.endpoint.org");
|
||||
var serviceDef = new OpenStackServiceDefinition("Test Service", "Test-Service",
|
||||
new List<OpenStackServiceEndpoint>()
|
||||
{
|
||||
new OpenStackServiceEndpoint(expectedEndpoint.ToString(), "some region", "1.0",
|
||||
"http://www.someplace.com", "http://www.someplace.com")
|
||||
});
|
||||
var catalog = new OpenStackServiceCatalog { serviceDef };
|
||||
var services = catalog.GetServicesInAvailabilityZone("some region").ToList();
|
||||
Assert.AreEqual(1,services.Count());
|
||||
Assert.AreEqual("Test Service",services.First().Name);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanGetServicesInRegionWithMultipleServices()
|
||||
{
|
||||
var catalog = new OpenStackServiceCatalog();
|
||||
catalog.Add(new OpenStackServiceDefinition("Test Service", "Test-Service",
|
||||
new List<OpenStackServiceEndpoint>()
|
||||
{
|
||||
new OpenStackServiceEndpoint("http://some.endpoint.com", "some region", "1.0",
|
||||
"http://www.someplace.com", "http://www.someplace.com")
|
||||
}));
|
||||
|
||||
catalog.Add(new OpenStackServiceDefinition("Other Test Service", "Test-Service",
|
||||
new List<OpenStackServiceEndpoint>()
|
||||
{
|
||||
new OpenStackServiceEndpoint("http://other.endpoint.org", "some region", "1.0",
|
||||
"http://www.someplace.com", "http://www.someplace.com")
|
||||
}));
|
||||
|
||||
var services = catalog.GetServicesInAvailabilityZone("some region").ToList();
|
||||
Assert.AreEqual(2, services.Count());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void GettingServicesInRegionWhenNonExistReturnsAnEmptyCollection()
|
||||
{
|
||||
var expectedEndpoint = new Uri("http://public.endpoint.org");
|
||||
var serviceDef = new OpenStackServiceDefinition("Test Service", "Test-Service",
|
||||
new List<OpenStackServiceEndpoint>()
|
||||
{
|
||||
new OpenStackServiceEndpoint(expectedEndpoint.ToString(), "some region", "1.0",
|
||||
"http://www.someplace.com", "http://www.someplace.com")
|
||||
});
|
||||
var catalog = new OpenStackServiceCatalog { serviceDef };
|
||||
var services = catalog.GetServicesInAvailabilityZone("some other region").ToList();
|
||||
Assert.AreEqual(0, services.Count());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanGetServicesForRegionWithMultipleEndpoints()
|
||||
{
|
||||
var expectedEndpoint = new Uri("http://public.endpoint.org");
|
||||
var serviceDef = new OpenStackServiceDefinition("Test Service", "Test-Service",
|
||||
new List<OpenStackServiceEndpoint>()
|
||||
{
|
||||
new OpenStackServiceEndpoint(expectedEndpoint.ToString(), "some region", "1.0",
|
||||
"http://www.someplace.com", "http://www.someplace.com"),
|
||||
new OpenStackServiceEndpoint(expectedEndpoint.ToString(), "some other region", "1.0",
|
||||
"http://www.someplace.com", "http://www.someplace.com")
|
||||
});
|
||||
var catalog = new OpenStackServiceCatalog { serviceDef };
|
||||
var services = catalog.GetServicesInAvailabilityZone("some other region").ToList();
|
||||
Assert.AreEqual(1, services.Count());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanGetPublicEndpointForAService()
|
||||
{
|
||||
var serviceName = "Test Service";
|
||||
var regionName = "some region";
|
||||
var expectedEndpoint = "http://public.endpoint.org";
|
||||
var serviceDef = new OpenStackServiceDefinition(serviceName, "Test-Service",
|
||||
new List<OpenStackServiceEndpoint>()
|
||||
{
|
||||
new OpenStackServiceEndpoint(expectedEndpoint, "some region", "1.0",
|
||||
"http://www.someplace.com", "http://www.someplace.com")
|
||||
});
|
||||
|
||||
var catalog = new OpenStackServiceCatalog { serviceDef };
|
||||
var endpoint = catalog.GetPublicEndpoint(serviceName, regionName);
|
||||
Assert.AreEqual(expectedEndpoint, endpoint);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(ArgumentNullException))]
|
||||
public void CannotGetPublicEndpointWithANullServiceName()
|
||||
{
|
||||
var catalog = new OpenStackServiceCatalog();
|
||||
catalog.GetPublicEndpoint(null, "Some region");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(ArgumentNullException))]
|
||||
public void CannotGetPublicEndpointWithANullRegion()
|
||||
{
|
||||
var catalog = new OpenStackServiceCatalog();
|
||||
catalog.GetPublicEndpoint("Test Service", null);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(ArgumentException))]
|
||||
public void CannotGetPublicEndpointWithAnEmptyServiceName()
|
||||
{
|
||||
var catalog = new OpenStackServiceCatalog();
|
||||
catalog.GetPublicEndpoint(string.Empty, "Some region");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(InvalidOperationException))]
|
||||
public void CannotGetPublicEndpointForAServiceThatIsNotInTheCatalog()
|
||||
{
|
||||
var serviceName = "Test Service";
|
||||
var regionName = "some region";
|
||||
var expectedEndpoint = "http://public.endpoint.org";
|
||||
var serviceDef = new OpenStackServiceDefinition(serviceName, "Test-Service",
|
||||
new List<OpenStackServiceEndpoint>()
|
||||
{
|
||||
new OpenStackServiceEndpoint(expectedEndpoint, "some region", "1.0",
|
||||
"http://www.someplace.com", "http://www.someplace.com")
|
||||
});
|
||||
|
||||
var catalog = new OpenStackServiceCatalog { serviceDef };
|
||||
catalog.GetPublicEndpoint("Not-In-Catalog", regionName);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(InvalidOperationException))]
|
||||
public void CannotGetPublicEndpointForAServiceThatIsNotInTheRegion()
|
||||
{
|
||||
var serviceName = "Test Service";
|
||||
var expectedEndpoint = "http://public.endpoint.org";
|
||||
var serviceDef = new OpenStackServiceDefinition(serviceName, "Test-Service",
|
||||
new List<OpenStackServiceEndpoint>()
|
||||
{
|
||||
new OpenStackServiceEndpoint(expectedEndpoint, "some region", "1.0",
|
||||
"http://www.someplace.com", "http://www.someplace.com")
|
||||
});
|
||||
|
||||
var catalog = new OpenStackServiceCatalog { serviceDef };
|
||||
catalog.GetPublicEndpoint(serviceName, "Not-in-catalog");
|
||||
}
|
||||
}
|
||||
}
|
@ -1,178 +0,0 @@
|
||||
// /* ============================================================================
|
||||
// Copyright 2014 Hewlett Packard
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ============================================================================ */
|
||||
|
||||
using System;
|
||||
using System.Linq;
|
||||
using System.Web;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
using OpenStack.Common.ServiceLocation;
|
||||
using OpenStack.Identity;
|
||||
|
||||
namespace OpenStack.Test.Identity
|
||||
{
|
||||
[TestClass]
|
||||
public class OpenStackServiceDefinitionPayloadConverterTests
|
||||
{
|
||||
[TestMethod]
|
||||
public void CanConvertJsonPayload()
|
||||
{
|
||||
var expectedName = "Object Storage";
|
||||
var expectedType = "object-store";
|
||||
|
||||
var serviceDefPayload = @" {
|
||||
""name"": ""Object Storage"",
|
||||
""type"": ""object-store"",
|
||||
""endpoints"": [
|
||||
{
|
||||
""tenantId"": ""10244656540440"",
|
||||
""publicURL"": ""https://region-a.geo-1.objects.hpcloudsvc.com/v1/10244656540440"",
|
||||
""region"": ""region-a.geo-1"",
|
||||
""versionId"": ""1.0"",
|
||||
""versionInfo"": ""https://region-a.geo-1.objects.hpcloudsvc.com/v1.0/"",
|
||||
""versionList"": ""https://region-a.geo-1.objects.hpcloudsvc.com""
|
||||
},
|
||||
{
|
||||
""tenantId"": ""10244656540440"",
|
||||
""publicURL"": ""https://region-b.geo-1.objects.hpcloudsvc.com:443/v1/10244656540440"",
|
||||
""region"": ""region-b.geo-1"",
|
||||
""versionId"": ""1"",
|
||||
""versionInfo"": ""https://region-b.geo-1.objects.hpcloudsvc.com:443/v1/"",
|
||||
""versionList"": ""https://region-b.geo-1.objects.hpcloudsvc.com:443""
|
||||
}
|
||||
]
|
||||
}";
|
||||
|
||||
var converter = new OpenStackServiceDefinitionPayloadConverter(new ServiceLocator());
|
||||
var service = converter.Convert(serviceDefPayload);
|
||||
|
||||
Assert.IsNotNull(service);
|
||||
Assert.AreEqual(expectedName, service.Name);
|
||||
Assert.AreEqual(expectedType, service.Type);
|
||||
Assert.AreEqual(2, service.Endpoints.Count());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(FormatException))]
|
||||
public void CannotConvertJsonPayloadWithMissingName()
|
||||
{
|
||||
var serviceDefPayload = @"{
|
||||
""type"": ""object-store"",
|
||||
""endpoints"": [
|
||||
{
|
||||
""tenantId"": ""10244656540440"",
|
||||
""publicURL"": ""https://region-a.geo-1.objects.hpcloudsvc.com/v1/10244656540440"",
|
||||
""region"": ""region-a.geo-1"",
|
||||
""versionId"": ""1.0"",
|
||||
""versionInfo"": ""https://region-a.geo-1.objects.hpcloudsvc.com/v1.0/"",
|
||||
""versionList"": ""https://region-a.geo-1.objects.hpcloudsvc.com""
|
||||
},
|
||||
{
|
||||
""tenantId"": ""10244656540440"",
|
||||
""publicURL"": ""https://region-b.geo-1.objects.hpcloudsvc.com:443/v1/10244656540440"",
|
||||
""region"": ""region-b.geo-1"",
|
||||
""versionId"": ""1"",
|
||||
""versionInfo"": ""https://region-b.geo-1.objects.hpcloudsvc.com:443/v1/"",
|
||||
""versionList"": ""https://region-b.geo-1.objects.hpcloudsvc.com:443""
|
||||
}
|
||||
]
|
||||
}";
|
||||
|
||||
var converter = new OpenStackServiceDefinitionPayloadConverter(new ServiceLocator());
|
||||
converter.Convert(serviceDefPayload);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(FormatException))]
|
||||
public void CannotConvertJsonPayloadWithMissingType()
|
||||
{
|
||||
var serviceDefPayload = @"{
|
||||
""name"": ""Object Storage"",
|
||||
""endpoints"": [
|
||||
{
|
||||
""tenantId"": ""10244656540440"",
|
||||
""publicURL"": ""https://region-a.geo-1.objects.hpcloudsvc.com/v1/10244656540440"",
|
||||
""region"": ""region-a.geo-1"",
|
||||
""versionId"": ""1.0"",
|
||||
""versionInfo"": ""https://region-a.geo-1.objects.hpcloudsvc.com/v1.0/"",
|
||||
""versionList"": ""https://region-a.geo-1.objects.hpcloudsvc.com""
|
||||
},
|
||||
{
|
||||
""tenantId"": ""10244656540440"",
|
||||
""publicURL"": ""https://region-b.geo-1.objects.hpcloudsvc.com:443/v1/10244656540440"",
|
||||
""region"": ""region-b.geo-1"",
|
||||
""versionId"": ""1"",
|
||||
""versionInfo"": ""https://region-b.geo-1.objects.hpcloudsvc.com:443/v1/"",
|
||||
""versionList"": ""https://region-b.geo-1.objects.hpcloudsvc.com:443""
|
||||
}
|
||||
]
|
||||
}";
|
||||
|
||||
var converter = new OpenStackServiceDefinitionPayloadConverter(new ServiceLocator());
|
||||
converter.Convert(serviceDefPayload);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof (FormatException))]
|
||||
public void CannotConvertJsonPayloadWithMissingEndpoints()
|
||||
{
|
||||
var serviceDefPayload = @"{
|
||||
""name"": ""Object Storage"",
|
||||
""type"": ""object-store"",
|
||||
}";
|
||||
|
||||
var converter = new OpenStackServiceDefinitionPayloadConverter(new ServiceLocator());
|
||||
converter.Convert(serviceDefPayload);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(FormatException))]
|
||||
public void CannotConvertJsonPayloadWithEmptyObject()
|
||||
{
|
||||
var serviceDefPayload = @" { }";
|
||||
|
||||
var converter = new OpenStackServiceDefinitionPayloadConverter(new ServiceLocator());
|
||||
converter.Convert(serviceDefPayload);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(ArgumentNullException))]
|
||||
public void CannotConvertWithNullJsonPayload()
|
||||
{
|
||||
var converter = new OpenStackServiceDefinitionPayloadConverter(new ServiceLocator());
|
||||
converter.Convert(null);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(FormatException))]
|
||||
public void CannotConvertInvalidJsonPayload()
|
||||
{
|
||||
var serviceDefPayload = @" { NOT JSON";
|
||||
|
||||
var converter = new OpenStackServiceDefinitionPayloadConverter(new ServiceLocator());
|
||||
converter.Convert(serviceDefPayload);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(FormatException))]
|
||||
public void CannotConvertNonObjectJsonPayload()
|
||||
{
|
||||
var serviceDefPayload = @"[]";
|
||||
|
||||
var converter = new OpenStackServiceDefinitionPayloadConverter(new ServiceLocator());
|
||||
converter.Convert(serviceDefPayload);
|
||||
}
|
||||
}
|
||||
}
|
@ -1,252 +0,0 @@
|
||||
// /* ============================================================================
|
||||
// Copyright 2014 Hewlett Packard
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ============================================================================ */
|
||||
|
||||
using System;
|
||||
using System.Web;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
using OpenStack.Identity;
|
||||
|
||||
namespace OpenStack.Test.Identity
|
||||
{
|
||||
[TestClass]
|
||||
public class OpenStackServiceEndpointPayloadConverterTests
|
||||
{
|
||||
[TestMethod]
|
||||
public void CanConvertJsonPayload()
|
||||
{
|
||||
var expectedPublicUri = "https://region-a.geo-1.block.hpcloudsvc.com/v1/10244656540440";
|
||||
var expectedRegion = "region-a.geo-1";
|
||||
var expectedVersion = "1.0";
|
||||
var expectedVersionList = "https://region-a.geo-1.block.hpcloudsvc.com";
|
||||
var expectedVersionInfo = "https://region-a.geo-1.block.hpcloudsvc.com/v1";
|
||||
|
||||
var endpointPayload = @" {
|
||||
""tenantId"": ""10244656540440"",
|
||||
""publicURL"": ""https://region-a.geo-1.block.hpcloudsvc.com/v1/10244656540440"",
|
||||
""publicURL2"": """",
|
||||
""region"": ""region-a.geo-1"",
|
||||
""versionId"": ""1.0"",
|
||||
""versionInfo"": ""https://region-a.geo-1.block.hpcloudsvc.com/v1"",
|
||||
""versionList"": ""https://region-a.geo-1.block.hpcloudsvc.com""
|
||||
}";
|
||||
|
||||
var converter = new OpenStackServiceEndpointPayloadConverter();
|
||||
var endpoint = converter.Convert(endpointPayload);
|
||||
|
||||
Assert.IsNotNull(endpoint);
|
||||
Assert.AreEqual(expectedPublicUri, endpoint.PublicUri.ToString());
|
||||
Assert.AreEqual(expectedRegion, endpoint.Region);
|
||||
Assert.AreEqual(expectedVersion, endpoint.Version);
|
||||
Assert.AreEqual(expectedVersionInfo, endpoint.VersionInformation.ToString());
|
||||
Assert.AreEqual(expectedVersionList, endpoint.VersionList.ToString());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(ArgumentNullException))]
|
||||
public void CannotConvertWithNullJsonPayload()
|
||||
{
|
||||
var converter = new OpenStackServiceEndpointPayloadConverter();
|
||||
converter.Convert(null);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(FormatException))]
|
||||
public void CannotConvertJsonPayloadWithMissingPublicUri()
|
||||
{
|
||||
var endpointPayload = @" {
|
||||
""tenantId"": ""10244656540440"",
|
||||
""publicURL2"": """",
|
||||
""region"": ""region-a.geo-1"",
|
||||
""versionId"": ""1.0"",
|
||||
""versionInfo"": ""https://region-a.geo-1.block.hpcloudsvc.com/v1"",
|
||||
""versionList"": ""https://region-a.geo-1.block.hpcloudsvc.com""
|
||||
}";
|
||||
|
||||
var converter = new OpenStackServiceEndpointPayloadConverter();
|
||||
converter.Convert(endpointPayload);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(FormatException))]
|
||||
public void CannotConvertJsonPayloadWithMissingRegion()
|
||||
{
|
||||
var endpointPayload = @" {
|
||||
""tenantId"": ""10244656540440"",
|
||||
""publicURL"": ""https://region-a.geo-1.block.hpcloudsvc.com/v1/10244656540440"",
|
||||
""publicURL2"": """",
|
||||
""versionId"": ""1.0"",
|
||||
""versionInfo"": ""https://region-a.geo-1.block.hpcloudsvc.com/v1"",
|
||||
""versionList"": ""https://region-a.geo-1.block.hpcloudsvc.com""
|
||||
}";
|
||||
|
||||
var converter = new OpenStackServiceEndpointPayloadConverter();
|
||||
converter.Convert(endpointPayload);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanConvertJsonPayloadWithMissingVersion()
|
||||
{
|
||||
var endpointPayload = @" {
|
||||
""tenantId"": ""10244656540440"",
|
||||
""publicURL"": ""https://region-a.geo-1.block.hpcloudsvc.com/v1/10244656540440"",
|
||||
""publicURL2"": """",
|
||||
""region"": ""region-a.geo-1"",
|
||||
""versionInfo"": ""https://region-a.geo-1.block.hpcloudsvc.com/v1"",
|
||||
""versionList"": ""https://region-a.geo-1.block.hpcloudsvc.com""
|
||||
}";
|
||||
|
||||
var converter = new OpenStackServiceEndpointPayloadConverter();
|
||||
converter.Convert(endpointPayload);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanConvertJsonPayloadWithMissingVersionInfoUri()
|
||||
{
|
||||
var endpointPayload = @" {
|
||||
""tenantId"": ""10244656540440"",
|
||||
""publicURL"": ""https://region-a.geo-1.block.hpcloudsvc.com/v1/10244656540440"",
|
||||
""publicURL2"": """",
|
||||
""region"": ""region-a.geo-1"",
|
||||
""versionId"": ""1.0"",
|
||||
""versionList"": ""https://region-a.geo-1.block.hpcloudsvc.com""
|
||||
}";
|
||||
|
||||
var converter = new OpenStackServiceEndpointPayloadConverter();
|
||||
converter.Convert(endpointPayload);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanConvertJsonPayloadWithMissingVersionListUri()
|
||||
{
|
||||
var endpointPayload = @" {
|
||||
""tenantId"": ""10244656540440"",
|
||||
""publicURL"": ""https://region-a.geo-1.block.hpcloudsvc.com/v1/10244656540440"",
|
||||
""publicURL2"": """",
|
||||
""region"": ""region-a.geo-1"",
|
||||
""versionId"": ""1.0"",
|
||||
""versionInfo"": ""https://region-a.geo-1.block.hpcloudsvc.com/v1""
|
||||
}";
|
||||
|
||||
var converter = new OpenStackServiceEndpointPayloadConverter();
|
||||
converter.Convert(endpointPayload);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanConvertJsonPayloadWithBadPublicUri()
|
||||
{
|
||||
var endpointPayload = @" {
|
||||
""tenantId"": ""10244656540440"",
|
||||
""publicURL"": ""httpsBAD://reg&VERYBAD&ion-a.geo-1.block.hpcloudsvc.com/v1/10244656540440"",
|
||||
""publicURL2"": """",
|
||||
""region"": ""region-a.geo-1"",
|
||||
""versionId"": ""1.0"",
|
||||
""versionInfo"": ""https://region-a.geo-1.block.hpcloudsvc.com/v1"",
|
||||
""versionList"": ""https://region-a.geo-1.block.hpcloudsvc.com""
|
||||
}";
|
||||
|
||||
var converter = new OpenStackServiceEndpointPayloadConverter();
|
||||
converter.Convert(endpointPayload);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanConvertJsonPayloadWithBadVersionInfoUri()
|
||||
{
|
||||
var endpointPayload = @" {
|
||||
""tenantId"": ""10244656540440"",
|
||||
""publicURL"": ""https://region-a.geo-1.block.hpcloudsvc.com/v1/10244656540440"",
|
||||
""publicURL2"": """",
|
||||
""region"": ""region-a.geo-1"",
|
||||
""versionId"": ""1.0"",
|
||||
""versionInfo"": ""htBADtps://region&BAD&-a.geo-1.block.hpcloudsvc.com/v1"",
|
||||
""versionList"": ""https://region-a.geo-1.block.hpcloudsvc.com""
|
||||
}";
|
||||
|
||||
var converter = new OpenStackServiceEndpointPayloadConverter();
|
||||
converter.Convert(endpointPayload);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanConvertJsonPayloadWithBadVersionListcUri()
|
||||
{
|
||||
var endpointPayload = @" {
|
||||
""tenantId"": ""10244656540440"",
|
||||
""publicURL"": ""https://region-a.geo-1.block.hpcloudsvc.com/v1/10244656540440"",
|
||||
""publicURL2"": """",
|
||||
""region"": ""region-a.geo-1"",
|
||||
""versionId"": ""1.0"",
|
||||
""versionInfo"": ""https://region-a.geo-1.block.hpcloudsvc.com/v1"",
|
||||
""versionList"": ""htBADtps://region-a.ge&BAD&o-1.block.hpcloudsvc.com""
|
||||
}";
|
||||
|
||||
var converter = new OpenStackServiceEndpointPayloadConverter();
|
||||
converter.Convert(endpointPayload);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanConvertJsonPayloadWithEmptyVersionInfoUri()
|
||||
{
|
||||
var endpointPayload = @" {
|
||||
""tenantId"": ""10244656540440"",
|
||||
""publicURL"": ""https://region-a.geo-1.block.hpcloudsvc.com/v1/10244656540440"",
|
||||
""publicURL2"": """",
|
||||
""region"": ""region-a.geo-1"",
|
||||
""versionId"": ""1.0"",
|
||||
""versionInfo"": """",
|
||||
""versionList"": ""https://region-a.geo-1.block.hpcloudsvc.com""
|
||||
}";
|
||||
|
||||
var converter = new OpenStackServiceEndpointPayloadConverter();
|
||||
converter.Convert(endpointPayload);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanConvertJsonPayloadWithEmptyVersionListcUri()
|
||||
{
|
||||
var endpointPayload = @" {
|
||||
""tenantId"": ""10244656540440"",
|
||||
""publicURL"": ""https://region-a.geo-1.block.hpcloudsvc.com/v1/10244656540440"",
|
||||
""publicURL2"": """",
|
||||
""region"": ""region-a.geo-1"",
|
||||
""versionId"": ""1.0"",
|
||||
""versionInfo"": ""https://region-a.geo-1.block.hpcloudsvc.com/v1"",
|
||||
""versionList"": """"
|
||||
}";
|
||||
|
||||
var converter = new OpenStackServiceEndpointPayloadConverter();
|
||||
converter.Convert(endpointPayload);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(FormatException))]
|
||||
public void CannotConvertInvalidJsonPayload()
|
||||
{
|
||||
var endpointPayload = @" { NOT JSON";
|
||||
|
||||
var converter = new OpenStackServiceEndpointPayloadConverter();
|
||||
converter.Convert(endpointPayload);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(FormatException))]
|
||||
public void CannotConvertNonObjectJsonPayload()
|
||||
{
|
||||
var endpointPayload = @" [] ";
|
||||
|
||||
var converter = new OpenStackServiceEndpointPayloadConverter();
|
||||
converter.Convert(endpointPayload);
|
||||
}
|
||||
}
|
||||
}
|
@ -1,49 +0,0 @@
|
||||
// /* ============================================================================
|
||||
// Copyright 2014 Hewlett Packard
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ============================================================================ */
|
||||
|
||||
using System;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using OpenStack.Common.ServiceLocation;
|
||||
using OpenStack.Identity;
|
||||
|
||||
namespace OpenStack.Test.Identity
|
||||
{
|
||||
public class TestIdentityServicePocoClient : IIdentityServicePocoClient
|
||||
{
|
||||
public Func<Task<IOpenStackCredential>> AuthenticationDelegate { get; set; }
|
||||
|
||||
public Task<IOpenStackCredential> Authenticate()
|
||||
{
|
||||
return AuthenticationDelegate();
|
||||
}
|
||||
}
|
||||
|
||||
public class TestIdentityServicePocoClientFactory : IIdentityServicePocoClientFactory
|
||||
{
|
||||
internal IIdentityServicePocoClient client;
|
||||
|
||||
public TestIdentityServicePocoClientFactory(IIdentityServicePocoClient client)
|
||||
{
|
||||
this.client = client;
|
||||
}
|
||||
|
||||
public IIdentityServicePocoClient Create(IOpenStackCredential credentials, string serviceName, CancellationToken token, IServiceLocator serviceLocator)
|
||||
{
|
||||
return client;
|
||||
}
|
||||
}
|
||||
}
|
@ -1,49 +0,0 @@
|
||||
// /* ============================================================================
|
||||
// Copyright 2014 Hewlett Packard
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ============================================================================ */
|
||||
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using OpenStack.Common.Http;
|
||||
using OpenStack.Common.ServiceLocation;
|
||||
using OpenStack.Identity;
|
||||
|
||||
namespace OpenStack.Test.Identity
|
||||
{
|
||||
public class TestIdentityServiceRestClient : IIdentityServiceRestClient
|
||||
{
|
||||
public IHttpResponseAbstraction Response { get; set; }
|
||||
|
||||
public Task<IHttpResponseAbstraction> Authenticate()
|
||||
{
|
||||
return Task.Factory.StartNew(() => Response);
|
||||
}
|
||||
}
|
||||
|
||||
public class TestIdentityServiceRestClientFactory : IIdentityServiceRestClientFactory
|
||||
{
|
||||
internal IIdentityServiceRestClient Client;
|
||||
|
||||
public TestIdentityServiceRestClientFactory(IIdentityServiceRestClient client)
|
||||
{
|
||||
this.Client = client;
|
||||
}
|
||||
|
||||
public IIdentityServiceRestClient Create(IOpenStackCredential credential, CancellationToken cancellationToken, IServiceLocator serviceLocator)
|
||||
{
|
||||
return Client;
|
||||
}
|
||||
}
|
||||
}
|
@ -1,186 +0,0 @@
|
||||
// /* ============================================================================
|
||||
// Copyright 2014 Hewlett Packard
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ============================================================================ */
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
using OpenStack.Compute;
|
||||
using OpenStack.Network;
|
||||
|
||||
namespace OpenStack.Test.Network
|
||||
{
|
||||
[TestClass]
|
||||
public class FloatingIpPayloadConverterTests
|
||||
{
|
||||
internal string CreateFloatingIpJsonFixtrue(string id, string ipAddress, FloatingIpStatus status)
|
||||
{
|
||||
var payloadFixture = @"{{
|
||||
""router_id"": ""fafac59b-a94a-4525-8700-f4f448e0ac97"",
|
||||
""status"": ""{1}"",
|
||||
""tenant_id"": ""ffe683d1060449d09dac0bf9d7a371cd"",
|
||||
""floating_network_id"": ""3eaab3f7-d3f2-430f-aa73-d07f39aae8f4"",
|
||||
""fixed_ip_address"": ""10.0.0.2"",
|
||||
""floating_ip_address"": ""{2}"",
|
||||
""port_id"": ""9da94672-6e6b-446c-9579-3dd5484b31fd"",
|
||||
""id"": ""{0}""
|
||||
}}";
|
||||
|
||||
return string.Format(payloadFixture, id, status, ipAddress);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanParseValidFloatingIpsJsonPayloadWithMultipleIps()
|
||||
{
|
||||
var validMultipleIpJsonFixture = @"{{ ""floatingips"": [ {0} ] }}";
|
||||
var firstIp = CreateFloatingIpJsonFixtrue("12345", "172.0.0.1", FloatingIpStatus.Active);
|
||||
var secondIp = CreateFloatingIpJsonFixtrue("54321", "172.0.0.2", FloatingIpStatus.Down);
|
||||
|
||||
var validMultipleIpsJson = string.Format(validMultipleIpJsonFixture,
|
||||
string.Join(",", new List<string>() { firstIp, secondIp }));
|
||||
|
||||
var converter = new FloatingIpPayloadConverter();
|
||||
var floatingIps = converter.ConvertFloatingIps(validMultipleIpsJson).ToList();
|
||||
|
||||
Assert.AreEqual(2, floatingIps.Count());
|
||||
var ip1 =
|
||||
floatingIps.First(o => string.Equals(o.Id, "12345", StringComparison.InvariantCultureIgnoreCase));
|
||||
var ip2 =
|
||||
floatingIps.First(o => string.Equals(o.Id, "54321", StringComparison.InvariantCultureIgnoreCase));
|
||||
Assert.IsNotNull(ip1);
|
||||
Assert.IsNotNull(ip2);
|
||||
|
||||
Assert.AreEqual("12345", ip1.Id);
|
||||
Assert.AreEqual("172.0.0.1", ip1.FloatingIpAddress);
|
||||
Assert.AreEqual(FloatingIpStatus.Active, ip1.Status);
|
||||
|
||||
Assert.AreEqual("54321", ip2.Id);
|
||||
Assert.AreEqual("172.0.0.2", ip2.FloatingIpAddress);
|
||||
Assert.AreEqual(FloatingIpStatus.Down, ip2.Status);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanConvertValidFloatingIpsJsonPayloadWithSingleNetwork()
|
||||
{
|
||||
var validSingleIpJsonPayload = @"{{ ""floatingips"": [ {0} ] }}";
|
||||
var firstIp = CreateFloatingIpJsonFixtrue("12345", "172.0.0.1", FloatingIpStatus.Active);
|
||||
|
||||
var validSingleIpPayload = string.Format(validSingleIpJsonPayload,
|
||||
string.Join(",", new List<string>() { firstIp }));
|
||||
|
||||
var converter = new FloatingIpPayloadConverter();
|
||||
var floatingIps = converter.ConvertFloatingIps(validSingleIpPayload).ToList();
|
||||
|
||||
Assert.AreEqual(1, floatingIps.Count());
|
||||
var ip1 =
|
||||
floatingIps.First(o => string.Equals(o.Id, "12345", StringComparison.InvariantCultureIgnoreCase));
|
||||
|
||||
Assert.IsNotNull(ip1);
|
||||
|
||||
Assert.AreEqual("12345", ip1.Id);
|
||||
Assert.AreEqual("172.0.0.1", ip1.FloatingIpAddress);
|
||||
Assert.AreEqual(FloatingIpStatus.Active, ip1.Status);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanParseValidFloatingIpsPayloadWithEmptyJsonArray()
|
||||
{
|
||||
var emptyJsonArray = @"{ ""floatingips"": [ ] }";
|
||||
|
||||
var converter = new FloatingIpPayloadConverter();
|
||||
var networks = converter.ConvertFloatingIps(emptyJsonArray).ToList();
|
||||
|
||||
Assert.AreEqual(0, networks.Count());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanParseAnEmptyFloatingIpsPayload()
|
||||
{
|
||||
var payload = string.Empty;
|
||||
|
||||
var converter = new FloatingIpPayloadConverter();
|
||||
var networks = converter.ConvertFloatingIps(payload).ToList();
|
||||
|
||||
Assert.AreEqual(0, networks.Count());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(ArgumentNullException))]
|
||||
public void CannotParseANullFloatingIpsPayload()
|
||||
{
|
||||
var converter = new FloatingIpPayloadConverter();
|
||||
converter.ConvertFloatingIps(null);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(FormatException))]
|
||||
public void CannotParseInvalidFloatingIpsJsonPayload()
|
||||
{
|
||||
var converter = new FloatingIpPayloadConverter();
|
||||
converter.ConvertFloatingIps("[ { \"SomeAtrib\" }]");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(FormatException))]
|
||||
public void CannotParseInvalidFloatingIpsPayload()
|
||||
{
|
||||
var converter = new FloatingIpPayloadConverter();
|
||||
converter.ConvertFloatingIps("NOT JSON");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanConvertValidFloatingIpJsonPayload()
|
||||
{
|
||||
var validSingleIpJsonPayload = @"{{ ""floatingip"": {0} }}";
|
||||
var firstIp = CreateFloatingIpJsonFixtrue("12345", "172.0.0.1", FloatingIpStatus.Active);
|
||||
|
||||
var validSingleIpPayload = string.Format(validSingleIpJsonPayload,
|
||||
string.Join(",", new List<string>() { firstIp }));
|
||||
|
||||
var converter = new FloatingIpPayloadConverter();
|
||||
var ip1 = converter.Convert(validSingleIpPayload);
|
||||
|
||||
Assert.IsNotNull(ip1);
|
||||
Assert.AreEqual("12345", ip1.Id);
|
||||
Assert.AreEqual("172.0.0.1", ip1.FloatingIpAddress);
|
||||
Assert.AreEqual(FloatingIpStatus.Active, ip1.Status);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(ArgumentNullException))]
|
||||
public void CannotParseANullFloatingIpPayload()
|
||||
{
|
||||
var converter = new FloatingIpPayloadConverter();
|
||||
converter.Convert(null);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(FormatException))]
|
||||
public void CannotParseInvalidFloatingIpJsonPayload()
|
||||
{
|
||||
var converter = new FloatingIpPayloadConverter();
|
||||
converter.Convert("[ { \"SomeAtrib\" }]");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(FormatException))]
|
||||
public void CannotParseInvalidFloatingIpPayload()
|
||||
{
|
||||
var converter = new FloatingIpPayloadConverter();
|
||||
converter.Convert("NOT JSON");
|
||||
}
|
||||
}
|
||||
}
|
@ -1,146 +0,0 @@
|
||||
// /* ============================================================================
|
||||
// Copyright 2014 Hewlett Packard
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ============================================================================ */
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
using OpenStack.Compute;
|
||||
using OpenStack.Network;
|
||||
|
||||
namespace OpenStack.Test.Network
|
||||
{
|
||||
[TestClass]
|
||||
public class NetworkPayloadConverterTests
|
||||
{
|
||||
internal string CreateNetworkJsonFixtrue(string id, string name, NetworkStatus status)
|
||||
{
|
||||
var NetworkJsonResponseFixture = @"{{
|
||||
""status"": ""{2}"",
|
||||
""subnets"": [
|
||||
""d3839504-ec4c-47a4-b7c7-07af079a48bb""
|
||||
],
|
||||
""name"": ""{1}"",
|
||||
""router:external"": false,
|
||||
""tenant_id"": ""ffe683d1060449d09dac0bf9d7a371cd"",
|
||||
""admin_state_up"": true,
|
||||
""shared"": false,
|
||||
""id"": ""{0}""
|
||||
}}";
|
||||
|
||||
return string.Format(NetworkJsonResponseFixture, id, name, status);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanParseValidNetworksJsonPayloadWithMultipleNetworks()
|
||||
{
|
||||
var validMultipleNetworkJsonFixture = @"{{ ""networks"": [ {0} ] }}";
|
||||
var firstNetwork = CreateNetworkJsonFixtrue("12345", "MyNetwork", NetworkStatus.Active);
|
||||
var secondNetwork = CreateNetworkJsonFixtrue("54321", "NetworkMy", NetworkStatus.Down);
|
||||
|
||||
var validMultipleNetworksJson = string.Format(validMultipleNetworkJsonFixture,
|
||||
string.Join(",", new List<string>() { firstNetwork, secondNetwork }));
|
||||
|
||||
var converter = new NetworkPayloadConverter();
|
||||
var networks = converter.ConvertNetworks(validMultipleNetworksJson).ToList();
|
||||
|
||||
Assert.AreEqual(2, networks.Count());
|
||||
var ntw1 =
|
||||
networks.First(o => string.Equals(o.Id, "12345", StringComparison.InvariantCultureIgnoreCase));
|
||||
var ntw2 =
|
||||
networks.First(o => string.Equals(o.Id, "54321", StringComparison.InvariantCultureIgnoreCase));
|
||||
Assert.IsNotNull(ntw1);
|
||||
Assert.IsNotNull(ntw2);
|
||||
|
||||
Assert.AreEqual("12345", ntw1.Id);
|
||||
Assert.AreEqual("MyNetwork", ntw1.Name);
|
||||
Assert.AreEqual(NetworkStatus.Active, ntw1.Status);
|
||||
|
||||
Assert.AreEqual("54321", ntw2.Id);
|
||||
Assert.AreEqual("NetworkMy", ntw2.Name);
|
||||
Assert.AreEqual(NetworkStatus.Down, ntw2.Status);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanConvertValidNetworksJsonPayloadWithSingleNetwork()
|
||||
{
|
||||
var validMultipleNetworkJsonFixture = @"{{ ""networks"": [ {0} ] }}";
|
||||
var firstNetwork = CreateNetworkJsonFixtrue("12345", "MyNetwork", NetworkStatus.Active);
|
||||
|
||||
var validMultipleNetworksJson = string.Format(validMultipleNetworkJsonFixture,
|
||||
string.Join(",", new List<string>() { firstNetwork }));
|
||||
|
||||
var converter = new NetworkPayloadConverter();
|
||||
var networks = converter.ConvertNetworks(validMultipleNetworksJson).ToList();
|
||||
|
||||
Assert.AreEqual(1, networks.Count());
|
||||
var ntw1 =
|
||||
networks.First(o => string.Equals(o.Id, "12345", StringComparison.InvariantCultureIgnoreCase));
|
||||
|
||||
Assert.IsNotNull(ntw1);
|
||||
|
||||
Assert.AreEqual("12345", ntw1.Id);
|
||||
Assert.AreEqual("MyNetwork", ntw1.Name);
|
||||
Assert.AreEqual(NetworkStatus.Active, ntw1.Status);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanParseValidNetworksPayloadWithEmptyJsonArray()
|
||||
{
|
||||
var emptyJsonArray = @"{ ""networks"": [ ] }";
|
||||
|
||||
var converter = new NetworkPayloadConverter();
|
||||
var networks = converter.ConvertNetworks(emptyJsonArray).ToList();
|
||||
|
||||
Assert.AreEqual(0, networks.Count());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanParseAnEmptyNetworksPayload()
|
||||
{
|
||||
var payload = string.Empty;
|
||||
|
||||
var converter = new NetworkPayloadConverter();
|
||||
var networks = converter.ConvertNetworks(payload).ToList();
|
||||
|
||||
Assert.AreEqual(0, networks.Count());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(ArgumentNullException))]
|
||||
public void CannotParseANullNetworksPayload()
|
||||
{
|
||||
var converter = new NetworkPayloadConverter();
|
||||
converter.ConvertNetworks(null);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(FormatException))]
|
||||
public void CannotParseInvalidNetworksJsonPayload()
|
||||
{
|
||||
var converter = new NetworkPayloadConverter();
|
||||
converter.ConvertNetworks("[ { \"SomeAtrib\" }]");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(FormatException))]
|
||||
public void CannotParseInvalidNetworksPayload()
|
||||
{
|
||||
var converter = new NetworkPayloadConverter();
|
||||
converter.ConvertNetworks("NOT JSON");
|
||||
}
|
||||
}
|
||||
}
|
@ -1,277 +0,0 @@
|
||||
// /* ============================================================================
|
||||
// Copyright 2014 Hewlett Packard
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ============================================================================ */
|
||||
|
||||
using System;
|
||||
using System.CodeDom.Compiler;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Mime;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using OpenStack.Common;
|
||||
using OpenStack.Common.Http;
|
||||
using OpenStack.Network;
|
||||
|
||||
namespace OpenStack.Test.Network
|
||||
{
|
||||
public class NetworkRestSimulator : RestSimulator
|
||||
{
|
||||
internal ICollection<OpenStack.Network.Network> Networks { get; private set; }
|
||||
|
||||
internal ICollection<FloatingIp> FloatingIps { get; private set; }
|
||||
|
||||
public NetworkRestSimulator() : base()
|
||||
{
|
||||
this.Networks = new List<OpenStack.Network.Network>();
|
||||
this.FloatingIps = new List<OpenStack.Network.FloatingIp>();
|
||||
}
|
||||
|
||||
public NetworkRestSimulator(CancellationToken token)
|
||||
: this()
|
||||
{
|
||||
}
|
||||
|
||||
protected override IHttpResponseAbstraction HandleGet()
|
||||
{
|
||||
if (this.Uri.Segments.Count() >= 3)
|
||||
{
|
||||
switch (this.Uri.Segments[2].TrimEnd('/').ToLower())
|
||||
{
|
||||
case "networks":
|
||||
return HandleGetNetworks();
|
||||
case "floatingips":
|
||||
return HandleGetFloatingIps();
|
||||
}
|
||||
}
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
internal IHttpResponseAbstraction HandleGetNetworks()
|
||||
{
|
||||
Stream networkContent;
|
||||
switch (this.Uri.Segments.Count())
|
||||
{
|
||||
case 3:
|
||||
//no flavor id given, list all flavors
|
||||
networkContent = TestHelper.CreateStream(GenerateCollectionPayload(this.Networks, this.GenerateNetworkPayload, "networks"));
|
||||
break;
|
||||
default:
|
||||
//Unknown Uri format
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
return TestHelper.CreateResponse(HttpStatusCode.OK, new Dictionary<string, string>(), networkContent);
|
||||
}
|
||||
|
||||
internal IHttpResponseAbstraction HandleGetFloatingIps()
|
||||
{
|
||||
Stream floatingIpContent;
|
||||
switch (this.Uri.Segments.Count())
|
||||
{
|
||||
case 3:
|
||||
floatingIpContent = TestHelper.CreateStream(GenerateCollectionPayload(this.FloatingIps, this.GenerateFloatingIpPayload, "floatingips"));
|
||||
break;
|
||||
case 4:
|
||||
var floatId = this.Uri.Segments[3].TrimEnd('/').ToLower();
|
||||
return HandleGetFloatingIp(floatId);
|
||||
default:
|
||||
//Unknown Uri format
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
return TestHelper.CreateResponse(HttpStatusCode.OK, new Dictionary<string, string>(), floatingIpContent);
|
||||
}
|
||||
|
||||
internal IHttpResponseAbstraction HandleGetFloatingIp(string floatingIpId)
|
||||
{
|
||||
var payloadFixture = @"{{
|
||||
""floatingip"": {0}
|
||||
}}";
|
||||
|
||||
var floatIp = this.FloatingIps.FirstOrDefault(ip => ip.Id == floatingIpId);
|
||||
if (floatIp == null)
|
||||
{
|
||||
return TestHelper.CreateResponse(HttpStatusCode.NotFound);
|
||||
}
|
||||
|
||||
var floatIpContent = string.Format(payloadFixture, GenerateFloatingIpPayload(floatIp)).ConvertToStream();
|
||||
return TestHelper.CreateResponse(HttpStatusCode.OK, new Dictionary<string, string>(), floatIpContent);
|
||||
}
|
||||
|
||||
protected override IHttpResponseAbstraction HandlePost()
|
||||
{
|
||||
if (this.Uri.Segments.Count() >= 3)
|
||||
{
|
||||
switch (this.Uri.Segments[2].TrimEnd('/').ToLower())
|
||||
{
|
||||
case "floatingips":
|
||||
return HandleCreateFloatingIp();
|
||||
}
|
||||
}
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
internal IHttpResponseAbstraction HandleCreateFloatingIp()
|
||||
{
|
||||
var payloadFixture = @"{{
|
||||
""floatingip"": {0}
|
||||
}}";
|
||||
|
||||
var ip = new FloatingIp(Guid.NewGuid().ToString(), "172.0.0." +(this.FloatingIps.Count +1), FloatingIpStatus.Active);
|
||||
this.FloatingIps.Add(ip);
|
||||
var floatIpContent = string.Format(payloadFixture, GenerateFloatingIpPayload(ip)).ConvertToStream();
|
||||
return TestHelper.CreateResponse(HttpStatusCode.Created, new Dictionary<string, string>(), floatIpContent);
|
||||
}
|
||||
|
||||
protected override IHttpResponseAbstraction HandlePut()
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
protected override IHttpResponseAbstraction HandleDelete()
|
||||
{
|
||||
if (this.Uri.Segments.Count() >= 3)
|
||||
{
|
||||
switch (this.Uri.Segments[2].TrimEnd('/').ToLower())
|
||||
{
|
||||
case "floatingips":
|
||||
if (this.Uri.Segments.Count() == 4)
|
||||
{
|
||||
var floatId = this.Uri.Segments[3].TrimEnd('/').ToLower();
|
||||
return HandleDeleteFloatingIps(floatId);
|
||||
}
|
||||
break;
|
||||
default:
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
}
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
internal IHttpResponseAbstraction HandleDeleteFloatingIps(string floatingIpId)
|
||||
{
|
||||
var floatIp = this.FloatingIps.FirstOrDefault(ip => ip.Id == floatingIpId);
|
||||
if (floatIp == null)
|
||||
{
|
||||
return TestHelper.CreateResponse(HttpStatusCode.NotFound);
|
||||
}
|
||||
|
||||
this.FloatingIps.Remove(floatIp);
|
||||
return TestHelper.CreateResponse(HttpStatusCode.NoContent, new Dictionary<string, string>());
|
||||
}
|
||||
|
||||
|
||||
protected override IHttpResponseAbstraction HandleHead()
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
protected override IHttpResponseAbstraction HandleCopy()
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
private string GenerateCollectionPayload<T>(IEnumerable<T> collection, Func<T, string> genFunc,
|
||||
string collectionName)
|
||||
{
|
||||
var payload = new StringBuilder();
|
||||
payload.Append(string.Format("{{ \"{0}\": [", collectionName));
|
||||
var first = true;
|
||||
foreach (var item in collection)
|
||||
{
|
||||
if (!first)
|
||||
{
|
||||
payload.Append(",");
|
||||
}
|
||||
|
||||
payload.Append(genFunc(item));
|
||||
first = false;
|
||||
}
|
||||
payload.Append("] }");
|
||||
return payload.ToString();
|
||||
}
|
||||
|
||||
private string GenerateNetworkPayload(OpenStack.Network.Network network)
|
||||
{
|
||||
var payloadFixture = @"{{
|
||||
""status"": ""{2}"",
|
||||
""subnets"": [
|
||||
""d3839504-ec4c-47a4-b7c7-07af079a48bb""
|
||||
],
|
||||
""name"": ""{0}"",
|
||||
""router:external"": false,
|
||||
""tenant_id"": ""ffe683d1060449d09dac0bf9d7a371cd"",
|
||||
""admin_state_up"": true,
|
||||
""shared"": false,
|
||||
""id"": ""{1}""
|
||||
}}";
|
||||
return string.Format(payloadFixture, network.Name, network.Id, network.Status.ToString().ToUpper());
|
||||
}
|
||||
|
||||
private string GenerateFloatingIpPayload(FloatingIp floatingIp)
|
||||
{
|
||||
var payloadFixture = @"{{
|
||||
""router_id"": ""fafac59b-a94a-4525-8700-f4f448e0ac97"",
|
||||
""status"": ""{1}"",
|
||||
""tenant_id"": ""ffe683d1060449d09dac0bf9d7a371cd"",
|
||||
""floating_network_id"": ""3eaab3f7-d3f2-430f-aa73-d07f39aae8f4"",
|
||||
""fixed_ip_address"": ""10.0.0.2"",
|
||||
""floating_ip_address"": ""{2}"",
|
||||
""port_id"": ""9da94672-6e6b-446c-9579-3dd5484b31fd"",
|
||||
""id"": ""{0}""
|
||||
}}";
|
||||
return string.Format(payloadFixture, floatingIp.Id, floatingIp.Status.ToString().ToUpper(), floatingIp.FloatingIpAddress);
|
||||
}
|
||||
}
|
||||
|
||||
public class NetworkRestSimulatorFactory : IHttpAbstractionClientFactory
|
||||
{
|
||||
internal NetworkRestSimulator Simulator = null;
|
||||
|
||||
public NetworkRestSimulatorFactory(NetworkRestSimulator simulator)
|
||||
{
|
||||
this.Simulator = simulator;
|
||||
}
|
||||
|
||||
public IHttpAbstractionClient Create()
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public IHttpAbstractionClient Create(CancellationToken token)
|
||||
{
|
||||
if (this.Simulator != null)
|
||||
{
|
||||
this.Simulator.Headers.Clear();
|
||||
}
|
||||
return this.Simulator ?? new NetworkRestSimulator(token);
|
||||
}
|
||||
|
||||
public IHttpAbstractionClient Create(TimeSpan timeout)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public IHttpAbstractionClient Create(TimeSpan timeout, CancellationToken token)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
}
|
||||
}
|
@ -1,192 +0,0 @@
|
||||
// /* ============================================================================
|
||||
// Copyright 2014 Hewlett Packard
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ============================================================================ */
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
using OpenStack.Common.ServiceLocation;
|
||||
using OpenStack.Identity;
|
||||
using OpenStack.Network;
|
||||
|
||||
namespace OpenStack.Test.Network
|
||||
{
|
||||
[TestClass]
|
||||
public class NetworkServiceClientTests
|
||||
{
|
||||
internal TestNetworkServicePocoClient ServicePocoClient;
|
||||
|
||||
internal string authId = "12345";
|
||||
internal string endpoint = "http://testcomputeendpoint.com/v2/1234567890";
|
||||
internal ServiceLocator ServiceLocator;
|
||||
|
||||
[TestInitialize]
|
||||
public void TestSetup()
|
||||
{
|
||||
this.ServicePocoClient = new TestNetworkServicePocoClient();
|
||||
this.ServiceLocator = new ServiceLocator();
|
||||
|
||||
var manager = this.ServiceLocator.Locate<IServiceLocationOverrideManager>();
|
||||
manager.RegisterServiceInstance(typeof(INetworkServicePocoClientFactory), new TestNetworkServicePocoClientFactory(this.ServicePocoClient));
|
||||
}
|
||||
|
||||
[TestCleanup]
|
||||
public void TestCleanup()
|
||||
{
|
||||
this.ServicePocoClient = new TestNetworkServicePocoClient();
|
||||
this.ServiceLocator = new ServiceLocator();
|
||||
}
|
||||
|
||||
IOpenStackCredential GetValidCreds()
|
||||
{
|
||||
var catalog = new OpenStackServiceCatalog();
|
||||
catalog.Add(new OpenStackServiceDefinition("Neutron", "Network Service",
|
||||
new List<OpenStackServiceEndpoint>()
|
||||
{
|
||||
new OpenStackServiceEndpoint(endpoint, string.Empty, "some version", "some version info", "1,2,3")
|
||||
}));
|
||||
|
||||
var creds = new OpenStackCredential(new Uri(this.endpoint), "SomeUser", "Password", "SomeTenant");
|
||||
creds.SetAccessTokenId(this.authId);
|
||||
creds.SetServiceCatalog(catalog);
|
||||
return creds;
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task CanGetNetworks()
|
||||
{
|
||||
var ntw1 = new OpenStack.Network.Network("12345","MyNetwork", NetworkStatus.Active);
|
||||
var ntw2 = new OpenStack.Network.Network("54321", "NetworkMy", NetworkStatus.Down);
|
||||
var networks = new List<OpenStack.Network.Network>() { ntw1, ntw2 };
|
||||
|
||||
this.ServicePocoClient.GetNetworksDelegate = () => Task.Factory.StartNew(() => (IEnumerable<OpenStack.Network.Network>)networks);
|
||||
|
||||
var client = new NetworkServiceClient(GetValidCreds(), "Neutron", CancellationToken.None, this.ServiceLocator);
|
||||
var resp = await client.GetNetworks();
|
||||
Assert.IsNotNull(resp);
|
||||
|
||||
var respNetworks = resp.ToList();
|
||||
Assert.AreEqual(2, respNetworks.Count());
|
||||
Assert.AreEqual(ntw1, respNetworks[0]);
|
||||
Assert.AreEqual(ntw2, respNetworks[1]);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task CanGetFloatingIps()
|
||||
{
|
||||
var ip1 = new OpenStack.Network.FloatingIp("12345", "172.0.0.1", FloatingIpStatus.Active);
|
||||
var ip2 = new OpenStack.Network.FloatingIp("54321", "172.0.0.2", FloatingIpStatus.Down);
|
||||
var ips = new List<OpenStack.Network.FloatingIp>() { ip1, ip2 };
|
||||
|
||||
this.ServicePocoClient.GetFloatingIpsDelegate = () => Task.Factory.StartNew(() => (IEnumerable<OpenStack.Network.FloatingIp>)ips);
|
||||
|
||||
var client = new NetworkServiceClient(GetValidCreds(), "Neutron", CancellationToken.None, this.ServiceLocator);
|
||||
var resp = await client.GetFloatingIps();
|
||||
Assert.IsNotNull(resp);
|
||||
|
||||
var respIps = resp.ToList();
|
||||
Assert.AreEqual(2, respIps.Count());
|
||||
Assert.AreEqual(ip1, respIps[0]);
|
||||
Assert.AreEqual(ip2, respIps[1]);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task CanGetFloatingIp()
|
||||
{
|
||||
var ip1 = new OpenStack.Network.FloatingIp("12345", "172.0.0.1", FloatingIpStatus.Active);
|
||||
|
||||
this.ServicePocoClient.GetFloatingIpDelegate = (ip) => Task.Factory.StartNew(() => ip1);
|
||||
|
||||
var client = new NetworkServiceClient(GetValidCreds(), "Neutron", CancellationToken.None, this.ServiceLocator);
|
||||
var resp = await client.GetFloatingIp("12345");
|
||||
Assert.IsNotNull(resp);
|
||||
Assert.AreEqual(ip1, resp);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(ArgumentNullException))]
|
||||
public async Task GetFloatingIpWithNullFloatingIpIdThrows()
|
||||
{
|
||||
var client = new NetworkServiceClient(GetValidCreds(), "Neutron", CancellationToken.None, this.ServiceLocator);
|
||||
await client.GetFloatingIp(null);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(ArgumentException))]
|
||||
public async Task GetFloatingIpWithEmptyFloatingIpIdThrows()
|
||||
{
|
||||
var client = new NetworkServiceClient(GetValidCreds(), "Neutron", CancellationToken.None, this.ServiceLocator);
|
||||
await client.GetFloatingIp(string.Empty);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task CanCreateFloatingIp()
|
||||
{
|
||||
var ip1 = new OpenStack.Network.FloatingIp("12345", "172.0.0.1", FloatingIpStatus.Active);
|
||||
|
||||
this.ServicePocoClient.CreateFloatingIpDelegate = (ip) => Task.Factory.StartNew(() => ip1);
|
||||
|
||||
var client = new NetworkServiceClient(GetValidCreds(), "Neutron", CancellationToken.None, this.ServiceLocator);
|
||||
var resp = await client.CreateFloatingIp("12345");
|
||||
Assert.IsNotNull(resp);
|
||||
Assert.AreEqual(ip1, resp);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(ArgumentNullException))]
|
||||
public async Task CreateFloatingIpWithNullNetworkIdThrows()
|
||||
{
|
||||
var client = new NetworkServiceClient(GetValidCreds(), "Neutron", CancellationToken.None, this.ServiceLocator);
|
||||
await client.CreateFloatingIp(null);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(ArgumentException))]
|
||||
public async Task CreateFloatingIpWithEmptyNetworkIdThrows()
|
||||
{
|
||||
var client = new NetworkServiceClient(GetValidCreds(), "Neutron", CancellationToken.None, this.ServiceLocator);
|
||||
await client.CreateFloatingIp(string.Empty);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task CanDeleteFloatingIp()
|
||||
{
|
||||
var ipId = "12345";
|
||||
this.ServicePocoClient.DeleteFloatingIpDelegate = (ip) => Task.Factory.StartNew(() => Assert.AreEqual(ipId, ip));
|
||||
|
||||
var client = new NetworkServiceClient(GetValidCreds(), "Neutron", CancellationToken.None, this.ServiceLocator);
|
||||
await client.DeleteFloatingIp(ipId);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(ArgumentNullException))]
|
||||
public async Task DeleteFloatingIpWithNullFloatingIpIdThrows()
|
||||
{
|
||||
var client = new NetworkServiceClient(GetValidCreds(), "Neutron", CancellationToken.None, this.ServiceLocator);
|
||||
await client.DeleteFloatingIp(null);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(ArgumentException))]
|
||||
public async Task DeleteFloatingIpWithEmptyFloatingIpIdThrows()
|
||||
{
|
||||
var client = new NetworkServiceClient(GetValidCreds(), "Neutron", CancellationToken.None, this.ServiceLocator);
|
||||
await client.DeleteFloatingIp(string.Empty);
|
||||
}
|
||||
}
|
||||
}
|
@ -1,363 +0,0 @@
|
||||
// /* ============================================================================
|
||||
// Copyright 2014 Hewlett Packard
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ============================================================================ */
|
||||
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using OpenStack.Common.Http;
|
||||
using OpenStack.Common.ServiceLocation;
|
||||
using OpenStack.Identity;
|
||||
using OpenStack.Network;
|
||||
|
||||
namespace OpenStack.Test.Network
|
||||
{
|
||||
[TestClass]
|
||||
public class NetworkServicePocoClientTests
|
||||
{
|
||||
internal TestNetworkServiceRestClient NetworkServiceRestClient;
|
||||
internal string authId = "12345";
|
||||
internal Uri endpoint = new Uri("http://testnetworkendpoint.com/v2.0/1234567890");
|
||||
internal IServiceLocator ServiceLocator;
|
||||
|
||||
[TestInitialize]
|
||||
public void TestSetup()
|
||||
{
|
||||
this.NetworkServiceRestClient = new TestNetworkServiceRestClient();
|
||||
this.ServiceLocator = new ServiceLocator();
|
||||
|
||||
var manager = this.ServiceLocator.Locate<IServiceLocationOverrideManager>();
|
||||
manager.RegisterServiceInstance(typeof(INetworkServiceRestClientFactory), new TestNetworkServiceRestClientFactory(this.NetworkServiceRestClient));
|
||||
}
|
||||
|
||||
[TestCleanup]
|
||||
public void TestCleanup()
|
||||
{
|
||||
this.NetworkServiceRestClient = new TestNetworkServiceRestClient();
|
||||
this.ServiceLocator = new ServiceLocator();
|
||||
}
|
||||
|
||||
ServiceClientContext GetValidContext()
|
||||
{
|
||||
var creds = new OpenStackCredential(this.endpoint, "SomeUser", "Password", "SomeTenant", "region-a.geo-1");
|
||||
creds.SetAccessTokenId(this.authId);
|
||||
|
||||
return new ServiceClientContext(creds, CancellationToken.None, "Object Storage", endpoint);
|
||||
}
|
||||
|
||||
#region Get Networks Tests
|
||||
|
||||
[TestMethod]
|
||||
public async Task CanGetNetworksWithOkResponse()
|
||||
{
|
||||
var payload = @"{
|
||||
""networks"": [
|
||||
{
|
||||
""status"": ""ACTIVE"",
|
||||
""subnets"": [
|
||||
""d3839504-ec4c-47a4-b7c7-07af079a48bb""
|
||||
],
|
||||
""name"": ""myNetwork"",
|
||||
""router:external"": false,
|
||||
""tenant_id"": ""ffe683d1060449d09dac0bf9d7a371cd"",
|
||||
""admin_state_up"": true,
|
||||
""shared"": false,
|
||||
""id"": ""12345""
|
||||
}
|
||||
]
|
||||
}";
|
||||
|
||||
var content = TestHelper.CreateStream(payload);
|
||||
|
||||
var restResp = new HttpResponseAbstraction(content, new HttpHeadersAbstraction(), HttpStatusCode.OK);
|
||||
this.NetworkServiceRestClient.Responses.Enqueue(restResp);
|
||||
|
||||
var client = new NetworkServicePocoClient(GetValidContext(), this.ServiceLocator);
|
||||
var result = await client.GetNetworks();
|
||||
|
||||
Assert.IsNotNull(result);
|
||||
|
||||
var networks = result.ToList();
|
||||
Assert.AreEqual(1, networks.Count());
|
||||
|
||||
var network = networks.First();
|
||||
Assert.AreEqual("myNetwork", network.Name);
|
||||
Assert.AreEqual("12345", network.Id);
|
||||
Assert.AreEqual(NetworkStatus.Active, network.Status);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(InvalidOperationException))]
|
||||
public async Task CannotGetNetworksWithNoContent()
|
||||
{
|
||||
|
||||
var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.NoContent);
|
||||
this.NetworkServiceRestClient.Responses.Enqueue(restResp);
|
||||
|
||||
var client = new NetworkServicePocoClient(GetValidContext(), this.ServiceLocator);
|
||||
await client.GetNetworks();
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(InvalidOperationException))]
|
||||
public async Task ExceptionthrownWhenGettingNetworksAndNotAuthed()
|
||||
{
|
||||
var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.Unauthorized);
|
||||
this.NetworkServiceRestClient.Responses.Enqueue(restResp);
|
||||
|
||||
var client = new NetworkServicePocoClient(GetValidContext(), this.ServiceLocator);
|
||||
await client.GetNetworks();
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(InvalidOperationException))]
|
||||
public async Task ExceptionthrownWhenGettingNetworksAndServerError()
|
||||
{
|
||||
var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.InternalServerError);
|
||||
this.NetworkServiceRestClient.Responses.Enqueue(restResp);
|
||||
|
||||
var client = new NetworkServicePocoClient(GetValidContext(), this.ServiceLocator);
|
||||
await client.GetNetworks();
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Get Floating IPs Tests
|
||||
|
||||
[TestMethod]
|
||||
public async Task CanGetFloatingIpsWithOkResponse()
|
||||
{
|
||||
var payload = @"{
|
||||
""floatingips"": [
|
||||
{
|
||||
""router_id"": ""fafac59b-a94a-4525-8700-f4f448e0ac97"",
|
||||
""status"": ""ACTIVE"",
|
||||
""tenant_id"": ""ffe683d1060449d09dac0bf9d7a371cd"",
|
||||
""floating_network_id"": ""3eaab3f7-d3f2-430f-aa73-d07f39aae8f4"",
|
||||
""fixed_ip_address"": ""10.0.0.2"",
|
||||
""floating_ip_address"": ""172.0.0.1"",
|
||||
""port_id"": ""9da94672-6e6b-446c-9579-3dd5484b31fd"",
|
||||
""id"": ""12345""
|
||||
}
|
||||
]
|
||||
}";
|
||||
|
||||
var content = TestHelper.CreateStream(payload);
|
||||
|
||||
var restResp = new HttpResponseAbstraction(content, new HttpHeadersAbstraction(), HttpStatusCode.OK);
|
||||
this.NetworkServiceRestClient.Responses.Enqueue(restResp);
|
||||
|
||||
var client = new NetworkServicePocoClient(GetValidContext(), this.ServiceLocator);
|
||||
var result = await client.GetFloatingIps();
|
||||
|
||||
Assert.IsNotNull(result);
|
||||
|
||||
var floatingIps = result.ToList();
|
||||
Assert.AreEqual(1, floatingIps.Count());
|
||||
|
||||
var floatingIp = floatingIps.First();
|
||||
Assert.AreEqual("12345", floatingIp.Id);
|
||||
Assert.AreEqual("172.0.0.1", floatingIp.FloatingIpAddress);
|
||||
Assert.AreEqual(FloatingIpStatus.Active, floatingIp.Status);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(InvalidOperationException))]
|
||||
public async Task ExceptionthrownWhenGettingFloatingIpsAndNotAuthed()
|
||||
{
|
||||
var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.Unauthorized);
|
||||
this.NetworkServiceRestClient.Responses.Enqueue(restResp);
|
||||
|
||||
var client = new NetworkServicePocoClient(GetValidContext(), this.ServiceLocator);
|
||||
await client.GetFloatingIps();
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(InvalidOperationException))]
|
||||
public async Task ExceptionthrownWhenGettingFloatingIpsAndServerError()
|
||||
{
|
||||
var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.InternalServerError);
|
||||
this.NetworkServiceRestClient.Responses.Enqueue(restResp);
|
||||
|
||||
var client = new NetworkServicePocoClient(GetValidContext(), this.ServiceLocator);
|
||||
await client.GetFloatingIps();
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Get Floating IP Tests
|
||||
|
||||
[TestMethod]
|
||||
public async Task CanGetFloatingIpWithOkResponse()
|
||||
{
|
||||
var payload = @"{
|
||||
""floatingip"":
|
||||
{
|
||||
""router_id"": ""fafac59b-a94a-4525-8700-f4f448e0ac97"",
|
||||
""status"": ""ACTIVE"",
|
||||
""tenant_id"": ""ffe683d1060449d09dac0bf9d7a371cd"",
|
||||
""floating_network_id"": ""3eaab3f7-d3f2-430f-aa73-d07f39aae8f4"",
|
||||
""fixed_ip_address"": ""10.0.0.2"",
|
||||
""floating_ip_address"": ""172.0.0.1"",
|
||||
""port_id"": ""9da94672-6e6b-446c-9579-3dd5484b31fd"",
|
||||
""id"": ""12345""
|
||||
}
|
||||
}";
|
||||
|
||||
var content = TestHelper.CreateStream(payload);
|
||||
|
||||
var restResp = new HttpResponseAbstraction(content, new HttpHeadersAbstraction(), HttpStatusCode.OK);
|
||||
this.NetworkServiceRestClient.Responses.Enqueue(restResp);
|
||||
|
||||
var client = new NetworkServicePocoClient(GetValidContext(), this.ServiceLocator);
|
||||
var result = await client.GetFloatingIp("12345");
|
||||
|
||||
Assert.IsNotNull(result);
|
||||
|
||||
Assert.AreEqual("12345", result.Id);
|
||||
Assert.AreEqual("172.0.0.1", result.FloatingIpAddress);
|
||||
Assert.AreEqual(FloatingIpStatus.Active, result.Status);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(InvalidOperationException))]
|
||||
public async Task ExceptionthrownWhenGettingFloatingIpAndNotAuthed()
|
||||
{
|
||||
var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.Unauthorized);
|
||||
this.NetworkServiceRestClient.Responses.Enqueue(restResp);
|
||||
|
||||
var client = new NetworkServicePocoClient(GetValidContext(), this.ServiceLocator);
|
||||
await client.GetFloatingIp("12345");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(InvalidOperationException))]
|
||||
public async Task ExceptionthrownWhenGettingFloatingIpAndServerError()
|
||||
{
|
||||
var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.InternalServerError);
|
||||
this.NetworkServiceRestClient.Responses.Enqueue(restResp);
|
||||
|
||||
var client = new NetworkServicePocoClient(GetValidContext(), this.ServiceLocator);
|
||||
await client.GetFloatingIp("12345");
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Create Floating IP Tests
|
||||
|
||||
[TestMethod]
|
||||
public async Task CanCreateFloatingIpWithCreatedResponse()
|
||||
{
|
||||
var payload = @"{
|
||||
""floatingip"":
|
||||
{
|
||||
""router_id"": ""fafac59b-a94a-4525-8700-f4f448e0ac97"",
|
||||
""status"": ""ACTIVE"",
|
||||
""tenant_id"": ""ffe683d1060449d09dac0bf9d7a371cd"",
|
||||
""floating_network_id"": ""3eaab3f7-d3f2-430f-aa73-d07f39aae8f4"",
|
||||
""fixed_ip_address"": ""10.0.0.2"",
|
||||
""floating_ip_address"": ""172.0.0.1"",
|
||||
""port_id"": ""9da94672-6e6b-446c-9579-3dd5484b31fd"",
|
||||
""id"": ""12345""
|
||||
}
|
||||
}";
|
||||
|
||||
var content = TestHelper.CreateStream(payload);
|
||||
|
||||
var restResp = new HttpResponseAbstraction(content, new HttpHeadersAbstraction(), HttpStatusCode.Created);
|
||||
this.NetworkServiceRestClient.Responses.Enqueue(restResp);
|
||||
|
||||
var client = new NetworkServicePocoClient(GetValidContext(), this.ServiceLocator);
|
||||
var result = await client.CreateFloatingIp("12345");
|
||||
|
||||
Assert.IsNotNull(result);
|
||||
|
||||
Assert.AreEqual("12345", result.Id);
|
||||
Assert.AreEqual("172.0.0.1", result.FloatingIpAddress);
|
||||
Assert.AreEqual(FloatingIpStatus.Active, result.Status);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(InvalidOperationException))]
|
||||
public async Task ExceptionthrownWhenCreatingFloatingIpAndNotAuthed()
|
||||
{
|
||||
var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.Unauthorized);
|
||||
this.NetworkServiceRestClient.Responses.Enqueue(restResp);
|
||||
|
||||
var client = new NetworkServicePocoClient(GetValidContext(), this.ServiceLocator);
|
||||
await client.CreateFloatingIp("12345");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(InvalidOperationException))]
|
||||
public async Task ExceptionthrownWhenCreatingFloatingIpAndServerError()
|
||||
{
|
||||
var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.InternalServerError);
|
||||
this.NetworkServiceRestClient.Responses.Enqueue(restResp);
|
||||
|
||||
var client = new NetworkServicePocoClient(GetValidContext(), this.ServiceLocator);
|
||||
await client.CreateFloatingIp("12345");
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Delete Floating IP Tests
|
||||
|
||||
[TestMethod]
|
||||
public async Task CanDeleteFloatingIpWithNoContentResponse()
|
||||
{
|
||||
|
||||
var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.NoContent);
|
||||
this.NetworkServiceRestClient.Responses.Enqueue(restResp);
|
||||
|
||||
var client = new NetworkServicePocoClient(GetValidContext(), this.ServiceLocator);
|
||||
await client.DeleteFloatingIp("12345");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(InvalidOperationException))]
|
||||
public async Task ExceptionthrownWhenDeletingFloatingIpAndNotAuthed()
|
||||
{
|
||||
var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.Unauthorized);
|
||||
this.NetworkServiceRestClient.Responses.Enqueue(restResp);
|
||||
|
||||
var client = new NetworkServicePocoClient(GetValidContext(), this.ServiceLocator);
|
||||
await client.DeleteFloatingIp("12345");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(InvalidOperationException))]
|
||||
public async Task ExceptionthrownWhenDeletingFloatingIpAndServerError()
|
||||
{
|
||||
var restResp = new HttpResponseAbstraction(new MemoryStream(), new HttpHeadersAbstraction(), HttpStatusCode.InternalServerError);
|
||||
this.NetworkServiceRestClient.Responses.Enqueue(restResp);
|
||||
|
||||
var client = new NetworkServicePocoClient(GetValidContext(), this.ServiceLocator);
|
||||
await client.DeleteFloatingIp("12345");
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
}
|
||||
}
|
@ -1,308 +0,0 @@
|
||||
// /* ============================================================================
|
||||
// Copyright 2014 Hewlett Packard
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ============================================================================ */
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using OpenStack.Common.Http;
|
||||
using OpenStack.Common.ServiceLocation;
|
||||
using OpenStack.Compute;
|
||||
using OpenStack.Identity;
|
||||
using OpenStack.Network;
|
||||
|
||||
namespace OpenStack.Test.Network
|
||||
{
|
||||
[TestClass]
|
||||
public class NetworkServiceRestClientTests
|
||||
{
|
||||
internal NetworkRestSimulator simulator;
|
||||
internal string authId = "12345";
|
||||
internal Uri endpoint = new Uri("http://testnetworkendpoint.com");
|
||||
internal IServiceLocator ServiceLocator;
|
||||
|
||||
[TestInitialize]
|
||||
public void TestSetup()
|
||||
{
|
||||
this.simulator = new NetworkRestSimulator();
|
||||
this.ServiceLocator = new ServiceLocator();
|
||||
|
||||
var manager = this.ServiceLocator.Locate<IServiceLocationOverrideManager>();
|
||||
manager.RegisterServiceInstance(typeof(IHttpAbstractionClientFactory), new NetworkRestSimulatorFactory(simulator));
|
||||
}
|
||||
|
||||
[TestCleanup]
|
||||
public void TestCleanup()
|
||||
{
|
||||
this.simulator = new NetworkRestSimulator();
|
||||
this.ServiceLocator = new ServiceLocator();
|
||||
}
|
||||
|
||||
ServiceClientContext GetValidContext()
|
||||
{
|
||||
return GetValidContext(CancellationToken.None);
|
||||
}
|
||||
|
||||
ServiceClientContext GetValidContext(CancellationToken token)
|
||||
{
|
||||
var creds = new OpenStackCredential(this.endpoint, "SomeUser", "Password", "SomeTenant", "region-a.geo-1");
|
||||
creds.SetAccessTokenId(this.authId);
|
||||
|
||||
return new ServiceClientContext(creds, token, "Nova", endpoint);
|
||||
}
|
||||
|
||||
#region Get Networks Test
|
||||
|
||||
[TestMethod]
|
||||
public async Task GetNetworksIncludesAuthHeader()
|
||||
{
|
||||
var client =
|
||||
new NetworkServiceRestClient(GetValidContext(), this.ServiceLocator);
|
||||
|
||||
await client.GetNetworks();
|
||||
|
||||
Assert.IsTrue(this.simulator.Headers.ContainsKey("X-Auth-Token"));
|
||||
Assert.AreEqual(this.authId, this.simulator.Headers["X-Auth-Token"]);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task GetNetworksFormsCorrectUrlAndMethod()
|
||||
{
|
||||
var client =
|
||||
new NetworkServiceRestClient(GetValidContext(), this.ServiceLocator);
|
||||
|
||||
await client.GetNetworks();
|
||||
|
||||
Assert.AreEqual(string.Format("{0}/networks", endpoint +"v2.0"), this.simulator.Uri.ToString());
|
||||
Assert.AreEqual(HttpMethod.Get, this.simulator.Method);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task CanGetNetworks()
|
||||
{
|
||||
this.simulator.Networks.Add(new OpenStack.Network.Network("12345","MyNetwork", NetworkStatus.Active));
|
||||
|
||||
var client =
|
||||
new NetworkServiceRestClient(GetValidContext(), this.ServiceLocator);
|
||||
|
||||
var resp = await client.GetNetworks();
|
||||
|
||||
Assert.AreEqual(HttpStatusCode.OK, resp.StatusCode);
|
||||
|
||||
var respContent = TestHelper.GetStringFromStream(resp.Content);
|
||||
Assert.IsTrue(respContent.Length > 0);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Get FloatingIps Tests
|
||||
|
||||
[TestMethod]
|
||||
public async Task GetFloatingIpsIncludesAuthHeader()
|
||||
{
|
||||
var client =
|
||||
new NetworkServiceRestClient(GetValidContext(), this.ServiceLocator);
|
||||
|
||||
await client.GetFloatingIps();
|
||||
|
||||
Assert.IsTrue(this.simulator.Headers.ContainsKey("X-Auth-Token"));
|
||||
Assert.AreEqual(this.authId, this.simulator.Headers["X-Auth-Token"]);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task GetFloatingIpsFormsCorrectUrlAndMethod()
|
||||
{
|
||||
var client =
|
||||
new NetworkServiceRestClient(GetValidContext(), this.ServiceLocator);
|
||||
|
||||
await client.GetFloatingIps();
|
||||
|
||||
Assert.AreEqual(string.Format("{0}/floatingips", endpoint + "v2.0"), this.simulator.Uri.ToString());
|
||||
Assert.AreEqual(HttpMethod.Get, this.simulator.Method);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task CanGetFloatingIps()
|
||||
{
|
||||
this.simulator.FloatingIps.Add(new OpenStack.Network.FloatingIp("12345", "172.0.0.1", FloatingIpStatus.Active));
|
||||
|
||||
var client =
|
||||
new NetworkServiceRestClient(GetValidContext(), this.ServiceLocator);
|
||||
|
||||
var resp = await client.GetFloatingIps();
|
||||
|
||||
Assert.AreEqual(HttpStatusCode.OK, resp.StatusCode);
|
||||
|
||||
var respContent = TestHelper.GetStringFromStream(resp.Content);
|
||||
Assert.IsTrue(respContent.Length > 0);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Get FloatingIp Tests
|
||||
|
||||
[TestMethod]
|
||||
public async Task GetFloatingIpIncludesAuthHeader()
|
||||
{
|
||||
var client =
|
||||
new NetworkServiceRestClient(GetValidContext(), this.ServiceLocator);
|
||||
|
||||
await client.GetNetworks();
|
||||
|
||||
Assert.IsTrue(this.simulator.Headers.ContainsKey("X-Auth-Token"));
|
||||
Assert.AreEqual(this.authId, this.simulator.Headers["X-Auth-Token"]);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task GetFloatingIpFormsCorrectUrlAndMethod()
|
||||
{
|
||||
var client =
|
||||
new NetworkServiceRestClient(GetValidContext(), this.ServiceLocator);
|
||||
|
||||
await client.GetFloatingIp("12345");
|
||||
|
||||
Assert.AreEqual(string.Format("{0}/floatingips/12345", endpoint + "v2.0"), this.simulator.Uri.ToString());
|
||||
Assert.AreEqual(HttpMethod.Get, this.simulator.Method);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task CanGetFloatinIp()
|
||||
{
|
||||
this.simulator.FloatingIps.Add(new OpenStack.Network.FloatingIp("12345", "172.0.0.1", FloatingIpStatus.Active));
|
||||
|
||||
var client =
|
||||
new NetworkServiceRestClient(GetValidContext(), this.ServiceLocator);
|
||||
|
||||
var resp = await client.GetFloatingIp("12345");
|
||||
|
||||
Assert.AreEqual(HttpStatusCode.OK, resp.StatusCode);
|
||||
|
||||
var respContent = TestHelper.GetStringFromStream(resp.Content);
|
||||
Assert.IsTrue(respContent.Length > 0);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Create FloatingIp Tests
|
||||
|
||||
[TestMethod]
|
||||
public async Task CreateFloatingIpIncludesAuthHeader()
|
||||
{
|
||||
var client =
|
||||
new NetworkServiceRestClient(GetValidContext(), this.ServiceLocator);
|
||||
|
||||
await client.CreateFloatingIp("12345");
|
||||
|
||||
Assert.IsTrue(this.simulator.Headers.ContainsKey("X-Auth-Token"));
|
||||
Assert.AreEqual(this.authId, this.simulator.Headers["X-Auth-Token"]);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task CreateFloatingIpFormsCorrectUrlAndMethod()
|
||||
{
|
||||
var client =
|
||||
new NetworkServiceRestClient(GetValidContext(), this.ServiceLocator);
|
||||
|
||||
await client.CreateFloatingIp("12345");
|
||||
|
||||
Assert.AreEqual(string.Format("{0}/floatingips", endpoint + "v2.0"), this.simulator.Uri.ToString());
|
||||
Assert.AreEqual(HttpMethod.Post, this.simulator.Method);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task CanCreateFloatinIp()
|
||||
{
|
||||
var client =
|
||||
new NetworkServiceRestClient(GetValidContext(), this.ServiceLocator);
|
||||
|
||||
var resp = await client.CreateFloatingIp("12345");
|
||||
|
||||
Assert.AreEqual(HttpStatusCode.Created, resp.StatusCode);
|
||||
|
||||
var respContent = TestHelper.GetStringFromStream(resp.Content);
|
||||
Assert.IsTrue(respContent.Length > 0);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task CreateFloatinIpFormCorrectBody()
|
||||
{
|
||||
var client =
|
||||
new NetworkServiceRestClient(GetValidContext(), this.ServiceLocator);
|
||||
|
||||
var resp = await client.CreateFloatingIp("12345");
|
||||
|
||||
Assert.AreEqual(HttpStatusCode.Created, resp.StatusCode);
|
||||
|
||||
this.simulator.Content.Position = 0;
|
||||
var body = TestHelper.GetStringFromStream(this.simulator.Content);
|
||||
var ipObj = JObject.Parse(body);
|
||||
Assert.IsNotNull(ipObj);
|
||||
Assert.IsNotNull(ipObj["floatingip"]);
|
||||
Assert.IsNotNull(ipObj["floatingip"]["floating_network_id"]);
|
||||
Assert.AreEqual("12345", (string)ipObj["floatingip"]["floating_network_id"]);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Delete Floating Ip Tests
|
||||
|
||||
[TestMethod]
|
||||
public async Task DeleteFloatingIpIncludesAuthHeader()
|
||||
{
|
||||
var client =
|
||||
new NetworkServiceRestClient(GetValidContext(), this.ServiceLocator);
|
||||
|
||||
await client.DeleteFloatingIp("12345");
|
||||
|
||||
Assert.IsTrue(this.simulator.Headers.ContainsKey("X-Auth-Token"));
|
||||
Assert.AreEqual(this.authId, this.simulator.Headers["X-Auth-Token"]);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task DeleteFloatingIpFormsCorrectUrlAndMethod()
|
||||
{
|
||||
var floatingIpId = "12345";
|
||||
var client =
|
||||
new NetworkServiceRestClient(GetValidContext(), this.ServiceLocator);
|
||||
|
||||
await client.DeleteFloatingIp(floatingIpId);
|
||||
|
||||
Assert.AreEqual(string.Format("{0}/floatingips/{1}", endpoint + "v2.0", floatingIpId), this.simulator.Uri.ToString());
|
||||
Assert.AreEqual(HttpMethod.Delete, this.simulator.Method);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task CanDeleteFloatinIp()
|
||||
{
|
||||
this.simulator.FloatingIps.Add(new FloatingIp("12345", "172.0.0.1", FloatingIpStatus.Active));
|
||||
var client =
|
||||
new NetworkServiceRestClient(GetValidContext(), this.ServiceLocator);
|
||||
|
||||
var resp = await client.DeleteFloatingIp("12345");
|
||||
|
||||
Assert.AreEqual(HttpStatusCode.NoContent, resp.StatusCode);
|
||||
|
||||
Assert.AreEqual(0, this.simulator.FloatingIps.Count);
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
@ -1,77 +0,0 @@
|
||||
// /* ============================================================================
|
||||
// Copyright 2014 Hewlett Packard
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ============================================================================ */
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading.Tasks;
|
||||
using OpenStack.Common.ServiceLocation;
|
||||
using OpenStack.Network;
|
||||
|
||||
namespace OpenStack.Test.Network
|
||||
{
|
||||
public class TestNetworkServicePocoClient : INetworkServicePocoClient
|
||||
{
|
||||
public Func<Task<IEnumerable<OpenStack.Network.Network>>> GetNetworksDelegate { get; set; }
|
||||
|
||||
public Func<Task<IEnumerable<OpenStack.Network.FloatingIp>>> GetFloatingIpsDelegate { get; set; }
|
||||
|
||||
public Func<string, Task<OpenStack.Network.FloatingIp>> GetFloatingIpDelegate { get; set; }
|
||||
|
||||
public Func<string, Task<OpenStack.Network.FloatingIp>> CreateFloatingIpDelegate { get; set; }
|
||||
|
||||
public Func<string, Task> DeleteFloatingIpDelegate { get; set; }
|
||||
|
||||
public async Task<IEnumerable<OpenStack.Network.Network>> GetNetworks()
|
||||
{
|
||||
return await this.GetNetworksDelegate();
|
||||
}
|
||||
|
||||
public async Task<IEnumerable<FloatingIp>> GetFloatingIps()
|
||||
{
|
||||
return await GetFloatingIpsDelegate();
|
||||
}
|
||||
|
||||
public async Task<FloatingIp> GetFloatingIp(string floatingIpId)
|
||||
{
|
||||
return await GetFloatingIpDelegate(floatingIpId);
|
||||
}
|
||||
|
||||
public async Task<FloatingIp> CreateFloatingIp(string networkId)
|
||||
{
|
||||
return await CreateFloatingIpDelegate(networkId);
|
||||
}
|
||||
|
||||
public async Task DeleteFloatingIp(string floatingIpId)
|
||||
{
|
||||
await DeleteFloatingIpDelegate(floatingIpId);
|
||||
}
|
||||
}
|
||||
|
||||
public class TestNetworkServicePocoClientFactory : INetworkServicePocoClientFactory
|
||||
{
|
||||
internal INetworkServicePocoClient client;
|
||||
|
||||
public TestNetworkServicePocoClientFactory(INetworkServicePocoClient client)
|
||||
{
|
||||
this.client = client;
|
||||
}
|
||||
|
||||
public INetworkServicePocoClient Create(ServiceClientContext context, IServiceLocator serviceLocator)
|
||||
{
|
||||
return client;
|
||||
}
|
||||
}
|
||||
}
|
@ -1,74 +0,0 @@
|
||||
// /* ============================================================================
|
||||
// Copyright 2014 Hewlett Packard
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ============================================================================ */
|
||||
|
||||
using System.Collections.Generic;
|
||||
using System.Threading.Tasks;
|
||||
using OpenStack.Common.Http;
|
||||
using OpenStack.Common.ServiceLocation;
|
||||
using OpenStack.Network;
|
||||
|
||||
namespace OpenStack.Test.Network
|
||||
{
|
||||
public class TestNetworkServiceRestClient : INetworkServiceRestClient
|
||||
{
|
||||
public TestNetworkServiceRestClient()
|
||||
{
|
||||
this.Responses = new Queue<IHttpResponseAbstraction>();
|
||||
}
|
||||
|
||||
public Queue<IHttpResponseAbstraction> Responses { get; set; }
|
||||
|
||||
public Task<IHttpResponseAbstraction> GetNetworks()
|
||||
{
|
||||
return Task.Factory.StartNew(() => Responses.Dequeue());
|
||||
}
|
||||
|
||||
public Task<IHttpResponseAbstraction> GetFloatingIps()
|
||||
{
|
||||
return Task.Factory.StartNew(() => Responses.Dequeue());
|
||||
}
|
||||
|
||||
public Task<IHttpResponseAbstraction> GetFloatingIp(string floatingIpId)
|
||||
{
|
||||
return Task.Factory.StartNew(() => Responses.Dequeue());
|
||||
}
|
||||
|
||||
public Task<IHttpResponseAbstraction> CreateFloatingIp(string networkId)
|
||||
{
|
||||
return Task.Factory.StartNew(() => Responses.Dequeue());
|
||||
}
|
||||
|
||||
public Task<IHttpResponseAbstraction> DeleteFloatingIp(string floatingIpId)
|
||||
{
|
||||
return Task.Factory.StartNew(() => Responses.Dequeue());
|
||||
}
|
||||
}
|
||||
|
||||
public class TestNetworkServiceRestClientFactory : INetworkServiceRestClientFactory
|
||||
{
|
||||
internal INetworkServiceRestClient Client;
|
||||
|
||||
public TestNetworkServiceRestClientFactory(INetworkServiceRestClient client)
|
||||
{
|
||||
this.Client = client;
|
||||
}
|
||||
|
||||
public INetworkServiceRestClient Create(ServiceClientContext context, IServiceLocator serviceLocator)
|
||||
{
|
||||
return Client;
|
||||
}
|
||||
}
|
||||
}
|
@ -1,161 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
||||
<PropertyGroup>
|
||||
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
|
||||
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
|
||||
<ProjectGuid>{7AF6DEC5-2257-4A29-BB55-66711DE3055D}</ProjectGuid>
|
||||
<OutputType>Library</OutputType>
|
||||
<AppDesignerFolder>Properties</AppDesignerFolder>
|
||||
<RootNamespace>OpenStack.Test</RootNamespace>
|
||||
<AssemblyName>OpenStack.Test</AssemblyName>
|
||||
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
|
||||
<FileAlignment>512</FileAlignment>
|
||||
<ProjectTypeGuids>{3AC096D0-A1C2-E12C-1390-A8335801FDAB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
|
||||
<VisualStudioVersion Condition="'$(VisualStudioVersion)' == ''">10.0</VisualStudioVersion>
|
||||
<VSToolsPath Condition="'$(VSToolsPath)' == ''">$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)</VSToolsPath>
|
||||
<ReferencePath>$(ProgramFiles)\Common Files\microsoft shared\VSTT\$(VisualStudioVersion)\UITestExtensionPackages</ReferencePath>
|
||||
<IsCodedUITest>False</IsCodedUITest>
|
||||
<TestProjectType>UnitTest</TestProjectType>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
|
||||
<DebugSymbols>true</DebugSymbols>
|
||||
<DebugType>full</DebugType>
|
||||
<Optimize>false</Optimize>
|
||||
<OutputPath>..\bin\net45\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\net45\Release\</OutputPath>
|
||||
<DefineConstants>TRACE</DefineConstants>
|
||||
<ErrorReport>prompt</ErrorReport>
|
||||
<WarningLevel>4</WarningLevel>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<Reference Include="Newtonsoft.Json, Version=6.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
|
||||
<SpecificVersion>False</SpecificVersion>
|
||||
<HintPath>..\packages\Newtonsoft.Json.6.0.2\lib\net45\Newtonsoft.Json.dll</HintPath>
|
||||
</Reference>
|
||||
<Reference Include="System" />
|
||||
<Reference Include="System.Net.Http" />
|
||||
<Reference Include="System.Net.Http.Formatting, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL" />
|
||||
<Reference Include="System.Web" />
|
||||
</ItemGroup>
|
||||
<Choose>
|
||||
<When Condition="('$(VisualStudioVersion)' == '10.0' or '$(VisualStudioVersion)' == '') and '$(TargetFrameworkVersion)' == 'v3.5'">
|
||||
<ItemGroup>
|
||||
<Reference Include="Microsoft.VisualStudio.QualityTools.UnitTestFramework, Version=10.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL" />
|
||||
</ItemGroup>
|
||||
</When>
|
||||
<Otherwise>
|
||||
<ItemGroup>
|
||||
<Reference Include="Microsoft.VisualStudio.QualityTools.UnitTestFramework" />
|
||||
</ItemGroup>
|
||||
</Otherwise>
|
||||
</Choose>
|
||||
<ItemGroup>
|
||||
<Compile Include="Compute\ComputeKeyPairPayloadConverterTests.cs" />
|
||||
<Compile Include="Compute\ComputeServerPayloadConverterTests.cs" />
|
||||
<Compile Include="Compute\ComputeImagePayloadConverterTests.cs" />
|
||||
<Compile Include="Compute\ComputeFlavorPayloadConverterTests.cs" />
|
||||
<Compile Include="Compute\ComputeItemMetadataPayloadConverterTests.cs" />
|
||||
<Compile Include="Compute\ComputeRestSimulator.cs" />
|
||||
<Compile Include="Compute\ComputeServiceRestClientTests.cs" />
|
||||
<Compile Include="Compute\ComputeServicePocoClientTests.cs" />
|
||||
<Compile Include="Compute\ComputeServiceClientTests.cs" />
|
||||
<Compile Include="Compute\TestComputeServiceRestClient.cs" />
|
||||
<Compile Include="Compute\TestComputeServicePocoClient.cs" />
|
||||
<Compile Include="Helper.cs" />
|
||||
<Compile Include="HttpAbstraction\HttpAbstractionClientTests.cs" />
|
||||
<Compile Include="HttpAbstraction\HttpHeadersAbstractionTests.cs" />
|
||||
<Compile Include="Identity\IdentityRestServiceSimulator.cs" />
|
||||
<Compile Include="Identity\IdentityServiceRestClientTests.cs" />
|
||||
<Compile Include="Identity\AccessTokenPayloadConverterTests.cs" />
|
||||
<Compile Include="Identity\IdentityServicePocoClientTests.cs" />
|
||||
<Compile Include="Identity\TestIdentityServicePocoClient.cs" />
|
||||
<Compile Include="Identity\TestIdentityServiceRestClient.cs" />
|
||||
<Compile Include="Identity\IdentityServiceClientTests.cs" />
|
||||
<Compile Include="Identity\OpenStackServiceEndpointPayloadConverterTests.cs" />
|
||||
<Compile Include="Identity\OpenStackServiceDefinitionPayloadConverterTests.cs" />
|
||||
<Compile Include="Identity\OpenStackServiceCatalogPayloadConverterTests.cs" />
|
||||
<Compile Include="Identity\OpenStackServiceCatalogTests.cs" />
|
||||
<Compile Include="Identity\IdentityServiceClientDefinitionTests.cs" />
|
||||
<Compile Include="Identity\OpenStackRegionResolverTests.cs" />
|
||||
<Compile Include="Network\FloatingIpPayloadConverterTests.cs" />
|
||||
<Compile Include="Network\NetworkServiceClientTests.cs" />
|
||||
<Compile Include="Network\NetworkServicePocoClientTests.cs" />
|
||||
<Compile Include="Network\NetworkPayloadConverterTests.cs" />
|
||||
<Compile Include="Network\NetworkRestSimulator.cs" />
|
||||
<Compile Include="Network\NetworkServiceRestClientTests.cs" />
|
||||
<Compile Include="Network\TestNetworkServicePocoClient.cs" />
|
||||
<Compile Include="Network\TestNetworkServiceRestClient.cs" />
|
||||
<Compile Include="RestSimulator.cs" />
|
||||
<Compile Include="ServiceLocation\ServiceLocationAssemblyScannerTests.cs" />
|
||||
<Compile Include="ServiceLocation\ServiceLocatorTests.cs" />
|
||||
<Compile Include="..\AssemblyVersionInfo.cs">
|
||||
<Link>Properties\AssemblyVersionInfo.cs</Link>
|
||||
</Compile>
|
||||
<Compile Include="Properties\AssemblyInfo.cs" />
|
||||
<Compile Include="Storage\StorageAccountPayloadConverterTests.cs" />
|
||||
<Compile Include="Storage\StorageContainerPayloadConverterTests.cs" />
|
||||
<Compile Include="Storage\StorageObjectPayloadConverterTests.cs" />
|
||||
<Compile Include="Storage\StorageServicePocoClientTests.cs" />
|
||||
<Compile Include="Storage\StorageServiceRestClientTests.cs" />
|
||||
<Compile Include="Storage\StorageRestSimulator.cs" />
|
||||
<Compile Include="Storage\TestLargeStorageObjectCreator.cs" />
|
||||
<Compile Include="Storage\TestStorageManifest.cs" />
|
||||
<Compile Include="Storage\TestStorageServiceClient.cs" />
|
||||
<Compile Include="Storage\TestStorageServicePocoClient.cs" />
|
||||
<Compile Include="Storage\TestStorageServiceRestClient.cs" />
|
||||
<Compile Include="Storage\StorageServiceClientTests.cs" />
|
||||
<Compile Include="Identity\OpenStackCredentialTests.cs" />
|
||||
<Compile Include="OpenStackClientManagerTests.cs" />
|
||||
<Compile Include="OpenStackServiceClientManagerTests.cs" />
|
||||
<Compile Include="Storage\StorageServiceClientDefinitionTests.cs" />
|
||||
<Compile Include="Storage\StorageFolderTests.cs" />
|
||||
<Compile Include="Storage\StorageFolderPayloadConverterTests.cs" />
|
||||
<Compile Include="Storage\StorageItemTests.cs" />
|
||||
<Compile Include="Storage\LargeStorageObjectProviderTests.cs" />
|
||||
<Compile Include="TestOpenStackRegionResolver.cs" />
|
||||
<Compile Include="OpenStackClientTests.cs" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<None Include="packages.config" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\OpenStack45-PCL\OpenStack45-PCL.csproj">
|
||||
<Project>{5660f8aa-14d5-4b3b-ada0-f79a286ef483}</Project>
|
||||
<Name>OpenStack45-PCL</Name>
|
||||
</ProjectReference>
|
||||
</ItemGroup>
|
||||
<Choose>
|
||||
<When Condition="'$(VisualStudioVersion)' == '10.0' And '$(IsCodedUITest)' == 'True'">
|
||||
<ItemGroup>
|
||||
<Reference Include="Microsoft.VisualStudio.QualityTools.CodedUITestFramework, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
|
||||
<Private>False</Private>
|
||||
</Reference>
|
||||
<Reference Include="Microsoft.VisualStudio.TestTools.UITest.Common, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
|
||||
<Private>False</Private>
|
||||
</Reference>
|
||||
<Reference Include="Microsoft.VisualStudio.TestTools.UITest.Extension, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
|
||||
<Private>False</Private>
|
||||
</Reference>
|
||||
<Reference Include="Microsoft.VisualStudio.TestTools.UITesting, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
|
||||
<Private>False</Private>
|
||||
</Reference>
|
||||
</ItemGroup>
|
||||
</When>
|
||||
</Choose>
|
||||
<Import Project="$(VSToolsPath)\TeamTest\Microsoft.TestTools.targets" Condition="Exists('$(VSToolsPath)\TeamTest\Microsoft.TestTools.targets')" />
|
||||
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
|
||||
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
|
||||
Other similar extension points exist, see Microsoft.Common.targets.
|
||||
<Target Name="BeforeBuild">
|
||||
</Target>
|
||||
<Target Name="AfterBuild">
|
||||
</Target>
|
||||
-->
|
||||
</Project>
|
@ -1,358 +0,0 @@
|
||||
// /* ============================================================================
|
||||
// Copyright 2014 Hewlett Packard
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ============================================================================ */
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
using OpenStack.Common.ServiceLocation;
|
||||
using OpenStack.Identity;
|
||||
|
||||
namespace OpenStack.Test
|
||||
{
|
||||
[TestClass]
|
||||
public class OpenStackClientManagerTests
|
||||
{
|
||||
internal class TestCredential : ICredential
|
||||
{
|
||||
public Uri AuthenticationEndpoint { get; private set; }
|
||||
public string AccessTokenId { get; private set; }
|
||||
|
||||
public OpenStackServiceCatalog ServiceCatalog
|
||||
{
|
||||
get
|
||||
{
|
||||
var catalog =
|
||||
new OpenStackServiceCatalog
|
||||
{
|
||||
new OpenStackServiceDefinition("Test", "Test",
|
||||
new List<OpenStackServiceEndpoint>()
|
||||
{
|
||||
new OpenStackServiceEndpoint("http://someplace.com", "somewhere", "2.0.0.0",
|
||||
"http://www.someplace.com", "http://www.someplace.com")
|
||||
})
|
||||
};
|
||||
return catalog;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal class TestOpenStackClient : IOpenStackClient
|
||||
{
|
||||
#region Test Client Impl
|
||||
|
||||
public IOpenStackCredential Credential { get; private set; }
|
||||
|
||||
public TestOpenStackClient(ICredential cred, CancellationToken token, IServiceLocator locator)
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
public Task Connect()
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public void SetRegion(string region)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public T CreateServiceClient<T>() where T : IOpenStackServiceClient
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public T CreateServiceClient<T>(string version) where T : IOpenStackServiceClient
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public T CreateServiceClientByName<T>(string serviceName) where T : IOpenStackServiceClient
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public T CreateServiceClientByName<T>(string serviceName, string version) where T : IOpenStackServiceClient
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public IEnumerable<string> GetSupportedVersions()
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public bool IsSupported(ICredential credential, string version)
|
||||
{
|
||||
return credential is TestCredential;
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
|
||||
internal class OtherTestOpenStackClient : IOpenStackClient
|
||||
{
|
||||
#region Test Client Impl
|
||||
|
||||
public IOpenStackCredential Credential { get; private set; }
|
||||
|
||||
public Task Connect()
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public void SetRegion(string region)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public T CreateServiceClient<T>() where T : IOpenStackServiceClient
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public T CreateServiceClient<T>(string version) where T : IOpenStackServiceClient
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public T CreateServiceClientByName<T>(string serviceName) where T : IOpenStackServiceClient
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public T CreateServiceClientByName<T>(string serviceName, string version) where T : IOpenStackServiceClient
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public IEnumerable<string> GetSupportedVersions()
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public bool IsSupported(ICredential credential, string version)
|
||||
{
|
||||
return credential is OpenStackCredential;
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
|
||||
internal class NonDefaultTestOpenStackClient : IOpenStackClient
|
||||
{
|
||||
public NonDefaultTestOpenStackClient(string parameter)
|
||||
{
|
||||
//forces a non-default ctor
|
||||
}
|
||||
|
||||
#region Test Client Impl
|
||||
|
||||
public IOpenStackCredential Credential { get; private set; }
|
||||
|
||||
public Task Connect()
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public void SetRegion(string region)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public T CreateServiceClient<T>() where T : IOpenStackServiceClient
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public T CreateServiceClient<T>(string version) where T : IOpenStackServiceClient
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public T CreateServiceClientByName<T>(string serviceName) where T : IOpenStackServiceClient
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public T CreateServiceClientByName<T>(string serviceName, string version) where T : IOpenStackServiceClient
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public IEnumerable<string> GetSupportedVersions()
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public bool IsSupported(ICredential credential, string version)
|
||||
{
|
||||
return credential is OpenStackCredential;
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanRegisterANewClient()
|
||||
{
|
||||
var manager = new OpenStackClientManager(new ServiceLocator());
|
||||
manager.RegisterClient<TestOpenStackClient>();
|
||||
|
||||
Assert.AreEqual(1, manager.clients.Count);
|
||||
Assert.AreEqual(typeof(TestOpenStackClient), manager.clients.First());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(InvalidOperationException))]
|
||||
public void CannotRegisterTheSameClientTwice()
|
||||
{
|
||||
var manager = new OpenStackClientManager(new ServiceLocator());
|
||||
manager.RegisterClient<TestOpenStackClient>();
|
||||
manager.RegisterClient<TestOpenStackClient>();
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanRegisterMultipleClients()
|
||||
{
|
||||
//var manager = OpenStackClientManager.Instance as OpenStackClientManager;
|
||||
var manager = new OpenStackClientManager(new ServiceLocator());
|
||||
manager.RegisterClient<TestOpenStackClient>();
|
||||
manager.RegisterClient<OtherTestOpenStackClient>();
|
||||
|
||||
Assert.AreEqual(2, manager.clients.Count);
|
||||
Assert.IsTrue(manager.clients.Contains(typeof(TestOpenStackClient)));
|
||||
Assert.IsTrue(manager.clients.Contains(typeof(OtherTestOpenStackClient)));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanListAvailableClients()
|
||||
{
|
||||
var manager = new OpenStackClientManager(new ServiceLocator());
|
||||
manager.clients.Add(typeof(TestOpenStackClient));
|
||||
manager.clients.Add(typeof(OtherTestOpenStackClient));
|
||||
|
||||
var clients = manager.ListAvailableClients().ToList();
|
||||
|
||||
Assert.AreEqual(2, clients.Count());
|
||||
Assert.IsTrue(clients.Contains(typeof(TestOpenStackClient)));
|
||||
Assert.IsTrue(clients.Contains(typeof(OtherTestOpenStackClient)));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanCreateAClient()
|
||||
{
|
||||
var manager = new OpenStackClientManager(new ServiceLocator());
|
||||
manager.clients.Add(typeof(TestOpenStackClient));
|
||||
|
||||
var client = manager.CreateClient(new TestCredential());
|
||||
|
||||
Assert.IsNotNull(client);
|
||||
Assert.IsInstanceOfType(client, typeof(TestOpenStackClient));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(InvalidOperationException))]
|
||||
public void CannotCreateAClientIfCredentialIsNotSupported()
|
||||
{
|
||||
var manager = new OpenStackClientManager(new ServiceLocator());
|
||||
manager.clients.Add(typeof(OtherTestOpenStackClient));
|
||||
|
||||
manager.CreateClient(new TestCredential());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(InvalidOperationException))]
|
||||
public void CannotCreateAClientIfNoClientsAreRegistered()
|
||||
{
|
||||
var manager = new OpenStackClientManager(new ServiceLocator());
|
||||
manager.CreateClient(new TestCredential());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(ArgumentNullException))]
|
||||
public void CannotCreateAClientWithNullCredential()
|
||||
{
|
||||
var manager = new OpenStackClientManager(new ServiceLocator());
|
||||
manager.clients.Add(typeof(TestOpenStackClient));
|
||||
|
||||
manager.CreateClient((ICredential)null);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(ArgumentNullException))]
|
||||
public void CannotCreateAClientWithNullCredentialAndVersion()
|
||||
{
|
||||
var manager = new OpenStackClientManager(new ServiceLocator());
|
||||
manager.clients.Add(typeof(TestOpenStackClient));
|
||||
|
||||
manager.CreateClient(null, "1.0.0..0");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(ArgumentNullException))]
|
||||
public void CannotCreateAClientWithCredentialAndNullVersion()
|
||||
{
|
||||
var manager = new OpenStackClientManager(new ServiceLocator());
|
||||
manager.clients.Add(typeof(TestOpenStackClient));
|
||||
|
||||
manager.CreateClient(new TestCredential(), null);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanCreateAnInstanceOfAClient()
|
||||
{
|
||||
var manager = new OpenStackClientManager(new ServiceLocator());
|
||||
var creds = new OpenStackCredential(new Uri("http://someurl.com"), "user", "password", "12345");
|
||||
|
||||
var client = manager.CreateClientInstance(typeof(TestOpenStackClient), creds, CancellationToken.None);
|
||||
Assert.IsNotNull(client);
|
||||
Assert.IsInstanceOfType(client, typeof(TestOpenStackClient));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(ArgumentNullException))]
|
||||
public void CanCreateAnInstanceOfAClientWithNullType()
|
||||
{
|
||||
var manager = new OpenStackClientManager(new ServiceLocator());
|
||||
var creds = new OpenStackCredential(new Uri("http://someurl.com"), "user", "password", "12345");
|
||||
|
||||
manager.CreateClientInstance((Type)null, creds, CancellationToken.None);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(InvalidOperationException))]
|
||||
public void CannotCreateAnInstanceOfANonOpenStackClient()
|
||||
{
|
||||
var manager = new OpenStackClientManager(new ServiceLocator());
|
||||
var creds = new OpenStackCredential(new Uri("http://someurl.com"), "user", "password", "12345");
|
||||
manager.CreateClientInstance(typeof(Object), creds, CancellationToken.None);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(InvalidOperationException))]
|
||||
public void CannotCreateAnInstanceOfAOpenStackClientWithoutADefaultCtor()
|
||||
{
|
||||
var manager = new OpenStackClientManager(new ServiceLocator());
|
||||
var creds = new OpenStackCredential(new Uri("http://someurl.com"), "user", "password", "12345");
|
||||
|
||||
manager.CreateClientInstance(typeof(NonDefaultTestOpenStackClient), creds, CancellationToken.None);
|
||||
}
|
||||
}
|
||||
}
|
@ -1,166 +0,0 @@
|
||||
// /* ============================================================================
|
||||
// Copyright 2014 Hewlett Packard
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ============================================================================ */
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Security;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
using OpenStack.Common.ServiceLocation;
|
||||
using OpenStack.Identity;
|
||||
|
||||
namespace OpenStack.Test
|
||||
{
|
||||
[TestClass]
|
||||
public class OpenStackClientTests
|
||||
{
|
||||
internal IServiceLocator ServiceLocator;
|
||||
|
||||
internal class TestIdentityServiceClient : IIdentityServiceClient
|
||||
{
|
||||
internal IOpenStackCredential cred;
|
||||
internal CancellationToken token;
|
||||
|
||||
public TestIdentityServiceClient(IOpenStackCredential cred, CancellationToken token)
|
||||
{
|
||||
this.cred = cred;
|
||||
this.token = token;
|
||||
}
|
||||
|
||||
public async Task<IOpenStackCredential> Authenticate()
|
||||
{
|
||||
return await Task.Run(() =>
|
||||
{
|
||||
this.cred.SetAccessTokenId("12345");
|
||||
return cred;
|
||||
} );
|
||||
}
|
||||
}
|
||||
|
||||
internal class TestIdentityServiceClientDefinition : IOpenStackServiceClientDefinition
|
||||
{
|
||||
public string Name { get; private set; }
|
||||
|
||||
public IOpenStackServiceClient Create(ICredential credential, string serviceName, CancellationToken cancellationToken, IServiceLocator serviceLocator)
|
||||
{
|
||||
return new TestIdentityServiceClient((IOpenStackCredential)credential, cancellationToken);
|
||||
}
|
||||
|
||||
public IEnumerable<string> ListSupportedVersions()
|
||||
{
|
||||
return new List<string>();
|
||||
}
|
||||
|
||||
public bool IsSupported(ICredential credential, string serviceName)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
[TestInitialize]
|
||||
public void TestSetup()
|
||||
{
|
||||
this.ServiceLocator = new ServiceLocator();
|
||||
|
||||
var manager = this.ServiceLocator.Locate<IServiceLocationOverrideManager>();
|
||||
var serviceManager = new OpenStackServiceClientManager(this.ServiceLocator);
|
||||
serviceManager.RegisterServiceClient<TestIdentityServiceClient>(new TestIdentityServiceClientDefinition());
|
||||
manager.RegisterServiceInstance(typeof(IOpenStackServiceClientManager), serviceManager);
|
||||
}
|
||||
|
||||
[TestCleanup]
|
||||
public void TestCleanup()
|
||||
{
|
||||
this.ServiceLocator = new ServiceLocator();
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task CanConnect()
|
||||
{
|
||||
var client =
|
||||
new OpenStackClient(
|
||||
new OpenStackCredential(new Uri("http://someplace.org"), "someuser", "password",
|
||||
"sometenant"), CancellationToken.None, this.ServiceLocator);
|
||||
await client.Connect();
|
||||
Assert.AreEqual("12345", client.Credential.AccessTokenId);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanSetRegion()
|
||||
{
|
||||
var expectedRegion = "newregion";
|
||||
var client = new OpenStackClient(
|
||||
new OpenStackCredential(new Uri("http://someplace.org"), "someuser", "password",
|
||||
"sometenant", "oldregion"), CancellationToken.None, this.ServiceLocator);
|
||||
client.SetRegion(expectedRegion);
|
||||
|
||||
Assert.AreEqual(expectedRegion, client.Credential.Region);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(ArgumentNullException))]
|
||||
public void CannotSetRegionWithNull()
|
||||
{
|
||||
var client = new OpenStackClient(
|
||||
new OpenStackCredential(new Uri("http://someplace.org"), "someuser", "password",
|
||||
"sometenant", "oldregion"), CancellationToken.None, this.ServiceLocator);
|
||||
client.SetRegion(null);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(ArgumentException))]
|
||||
public void CannotSetRegionWithEmptyString()
|
||||
{
|
||||
var client = new OpenStackClient(
|
||||
new OpenStackCredential(new Uri("http://someplace.org"), "someuser", "password",
|
||||
"sometenant", "oldregion"), CancellationToken.None, this.ServiceLocator);
|
||||
client.SetRegion(string.Empty);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanSupportAnyVersion()
|
||||
{
|
||||
var client = new OpenStackClient();
|
||||
var versions = client.GetSupportedVersions();
|
||||
Assert.IsTrue(versions.Contains("Any"));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanSupportOpenStackCredential()
|
||||
{
|
||||
var cred = new OpenStackCredential(new Uri("http://someplace.org"), "someuser", "password", "sometenant");
|
||||
var client = new OpenStackClient();
|
||||
Assert.IsTrue(client.IsSupported(cred,string.Empty));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CannotSupportNullCredential()
|
||||
{
|
||||
var client = new OpenStackClient();
|
||||
Assert.IsFalse(client.IsSupported(null, string.Empty));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanSupportNullVersion()
|
||||
{
|
||||
var cred = new OpenStackCredential(new Uri("http://someplace.org"), "someuser", "password", "sometenant");
|
||||
var client = new OpenStackClient();
|
||||
Assert.IsTrue(client.IsSupported(cred, null));
|
||||
}
|
||||
}
|
||||
}
|
@ -1,237 +0,0 @@
|
||||
// /* ============================================================================
|
||||
// Copyright 2014 Hewlett Packard
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ============================================================================ */
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
using OpenStack.Common.ServiceLocation;
|
||||
using OpenStack.Identity;
|
||||
|
||||
namespace OpenStack.Test
|
||||
{
|
||||
[TestClass]
|
||||
public class OpenStackServiceClientManagerTests
|
||||
{
|
||||
internal class TestOpenStackServiceClient : IOpenStackServiceClient
|
||||
{
|
||||
public TestOpenStackServiceClient(ICredential credential, CancellationToken token)
|
||||
{
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
internal class TestOpenStackServiceClientDefinition : IOpenStackServiceClientDefinition
|
||||
{
|
||||
public string Name { get; private set; }
|
||||
|
||||
public IOpenStackServiceClient Create(ICredential credential, string serviceName, CancellationToken token, IServiceLocator serviceLocator)
|
||||
{
|
||||
return new TestOpenStackServiceClient(credential, token);
|
||||
}
|
||||
|
||||
public IEnumerable<string> ListSupportedVersions()
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public bool IsSupported(ICredential credential, string serviceName)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
internal class OtherTestOpenStackServiceClient : IOpenStackServiceClient
|
||||
{
|
||||
public OtherTestOpenStackServiceClient(ICredential credential, CancellationToken token)
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
public IEnumerable<string> ListSupportedVersions()
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public bool IsSupported()
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
public static IOpenStackServiceClient Create(ICredential credential, CancellationToken token)
|
||||
{
|
||||
return new OtherTestOpenStackServiceClient(credential, token);
|
||||
}
|
||||
}
|
||||
|
||||
internal class OtherTestOpenStackServiceClientDefinition : IOpenStackServiceClientDefinition
|
||||
{
|
||||
public string Name { get; private set; }
|
||||
|
||||
public IOpenStackServiceClient Create(ICredential credential, string serviceName, CancellationToken token, IServiceLocator serviceLocator)
|
||||
{
|
||||
return new OtherTestOpenStackServiceClient(credential, token);
|
||||
}
|
||||
|
||||
public IEnumerable<string> ListSupportedVersions()
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public bool IsSupported(ICredential credential, string serviceName)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
internal class NoValidCtroTestOpenStackServiceClient : IOpenStackServiceClient
|
||||
{
|
||||
public IEnumerable<string> ListSupportedVersions()
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public bool IsSupported()
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanRegisterANewService()
|
||||
{
|
||||
var manager = new OpenStackServiceClientManager(new ServiceLocator());
|
||||
manager.RegisterServiceClient<TestOpenStackServiceClient>(new TestOpenStackServiceClientDefinition());
|
||||
|
||||
Assert.AreEqual(1, manager.serviceClientDefinitions.Count);
|
||||
Assert.IsTrue(manager.serviceClientDefinitions.ContainsKey(typeof(TestOpenStackServiceClient)));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(InvalidOperationException))]
|
||||
public void CannotRegisterTheSameServiceTwice()
|
||||
{
|
||||
var manager = new OpenStackServiceClientManager(new ServiceLocator());
|
||||
manager.RegisterServiceClient<TestOpenStackServiceClient>(new TestOpenStackServiceClientDefinition());
|
||||
manager.RegisterServiceClient<TestOpenStackServiceClient>(new TestOpenStackServiceClientDefinition());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanRegisterMultipleServices()
|
||||
{
|
||||
var manager = new OpenStackServiceClientManager(new ServiceLocator());
|
||||
manager.RegisterServiceClient<TestOpenStackServiceClient>(new TestOpenStackServiceClientDefinition());
|
||||
manager.RegisterServiceClient<OtherTestOpenStackServiceClient>(new OtherTestOpenStackServiceClientDefinition());
|
||||
|
||||
Assert.AreEqual(2, manager.serviceClientDefinitions.Count);
|
||||
Assert.IsTrue(manager.serviceClientDefinitions.ContainsKey(typeof(TestOpenStackServiceClient)));
|
||||
Assert.IsTrue(manager.serviceClientDefinitions.ContainsKey(typeof(OtherTestOpenStackServiceClient)));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanListAvailableClients()
|
||||
{
|
||||
var manager = new OpenStackServiceClientManager(new ServiceLocator());
|
||||
manager.serviceClientDefinitions.Add(typeof(TestOpenStackServiceClient), new TestOpenStackServiceClientDefinition());
|
||||
manager.serviceClientDefinitions.Add(typeof(OtherTestOpenStackServiceClient), new OtherTestOpenStackServiceClientDefinition());
|
||||
|
||||
var services = manager.ListAvailableServiceClients().ToList();
|
||||
|
||||
Assert.AreEqual(2, services.Count());
|
||||
Assert.IsTrue(services.Contains(typeof(TestOpenStackServiceClient)));
|
||||
Assert.IsTrue(services.Contains(typeof(OtherTestOpenStackServiceClient)));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanCreateAClient()
|
||||
{
|
||||
var manager = new OpenStackServiceClientManager(new ServiceLocator());
|
||||
manager.serviceClientDefinitions.Add(typeof(TestOpenStackServiceClient), new TestOpenStackServiceClientDefinition());
|
||||
|
||||
var service = manager.CreateServiceClient<TestOpenStackServiceClient>(new OpenStackClientManagerTests.TestCredential(), CancellationToken.None);
|
||||
|
||||
Assert.IsNotNull(service);
|
||||
Assert.IsInstanceOfType(service, typeof(TestOpenStackServiceClient));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(InvalidOperationException))]
|
||||
public void CannotCreateAServiceIfVersionIsNotSupported()
|
||||
{
|
||||
var manager = new OpenStackServiceClientManager(new ServiceLocator());
|
||||
manager.serviceClientDefinitions.Add(typeof(OtherTestOpenStackServiceClient), new OtherTestOpenStackServiceClientDefinition());
|
||||
|
||||
manager.CreateServiceClient<OtherTestOpenStackServiceClient>(new OpenStackClientManagerTests.TestCredential(), CancellationToken.None);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(InvalidOperationException))]
|
||||
public void CannotCreateAClientIfNoServicesAreRegistered()
|
||||
{
|
||||
var manager = new OpenStackServiceClientManager(new ServiceLocator());
|
||||
manager.CreateServiceClient<OtherTestOpenStackServiceClient>(new OpenStackClientManagerTests.TestCredential(), CancellationToken.None);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(ArgumentNullException))]
|
||||
public void CannotCreateAServiceWithNullCredential()
|
||||
{
|
||||
var manager = new OpenStackServiceClientManager(new ServiceLocator());
|
||||
manager.serviceClientDefinitions.Add(typeof(TestOpenStackServiceClient), new TestOpenStackServiceClientDefinition());
|
||||
|
||||
manager.CreateServiceClient<TestOpenStackServiceClient>((ICredential)null, CancellationToken.None);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(ArgumentNullException))]
|
||||
public void CannotCreateAServiceWithNullCredentialAndVersion()
|
||||
{
|
||||
var manager = new OpenStackServiceClientManager(new ServiceLocator());
|
||||
manager.serviceClientDefinitions.Add(typeof(TestOpenStackServiceClient), new TestOpenStackServiceClientDefinition());
|
||||
|
||||
manager.CreateServiceClient<TestOpenStackServiceClient>((ICredential)null, CancellationToken.None);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(InvalidOperationException))]
|
||||
public void CannotCreateAServiceWithCredentialAndNullFactory()
|
||||
{
|
||||
var manager = new OpenStackServiceClientManager(new ServiceLocator());
|
||||
manager.serviceClientDefinitions.Add(typeof(TestOpenStackServiceClient), null);
|
||||
|
||||
manager.CreateServiceClient<TestOpenStackServiceClient>(new OpenStackClientManagerTests.TestCredential(), CancellationToken.None);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanCreateAnInstanceOfAService()
|
||||
{
|
||||
var manager = new OpenStackServiceClientManager(new ServiceLocator());
|
||||
|
||||
var service = manager.CreateServiceClientInstance(new TestOpenStackServiceClientDefinition(), new OpenStackClientManagerTests.TestCredential(), string.Empty, CancellationToken.None);
|
||||
Assert.IsNotNull(service);
|
||||
Assert.IsInstanceOfType(service, typeof(TestOpenStackServiceClient));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(ArgumentNullException))]
|
||||
public void CanCreateAnInstanceOfAServiceWithNullFactory()
|
||||
{
|
||||
var manager = new OpenStackServiceClientManager(new ServiceLocator());
|
||||
manager.CreateServiceClientInstance(null, new OpenStackClientManagerTests.TestCredential(), string.Empty, CancellationToken.None);
|
||||
}
|
||||
}
|
||||
}
|
@ -1,39 +0,0 @@
|
||||
// /* ============================================================================
|
||||
// Copyright 2014 Hewlett Packard
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ============================================================================ */
|
||||
|
||||
using System.Reflection;
|
||||
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("OpenStack.Test")]
|
||||
[assembly: AssemblyDescription("")]
|
||||
[assembly: AssemblyConfiguration("")]
|
||||
[assembly: AssemblyCompany("OpenStack.org")]
|
||||
[assembly: AssemblyProduct("OpenStack.Test")]
|
||||
[assembly: AssemblyCopyright("")]
|
||||
[assembly: AssemblyTrademark("")]
|
||||
[assembly: AssemblyCulture("")]
|
||||
|
||||
// Setting ComVisible to false makes the types in this assembly not visible
|
||||
// to COM components. 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("47bc2198-4d59-47a0-9b5f-a3985ff6ab5a")]
|
||||
|
@ -1,102 +0,0 @@
|
||||
// /* ============================================================================
|
||||
// Copyright 2014 Hewlett Packard
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ============================================================================ */
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using OpenStack.Common.Http;
|
||||
|
||||
namespace OpenStack.Test
|
||||
{
|
||||
public abstract class RestSimulator : DisposableClass, IHttpAbstractionClient
|
||||
{
|
||||
protected RestSimulator()
|
||||
{
|
||||
this.Headers = new Dictionary<string, string>();
|
||||
this.Delay = TimeSpan.FromMilliseconds(0);
|
||||
}
|
||||
|
||||
protected RestSimulator(CancellationToken token) : this()
|
||||
{
|
||||
}
|
||||
|
||||
public HttpMethod Method { get; set; }
|
||||
|
||||
public Uri Uri { get; set; }
|
||||
|
||||
public Stream Content { get; set; }
|
||||
|
||||
public IDictionary<string, string> Headers { get; private set; }
|
||||
|
||||
public string ContentType { get; set; }
|
||||
|
||||
public TimeSpan Timeout { get; set; }
|
||||
|
||||
public TimeSpan Delay { get; set; }
|
||||
|
||||
public Task<IHttpResponseAbstraction> SendAsync()
|
||||
{
|
||||
if (!this.Headers.ContainsKey("X-Auth-Token") || this.Headers["X-Auth-Token"] != "12345")
|
||||
{
|
||||
return Task.Factory.StartNew(() => TestHelper.CreateResponse(HttpStatusCode.Unauthorized));
|
||||
}
|
||||
IHttpResponseAbstraction retVal;
|
||||
switch (this.Method.ToString().ToLowerInvariant())
|
||||
{
|
||||
case "get":
|
||||
retVal = HandleGet();
|
||||
break;
|
||||
case "post":
|
||||
retVal = HandlePost();
|
||||
break;
|
||||
case "put":
|
||||
retVal = HandlePut();
|
||||
break;
|
||||
case "delete":
|
||||
retVal = HandleDelete();
|
||||
break;
|
||||
case "head":
|
||||
retVal = HandleHead();
|
||||
break;
|
||||
case "copy":
|
||||
retVal = HandleCopy();
|
||||
break;
|
||||
default:
|
||||
retVal = TestHelper.CreateErrorResponse();
|
||||
break;
|
||||
}
|
||||
|
||||
Thread.Sleep(Delay);
|
||||
return Task.Factory.StartNew(() => retVal);
|
||||
}
|
||||
|
||||
protected abstract IHttpResponseAbstraction HandleGet();
|
||||
|
||||
protected abstract IHttpResponseAbstraction HandlePost();
|
||||
|
||||
protected abstract IHttpResponseAbstraction HandlePut();
|
||||
|
||||
protected abstract IHttpResponseAbstraction HandleDelete();
|
||||
|
||||
protected abstract IHttpResponseAbstraction HandleHead();
|
||||
|
||||
protected abstract IHttpResponseAbstraction HandleCopy();
|
||||
}
|
||||
}
|
@ -1,222 +0,0 @@
|
||||
// /* ============================================================================
|
||||
// Copyright 2014 Hewlett Packard
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ============================================================================ */
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Web.Management;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
using OpenStack.Common.ServiceLocation;
|
||||
|
||||
namespace OpenStack.Test.ServiceLocation
|
||||
{
|
||||
[TestClass]
|
||||
public class ServiceLocationAssemblyScannerTests
|
||||
{
|
||||
internal class TestRegistrar : IServiceLocationRegistrar
|
||||
{
|
||||
public void Register(IServiceLocationManager manager, IServiceLocator locator)
|
||||
{
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
internal class OtherTestRegistrar : IServiceLocationRegistrar
|
||||
{
|
||||
public void Register(IServiceLocationManager manager, IServiceLocator locator)
|
||||
{
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
internal class NonDefaultTestRegistrar : IServiceLocationRegistrar
|
||||
{
|
||||
public NonDefaultTestRegistrar(string beans)
|
||||
{
|
||||
//this is here to force a non-default constructor, this should not be loaded as a registrar.
|
||||
}
|
||||
|
||||
public void Register(IServiceLocationManager manager, IServiceLocator locator)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanAddNewAssembly()
|
||||
{
|
||||
var sweeper = new ServiceLocationAssemblyScanner();
|
||||
var assemblies = AppDomain.CurrentDomain.GetAssemblies().ToList();
|
||||
var temp = assemblies.First();
|
||||
|
||||
Assert.IsFalse(sweeper.HasNewAssemblies);
|
||||
|
||||
sweeper.AddAssembly(temp);
|
||||
|
||||
Assert.IsTrue(sweeper.HasNewAssemblies);
|
||||
Assert.AreEqual(1,sweeper._assemblies.Count);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanAddExistingAssembly()
|
||||
{
|
||||
var sweeper = new ServiceLocationAssemblyScanner();
|
||||
var assemblies = AppDomain.CurrentDomain.GetAssemblies().ToList();
|
||||
var temp = assemblies.First();
|
||||
|
||||
Assert.IsFalse(sweeper.HasNewAssemblies);
|
||||
sweeper.AddAssembly(temp);
|
||||
Assert.IsTrue(sweeper.HasNewAssemblies);
|
||||
|
||||
sweeper.AddAssembly(temp);
|
||||
|
||||
Assert.IsTrue(sweeper.HasNewAssemblies);
|
||||
Assert.AreEqual(1, sweeper._assemblies.Count);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanGetRegistrarTypes()
|
||||
{
|
||||
var sweeper = new ServiceLocationAssemblyScanner();
|
||||
Assert.IsFalse(sweeper.HasNewAssemblies);
|
||||
|
||||
sweeper.AddAssembly(this.GetType().Assembly);
|
||||
Assert.IsTrue(sweeper.HasNewAssemblies);
|
||||
|
||||
var types = sweeper.GetRegistrarTypes().ToList();
|
||||
Assert.IsTrue(sweeper.HasNewAssemblies);
|
||||
Assert.AreEqual(2, types.Count());
|
||||
Assert.IsTrue(types.Contains(typeof(TestRegistrar)));
|
||||
Assert.IsTrue(types.Contains(typeof(OtherTestRegistrar)));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanGetRegistrarTypesWithAssemblyThatHasNoRegistrars()
|
||||
{
|
||||
var sweeper = new ServiceLocationAssemblyScanner();
|
||||
Assert.IsFalse(sweeper.HasNewAssemblies);
|
||||
var assemblies = AppDomain.CurrentDomain.GetAssemblies().ToList();
|
||||
var temp = assemblies.First();
|
||||
|
||||
sweeper.AddAssembly(temp);
|
||||
Assert.IsTrue(sweeper.HasNewAssemblies);
|
||||
|
||||
var types = sweeper.GetRegistrarTypes().ToList();
|
||||
Assert.IsTrue(sweeper.HasNewAssemblies);
|
||||
|
||||
Assert.AreEqual(0, types.Count());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanGetRegistrarTypesWithEmptyAssembliesCollection()
|
||||
{
|
||||
var sweeper = new ServiceLocationAssemblyScanner();
|
||||
Assert.IsFalse(sweeper.HasNewAssemblies);
|
||||
|
||||
var types = sweeper.GetRegistrarTypes().ToList();
|
||||
Assert.IsFalse(sweeper.HasNewAssemblies);
|
||||
|
||||
Assert.AreEqual(0, types.Count());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void NoNewRegistrarsIfNoNewAssemblies()
|
||||
{
|
||||
bool getRegistrarsCalled = false;
|
||||
var sweeper = new ServiceLocationAssemblyScanner();
|
||||
sweeper.GetRegistrarTypes = () => { getRegistrarsCalled = false;
|
||||
return new List<Type>();
|
||||
};
|
||||
|
||||
var regs = sweeper.GetRegistrars();
|
||||
Assert.IsFalse(getRegistrarsCalled);
|
||||
Assert.AreEqual(0, regs.Count());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void NewRegistrarsIfNewAssembliesPresent()
|
||||
{
|
||||
bool getRegistrarsCalled = false;
|
||||
var sweeper = new ServiceLocationAssemblyScanner();
|
||||
sweeper.HasNewAssemblies = true;
|
||||
sweeper.GetRegistrarTypes = () =>
|
||||
{
|
||||
getRegistrarsCalled = true;
|
||||
return new List<Type>() { typeof(TestRegistrar)};
|
||||
};
|
||||
|
||||
var regs = sweeper.GetRegistrars().ToList();
|
||||
Assert.IsTrue(getRegistrarsCalled);
|
||||
Assert.AreEqual(1, regs.Count());
|
||||
Assert.IsTrue(regs.First() is TestRegistrar);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void ExistingRegistrarIsOverwritenWhenNewAssemblyFoundThatContainsIt()
|
||||
{
|
||||
bool getRegistrarsCalled = false;
|
||||
var sweeper = new ServiceLocationAssemblyScanner();
|
||||
sweeper._registrars.Add(typeof(TestRegistrar));
|
||||
sweeper.HasNewAssemblies = true;
|
||||
sweeper.GetRegistrarTypes = () =>
|
||||
{
|
||||
getRegistrarsCalled = true;
|
||||
return new List<Type>() { typeof(TestRegistrar) };
|
||||
};
|
||||
|
||||
var regs = sweeper.GetRegistrars().ToList();
|
||||
Assert.IsTrue(getRegistrarsCalled);
|
||||
Assert.AreEqual(1, regs.Count());
|
||||
Assert.IsTrue(regs.First() is TestRegistrar);
|
||||
Assert.AreEqual(1, sweeper._registrars.Count);
|
||||
Assert.AreEqual(typeof(TestRegistrar), sweeper._registrars.First());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanGetOnlyRegistrars()
|
||||
{
|
||||
var sweeper = new ServiceLocationAssemblyScanner();
|
||||
var assemblies = AppDomain.CurrentDomain.GetAssemblies().ToList();
|
||||
assemblies.Remove(this.GetType().Assembly);
|
||||
assemblies.ForEach(sweeper.AddAssembly);
|
||||
Assert.IsTrue(sweeper.HasNewAssemblies);
|
||||
|
||||
var registrars = sweeper.GetRegistrars();
|
||||
Assert.IsFalse(sweeper.HasNewAssemblies);
|
||||
Assert.AreEqual(1, registrars.Count());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanGetNewRegistrars()
|
||||
{
|
||||
var sweeper = new ServiceLocationAssemblyScanner();
|
||||
var assemblies = AppDomain.CurrentDomain.GetAssemblies().ToList();
|
||||
Assert.IsFalse(sweeper.HasNewAssemblies);
|
||||
|
||||
var registrars = sweeper.GetRegistrars();
|
||||
Assert.IsFalse(sweeper.HasNewAssemblies);
|
||||
Assert.AreEqual(0, registrars.Count());
|
||||
|
||||
sweeper.AddAssembly( this.GetType().Assembly );
|
||||
Assert.IsTrue(sweeper.HasNewAssemblies);
|
||||
|
||||
registrars = sweeper.GetRegistrars();
|
||||
Assert.IsFalse(sweeper.HasNewAssemblies);
|
||||
Assert.AreEqual(2, registrars.Count());
|
||||
}
|
||||
}
|
||||
}
|
@ -1,236 +0,0 @@
|
||||
// /* ============================================================================
|
||||
// Copyright 2014 Hewlett Packard
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ============================================================================ */
|
||||
|
||||
using System;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
using OpenStack.Common.ServiceLocation;
|
||||
|
||||
namespace OpenStack.Test.ServiceLocation
|
||||
{
|
||||
|
||||
[TestClass]
|
||||
public class ServiceLocatorTests
|
||||
{
|
||||
public interface ITestEchoService
|
||||
{
|
||||
string Echo(string msg);
|
||||
}
|
||||
|
||||
public class TestEchoService : ITestEchoService
|
||||
{
|
||||
public string Echo(string msg)
|
||||
{
|
||||
return msg;
|
||||
}
|
||||
}
|
||||
|
||||
public class TestReverseEchoService : ITestEchoService
|
||||
{
|
||||
public string Echo(string msg)
|
||||
{
|
||||
return new string(msg.Reverse().ToArray());
|
||||
}
|
||||
}
|
||||
|
||||
internal class TestServiceLocator : IServiceLocator
|
||||
{
|
||||
public T Locate<T>()
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public void EnsureAssemblyRegistration(Assembly target)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
}
|
||||
|
||||
internal class TestServiceManager : IServiceLocationRuntimeManager
|
||||
{
|
||||
public void RegisterServiceInstance<TService>(TService instance)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public void RegisterServiceInstance(Type type, object instance)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public void RegisterServiceType<T>(Type type)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public void RegisterServiceType<TInterface, TConcretion>() where TConcretion : class, TInterface
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public void RegisterServiceType(Type type, Type registrationValue)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
}
|
||||
|
||||
internal class TestServiceOverrideManager : IServiceLocationOverrideManager
|
||||
{
|
||||
public void RegisterServiceInstance<TService>(TService instance)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public void RegisterServiceInstance(Type type, object instance)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public void RegisterServiceType<T>(Type type)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public void RegisterServiceType<TInterface, TConcretion>() where TConcretion : class, TInterface
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public void RegisterServiceType(Type type, Type registrationValue)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
}
|
||||
|
||||
[TestInitialize]
|
||||
public void Initialize()
|
||||
{
|
||||
}
|
||||
|
||||
[TestCleanup]
|
||||
public void TestCleanup()
|
||||
{
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanRegisterAndLocateAService()
|
||||
{
|
||||
var locator = new ServiceLocator();
|
||||
var myServiceInstance = new TestEchoService();
|
||||
var manager = locator.Locate<IServiceLocationRuntimeManager>();
|
||||
|
||||
Assert.IsNotNull(manager);
|
||||
manager.RegisterServiceInstance<ITestEchoService>(myServiceInstance);
|
||||
|
||||
var service = locator.Locate<ITestEchoService>();
|
||||
|
||||
Assert.IsNotNull(service);
|
||||
Assert.AreEqual("Works", service.Echo("Works"));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(InvalidOperationException))]
|
||||
public void CannotLocateAServiceThatHasNotBeenRegistered()
|
||||
{
|
||||
var locator = new ServiceLocator();
|
||||
locator.Locate<ITestEchoService>();
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanOverrideAndLocateAService()
|
||||
{
|
||||
var locator = new ServiceLocator();
|
||||
var echoServiceInstance = new TestEchoService();
|
||||
var reverseEchoServiceInstance = new TestReverseEchoService();
|
||||
var runtimeManager = locator.Locate<IServiceLocationRuntimeManager>();
|
||||
var overrrideManager = locator.Locate<IServiceLocationOverrideManager>();
|
||||
|
||||
Assert.IsNotNull(runtimeManager);
|
||||
Assert.IsNotNull(overrrideManager);
|
||||
|
||||
runtimeManager.RegisterServiceInstance<ITestEchoService>(echoServiceInstance);
|
||||
overrrideManager.RegisterServiceInstance<ITestEchoService>(reverseEchoServiceInstance);
|
||||
|
||||
|
||||
var service = locator.Locate<ITestEchoService>();
|
||||
|
||||
Assert.IsNotNull(service);
|
||||
Assert.IsInstanceOfType(service, typeof(TestReverseEchoService));
|
||||
Assert.AreEqual("skroW", service.Echo("Works"));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(InvalidOperationException))]
|
||||
public void CannotRegisterNullService()
|
||||
{
|
||||
var locator = new ServiceLocator();
|
||||
var runtimeManager = locator.Locate<IServiceLocationRuntimeManager>();
|
||||
|
||||
runtimeManager.RegisterServiceInstance<ITestEchoService>(null);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(InvalidOperationException))]
|
||||
public void CannotRegisterNullType()
|
||||
{
|
||||
var locator = new ServiceLocator();
|
||||
var runtimeManager = locator.Locate<IServiceLocationRuntimeManager>();
|
||||
|
||||
runtimeManager.RegisterServiceInstance(null,new TestEchoService());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(InvalidOperationException))]
|
||||
public void CannotRegisterNonInterface()
|
||||
{
|
||||
var locator = new ServiceLocator();
|
||||
var runtimeManager = locator.Locate<IServiceLocationRuntimeManager>();
|
||||
|
||||
runtimeManager.RegisterServiceInstance<string>("Hello!");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(InvalidOperationException))]
|
||||
public void CannotRegisterAServiceLocator()
|
||||
{
|
||||
var locator = new ServiceLocator();
|
||||
var runtimeManager = locator.Locate<IServiceLocationRuntimeManager>();
|
||||
|
||||
runtimeManager.RegisterServiceInstance<IServiceLocator>(new TestServiceLocator());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(InvalidOperationException))]
|
||||
public void CannotRegisterAServiceManager()
|
||||
{
|
||||
var locator = new ServiceLocator();
|
||||
var runtimeManager = locator.Locate<IServiceLocationRuntimeManager>();
|
||||
|
||||
runtimeManager.RegisterServiceInstance<IServiceLocationRuntimeManager>(new TestServiceManager());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(InvalidOperationException))]
|
||||
public void CannotRegisterAnOverrideManager()
|
||||
{
|
||||
var locator = new ServiceLocator();
|
||||
var runtimeManager = locator.Locate<IServiceLocationRuntimeManager>();
|
||||
|
||||
runtimeManager.RegisterServiceInstance<IServiceLocationOverrideManager>(new TestServiceOverrideManager());
|
||||
}
|
||||
}
|
||||
}
|
File diff suppressed because it is too large
Load Diff
@ -1,270 +0,0 @@
|
||||
// /* ============================================================================
|
||||
// Copyright 2014 Hewlett Packard
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ============================================================================ */
|
||||
|
||||
using System;
|
||||
using System.Linq;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
using OpenStack.Common.Http;
|
||||
using OpenStack.Common.ServiceLocation;
|
||||
using OpenStack.Storage;
|
||||
|
||||
namespace OpenStack.Test.Storage
|
||||
{
|
||||
[TestClass]
|
||||
public class StorageAccountPayloadConverterTests
|
||||
{
|
||||
[TestMethod]
|
||||
public void CanParseAccountWithValidJsonPayloadAndHeaders()
|
||||
{
|
||||
var accountName = "1234567890";
|
||||
var validSingleContainerJson = @"[
|
||||
{
|
||||
""count"": 1,
|
||||
""bytes"": 7,
|
||||
""name"": ""TestContainer""
|
||||
}]";
|
||||
|
||||
var headers = new HttpHeadersAbstraction
|
||||
{
|
||||
{"X-Account-Bytes-Used", "12345"},
|
||||
{"X-Account-Object-Count", "1"},
|
||||
{"X-Account-Container-Count", "1"}
|
||||
};
|
||||
|
||||
var converter = new StorageAccountPayloadConverter(new ServiceLocator());
|
||||
var account = converter.Convert(accountName, headers, validSingleContainerJson);
|
||||
|
||||
Assert.IsNotNull(account);
|
||||
Assert.AreEqual(accountName, account.Name);
|
||||
Assert.AreEqual(12345, account.TotalBytesUsed);
|
||||
Assert.AreEqual(1, account.TotalObjectCount);
|
||||
Assert.AreEqual(1, account.TotalContainerCount);
|
||||
Assert.AreEqual(1, account.Containers.ToList().Count());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(FormatException))]
|
||||
public void CannotParseAccountWithMissingBytesUsedHeader()
|
||||
{
|
||||
var accountName = "1234567890";
|
||||
var validSingleContainerJson = @"[
|
||||
{
|
||||
""count"": 1,
|
||||
""bytes"": 7,
|
||||
""name"": ""TestContainer""
|
||||
}]";
|
||||
|
||||
var headers = new HttpHeadersAbstraction
|
||||
{
|
||||
{"X-Account-Object-Count", "1"},
|
||||
{"X-Account-Container-Count", "1"}
|
||||
};
|
||||
|
||||
var converter = new StorageAccountPayloadConverter(new ServiceLocator());
|
||||
converter.Convert(accountName, headers, validSingleContainerJson);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(FormatException))]
|
||||
public void CannotParseAccountWithMissingObjectCountHeader()
|
||||
{
|
||||
var accountName = "1234567890";
|
||||
var validSingleContainerJson = @"[
|
||||
{
|
||||
""count"": 1,
|
||||
""bytes"": 7,
|
||||
""name"": ""TestContainer""
|
||||
}]";
|
||||
|
||||
var headers = new HttpHeadersAbstraction
|
||||
{
|
||||
{"X-Account-Bytes-Used", "12345"},
|
||||
{"X-Account-Container-Count", "1"}
|
||||
};
|
||||
|
||||
var converter = new StorageAccountPayloadConverter(new ServiceLocator());
|
||||
converter.Convert(accountName, headers, validSingleContainerJson);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(FormatException))]
|
||||
public void CannotParseAccountWithMissingContainerCountHeader()
|
||||
{
|
||||
var accountName = "1234567890";
|
||||
var validSingleContainerJson = @"[
|
||||
{
|
||||
""count"": 1,
|
||||
""bytes"": 7,
|
||||
""name"": ""TestContainer""
|
||||
}]";
|
||||
|
||||
var headers = new HttpHeadersAbstraction
|
||||
{
|
||||
{"X-Account-Bytes-Used", "12345"},
|
||||
{"X-Account-Object-Count", "1"}
|
||||
};
|
||||
|
||||
var converter = new StorageAccountPayloadConverter(new ServiceLocator());
|
||||
converter.Convert(accountName, headers, validSingleContainerJson);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(FormatException))]
|
||||
public void CannotParseAccountWithBadBytesUsedHeader()
|
||||
{
|
||||
var accountName = "1234567890";
|
||||
var validSingleContainerJson = @"[
|
||||
{
|
||||
""count"": 1,
|
||||
""bytes"": 7,
|
||||
""name"": ""TestContainer""
|
||||
}]";
|
||||
|
||||
var headers = new HttpHeadersAbstraction
|
||||
{
|
||||
{"X-Account-Bytes-Used", "NOT A NUMBER"},
|
||||
{"X-Account-Object-Count", "1"},
|
||||
{"X-Account-Container-Count", "1"}
|
||||
};
|
||||
|
||||
var converter = new StorageAccountPayloadConverter(new ServiceLocator());
|
||||
converter.Convert(accountName, headers, validSingleContainerJson);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(FormatException))]
|
||||
public void CannotParseAccountWithBadObjectCountHeader()
|
||||
{
|
||||
var accountName = "1234567890";
|
||||
var validSingleContainerJson = @"[
|
||||
{
|
||||
""count"": 1,
|
||||
""bytes"": 7,
|
||||
""name"": ""TestContainer""
|
||||
}]";
|
||||
|
||||
var headers = new HttpHeadersAbstraction
|
||||
{
|
||||
{"X-Account-Bytes-Used", "12345"},
|
||||
{"X-Account-Object-Count", "NOT A NUMBER"},
|
||||
{"X-Account-Container-Count", "1"}
|
||||
};
|
||||
|
||||
var converter = new StorageAccountPayloadConverter(new ServiceLocator());
|
||||
converter.Convert(accountName, headers, validSingleContainerJson);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(FormatException))]
|
||||
public void CannotParseAccountWithBadContainerCountHeader()
|
||||
{
|
||||
var accountName = "1234567890";
|
||||
var validSingleContainerJson = @"[
|
||||
{
|
||||
""count"": 1,
|
||||
""bytes"": 7,
|
||||
""name"": ""TestContainer""
|
||||
}]";
|
||||
|
||||
var headers = new HttpHeadersAbstraction
|
||||
{
|
||||
{"X-Account-Bytes-Used", "12345"},
|
||||
{"X-Account-Object-Count", "1"},
|
||||
{"X-Account-Container-Count", "NOT A NUMBER"}
|
||||
};
|
||||
|
||||
var converter = new StorageAccountPayloadConverter(new ServiceLocator());
|
||||
converter.Convert(accountName, headers, validSingleContainerJson);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(FormatException))]
|
||||
public void CannotParseAccountWithBadPayload()
|
||||
{
|
||||
var accountName = "1234567890";
|
||||
var invalidSingleContainerJson = @"[
|
||||
{
|
||||
""bytes"": 7,
|
||||
""name"": ""TestContainer""
|
||||
}]";
|
||||
|
||||
var headers = new HttpHeadersAbstraction
|
||||
{
|
||||
{"X-Account-Bytes-Used", "12345"},
|
||||
{"X-Account-Object-Count", "1"},
|
||||
{"X-Account-Container-Count", "1"}
|
||||
};
|
||||
|
||||
var converter = new StorageAccountPayloadConverter(new ServiceLocator());
|
||||
converter.Convert(accountName, headers, invalidSingleContainerJson);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(ArgumentNullException))]
|
||||
public void CannotParseAccountWithNullName()
|
||||
{
|
||||
var validSingleContainerJson = @"[
|
||||
{
|
||||
""count"": 1,
|
||||
""bytes"": 7,
|
||||
""name"": ""TestContainer""
|
||||
}]";
|
||||
|
||||
var headers = new HttpHeadersAbstraction
|
||||
{
|
||||
{"X-Account-Bytes-Used", "12345"},
|
||||
{"X-Account-Object-Count", "1"},
|
||||
{"X-Account-Container-Count", "1"}
|
||||
};
|
||||
|
||||
var converter = new StorageAccountPayloadConverter(new ServiceLocator());
|
||||
converter.Convert(null, headers, validSingleContainerJson);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(ArgumentNullException))]
|
||||
public void CannotParseAccountWithNullHeaders()
|
||||
{
|
||||
var accountName = "1234567890";
|
||||
var validSingleContainerJson = @"[
|
||||
{
|
||||
""count"": 1,
|
||||
""bytes"": 7,
|
||||
""name"": ""TestContainer""
|
||||
}]";
|
||||
|
||||
var converter = new StorageAccountPayloadConverter(new ServiceLocator());
|
||||
converter.Convert(accountName, null, validSingleContainerJson);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(ArgumentNullException))]
|
||||
public void CannotParseAccountWithNullPayload()
|
||||
{
|
||||
var accountName = "1234567890";
|
||||
|
||||
var headers = new HttpHeadersAbstraction
|
||||
{
|
||||
{"X-Account-Bytes-Used", "12345"},
|
||||
{"X-Account-Object-Count", "1"},
|
||||
{"X-Account-Container-Count", "1"}
|
||||
};
|
||||
|
||||
var converter = new StorageAccountPayloadConverter(new ServiceLocator());
|
||||
converter.Convert(accountName, headers, null);
|
||||
}
|
||||
}
|
||||
}
|
@ -1,530 +0,0 @@
|
||||
// /* ============================================================================
|
||||
// Copyright 2014 Hewlett Packard
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ============================================================================ */
|
||||
|
||||
using System;
|
||||
using System.Linq;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
using OpenStack.Common.Http;
|
||||
using OpenStack.Common.ServiceLocation;
|
||||
using OpenStack.Storage;
|
||||
|
||||
namespace OpenStack.Test.Storage
|
||||
{
|
||||
[TestClass]
|
||||
public class StorageContainerPayloadConverterTests
|
||||
{
|
||||
[TestMethod]
|
||||
public void CanParseValidJsonPayloadWithMultipleObjects()
|
||||
{
|
||||
var validMultipleContainerJson = @"[
|
||||
{
|
||||
""count"": 1,
|
||||
""bytes"": 7,
|
||||
""name"": ""TestContainer""
|
||||
},
|
||||
{
|
||||
""count"": 5,
|
||||
""bytes"": 2000,
|
||||
""name"": ""OtherTestContainer""
|
||||
}
|
||||
]";
|
||||
|
||||
var converter = new StorageContainerPayloadConverter(new ServiceLocator());
|
||||
var containers = converter.Convert(validMultipleContainerJson).ToList();
|
||||
|
||||
Assert.AreEqual(2, containers.Count());
|
||||
var obj1 =
|
||||
containers.First(o => string.Equals(o.Name, "TestContainer", StringComparison.InvariantCultureIgnoreCase));
|
||||
var obj2 =
|
||||
containers.First(o => string.Equals(o.Name, "OtherTestContainer", StringComparison.InvariantCultureIgnoreCase));
|
||||
Assert.IsNotNull(obj1);
|
||||
Assert.IsNotNull(obj2);
|
||||
|
||||
Assert.AreEqual(7, obj1.TotalBytesUsed);
|
||||
Assert.AreEqual("TestContainer", obj1.Name);
|
||||
Assert.AreEqual(1, obj1.TotalObjectCount);
|
||||
|
||||
Assert.AreEqual(2000, obj2.TotalBytesUsed);
|
||||
Assert.AreEqual("OtherTestContainer", obj2.Name);
|
||||
Assert.AreEqual(5, obj2.TotalObjectCount);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanParseValidJsonPayloadWithSingleObject()
|
||||
{
|
||||
var validSingleContainerJson = @"[
|
||||
{
|
||||
""count"": 1,
|
||||
""bytes"": 7,
|
||||
""name"": ""TestContainer""
|
||||
}]";
|
||||
|
||||
var converter = new StorageContainerPayloadConverter(new ServiceLocator());
|
||||
var containers = converter.Convert(validSingleContainerJson).ToList();
|
||||
|
||||
Assert.AreEqual(1, containers.Count());
|
||||
var obj1 =
|
||||
containers.First(o => string.Equals(o.Name, "TestContainer", StringComparison.InvariantCultureIgnoreCase));
|
||||
Assert.IsNotNull(obj1);
|
||||
|
||||
Assert.AreEqual(7, obj1.TotalBytesUsed);
|
||||
Assert.AreEqual("TestContainer", obj1.Name);
|
||||
Assert.AreEqual(1, obj1.TotalObjectCount);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanParseValidEmptyJsonArrayPayload()
|
||||
{
|
||||
var emptyJsonArray = @"[]";
|
||||
|
||||
var converter = new StorageContainerPayloadConverter(new ServiceLocator());
|
||||
var containers = converter.Convert(emptyJsonArray).ToList();
|
||||
|
||||
Assert.AreEqual(0, containers.Count());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanParseAnEmptyPayload()
|
||||
{
|
||||
var payload = string.Empty;
|
||||
|
||||
var converter = new StorageContainerPayloadConverter(new ServiceLocator());
|
||||
var containers = converter.Convert(payload).ToList();
|
||||
|
||||
Assert.AreEqual(0, containers.Count());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(ArgumentNullException))]
|
||||
public void CannotParseANullPayload()
|
||||
{
|
||||
var converter = new StorageContainerPayloadConverter(new ServiceLocator());
|
||||
converter.Convert(null);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(FormatException))]
|
||||
public void CannotParseInvalidJsonPayload()
|
||||
{
|
||||
var converter = new StorageContainerPayloadConverter(new ServiceLocator());
|
||||
converter.Convert("[ { \"SomeAtrib\" }]");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(FormatException))]
|
||||
public void CannotParseInvalidPayload()
|
||||
{
|
||||
var converter = new StorageContainerPayloadConverter(new ServiceLocator());
|
||||
converter.Convert("NOT JSON");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(FormatException))]
|
||||
public void CannotParseJsonPayloadWithMissingBytesProperty()
|
||||
{
|
||||
var InvalidJsonWithoutBytes = @"[
|
||||
{
|
||||
""count"": 1,
|
||||
""name"": ""TestContainer""
|
||||
}]";
|
||||
|
||||
var converter = new StorageContainerPayloadConverter(new ServiceLocator());
|
||||
converter.Convert(InvalidJsonWithoutBytes);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(FormatException))]
|
||||
public void CannotParseJsonPayloadWithMissingCountProperty()
|
||||
{
|
||||
string InvalidJsonWithoutCount = @"[
|
||||
{
|
||||
""bytes"": 7,
|
||||
""name"": ""TestContainer""
|
||||
}]";
|
||||
|
||||
var converter = new StorageContainerPayloadConverter(new ServiceLocator());
|
||||
converter.Convert(InvalidJsonWithoutCount);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(FormatException))]
|
||||
public void CannotParseJsonPayloadWithMissingNameProperty()
|
||||
{
|
||||
string InvalidJsonWithoutName = @"[
|
||||
{
|
||||
""count"": 1,
|
||||
""bytes"": 7
|
||||
}]";
|
||||
|
||||
var converter = new StorageContainerPayloadConverter(new ServiceLocator());
|
||||
converter.Convert(InvalidJsonWithoutName);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void ParseExceptionIncludesNameWhenPossible()
|
||||
{
|
||||
string InvalidJsonWithoutBytes = @"[
|
||||
{
|
||||
""count"": 1,
|
||||
""name"": ""TestContainer""
|
||||
}]";
|
||||
|
||||
var converter = new StorageContainerPayloadConverter(new ServiceLocator());
|
||||
try
|
||||
{
|
||||
converter.Convert(InvalidJsonWithoutBytes);
|
||||
Assert.Fail("Parsing did not fail as expected.");
|
||||
}
|
||||
catch (FormatException ex)
|
||||
{
|
||||
Assert.IsTrue(ex.Message.StartsWith("Storage Container 'TestContainer'"));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(FormatException))]
|
||||
public void CannotParseJsonPayloadWithBadBytesValue()
|
||||
{
|
||||
string InvalidJsonWithBadBytesValue = @"[
|
||||
{
|
||||
""count"": 1,
|
||||
""bytes"": ""NOT A NUMBER"",
|
||||
""name"": ""TestContainer""
|
||||
}]";
|
||||
|
||||
var converter = new StorageContainerPayloadConverter(new ServiceLocator());
|
||||
converter.Convert(InvalidJsonWithBadBytesValue);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(FormatException))]
|
||||
public void CannotParseJsonPayloadWithBadCountValue()
|
||||
{
|
||||
string InvalidJsonWithBadCountValue = @"[
|
||||
{
|
||||
""count"": ""NOT A NUMBER"",
|
||||
""bytes"": 12345,
|
||||
""name"": ""TestContainer""
|
||||
}]";
|
||||
|
||||
var converter = new StorageContainerPayloadConverter(new ServiceLocator());
|
||||
converter.Convert(InvalidJsonWithBadCountValue);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanParseContainerWithValidJsonPayloadAndHeaders()
|
||||
{
|
||||
var containerName = "TestContainer";
|
||||
var validObjectJson = @"[
|
||||
{
|
||||
""hash"": ""d41d8cd98f00b204e9800998ecf8427e"",
|
||||
""last_modified"": ""2014-03-07T21:31:31.588170"",
|
||||
""bytes"": 0,
|
||||
""name"": ""BLAH"",
|
||||
""content_type"": ""application/octet-stream""
|
||||
}]";
|
||||
|
||||
var converter = new StorageContainerPayloadConverter(new ServiceLocator());
|
||||
var headers = new HttpHeadersAbstraction
|
||||
{
|
||||
{"X-Container-Bytes-Used", "12345"},
|
||||
{"X-Container-Object-Count", "1"}
|
||||
};
|
||||
|
||||
var container = converter.Convert(containerName, headers, validObjectJson);
|
||||
Assert.IsNotNull(container);
|
||||
Assert.AreEqual(containerName,container.Name);
|
||||
Assert.AreEqual(12345, container.TotalBytesUsed);
|
||||
Assert.AreEqual(1, container.TotalObjectCount);
|
||||
Assert.AreEqual(1, container.Objects.ToList().Count());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanParseContainerWithValidJsonPayloadWithNestedFoldersAndObjects()
|
||||
{
|
||||
var containerName = "TestContainer";
|
||||
var validObjectJson = @"[
|
||||
{
|
||||
""hash"": ""d41d8cd98f00b204e9800998ecf8427e"",
|
||||
""last_modified"": ""2014-03-27T20:57:11.150910"",
|
||||
""bytes"": 0,
|
||||
""name"": ""a/"",
|
||||
""content_type"": ""application/octet-stream""
|
||||
},
|
||||
{
|
||||
""hash"": ""d41d8cd98f00b204e9800998ecf8427e"",
|
||||
""last_modified"": ""2014-03-27T20:57:36.676350"",
|
||||
""bytes"": 0,
|
||||
""name"": ""a/b/"",
|
||||
""content_type"": ""application/octet-stream""
|
||||
},
|
||||
{
|
||||
""hash"": ""437b930db84b8079c2dd804a71936b5f"",
|
||||
""last_modified"": ""2014-03-27T20:58:36.676620"",
|
||||
""bytes"": 9,
|
||||
""name"": ""a/b/b"",
|
||||
""content_type"": ""text/plain;charset=UTF-8""
|
||||
},
|
||||
{
|
||||
""hash"": ""437b930db84b8079c2dd804a71936b5f"",
|
||||
""last_modified"": ""2014-03-27T20:58:43.935540"",
|
||||
""bytes"": 9,
|
||||
""name"": ""a/b/c"",
|
||||
""content_type"": ""text/plain;charset=UTF-8""
|
||||
},
|
||||
{
|
||||
""hash"": ""437b930db84b8079c2dd804a71936b5f"",
|
||||
""last_modified"": ""2014-03-27T20:58:54.142580"",
|
||||
""bytes"": 9,
|
||||
""name"": ""a/b/c/object3"",
|
||||
""content_type"": ""text/plain;charset=UTF-8""
|
||||
},
|
||||
{
|
||||
""hash"": ""437b930db84b8079c2dd804a71936b5f"",
|
||||
""last_modified"": ""2014-03-27T20:58:25.771530"",
|
||||
""bytes"": 9,
|
||||
""name"": ""a/object2"",
|
||||
""content_type"": ""text/plain;charset=UTF-8""
|
||||
},
|
||||
{
|
||||
""hash"": ""d41d8cd98f00b204e9800998ecf8427e"",
|
||||
""last_modified"": ""2014-03-27T20:57:47.122360"",
|
||||
""bytes"": 0,
|
||||
""name"": ""a/x/"",
|
||||
""content_type"": ""application/octet-stream""
|
||||
},
|
||||
{
|
||||
""hash"": ""437b930db84b8079c2dd804a71936b5f"",
|
||||
""last_modified"": ""2014-03-27T20:58:15.696360"",
|
||||
""bytes"": 9,
|
||||
""name"": ""object1"",
|
||||
""content_type"": ""text/plain;charset=UTF-8""
|
||||
}
|
||||
]";
|
||||
|
||||
var converter = new StorageContainerPayloadConverter(new ServiceLocator());
|
||||
var headers = new HttpHeadersAbstraction
|
||||
{
|
||||
{"X-Container-Bytes-Used", "45"},
|
||||
{"X-Container-Object-Count", "8"}
|
||||
};
|
||||
|
||||
var container = converter.Convert(containerName, headers, validObjectJson);
|
||||
Assert.IsNotNull(container);
|
||||
Assert.AreEqual(containerName, container.Name);
|
||||
Assert.AreEqual(45, container.TotalBytesUsed);
|
||||
Assert.AreEqual(8, container.TotalObjectCount);
|
||||
Assert.AreEqual(8, container.Objects.ToList().Count());
|
||||
Assert.IsTrue(container.Objects.ToList().Any(o => o.Name == "object1"));
|
||||
|
||||
var folders = container.Folders.ToList();
|
||||
Assert.AreEqual(1, folders.Count());
|
||||
|
||||
var aNode = folders.First();
|
||||
Assert.AreEqual("a", aNode.Name);
|
||||
Assert.AreEqual(2, aNode.Folders.Count);
|
||||
Assert.AreEqual(1, aNode.Objects.Count);
|
||||
Assert.IsTrue(aNode.Objects.Any(f => f.FullName == "a/object2"));
|
||||
|
||||
var xNode = aNode.Folders.First(f => f.Name == "x");
|
||||
Assert.AreEqual(0, xNode.Folders.Count);
|
||||
Assert.AreEqual(0, xNode.Objects.Count);
|
||||
|
||||
var bNode = aNode.Folders.First(f => f.Name == "b");
|
||||
Assert.AreEqual(1, bNode.Folders.Count);
|
||||
Assert.AreEqual(2, bNode.Objects.Count);
|
||||
Assert.IsTrue(bNode.Folders.Any(f => f.Name == "c"));
|
||||
Assert.IsTrue(bNode.Objects.Any(f => f.FullName == "a/b/c"));
|
||||
Assert.IsTrue(bNode.Objects.Any(f => f.FullName == "a/b/b"));
|
||||
|
||||
var cNode = bNode.Folders.First(f => f.Name == "c");
|
||||
Assert.AreEqual(0, cNode.Folders.Count);
|
||||
Assert.AreEqual(1, cNode.Objects.Count);
|
||||
Assert.IsTrue(cNode.Objects.Any(f => f.FullName == "a/b/c/object3"));
|
||||
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(FormatException))]
|
||||
public void CannotParseContainerWithMissingBytesUsedHeader()
|
||||
{
|
||||
var containerName = "TestContainer";
|
||||
var validObjectJson = @"[
|
||||
{
|
||||
""hash"": ""d41d8cd98f00b204e9800998ecf8427e"",
|
||||
""last_modified"": ""2014-03-07T21:31:31.588170"",
|
||||
""bytes"": 0,
|
||||
""name"": ""BLAH"",
|
||||
""content_type"": ""application/octet-stream""
|
||||
}]";
|
||||
|
||||
var converter = new StorageContainerPayloadConverter(new ServiceLocator());
|
||||
var headers = new HttpHeadersAbstraction
|
||||
{
|
||||
{"X-Container-Object-Count", "1"}
|
||||
};
|
||||
|
||||
converter.Convert(containerName, headers, validObjectJson);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(FormatException))]
|
||||
public void CannotParseContainerWithMissingObjectCountHeader()
|
||||
{
|
||||
var containerName = "TestContainer";
|
||||
var validObjectJson = @"[
|
||||
{
|
||||
""hash"": ""d41d8cd98f00b204e9800998ecf8427e"",
|
||||
""last_modified"": ""2014-03-07T21:31:31.588170"",
|
||||
""bytes"": 0,
|
||||
""name"": ""BLAH"",
|
||||
""content_type"": ""application/octet-stream""
|
||||
}]";
|
||||
|
||||
var converter = new StorageContainerPayloadConverter(new ServiceLocator());
|
||||
var headers = new HttpHeadersAbstraction
|
||||
{
|
||||
{"X-Container-Bytes-Used", "12345"}
|
||||
};
|
||||
|
||||
converter.Convert(containerName, headers, validObjectJson);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(FormatException))]
|
||||
public void CannotParseContainerWithBadBytesUsedHeader()
|
||||
{
|
||||
var containerName = "TestContainer";
|
||||
var validObjectJson = @"[
|
||||
{
|
||||
""hash"": ""d41d8cd98f00b204e9800998ecf8427e"",
|
||||
""last_modified"": ""2014-03-07T21:31:31.588170"",
|
||||
""bytes"": 0,
|
||||
""name"": ""BLAH"",
|
||||
""content_type"": ""application/octet-stream""
|
||||
}]";
|
||||
|
||||
var converter = new StorageContainerPayloadConverter(new ServiceLocator());
|
||||
var headers = new HttpHeadersAbstraction
|
||||
{
|
||||
{"X-Container-Bytes-Used", "This is not a number"},
|
||||
{"X-Container-Object-Count", "1"}
|
||||
};
|
||||
|
||||
converter.Convert(containerName, headers, validObjectJson);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(FormatException))]
|
||||
public void CannotParseContainerWithBadObjectCountHeader()
|
||||
{
|
||||
var containerName = "TestContainer";
|
||||
var validObjectJson = @"[
|
||||
{
|
||||
""hash"": ""d41d8cd98f00b204e9800998ecf8427e"",
|
||||
""last_modified"": ""2014-03-07T21:31:31.588170"",
|
||||
""bytes"": 0,
|
||||
""name"": ""BLAH"",
|
||||
""content_type"": ""application/octet-stream""
|
||||
}]";
|
||||
|
||||
var converter = new StorageContainerPayloadConverter(new ServiceLocator());
|
||||
var headers = new HttpHeadersAbstraction
|
||||
{
|
||||
{"X-Container-Bytes-Used", "12345"},
|
||||
{"X-Container-Object-Count", "This is not a number"}
|
||||
};
|
||||
|
||||
converter.Convert(containerName, headers, validObjectJson);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(FormatException))]
|
||||
public void CannotParseContainerWithBadPayload()
|
||||
{
|
||||
var containerName = "TestContainer";
|
||||
var validObjectJson = @"[
|
||||
{
|
||||
""hash"": ""d41d8cd98f00b204e9800998ecf8427e"",
|
||||
""last_modified"":";
|
||||
|
||||
var converter = new StorageContainerPayloadConverter(new ServiceLocator());
|
||||
var headers = new HttpHeadersAbstraction
|
||||
{
|
||||
{"X-Container-Bytes-Used", "12345"},
|
||||
{"X-Container-Object-Count", "1"}
|
||||
};
|
||||
|
||||
converter.Convert(containerName, headers, validObjectJson);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(ArgumentNullException))]
|
||||
public void CannotParseContainerWithNullName()
|
||||
{
|
||||
var validObjectJson = @"[
|
||||
{
|
||||
""hash"": ""d41d8cd98f00b204e9800998ecf8427e"",
|
||||
""last_modified"": ""2014-03-07T21:31:31.588170"",
|
||||
""bytes"": 0,
|
||||
""name"": ""BLAH"",
|
||||
""content_type"": ""application/octet-stream""
|
||||
}]";
|
||||
|
||||
var converter = new StorageContainerPayloadConverter(new ServiceLocator());
|
||||
var headers = new HttpHeadersAbstraction
|
||||
{
|
||||
{"X-Container-Bytes-Used", "12345"},
|
||||
{"X-Container-Object-Count", "1"}
|
||||
};
|
||||
|
||||
converter.Convert(null, headers, validObjectJson);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(ArgumentNullException))]
|
||||
public void CannotParseContainerWithNullHeaders()
|
||||
{
|
||||
var validObjectJson = @"[
|
||||
{
|
||||
""hash"": ""d41d8cd98f00b204e9800998ecf8427e"",
|
||||
""last_modified"": ""2014-03-07T21:31:31.588170"",
|
||||
""bytes"": 0,
|
||||
""name"": ""BLAH"",
|
||||
""content_type"": ""application/octet-stream""
|
||||
}]";
|
||||
|
||||
var converter = new StorageContainerPayloadConverter(new ServiceLocator());
|
||||
|
||||
converter.Convert("Name", null, validObjectJson);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(ArgumentNullException))]
|
||||
public void CannotParseContainerWithNullPayload()
|
||||
{
|
||||
var converter = new StorageContainerPayloadConverter(new ServiceLocator());
|
||||
var headers = new HttpHeadersAbstraction
|
||||
{
|
||||
{"X-Container-Bytes-Used", "12345"},
|
||||
{"X-Container-Object-Count", "1"}
|
||||
};
|
||||
|
||||
converter.Convert("Name", headers, null);
|
||||
}
|
||||
}
|
||||
}
|
@ -1,432 +0,0 @@
|
||||
// /* ============================================================================
|
||||
// Copyright 2014 Hewlett Packard
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ============================================================================ */
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
using OpenStack.Common.ServiceLocation;
|
||||
using OpenStack.Storage;
|
||||
|
||||
namespace OpenStack.Test.Storage
|
||||
{
|
||||
[TestClass]
|
||||
public class StorageFolderPayloadConverterTests
|
||||
{
|
||||
[TestMethod]
|
||||
public void CanAddFolderWithNestedFolders()
|
||||
{
|
||||
var objects = new List<StorageObject>() { new StorageObject("a/b/c/d/","a") };
|
||||
var converter = new StorageFolderPayloadConverter(new ServiceLocator());
|
||||
var folders = converter.Convert(objects).ToList();
|
||||
|
||||
Assert.AreEqual(1,folders.Count);
|
||||
Assert.AreEqual("a",folders[0].Name);
|
||||
Assert.AreEqual(1, folders[0].Folders.Count);
|
||||
Assert.AreEqual("b", folders[0].Folders.First().Name);
|
||||
Assert.AreEqual(1, folders[0].Folders.First().Folders.Count);
|
||||
Assert.AreEqual("c", folders[0].Folders.First().Folders.First().Name);
|
||||
Assert.AreEqual(1, folders[0].Folders.First().Folders.First().Folders.Count);
|
||||
Assert.AreEqual("d", folders[0].Folders.First().Folders.First().Folders.First().Name);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanAddFolderWithNestedFoldersAndDuplicateNames()
|
||||
{
|
||||
var objects = new List<StorageObject>() { new StorageObject("a/c/c/c/", "a") };
|
||||
var converter = new StorageFolderPayloadConverter(new ServiceLocator());
|
||||
var folders = converter.Convert(objects).ToList();
|
||||
|
||||
Assert.AreEqual(1, folders.Count);
|
||||
Assert.AreEqual("a", folders[0].Name);
|
||||
Assert.AreEqual(1, folders[0].Folders.Count);
|
||||
Assert.AreEqual("c", folders[0].Folders.First().Name);
|
||||
Assert.AreEqual(1, folders[0].Folders.First().Folders.Count);
|
||||
Assert.AreEqual("c", folders[0].Folders.First().Folders.First().Name);
|
||||
Assert.AreEqual(1, folders[0].Folders.First().Folders.First().Folders.Count);
|
||||
Assert.AreEqual("c", folders[0].Folders.First().Folders.First().Folders.First().Name);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanAddSingleFolder()
|
||||
{
|
||||
var objects = new List<StorageObject>() { new StorageObject("a/", "a") };
|
||||
var converter = new StorageFolderPayloadConverter(new ServiceLocator());
|
||||
var folders = converter.Convert(objects).ToList();
|
||||
|
||||
Assert.AreEqual(1, folders.Count);
|
||||
Assert.AreEqual("a", folders[0].Name);
|
||||
Assert.AreEqual(0, folders[0].Folders.Count);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
|
||||
[ExpectedException(typeof(ArgumentNullException))]
|
||||
public void CanAddFolderWithNullObjectList()
|
||||
{
|
||||
var converter = new StorageFolderPayloadConverter(new ServiceLocator());
|
||||
converter.Convert(null);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanAddNestedFoldersWhenRootExists()
|
||||
{
|
||||
var objects = new List<StorageObject>() { new StorageObject("a/", "a"), new StorageObject("a/b/c/d/", "a") };
|
||||
|
||||
var converter = new StorageFolderPayloadConverter(new ServiceLocator());
|
||||
var folders = converter.Convert(objects).ToList();
|
||||
|
||||
Assert.AreEqual(1, folders.Count);
|
||||
Assert.AreEqual("a", folders[0].Name);
|
||||
Assert.AreEqual(1, folders[0].Folders.Count);
|
||||
Assert.AreEqual("b", folders[0].Folders.First().Name);
|
||||
Assert.AreEqual(1, folders[0].Folders.First().Folders.Count);
|
||||
Assert.AreEqual("c", folders[0].Folders.First().Folders.First().Name);
|
||||
Assert.AreEqual(1, folders[0].Folders.First().Folders.First().Folders.Count);
|
||||
Assert.AreEqual("d", folders[0].Folders.First().Folders.First().Folders.First().Name);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanAddNestedFoldersWhenRootExistsWithObjectsAtLeaf()
|
||||
{
|
||||
var objects = new List<StorageObject>() { new StorageObject("a/b/c/d/foo", "a"), new StorageObject("a/b/c/d/bar", "a") };
|
||||
|
||||
var converter = new StorageFolderPayloadConverter(new ServiceLocator());
|
||||
var folders = converter.Convert(objects).ToList();
|
||||
|
||||
Assert.AreEqual(1, folders.Count);
|
||||
Assert.AreEqual("a", folders[0].Name);
|
||||
Assert.AreEqual(1, folders[0].Folders.Count);
|
||||
Assert.AreEqual("b", folders[0].Folders.First().Name);
|
||||
Assert.AreEqual(1, folders[0].Folders.First().Folders.Count);
|
||||
Assert.AreEqual("c", folders[0].Folders.First().Folders.First().Name);
|
||||
Assert.AreEqual(1, folders[0].Folders.First().Folders.First().Folders.Count);
|
||||
|
||||
var leaf = folders[0].Folders.First().Folders.First().Folders.First();
|
||||
Assert.AreEqual("d", leaf.Name);
|
||||
Assert.AreEqual(2,leaf.Objects.Count);
|
||||
Assert.IsTrue(leaf.Objects.Any(o => o.FullName == "a/b/c/d/foo"));
|
||||
Assert.IsTrue(leaf.Objects.Any(o => o.FullName == "a/b/c/d/bar"));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanAddNestedFoldersWhenRootExistsWithObjectsAtLeafAndRoot()
|
||||
{
|
||||
var objects = new List<StorageObject>() { new StorageObject("a/b/c/d/foo", "a"), new StorageObject("a/b/c/d/bar", "a"), new StorageObject("xyz", "a") };
|
||||
|
||||
var converter = new StorageFolderPayloadConverter(new ServiceLocator());
|
||||
var folders = converter.Convert(objects).ToList();
|
||||
|
||||
Assert.AreEqual(1, folders.Count);
|
||||
Assert.AreEqual("a", folders[0].Name);
|
||||
Assert.AreEqual(1, folders[0].Folders.Count);
|
||||
Assert.AreEqual("b", folders[0].Folders.First().Name);
|
||||
Assert.AreEqual(1, folders[0].Folders.First().Folders.Count);
|
||||
Assert.AreEqual("c", folders[0].Folders.First().Folders.First().Name);
|
||||
Assert.AreEqual(1, folders[0].Folders.First().Folders.First().Folders.Count);
|
||||
|
||||
var leaf = folders[0].Folders.First().Folders.First().Folders.First();
|
||||
Assert.AreEqual("d", leaf.Name);
|
||||
Assert.AreEqual(2, leaf.Objects.Count);
|
||||
Assert.IsTrue(leaf.Objects.Any(o => o.FullName == "a/b/c/d/foo"));
|
||||
Assert.IsTrue(leaf.Objects.Any(o => o.FullName == "a/b/c/d/bar"));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanAddNestedFoldersWhenRootExistsWithObjectsAtLeafAndLongNameAtRoot()
|
||||
{
|
||||
var objects = new List<StorageObject>() { new StorageObject("a/b/c/d/foo", "a"), new StorageObject("a/b/c/d/bar", "a"), new StorageObject("thiswillsorttothetopofthelist", "a") };
|
||||
|
||||
var converter = new StorageFolderPayloadConverter(new ServiceLocator());
|
||||
var folders = converter.Convert(objects).ToList();
|
||||
|
||||
Assert.AreEqual(1, folders.Count);
|
||||
Assert.AreEqual("a", folders[0].Name);
|
||||
Assert.AreEqual(1, folders[0].Folders.Count);
|
||||
Assert.AreEqual("b", folders[0].Folders.First().Name);
|
||||
Assert.AreEqual(1, folders[0].Folders.First().Folders.Count);
|
||||
Assert.AreEqual("c", folders[0].Folders.First().Folders.First().Name);
|
||||
Assert.AreEqual(1, folders[0].Folders.First().Folders.First().Folders.Count);
|
||||
|
||||
var leaf = folders[0].Folders.First().Folders.First().Folders.First();
|
||||
Assert.AreEqual("d", leaf.Name);
|
||||
Assert.AreEqual(2, leaf.Objects.Count);
|
||||
Assert.IsTrue(leaf.Objects.Any(o => o.FullName == "a/b/c/d/foo"));
|
||||
Assert.IsTrue(leaf.Objects.Any(o => o.FullName == "a/b/c/d/bar"));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanAddNestedFoldersWhenRootExistsWithObjectsAtManyLevels()
|
||||
{
|
||||
var objects = new List<StorageObject>() { new StorageObject("a/b/c/d/foo", "a"),
|
||||
new StorageObject("a/b/bar", "a"),
|
||||
new StorageObject("a/b/c/beans", "a"),
|
||||
new StorageObject("a/string", "a"),
|
||||
new StorageObject("a/b/c/d/", "a") ,
|
||||
new StorageObject("a/b/c/", "a") ,
|
||||
new StorageObject("a/", "a")
|
||||
};
|
||||
|
||||
var converter = new StorageFolderPayloadConverter(new ServiceLocator());
|
||||
var folders = converter.Convert(objects).ToList();
|
||||
|
||||
var aNode = folders[0];
|
||||
var bNode = folders[0].Folders.First();
|
||||
var cNode = folders[0].Folders.First().Folders.First();
|
||||
var dNode = folders[0].Folders.First().Folders.First().Folders.First();
|
||||
|
||||
Assert.AreEqual(1, folders.Count);
|
||||
|
||||
Assert.AreEqual("a", aNode.Name);
|
||||
Assert.AreEqual(1, aNode.Folders.Count);
|
||||
Assert.AreEqual(1, aNode.Objects.Count);
|
||||
Assert.IsTrue(aNode.Objects.Any(o => o.FullName == "a/string"));
|
||||
|
||||
Assert.AreEqual("b", bNode.Name);
|
||||
Assert.AreEqual("a/b", bNode.FullName);
|
||||
Assert.AreEqual(1, bNode.Folders.Count);
|
||||
Assert.AreEqual(1, bNode.Objects.Count);
|
||||
Assert.IsTrue(bNode.Objects.Any(o => o.FullName == "a/b/bar"));
|
||||
|
||||
Assert.AreEqual("c", cNode.Name);
|
||||
Assert.AreEqual("a/b/c", cNode.FullName);
|
||||
Assert.AreEqual(1, cNode.Folders.Count);
|
||||
Assert.AreEqual(1, cNode.Objects.Count);
|
||||
Assert.IsTrue(cNode.Objects.Any(o => o.FullName == "a/b/c/beans"));
|
||||
|
||||
Assert.AreEqual("d", dNode.Name);
|
||||
Assert.AreEqual("a/b/c/d", dNode.FullName);
|
||||
Assert.AreEqual(1, dNode.Objects.Count);
|
||||
Assert.IsTrue(dNode.Objects.Any(o => o.FullName == "a/b/c/d/foo"));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanConvertFoldersWithObjects()
|
||||
{
|
||||
var objects = new List<StorageObject>()
|
||||
{
|
||||
new StorageObject("a", "a"),
|
||||
new StorageObject("a/", "a"),
|
||||
new StorageObject("b//", "a"),
|
||||
new StorageObject("//a/", "a"),
|
||||
new StorageObject("a/b/", "a", DateTime.Now, "12345", 100, "application/directory")
|
||||
};
|
||||
|
||||
var converter = new StorageFolderPayloadConverter(new ServiceLocator());
|
||||
var resp = converter.Convert(objects).ToList();
|
||||
|
||||
Assert.AreEqual(1, resp.Count);
|
||||
|
||||
var aNode = resp.First();
|
||||
Assert.AreEqual("a", aNode.Name);
|
||||
Assert.AreEqual(1, aNode.Folders.Count);
|
||||
Assert.AreEqual(0, aNode.Objects.Count);
|
||||
|
||||
var bNode = aNode.Folders.First();
|
||||
Assert.AreEqual("b", bNode.Name);
|
||||
Assert.AreEqual("a/b", bNode.FullName);
|
||||
Assert.AreEqual(0, bNode.Folders.Count);
|
||||
Assert.AreEqual(0, bNode.Objects.Count);
|
||||
|
||||
Assert.AreEqual(5, objects.Count);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanConvertFoldersWithNoInputObjects()
|
||||
{
|
||||
var objects = new List<StorageObject>();
|
||||
|
||||
var converter = new StorageFolderPayloadConverter(new ServiceLocator());
|
||||
var resp = converter.Convert(objects).ToList();
|
||||
|
||||
Assert.AreEqual(0, resp.Count);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(ArgumentNullException))]
|
||||
public void CannotConvertFoldersWithNullObjectList()
|
||||
{
|
||||
var converter = new StorageFolderPayloadConverter(new ServiceLocator());
|
||||
var resp = converter.Convert(null);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanConvertFolderWithValidJsonAndNoSubFoldersOrFolderObject()
|
||||
{
|
||||
var containerName = "container";
|
||||
var folderName = "a/b/c/";
|
||||
var payload = @"[
|
||||
{
|
||||
""hash"": ""d41d8cd98f00b204e9800998ecf8427e"",
|
||||
""last_modified"": ""2014-03-07T21:31:31.588170"",
|
||||
""bytes"": 0,
|
||||
""name"": ""a/b/c/BLAH"",
|
||||
""content_type"": ""application/octet-stream""
|
||||
}]";
|
||||
|
||||
var converter = new StorageFolderPayloadConverter(new ServiceLocator());
|
||||
var resp = converter.Convert(containerName, folderName, payload);
|
||||
|
||||
Assert.AreEqual(1, resp.Objects.Count);
|
||||
Assert.AreEqual(0, resp.Folders.Count);
|
||||
Assert.AreEqual("a/b/c/", resp.FullName);
|
||||
Assert.AreEqual("c", resp.Name);
|
||||
|
||||
var obj = resp.Objects.First();
|
||||
Assert.AreEqual("a/b/c/BLAH", obj.FullName);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(InvalidDataException))]
|
||||
public void CannotConvertEmptyJsonArrayPayload()
|
||||
{
|
||||
var containerName = "container";
|
||||
var folderName = "a/b/c/";
|
||||
var payload = @"[]";
|
||||
|
||||
var converter = new StorageFolderPayloadConverter(new ServiceLocator());
|
||||
converter.Convert(containerName, folderName, payload);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanConvertFolderWithValidJsonFolderObjectAndNoSubFolders()
|
||||
{
|
||||
var containerName = "container";
|
||||
var folderName = "a/b/c/";
|
||||
var payload = @"[
|
||||
{
|
||||
""hash"": ""d41d8cd98f00b204e9800998ecf8427e"",
|
||||
""last_modified"": ""2014-03-07T21:31:31.588170"",
|
||||
""bytes"": 0,
|
||||
""name"": ""a/b/c/"",
|
||||
""content_type"": ""application/octet-stream""
|
||||
},
|
||||
{
|
||||
""hash"": ""d41d8cd98f00b204e9800998ecf8427e"",
|
||||
""last_modified"": ""2014-03-07T21:31:31.588170"",
|
||||
""bytes"": 0,
|
||||
""name"": ""a/b/c/BLAH"",
|
||||
""content_type"": ""application/octet-stream""
|
||||
}]";
|
||||
|
||||
var converter = new StorageFolderPayloadConverter(new ServiceLocator());
|
||||
var resp = converter.Convert(containerName, folderName, payload);
|
||||
|
||||
Assert.AreEqual(1, resp.Objects.Count);
|
||||
Assert.AreEqual(0, resp.Folders.Count);
|
||||
Assert.AreEqual("a/b/c/", resp.FullName);
|
||||
Assert.AreEqual("c", resp.Name);
|
||||
|
||||
var obj = resp.Objects.First();
|
||||
Assert.AreEqual("a/b/c/BLAH", obj.FullName);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanConvertFolderWithValidJsonSubFoldersAndNoFolderObject()
|
||||
{
|
||||
var containerName = "container";
|
||||
var folderName = "a/b/c/";
|
||||
var payload = @"[
|
||||
{
|
||||
""hash"": ""d41d8cd98f00b204e9800998ecf8427e"",
|
||||
""last_modified"": ""2014-03-07T21:31:31.588170"",
|
||||
""bytes"": 0,
|
||||
""name"": ""a/b/c/BLAH"",
|
||||
""content_type"": ""application/octet-stream""
|
||||
},
|
||||
{
|
||||
""subdir"": ""a/b/c/d/""
|
||||
},
|
||||
{
|
||||
""subdir"": ""a/b/c/x/""
|
||||
}]";
|
||||
|
||||
var converter = new StorageFolderPayloadConverter(new ServiceLocator());
|
||||
var resp = converter.Convert(containerName, folderName, payload);
|
||||
|
||||
Assert.AreEqual(1, resp.Objects.Count);
|
||||
Assert.AreEqual(2, resp.Folders.Count);
|
||||
Assert.AreEqual("a/b/c/", resp.FullName);
|
||||
Assert.AreEqual("c", resp.Name);
|
||||
|
||||
var obj = resp.Objects.First();
|
||||
Assert.AreEqual("a/b/c/BLAH", obj.FullName);
|
||||
|
||||
var dNode = resp.Folders.First(f => f.FullName == "a/b/c/d/");
|
||||
var xNode = resp.Folders.First(f => f.FullName == "a/b/c/x/");
|
||||
|
||||
Assert.AreEqual("d", dNode.Name);
|
||||
Assert.AreEqual(0, dNode.Folders.Count);
|
||||
Assert.AreEqual(0, dNode.Objects.Count);
|
||||
|
||||
Assert.AreEqual("x", xNode.Name);
|
||||
Assert.AreEqual(0, xNode.Folders.Count);
|
||||
Assert.AreEqual(0, xNode.Objects.Count);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanConvertFolderWithValidJsonFolderObjectAndSubFolders()
|
||||
{
|
||||
var containerName = "container";
|
||||
var folderName = "a/b/c/";
|
||||
var payload = @"[
|
||||
{
|
||||
""hash"": ""d41d8cd98f00b204e9800998ecf8427e"",
|
||||
""last_modified"": ""2014-03-07T21:31:31.588170"",
|
||||
""bytes"": 0,
|
||||
""name"": ""a/b/c/"",
|
||||
""content_type"": ""application/octet-stream""
|
||||
},
|
||||
{
|
||||
""hash"": ""d41d8cd98f00b204e9800998ecf8427e"",
|
||||
""last_modified"": ""2014-03-07T21:31:31.588170"",
|
||||
""bytes"": 0,
|
||||
""name"": ""a/b/c/BLAH"",
|
||||
""content_type"": ""application/octet-stream""
|
||||
},
|
||||
{
|
||||
""subdir"": ""a/b/c/d/""
|
||||
},
|
||||
{
|
||||
""subdir"": ""a/b/c/x/""
|
||||
}
|
||||
]";
|
||||
|
||||
var converter = new StorageFolderPayloadConverter(new ServiceLocator());
|
||||
var resp = converter.Convert(containerName, folderName, payload);
|
||||
|
||||
Assert.AreEqual("c", resp.Name);
|
||||
Assert.AreEqual("a/b/c/", resp.FullName);
|
||||
Assert.AreEqual(1, resp.Objects.Count);
|
||||
Assert.AreEqual(2, resp.Folders.Count);
|
||||
|
||||
var obj = resp.Objects.First();
|
||||
Assert.AreEqual("a/b/c/BLAH", obj.FullName);
|
||||
|
||||
var dNode = resp.Folders.First(f => f.FullName == "a/b/c/d/");
|
||||
var xNode = resp.Folders.First(f => f.FullName == "a/b/c/x/");
|
||||
|
||||
Assert.AreEqual("d", dNode.Name);
|
||||
Assert.AreEqual(0, dNode.Folders.Count);
|
||||
Assert.AreEqual(0, dNode.Objects.Count);
|
||||
|
||||
Assert.AreEqual("x", xNode.Name);
|
||||
Assert.AreEqual(0, xNode.Folders.Count);
|
||||
Assert.AreEqual(0, xNode.Objects.Count);
|
||||
}
|
||||
}
|
||||
}
|
@ -1,68 +0,0 @@
|
||||
// /* ============================================================================
|
||||
// Copyright 2014 Hewlett Packard
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ============================================================================ */
|
||||
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
using OpenStack.Storage;
|
||||
|
||||
namespace OpenStack.Test.Storage
|
||||
{
|
||||
[TestClass]
|
||||
public class StorageFolderTests
|
||||
{
|
||||
[TestMethod]
|
||||
public void CanCreateFolder()
|
||||
{
|
||||
var folder = new StorageFolder("MyFolder", new List<StorageFolder>());
|
||||
Assert.AreEqual("MyFolder", folder.FullName);
|
||||
Assert.AreEqual("MyFolder", folder.Name);
|
||||
Assert.AreEqual(0,folder.Folders.Count());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanCreateFolderWithLeadingSlashes()
|
||||
{
|
||||
var expectedFullFolderName = "//MyFolder";
|
||||
var expectedFolderName = "MyFolder";
|
||||
var folder = new StorageFolder("//MyFolder", new List<StorageFolder>());
|
||||
Assert.AreEqual(expectedFullFolderName, folder.FullName);
|
||||
Assert.AreEqual(expectedFolderName, folder.Name);
|
||||
Assert.AreEqual(0, folder.Folders.Count());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanCreateFolderWithTrailingSlashes()
|
||||
{
|
||||
var expectedFullFolderName = "MyFolder//";
|
||||
var expectedFolderName = "MyFolder";
|
||||
var folder = new StorageFolder("MyFolder//", new List<StorageFolder>());
|
||||
Assert.AreEqual(expectedFullFolderName, folder.FullName);
|
||||
Assert.AreEqual(expectedFolderName, folder.Name);
|
||||
Assert.AreEqual(0, folder.Folders.Count());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanCreateFolderWithMultipleFoldersInName()
|
||||
{
|
||||
var expectedFolderName = "MyFolder";
|
||||
var folder = new StorageFolder("//Some/Folder/MyFolder", new List<StorageFolder>());
|
||||
Assert.AreEqual("//Some/Folder/MyFolder", folder.FullName);
|
||||
Assert.AreEqual(expectedFolderName, folder.Name);
|
||||
Assert.AreEqual(0, folder.Folders.Count());
|
||||
}
|
||||
}
|
||||
}
|
@ -1,105 +0,0 @@
|
||||
// /* ============================================================================
|
||||
// Copyright 2014 Hewlett Packard
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ============================================================================ */
|
||||
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
using OpenStack.Storage;
|
||||
|
||||
namespace OpenStack.Test.Storage
|
||||
{
|
||||
[TestClass]
|
||||
public class StorageItemTests
|
||||
{
|
||||
[TestMethod]
|
||||
public void CanExtractNameWithNoSlashes()
|
||||
{
|
||||
var expectedFolderName = "myFolder";
|
||||
var folderName = StorageItem.ExtractName("myFolder");
|
||||
Assert.AreEqual(expectedFolderName, folderName);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanExtractNameWithLeadingSlash()
|
||||
{
|
||||
var expectedFolderName = "myFolder";
|
||||
var folderName = StorageItem.ExtractName("/myFolder");
|
||||
Assert.AreEqual(expectedFolderName, folderName);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanExtractNameWithTrailingSlash()
|
||||
{
|
||||
var expectedFolderName = "myFolder";
|
||||
var folderName = StorageItem.ExtractName("myFolder/");
|
||||
Assert.AreEqual(expectedFolderName, folderName);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanExtractNameWithTrailingAndLeadingSlash()
|
||||
{
|
||||
var expectedFolderName = "myFolder";
|
||||
var folderName = StorageItem.ExtractName("/myFolder/");
|
||||
Assert.AreEqual(expectedFolderName, folderName);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanExtractNameWithJustSlash()
|
||||
{
|
||||
var expectedFolderName = string.Empty;
|
||||
var folderName = StorageItem.ExtractName("/");
|
||||
Assert.AreEqual(expectedFolderName, folderName);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanExtractNameWithDoubleLeadingSlash()
|
||||
{
|
||||
var expectedFolderName = "MyFolder";
|
||||
var folderName = StorageItem.ExtractName("//MyFolder");
|
||||
Assert.AreEqual(expectedFolderName, folderName);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanExtractNameWithDoubleTrailingSlash()
|
||||
{
|
||||
var expectedFolderName = "MyFolder";
|
||||
var folderName = StorageItem.ExtractName("MyFolder//");
|
||||
Assert.AreEqual(expectedFolderName, folderName);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanExtractNameWithDoubleTrailingAndLeadingSlashes()
|
||||
{
|
||||
var expectedFolderName = "MyFolder";
|
||||
var folderName = StorageItem.ExtractName("//MyFolder//");
|
||||
Assert.AreEqual(expectedFolderName, folderName);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanExtractNameWithMultipleFolders()
|
||||
{
|
||||
var expectedFolderName = "MyFolder";
|
||||
var folderName = StorageItem.ExtractName("Folder1/Folder2/Folder3/MyFolder");
|
||||
Assert.AreEqual(expectedFolderName, folderName);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanExtractNameWithMultipleFoldersAndSlashes()
|
||||
{
|
||||
var expectedFolderName = "MyFolder";
|
||||
var folderName = StorageItem.ExtractName("Folder1//Folder2/Folder3//MyFolder/");
|
||||
Assert.AreEqual(expectedFolderName, folderName);
|
||||
}
|
||||
}
|
||||
}
|
@ -1,834 +0,0 @@
|
||||
// /* ============================================================================
|
||||
// Copyright 2014 Hewlett Packard
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ============================================================================ */
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Web;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using OpenStack.Common.Http;
|
||||
using OpenStack.Storage;
|
||||
|
||||
namespace OpenStack.Test.Storage
|
||||
{
|
||||
[TestClass]
|
||||
public class StorageObjectPayloadConverterTests
|
||||
{
|
||||
[TestMethod]
|
||||
public void CanParseValidJsonPayloadWithMultipleObjects()
|
||||
{
|
||||
var validMultipleObjectJson = @"[
|
||||
{
|
||||
""hash"": ""d41d8cd98f00b204e9800998ecf8427e"",
|
||||
""last_modified"": ""2014-03-07T21:31:31.588170"",
|
||||
""bytes"": 0,
|
||||
""name"": ""BLAH"",
|
||||
""content_type"": ""application/octet-stream""
|
||||
},
|
||||
{
|
||||
""hash"": ""97cdd4bb45c3d5d652c0079901fb4eec"",
|
||||
""last_modified"": ""2014-03-05T01:10:22.786140"",
|
||||
""bytes"": 2147483649,
|
||||
""name"": ""LargeFile.bin"",
|
||||
""content_type"": ""application/octet-stream""
|
||||
}
|
||||
]";
|
||||
|
||||
var converter = new StorageObjectPayloadConverter();
|
||||
var objects = converter.Convert("TestContainer", validMultipleObjectJson).ToList();
|
||||
|
||||
Assert.AreEqual(2,objects.Count());
|
||||
var obj1 =
|
||||
objects.First(o => string.Equals(o.Name, "BLAH", StringComparison.InvariantCultureIgnoreCase));
|
||||
var obj2 =
|
||||
objects.First(o => string.Equals(o.Name, "LargeFile.bin", StringComparison.InvariantCultureIgnoreCase));
|
||||
Assert.IsNotNull(obj1);
|
||||
Assert.IsNotNull(obj2);
|
||||
|
||||
Assert.AreEqual(0,obj1.Length);
|
||||
Assert.AreEqual("d41d8cd98f00b204e9800998ecf8427e", obj1.ETag);
|
||||
Assert.AreEqual("application/octet-stream", obj1.ContentType);
|
||||
Assert.AreEqual(DateTime.Parse("2014-03-07T21:31:31.588170"), obj1.LastModified);
|
||||
Assert.AreEqual("BLAH", obj1.Name);
|
||||
Assert.AreEqual("TestContainer", obj1.ContainerName);
|
||||
|
||||
Assert.AreEqual(2147483649, obj2.Length);
|
||||
Assert.AreEqual("97cdd4bb45c3d5d652c0079901fb4eec", obj2.ETag);
|
||||
Assert.AreEqual("application/octet-stream", obj2.ContentType);
|
||||
Assert.AreEqual(DateTime.Parse("2014-03-05T01:10:22.786140"), obj2.LastModified);
|
||||
Assert.AreEqual("LargeFile.bin", obj2.Name);
|
||||
Assert.AreEqual("TestContainer", obj2.ContainerName);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanParseValidJsonPayloadWithSingleObject()
|
||||
{
|
||||
var validSingleObjectJson = @"[
|
||||
{
|
||||
""hash"": ""d41d8cd98f00b204e9800998ecf8427e"",
|
||||
""last_modified"": ""2014-03-07T21:31:31.588170"",
|
||||
""bytes"": 0,
|
||||
""name"": ""BLAH"",
|
||||
""content_type"": ""application/octet-stream""
|
||||
}]";
|
||||
|
||||
var converter = new StorageObjectPayloadConverter();
|
||||
var objects = converter.Convert("TestContainer", validSingleObjectJson).ToList();
|
||||
|
||||
Assert.AreEqual(1, objects.Count());
|
||||
var obj1 =
|
||||
objects.First(o => string.Equals(o.Name, "BLAH", StringComparison.InvariantCultureIgnoreCase));
|
||||
Assert.IsNotNull(obj1);
|
||||
|
||||
Assert.AreEqual(0, obj1.Length);
|
||||
Assert.AreEqual("d41d8cd98f00b204e9800998ecf8427e", obj1.ETag);
|
||||
Assert.AreEqual("application/octet-stream", obj1.ContentType);
|
||||
Assert.AreEqual(DateTime.Parse("2014-03-07T21:31:31.588170"), obj1.LastModified);
|
||||
Assert.AreEqual("BLAH", obj1.Name);
|
||||
Assert.AreEqual("TestContainer", obj1.ContainerName);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanParseValidEmptyJsonArrayPayload()
|
||||
{
|
||||
var emptyJsonArray = @"[]";
|
||||
|
||||
var converter = new StorageObjectPayloadConverter();
|
||||
var objects = converter.Convert("TestContainer", emptyJsonArray).ToList();
|
||||
|
||||
Assert.AreEqual(0, objects.Count());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanParseAnEmptyPayload()
|
||||
{
|
||||
var payload = string.Empty;
|
||||
|
||||
var converter = new StorageObjectPayloadConverter();
|
||||
var objects = converter.Convert("TestContainer", payload).ToList();
|
||||
|
||||
Assert.AreEqual(0, objects.Count());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(ArgumentNullException))]
|
||||
public void CannotParseANullPayload()
|
||||
{
|
||||
var converter = new StorageObjectPayloadConverter();
|
||||
converter.Convert("TestContainer", null);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(FormatException))]
|
||||
public void CannotParseInvalidJsonPayload()
|
||||
{
|
||||
var converter = new StorageObjectPayloadConverter();
|
||||
converter.Convert("TestContainer", "[ { \"SomeAtrib\" }]");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(FormatException))]
|
||||
public void CannotParseInvalidPayload()
|
||||
{
|
||||
var converter = new StorageObjectPayloadConverter();
|
||||
converter.Convert("TestContainer", "NOT JSON");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(FormatException))]
|
||||
public void CannotParseJsonPayloadWithMissingBytesProperty()
|
||||
{
|
||||
string InvalidJsonWithoutBytes = @"[
|
||||
{
|
||||
""hash"": ""d41d8cd98f00b204e9800998ecf8427e"",
|
||||
""last_modified"": ""2014-03-07T21:31:31.588170"",
|
||||
""name"": ""BLAH"",
|
||||
""content_type"": ""application/octet-stream""
|
||||
}
|
||||
]";
|
||||
|
||||
var converter = new StorageObjectPayloadConverter();
|
||||
converter.Convert("TestContainer", InvalidJsonWithoutBytes);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(FormatException))]
|
||||
public void CannotParseJsonPayloadWithMissingHashProperty()
|
||||
{
|
||||
string InvalidJsonWithoutHash = @"[
|
||||
{
|
||||
""last_modified"": ""2014-03-07T21:31:31.588170"",
|
||||
""bytes"": 0,
|
||||
""name"": ""BLAH"",
|
||||
""content_type"": ""application/octet-stream""
|
||||
}]";
|
||||
|
||||
var converter = new StorageObjectPayloadConverter();
|
||||
converter.Convert("TestContainer", InvalidJsonWithoutHash);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(FormatException))]
|
||||
public void CannotParseJsonPayloadWithMissingModifiedProperty()
|
||||
{
|
||||
string InvalidJsonWithoutLastModified = @"[
|
||||
{
|
||||
""hash"": ""d41d8cd98f00b204e9800998ecf8427e"",
|
||||
""bytes"": 0,
|
||||
""name"": ""BLAH"",
|
||||
""content_type"": ""application/octet-stream""
|
||||
}]";
|
||||
|
||||
var converter = new StorageObjectPayloadConverter();
|
||||
converter.Convert("TestContainer", InvalidJsonWithoutLastModified);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CannotParseJsonPayloadWithMissingNameProperty()
|
||||
{
|
||||
string InvalidJsonWithoutName = @"[
|
||||
{
|
||||
""hash"": ""d41d8cd98f00b204e9800998ecf8427e"",
|
||||
""last_modified"": ""2014-03-07T21:31:31.588170"",
|
||||
""bytes"": 0,
|
||||
""content_type"": ""application/octet-stream""
|
||||
}]";
|
||||
|
||||
var converter = new StorageObjectPayloadConverter();
|
||||
|
||||
try
|
||||
{
|
||||
converter.Convert("TestContainer", InvalidJsonWithoutName);
|
||||
Assert.Fail("Parsing did not fail as expected.");
|
||||
}
|
||||
catch (FormatException ex)
|
||||
{
|
||||
Assert.IsTrue(ex.Message.StartsWith("Storage Object payload could not be parsed."));
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void ParseExceptionIncludesNameWhenPossible()
|
||||
{
|
||||
string InvalidJsonWithoutHash = @"[
|
||||
{
|
||||
""last_modified"": ""2014-03-07T21:31:31.588170"",
|
||||
""bytes"": 0,
|
||||
""name"": ""BLAH"",
|
||||
""content_type"": ""application/octet-stream""
|
||||
}]";
|
||||
|
||||
var converter = new StorageObjectPayloadConverter();
|
||||
try
|
||||
{
|
||||
converter.Convert("TestContainer", InvalidJsonWithoutHash);
|
||||
Assert.Fail("Parsing did not fail as expected.");
|
||||
}
|
||||
catch (FormatException ex)
|
||||
{
|
||||
Assert.IsTrue(ex.Message.StartsWith("Storage Object 'BLAH'"));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(FormatException))]
|
||||
public void CannotParseJsonPayloadWithMissingContentTypeProperty()
|
||||
{
|
||||
string InvalidJsonWithoutContentType = @"[
|
||||
{
|
||||
""hash"": ""d41d8cd98f00b204e9800998ecf8427e"",
|
||||
""last_modified"": ""2014-03-07T21:31:31.588170"",
|
||||
""bytes"": 0,
|
||||
""name"": ""BLAH""
|
||||
}]";
|
||||
|
||||
var converter = new StorageObjectPayloadConverter();
|
||||
converter.Convert("TestContainer", InvalidJsonWithoutContentType);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(FormatException))]
|
||||
public void CannotParseJsonPayloadWithBadModifiedDate()
|
||||
{
|
||||
string InvalidJsonWithBadDateType = @"[
|
||||
{
|
||||
""hash"": ""d41d8cd98f00b204e9800998ecf8427e"",
|
||||
""last_modified"": ""This is not a date"",
|
||||
""bytes"": 0,
|
||||
""name"": ""BLAH"",
|
||||
""content_type"": ""application/octet-stream""
|
||||
}]";
|
||||
|
||||
var converter = new StorageObjectPayloadConverter();
|
||||
converter.Convert("TestContainer", InvalidJsonWithBadDateType);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(FormatException))]
|
||||
public void CannotParseJsonPayloadWithBadBytesValue()
|
||||
{
|
||||
string InvalidJsonWithBadBytesValue = @"[
|
||||
{
|
||||
""hash"": ""d41d8cd98f00b204e9800998ecf8427e"",
|
||||
""last_modified"": ""2014-03-07T21:31:31.588170"",
|
||||
""bytes"": ""This is not a number"",
|
||||
""name"": ""BLAH"",
|
||||
""content_type"": ""application/octet-stream""
|
||||
}]";
|
||||
|
||||
var converter = new StorageObjectPayloadConverter();
|
||||
converter.Convert("TestContainer", InvalidJsonWithBadBytesValue);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanParseObjectFromHeaders()
|
||||
{
|
||||
var containerName = "TestContainer";
|
||||
var objectName = "TestObject";
|
||||
|
||||
var headers = new HttpHeadersAbstraction()
|
||||
{
|
||||
{"Content-Length", "1234"},
|
||||
{"Content-Type", "application/octet-stream"},
|
||||
{"Last-Modified", "Wed, 12 Mar 2014 23:42:23 GMT"},
|
||||
{"ETag", "d41d8cd98f00b204e9800998ecf8427e"}
|
||||
};
|
||||
|
||||
var converter = new StorageObjectPayloadConverter();
|
||||
var obj = converter.Convert(containerName, objectName, headers);
|
||||
|
||||
Assert.IsNotNull(obj);
|
||||
Assert.IsInstanceOfType(obj, typeof(StorageObject));
|
||||
Assert.AreEqual(1234, obj.Length);
|
||||
Assert.AreEqual("d41d8cd98f00b204e9800998ecf8427e", obj.ETag);
|
||||
Assert.AreEqual("application/octet-stream", obj.ContentType);
|
||||
Assert.AreEqual(DateTime.Parse("Wed, 12 Mar 2014 23:42:23 GMT"), obj.LastModified);
|
||||
Assert.AreEqual(objectName, obj.Name);
|
||||
Assert.AreEqual(containerName, obj.ContainerName);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanParseObjectFromHeadersAndSpecificObjectLength()
|
||||
{
|
||||
var containerName = "TestContainer";
|
||||
var objectName = "TestObject";
|
||||
|
||||
var headers = new HttpHeadersAbstraction()
|
||||
{
|
||||
{"Content-Length", "1234"},
|
||||
{"Content-Type", "application/octet-stream"},
|
||||
{"Last-Modified", "Wed, 12 Mar 2014 23:42:23 GMT"},
|
||||
{"ETag", "d41d8cd98f00b204e9800998ecf8427e"}
|
||||
};
|
||||
|
||||
var converter = new StorageObjectPayloadConverter();
|
||||
var obj = converter.Convert(containerName, objectName, headers, 100);
|
||||
|
||||
Assert.IsNotNull(obj);
|
||||
Assert.IsInstanceOfType(obj, typeof(StorageObject));
|
||||
Assert.AreEqual(100, obj.Length);
|
||||
Assert.AreEqual("d41d8cd98f00b204e9800998ecf8427e", obj.ETag);
|
||||
Assert.AreEqual("application/octet-stream", obj.ContentType);
|
||||
Assert.AreEqual(DateTime.Parse("Wed, 12 Mar 2014 23:42:23 GMT"), obj.LastModified);
|
||||
Assert.AreEqual(objectName, obj.Name);
|
||||
Assert.AreEqual(containerName, obj.ContainerName);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanParseObjectFromHeadersWithMetadata()
|
||||
{
|
||||
var containerName = "TestContainer";
|
||||
var objectName = "TestObject";
|
||||
|
||||
var headers = new HttpHeadersAbstraction()
|
||||
{
|
||||
{"Content-Length", "1234"},
|
||||
{"Content-Type", "application/octet-stream"},
|
||||
{"Last-Modified", "Wed, 12 Mar 2014 23:42:23 GMT"},
|
||||
{"ETag", "d41d8cd98f00b204e9800998ecf8427e"},
|
||||
{"X-Object-Meta-Test1","Test1"}
|
||||
};
|
||||
|
||||
var converter = new StorageObjectPayloadConverter();
|
||||
var obj = converter.Convert(containerName, objectName, headers);
|
||||
|
||||
Assert.IsNotNull(obj);
|
||||
Assert.IsInstanceOfType(obj, typeof(StorageObject));
|
||||
Assert.AreEqual(1234, obj.Length);
|
||||
Assert.AreEqual("d41d8cd98f00b204e9800998ecf8427e", obj.ETag);
|
||||
Assert.AreEqual("application/octet-stream", obj.ContentType);
|
||||
Assert.AreEqual(DateTime.Parse("Wed, 12 Mar 2014 23:42:23 GMT"), obj.LastModified);
|
||||
Assert.AreEqual(objectName, obj.Name);
|
||||
Assert.AreEqual(containerName, obj.ContainerName);
|
||||
Assert.AreEqual(1, obj.Metadata.Count());
|
||||
Assert.IsTrue(obj.Metadata.ContainsKey("Test1"));
|
||||
Assert.AreEqual("Test1", obj.Metadata["Test1"]);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanParseStaticManifestFromHeadersWithMetadata()
|
||||
{
|
||||
var containerName = "TestContainer";
|
||||
var objectName = "TestObject";
|
||||
|
||||
var headers = new HttpHeadersAbstraction()
|
||||
{
|
||||
{"Content-Length", "1234"},
|
||||
{"Content-Type", "application/octet-stream"},
|
||||
{"Last-Modified", "Wed, 12 Mar 2014 23:42:23 GMT"},
|
||||
{"ETag", "d41d8cd98f00b204e9800998ecf8427e"},
|
||||
{"X-Object-Meta-Test1","Test1"},
|
||||
{"X-Static-Large-Object","True"}
|
||||
};
|
||||
|
||||
var converter = new StorageObjectPayloadConverter();
|
||||
var obj = converter.Convert(containerName, objectName, headers);
|
||||
|
||||
Assert.IsNotNull(obj);
|
||||
Assert.IsInstanceOfType(obj, typeof(StaticLargeObjectManifest));
|
||||
Assert.AreEqual(1234, obj.Length);
|
||||
Assert.AreEqual("d41d8cd98f00b204e9800998ecf8427e", obj.ETag);
|
||||
Assert.AreEqual("application/octet-stream", obj.ContentType);
|
||||
Assert.AreEqual(DateTime.Parse("Wed, 12 Mar 2014 23:42:23 GMT"), obj.LastModified);
|
||||
Assert.AreEqual(objectName, obj.Name);
|
||||
Assert.AreEqual(containerName, obj.ContainerName);
|
||||
Assert.AreEqual(1, obj.Metadata.Count());
|
||||
Assert.IsTrue(obj.Metadata.ContainsKey("Test1"));
|
||||
Assert.AreEqual("Test1", obj.Metadata["Test1"]);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanParseObjectFromHeadersWithStaticManifestFlagSetToNonTrue()
|
||||
{
|
||||
var containerName = "TestContainer";
|
||||
var objectName = "TestObject";
|
||||
|
||||
var headers = new HttpHeadersAbstraction()
|
||||
{
|
||||
{"Content-Length", "1234"},
|
||||
{"Content-Type", "application/octet-stream"},
|
||||
{"Last-Modified", "Wed, 12 Mar 2014 23:42:23 GMT"},
|
||||
{"ETag", "d41d8cd98f00b204e9800998ecf8427e"},
|
||||
{"X-Object-Meta-Test1","Test1"},
|
||||
{"X-Static-Large-Object","False"}
|
||||
};
|
||||
|
||||
var converter = new StorageObjectPayloadConverter();
|
||||
var obj = converter.Convert(containerName, objectName, headers);
|
||||
|
||||
Assert.IsNotNull(obj);
|
||||
Assert.IsInstanceOfType(obj, typeof(StorageObject));
|
||||
Assert.AreEqual(1234, obj.Length);
|
||||
Assert.AreEqual("d41d8cd98f00b204e9800998ecf8427e", obj.ETag);
|
||||
Assert.AreEqual("application/octet-stream", obj.ContentType);
|
||||
Assert.AreEqual(DateTime.Parse("Wed, 12 Mar 2014 23:42:23 GMT"), obj.LastModified);
|
||||
Assert.AreEqual(objectName, obj.Name);
|
||||
Assert.AreEqual(containerName, obj.ContainerName);
|
||||
Assert.AreEqual(1, obj.Metadata.Count());
|
||||
Assert.IsTrue(obj.Metadata.ContainsKey("Test1"));
|
||||
Assert.AreEqual("Test1", obj.Metadata["Test1"]);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanParseObjectFromHeadersWithStaticManifestFlagSetToNull()
|
||||
{
|
||||
var containerName = "TestContainer";
|
||||
var objectName = "TestObject";
|
||||
|
||||
var headers = new HttpHeadersAbstraction()
|
||||
{
|
||||
{"Content-Length", "1234"},
|
||||
{"Content-Type", "application/octet-stream"},
|
||||
{"Last-Modified", "Wed, 12 Mar 2014 23:42:23 GMT"},
|
||||
{"ETag", "d41d8cd98f00b204e9800998ecf8427e"},
|
||||
{"X-Object-Meta-Test1","Test1"},
|
||||
{"X-Static-Large-Object", (string)null}
|
||||
};
|
||||
|
||||
var converter = new StorageObjectPayloadConverter();
|
||||
var obj = converter.Convert(containerName, objectName, headers);
|
||||
|
||||
Assert.IsNotNull(obj);
|
||||
Assert.IsInstanceOfType(obj, typeof(StorageObject));
|
||||
Assert.AreEqual(1234, obj.Length);
|
||||
Assert.AreEqual("d41d8cd98f00b204e9800998ecf8427e", obj.ETag);
|
||||
Assert.AreEqual("application/octet-stream", obj.ContentType);
|
||||
Assert.AreEqual(DateTime.Parse("Wed, 12 Mar 2014 23:42:23 GMT"), obj.LastModified);
|
||||
Assert.AreEqual(objectName, obj.Name);
|
||||
Assert.AreEqual(containerName, obj.ContainerName);
|
||||
Assert.AreEqual(1, obj.Metadata.Count());
|
||||
Assert.IsTrue(obj.Metadata.ContainsKey("Test1"));
|
||||
Assert.AreEqual("Test1", obj.Metadata["Test1"]);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanParseObjectFromHeadersWithDynamicFlagSetToNull()
|
||||
{
|
||||
var containerName = "TestContainer";
|
||||
var objectName = "TestObject";
|
||||
|
||||
var headers = new HttpHeadersAbstraction()
|
||||
{
|
||||
{"Content-Length", "1234"},
|
||||
{"Content-Type", "application/octet-stream"},
|
||||
{"Last-Modified", "Wed, 12 Mar 2014 23:42:23 GMT"},
|
||||
{"ETag", "d41d8cd98f00b204e9800998ecf8427e"},
|
||||
{"X-Object-Meta-Test1","Test1"},
|
||||
{"X-Object-Manifest", (string)null}
|
||||
};
|
||||
|
||||
var converter = new StorageObjectPayloadConverter();
|
||||
var obj = converter.Convert(containerName, objectName, headers);
|
||||
|
||||
Assert.IsNotNull(obj);
|
||||
Assert.IsInstanceOfType(obj, typeof(StorageObject));
|
||||
Assert.AreEqual(1234, obj.Length);
|
||||
Assert.AreEqual("d41d8cd98f00b204e9800998ecf8427e", obj.ETag);
|
||||
Assert.AreEqual("application/octet-stream", obj.ContentType);
|
||||
Assert.AreEqual(DateTime.Parse("Wed, 12 Mar 2014 23:42:23 GMT"), obj.LastModified);
|
||||
Assert.AreEqual(objectName, obj.Name);
|
||||
Assert.AreEqual(containerName, obj.ContainerName);
|
||||
Assert.AreEqual(1, obj.Metadata.Count());
|
||||
Assert.IsTrue(obj.Metadata.ContainsKey("Test1"));
|
||||
Assert.AreEqual("Test1", obj.Metadata["Test1"]);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanParseObjectFromHeadersWithDynamicFlagSetToEmpty()
|
||||
{
|
||||
var containerName = "TestContainer";
|
||||
var objectName = "TestObject";
|
||||
|
||||
var headers = new HttpHeadersAbstraction()
|
||||
{
|
||||
{"Content-Length", "1234"},
|
||||
{"Content-Type", "application/octet-stream"},
|
||||
{"Last-Modified", "Wed, 12 Mar 2014 23:42:23 GMT"},
|
||||
{"ETag", "d41d8cd98f00b204e9800998ecf8427e"},
|
||||
{"X-Object-Meta-Test1","Test1"},
|
||||
{"X-Object-Manifest", string.Empty}
|
||||
};
|
||||
|
||||
var converter = new StorageObjectPayloadConverter();
|
||||
var obj = converter.Convert(containerName, objectName, headers);
|
||||
|
||||
Assert.IsNotNull(obj);
|
||||
Assert.IsInstanceOfType(obj, typeof(StorageObject));
|
||||
Assert.AreEqual(1234, obj.Length);
|
||||
Assert.AreEqual("d41d8cd98f00b204e9800998ecf8427e", obj.ETag);
|
||||
Assert.AreEqual("application/octet-stream", obj.ContentType);
|
||||
Assert.AreEqual(DateTime.Parse("Wed, 12 Mar 2014 23:42:23 GMT"), obj.LastModified);
|
||||
Assert.AreEqual(objectName, obj.Name);
|
||||
Assert.AreEqual(containerName, obj.ContainerName);
|
||||
Assert.AreEqual(1, obj.Metadata.Count());
|
||||
Assert.IsTrue(obj.Metadata.ContainsKey("Test1"));
|
||||
Assert.AreEqual("Test1", obj.Metadata["Test1"]);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanParseDynamicManifestFromHeadersWithMetadata()
|
||||
{
|
||||
var containerName = "TestContainer";
|
||||
var objectName = "TestObject";
|
||||
|
||||
var headers = new HttpHeadersAbstraction()
|
||||
{
|
||||
{"Content-Length", "1234"},
|
||||
{"Content-Type", "application/octet-stream"},
|
||||
{"Last-Modified", "Wed, 12 Mar 2014 23:42:23 GMT"},
|
||||
{"ETag", "d41d8cd98f00b204e9800998ecf8427e"},
|
||||
{"X-Object-Meta-Test1","Test1"},
|
||||
{"X-Object-Manifest","a/b"}
|
||||
};
|
||||
|
||||
var converter = new StorageObjectPayloadConverter();
|
||||
var obj = converter.Convert(containerName, objectName, headers);
|
||||
|
||||
Assert.IsNotNull(obj);
|
||||
Assert.IsInstanceOfType(obj, typeof(DynamicLargeObjectManifest));
|
||||
Assert.AreEqual(1234, obj.Length);
|
||||
Assert.AreEqual("d41d8cd98f00b204e9800998ecf8427e", obj.ETag);
|
||||
Assert.AreEqual("application/octet-stream", obj.ContentType);
|
||||
Assert.AreEqual(DateTime.Parse("Wed, 12 Mar 2014 23:42:23 GMT"), obj.LastModified);
|
||||
Assert.AreEqual(objectName, obj.Name);
|
||||
Assert.AreEqual(containerName, obj.ContainerName);
|
||||
Assert.AreEqual(1, obj.Metadata.Count());
|
||||
Assert.IsTrue(obj.Metadata.ContainsKey("Test1"));
|
||||
Assert.AreEqual("Test1", obj.Metadata["Test1"]);
|
||||
|
||||
var manifest = obj as DynamicLargeObjectManifest;
|
||||
Assert.AreEqual("a/b", manifest.SegmentsPath);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(ArgumentNullException))]
|
||||
public void CannotParseWithANullObjectName()
|
||||
{
|
||||
var containerName = "TestContainer";
|
||||
|
||||
var headers = new HttpHeadersAbstraction()
|
||||
{
|
||||
{"Content-Length", "1234"},
|
||||
{"Content-Type", "application/octet-stream"},
|
||||
{"Last-Modified", "Wed, 12 Mar 2014 23:42:23 GMT"},
|
||||
{"Etag", "d41d8cd98f00b204e9800998ecf8427e"}
|
||||
};
|
||||
|
||||
var converter = new StorageObjectPayloadConverter();
|
||||
converter.Convert(containerName, null, headers);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(ArgumentException))]
|
||||
public void CannotParseWithAnEmptyConatinerName()
|
||||
{
|
||||
var containerName = string.Empty;
|
||||
var objectName = "TestObject";
|
||||
|
||||
var headers = new HttpHeadersAbstraction()
|
||||
{
|
||||
{"Content-Length", "1234"},
|
||||
{"Content-Type", "application/octet-stream"},
|
||||
{"Last-Modified", "Wed, 12 Mar 2014 23:42:23 GMT"},
|
||||
{"Etag", "d41d8cd98f00b204e9800998ecf8427e"}
|
||||
};
|
||||
|
||||
var converter = new StorageObjectPayloadConverter();
|
||||
converter.Convert(containerName, objectName, headers);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(ArgumentNullException))]
|
||||
public void CannotParseWithNullHeaders()
|
||||
{
|
||||
var containerName = "TestContainer";
|
||||
var objectName = "TestObject";
|
||||
|
||||
var converter = new StorageObjectPayloadConverter();
|
||||
converter.Convert(containerName, objectName, null);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(ArgumentException))]
|
||||
public void CannotParseWithAnEmptyObjectName()
|
||||
{
|
||||
var containerName = "TestContainer";
|
||||
var objectName =string.Empty;
|
||||
|
||||
var headers = new HttpHeadersAbstraction()
|
||||
{
|
||||
{"Content-Length", "1234"},
|
||||
{"Content-Type", "application/octet-stream"},
|
||||
{"Last-Modified", "Wed, 12 Mar 2014 23:42:23 GMT"},
|
||||
{"Etag", "d41d8cd98f00b204e9800998ecf8427e"}
|
||||
};
|
||||
|
||||
var converter = new StorageObjectPayloadConverter();
|
||||
converter.Convert(containerName, objectName, headers);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(ArgumentNullException))]
|
||||
public void CannotParseWithNullConatinerName()
|
||||
{
|
||||
var objectName = "TestObject";
|
||||
|
||||
var headers = new HttpHeadersAbstraction()
|
||||
{
|
||||
{"Content-Length", "1234"},
|
||||
{"Content-Type", "application/octet-stream"},
|
||||
{"Last-Modified", "Wed, 12 Mar 2014 23:42:23 GMT"},
|
||||
{"Etag", "d41d8cd98f00b204e9800998ecf8427e"}
|
||||
};
|
||||
|
||||
var converter = new StorageObjectPayloadConverter();
|
||||
converter.Convert(null, objectName, headers);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(FormatException))]
|
||||
public void CannotParseWithMissingContentLengthHeader()
|
||||
{
|
||||
var containerName = "TestContainer";
|
||||
var objectName = "TestObject";
|
||||
|
||||
var headers = new HttpHeadersAbstraction()
|
||||
{
|
||||
{"Content-Length", "1234"},
|
||||
{"Last-Modified", "Wed, 12 Mar 2014 23:42:23 GMT"},
|
||||
{"Etag", "d41d8cd98f00b204e9800998ecf8427e"}
|
||||
};
|
||||
|
||||
var converter = new StorageObjectPayloadConverter();
|
||||
converter.Convert(containerName, objectName, headers);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(FormatException))]
|
||||
public void CannotParseWithMissingETagHeader()
|
||||
{
|
||||
var containerName = "TestContainer";
|
||||
var objectName = "TestObject";
|
||||
|
||||
var headers = new HttpHeadersAbstraction()
|
||||
{
|
||||
{"Content-Length", "1234"},
|
||||
{"Content-Type", "application/octet-stream"},
|
||||
{"Last-Modified", "Wed, 12 Mar 2014 23:42:23 GMT"}
|
||||
};
|
||||
|
||||
var converter = new StorageObjectPayloadConverter();
|
||||
converter.Convert(containerName, objectName, headers);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(FormatException))]
|
||||
public void CannotParseWithMissingModifiedHeader()
|
||||
{
|
||||
var containerName = "TestContainer";
|
||||
var objectName = "TestObject";
|
||||
|
||||
var headers = new HttpHeadersAbstraction()
|
||||
{
|
||||
{"Content-Length", "1234"},
|
||||
{"Content-Type", "application/octet-stream"},
|
||||
{"Etag", "d41d8cd98f00b204e9800998ecf8427e"}
|
||||
};
|
||||
|
||||
var converter = new StorageObjectPayloadConverter();
|
||||
converter.Convert(containerName, objectName, headers);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(FormatException))]
|
||||
public void CannotParseWithMissingContentTypeHeader()
|
||||
{
|
||||
var containerName = "TestContainer";
|
||||
var objectName = "TestObject";
|
||||
|
||||
var headers = new HttpHeadersAbstraction()
|
||||
{
|
||||
{"Content-Length", "1234"},
|
||||
{"Last-Modified", "Wed, 12 Mar 2014 23:42:23 GMT"},
|
||||
{"Etag", "d41d8cd98f00b204e9800998ecf8427e"}
|
||||
};
|
||||
|
||||
var converter = new StorageObjectPayloadConverter();
|
||||
converter.Convert(containerName, objectName, headers);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(FormatException))]
|
||||
public void CannotParseWithBadModifiedDateHeader()
|
||||
{
|
||||
var containerName = "TestContainer";
|
||||
var objectName = "TestObject";
|
||||
|
||||
var headers = new HttpHeadersAbstraction()
|
||||
{
|
||||
{"Content-Length", "1234"},
|
||||
{"Content-Type", "application/octet-stream"},
|
||||
{"Last-Modified", "This is not a date"},
|
||||
{"Etag", "d41d8cd98f00b204e9800998ecf8427e"}
|
||||
};
|
||||
|
||||
var converter = new StorageObjectPayloadConverter();
|
||||
converter.Convert(containerName, objectName, headers);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(FormatException))]
|
||||
public void CannotParseWithBadBytesHeader()
|
||||
{
|
||||
var containerName = "TestContainer";
|
||||
var objectName = "TestObject";
|
||||
|
||||
var headers = new HttpHeadersAbstraction()
|
||||
{
|
||||
{"Content-Length", "This is not a number"},
|
||||
{"Content-Type", "application/octet-stream"},
|
||||
{"Last-Modified", "Wed, 12 Mar 2014 23:42:23 GMT"},
|
||||
{"Etag", "d41d8cd98f00b204e9800998ecf8427e"}
|
||||
};
|
||||
|
||||
var converter = new StorageObjectPayloadConverter();
|
||||
converter.Convert(containerName, objectName, headers);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanConvertSingleStorageObjectToJson()
|
||||
{
|
||||
var obj = new StorageObject("a/b/c", "TestContainer", DateTime.UtcNow, "12345", 54321, string.Empty,
|
||||
new Dictionary<string, string>());
|
||||
|
||||
var converter = new StorageObjectPayloadConverter();
|
||||
var payload = converter.Convert(new List<StorageObject>() { obj});
|
||||
|
||||
var result = JArray.Parse(payload);
|
||||
Assert.AreEqual(1,result.Count);
|
||||
|
||||
var item = result[0];
|
||||
Assert.AreEqual("TestContainer/a/b/c", item["path"]);
|
||||
Assert.AreEqual(54321, item["size_bytes"]);
|
||||
Assert.AreEqual("12345", item["etag"]);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanConvertMultipleStorageObjectToJson()
|
||||
{
|
||||
var obj = new StorageObject("a/b/c", "TestContainer", DateTime.UtcNow, "12345", 54321, string.Empty,
|
||||
new Dictionary<string, string>());
|
||||
|
||||
var obj2 = new StorageObject("a/b/d", "TestContainer", DateTime.UtcNow, "00000", 11111, string.Empty,
|
||||
new Dictionary<string, string>());
|
||||
|
||||
var converter = new StorageObjectPayloadConverter();
|
||||
var payload = converter.Convert(new List<StorageObject>() { obj, obj2 });
|
||||
|
||||
var result = JArray.Parse(payload);
|
||||
Assert.AreEqual(2, result.Count);
|
||||
|
||||
var item = result[0];
|
||||
Assert.AreEqual("TestContainer/a/b/c", item["path"]);
|
||||
Assert.AreEqual(54321, item["size_bytes"]);
|
||||
Assert.AreEqual("12345", item["etag"]);
|
||||
|
||||
var item2 = result[1];
|
||||
Assert.AreEqual("TestContainer/a/b/d", item2["path"]);
|
||||
Assert.AreEqual(11111, item2["size_bytes"]);
|
||||
Assert.AreEqual("00000", item2["etag"]);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanConvertEmptyStorageObjectsToJson()
|
||||
{
|
||||
var converter = new StorageObjectPayloadConverter();
|
||||
var payload = converter.Convert(new List<StorageObject>());
|
||||
var result = JArray.Parse(payload);
|
||||
Assert.AreEqual(0, result.Count);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(ArgumentNullException))]
|
||||
public void CannotConvertNullStorageObjectsToJson()
|
||||
{
|
||||
var converter = new StorageObjectPayloadConverter();
|
||||
converter.Convert(null);
|
||||
}
|
||||
}
|
||||
}
|
@ -1,484 +0,0 @@
|
||||
// /* ============================================================================
|
||||
// Copyright 2014 Hewlett Packard
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ============================================================================ */
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using OpenStack.Common.Http;
|
||||
|
||||
namespace OpenStack.Test.Storage
|
||||
{
|
||||
public class StorageRestSimulator : RestSimulator
|
||||
{
|
||||
internal class StorageItem
|
||||
{
|
||||
public string Name { get; set; }
|
||||
|
||||
public IDictionary<string,string> MetaData { get; set; }
|
||||
|
||||
public Stream Content { get; set; }
|
||||
|
||||
public StorageItem()
|
||||
{
|
||||
this.MetaData = new Dictionary<string, string>();
|
||||
}
|
||||
|
||||
public StorageItem(string name) : this()
|
||||
{
|
||||
this.Name = name;
|
||||
}
|
||||
|
||||
public void ProcessMetaDataFromHeaders(IDictionary<string, string> headers)
|
||||
{
|
||||
headers.Keys.Where(k => k.ToLowerInvariant().StartsWith("x-object-meta-")).ToList().ForEach(i => this.MetaData.Add(i, headers[i]));
|
||||
headers.Keys.Where(k => k.ToLowerInvariant().StartsWith("x-container-meta-")).ToList().ForEach(i => this.MetaData.Add(i, headers[i]));
|
||||
}
|
||||
|
||||
public void LoadContent(Stream content)
|
||||
{
|
||||
var memStream = new MemoryStream();
|
||||
if (content != null)
|
||||
{
|
||||
content.CopyTo(memStream);
|
||||
memStream.Position = 0;
|
||||
}
|
||||
this.Content = memStream;
|
||||
}
|
||||
}
|
||||
|
||||
public StorageRestSimulator() : base()
|
||||
{
|
||||
this.Containers = new Dictionary<string, StorageItem>();
|
||||
this.Objects = new Dictionary<string, StorageItem>();
|
||||
this.IsContainerEmpty = true;
|
||||
}
|
||||
|
||||
public StorageRestSimulator(CancellationToken token) : this()
|
||||
{
|
||||
}
|
||||
|
||||
internal Dictionary<string, StorageItem> Containers { get; set; }
|
||||
|
||||
internal Dictionary<string, StorageItem> Objects { get; set; }
|
||||
|
||||
public bool IsContainerEmpty { get; set; }
|
||||
|
||||
//public event EventHandler<HttpProgressEventArgs> HttpReceiveProgress;
|
||||
//public event EventHandler<HttpProgressEventArgs> HttpSendProgress;
|
||||
|
||||
protected override IHttpResponseAbstraction HandleCopy()
|
||||
{
|
||||
var containerName = GetContainerName(this.Uri.Segments);
|
||||
var objectName = GetObjectName(this.Uri.Segments);
|
||||
|
||||
if (containerName == null && objectName == null)
|
||||
{
|
||||
return TestHelper.CreateErrorResponse();
|
||||
}
|
||||
|
||||
//cannot copy a container
|
||||
if (objectName == null)
|
||||
{
|
||||
return TestHelper.CreateResponse(HttpStatusCode.MethodNotAllowed);
|
||||
}
|
||||
|
||||
if (!this.Containers.ContainsKey(containerName))
|
||||
{
|
||||
return TestHelper.CreateResponse(HttpStatusCode.NotFound);
|
||||
}
|
||||
|
||||
if (!this.Headers.ContainsKey("Destination"))
|
||||
{
|
||||
return TestHelper.CreateResponse(HttpStatusCode.PreconditionFailed);
|
||||
}
|
||||
|
||||
if (!this.Objects.ContainsKey(objectName))
|
||||
{
|
||||
return TestHelper.CreateResponse(HttpStatusCode.NotFound);
|
||||
}
|
||||
|
||||
var destination = this.Headers["Destination"];
|
||||
var destinationSegs = destination.Split('/');
|
||||
if (destinationSegs.Count() < 2)
|
||||
{
|
||||
return TestHelper.CreateResponse(HttpStatusCode.PreconditionFailed);
|
||||
}
|
||||
|
||||
if (destinationSegs[1] == string.Empty)
|
||||
{
|
||||
return TestHelper.CreateResponse(HttpStatusCode.MethodNotAllowed);
|
||||
}
|
||||
|
||||
if (!this.Containers.ContainsKey(destinationSegs[0]))
|
||||
{
|
||||
return TestHelper.CreateResponse(HttpStatusCode.NotFound);
|
||||
}
|
||||
|
||||
var destObjectName = string.Join("", destinationSegs.Skip(1));
|
||||
var srcObj = this.Objects[objectName];
|
||||
|
||||
var obj = new StorageItem(destObjectName);
|
||||
obj.MetaData = srcObj.MetaData;
|
||||
obj.ProcessMetaDataFromHeaders(this.Headers);
|
||||
var content = new MemoryStream();
|
||||
srcObj.Content.CopyTo(content);
|
||||
srcObj.Content.Position = 0;
|
||||
content.Position = 0;
|
||||
obj.Content = content;
|
||||
|
||||
this.Objects[obj.Name] = obj;
|
||||
|
||||
var headers = GenerateObjectResponseHeaders(obj);
|
||||
|
||||
return TestHelper.CreateResponse(HttpStatusCode.Created, headers);
|
||||
|
||||
}
|
||||
|
||||
protected override IHttpResponseAbstraction HandleHead()
|
||||
{
|
||||
var containerName = GetContainerName(this.Uri.Segments);
|
||||
var objectName = GetObjectName(this.Uri.Segments);
|
||||
|
||||
if (containerName == null && objectName == null)
|
||||
{
|
||||
return TestHelper.CreateErrorResponse();
|
||||
}
|
||||
|
||||
var headers = new Dictionary<string, string>();
|
||||
|
||||
if (objectName != null)
|
||||
{
|
||||
if (!this.Objects.ContainsKey(objectName))
|
||||
{
|
||||
return TestHelper.CreateResponse(HttpStatusCode.NotFound);
|
||||
}
|
||||
headers = GenerateObjectResponseHeaders(this.Objects[objectName]);
|
||||
}
|
||||
else
|
||||
{
|
||||
if (!this.Containers.ContainsKey(containerName))
|
||||
{
|
||||
return TestHelper.CreateResponse(HttpStatusCode.NotFound);
|
||||
}
|
||||
headers = GenerateContainerResponseHeaders(this.Containers[containerName]);
|
||||
}
|
||||
|
||||
return TestHelper.CreateResponse(HttpStatusCode.NoContent, headers);
|
||||
}
|
||||
|
||||
protected override IHttpResponseAbstraction HandleDelete()
|
||||
{
|
||||
var containerName = GetContainerName(this.Uri.Segments);
|
||||
var objectName = GetObjectName(this.Uri.Segments);
|
||||
|
||||
if (containerName == null && objectName == null)
|
||||
{
|
||||
return TestHelper.CreateErrorResponse();
|
||||
}
|
||||
|
||||
if (objectName != null)
|
||||
{
|
||||
if (!this.Objects.ContainsKey(objectName))
|
||||
{
|
||||
return TestHelper.CreateResponse(HttpStatusCode.NotFound);
|
||||
}
|
||||
|
||||
this.Objects.Remove(objectName);
|
||||
|
||||
return TestHelper.CreateResponse(HttpStatusCode.NoContent, GenerateDeleteHeaders());
|
||||
}
|
||||
|
||||
if (!this.Containers.ContainsKey(containerName))
|
||||
{
|
||||
return TestHelper.CreateResponse(HttpStatusCode.NotFound);
|
||||
}
|
||||
|
||||
var statusCode = HttpStatusCode.NoContent;
|
||||
|
||||
if (!this.IsContainerEmpty)
|
||||
{
|
||||
statusCode = HttpStatusCode.Conflict;
|
||||
}
|
||||
else
|
||||
{
|
||||
this.Containers.Remove(containerName);
|
||||
}
|
||||
|
||||
return TestHelper.CreateResponse(statusCode, GenerateDeleteHeaders());
|
||||
}
|
||||
|
||||
protected override IHttpResponseAbstraction HandlePut()
|
||||
{
|
||||
var containerName = GetContainerName(this.Uri.Segments);
|
||||
var objectName = GetObjectName(this.Uri.Segments);
|
||||
|
||||
if (containerName == null && objectName == null)
|
||||
{
|
||||
return TestHelper.CreateErrorResponse();
|
||||
}
|
||||
|
||||
if (objectName != null)
|
||||
{
|
||||
var obj = new StorageItem(objectName);
|
||||
obj.ProcessMetaDataFromHeaders(this.Headers);
|
||||
obj.LoadContent(this.Content);
|
||||
this.Objects[obj.Name] = obj;
|
||||
|
||||
var headers = GenerateObjectResponseHeaders(obj);
|
||||
|
||||
return TestHelper.CreateResponse(HttpStatusCode.Created, headers);
|
||||
}
|
||||
else
|
||||
{
|
||||
var container = new StorageItem(containerName);
|
||||
container.ProcessMetaDataFromHeaders(this.Headers);
|
||||
|
||||
var containerUpdated = this.Containers.Keys.Any(k => String.Equals(k, container.Name, StringComparison.InvariantCultureIgnoreCase));
|
||||
|
||||
this.Containers[container.Name] = container;
|
||||
|
||||
return TestHelper.CreateResponse(containerUpdated ? HttpStatusCode.Accepted : HttpStatusCode.Created);
|
||||
}
|
||||
}
|
||||
|
||||
protected override IHttpResponseAbstraction HandlePost()
|
||||
{
|
||||
var containerName = GetContainerName(this.Uri.Segments);
|
||||
var objectName = GetObjectName(this.Uri.Segments);
|
||||
|
||||
if (containerName == null && objectName == null)
|
||||
{
|
||||
return TestHelper.CreateErrorResponse();
|
||||
}
|
||||
|
||||
StorageItem storageItem;
|
||||
|
||||
if (objectName != null)
|
||||
{
|
||||
if (!this.Objects.ContainsKey(objectName))
|
||||
{
|
||||
return TestHelper.CreateResponse(HttpStatusCode.NotFound);
|
||||
}
|
||||
|
||||
storageItem = this.Objects[objectName];
|
||||
}
|
||||
else
|
||||
{
|
||||
if (!this.Containers.ContainsKey(containerName))
|
||||
{
|
||||
return TestHelper.CreateResponse(HttpStatusCode.NotFound);
|
||||
}
|
||||
|
||||
storageItem = this.Containers[containerName];
|
||||
}
|
||||
|
||||
storageItem.MetaData.Clear();
|
||||
storageItem.ProcessMetaDataFromHeaders(this.Headers);
|
||||
|
||||
return TestHelper.CreateResponse(HttpStatusCode.Accepted);
|
||||
}
|
||||
|
||||
protected override IHttpResponseAbstraction HandleGet()
|
||||
{
|
||||
var containerName = GetContainerName(this.Uri.Segments);
|
||||
var objectName = GetObjectName(this.Uri.Segments);
|
||||
var accountName = GetAccountName(this.Uri.Segments);
|
||||
|
||||
if (containerName == null && objectName == null)
|
||||
{
|
||||
if (accountName == null)
|
||||
{
|
||||
return TestHelper.CreateErrorResponse();
|
||||
}
|
||||
|
||||
var accountHeaders = GenerateAccountResponseHeaders();
|
||||
var accountContent = TestHelper.CreateStream(GenerateAccountPayload());
|
||||
|
||||
return TestHelper.CreateResponse(HttpStatusCode.OK, accountHeaders, accountContent);
|
||||
|
||||
}
|
||||
|
||||
if (objectName != null)
|
||||
{
|
||||
return this.GetObject(objectName);
|
||||
}
|
||||
|
||||
var query = this.Uri.ParseQueryString();
|
||||
if (query.HasKeys() && query["prefix"] != null && query["delimiter"] != null)
|
||||
{
|
||||
return this.GetObject(query["prefix"]);
|
||||
}
|
||||
|
||||
if (!this.Containers.ContainsKey(containerName))
|
||||
{
|
||||
return TestHelper.CreateResponse(HttpStatusCode.NotFound);
|
||||
}
|
||||
|
||||
var container = this.Containers[containerName];
|
||||
var headers = GenerateContainerResponseHeaders(container);
|
||||
var content = TestHelper.CreateStream("[]");
|
||||
|
||||
return TestHelper.CreateResponse(HttpStatusCode.OK, headers, content);
|
||||
}
|
||||
|
||||
public IHttpResponseAbstraction GetObject(string objectName)
|
||||
{
|
||||
if (!this.Objects.ContainsKey(objectName))
|
||||
{
|
||||
return TestHelper.CreateResponse(HttpStatusCode.NotFound);
|
||||
}
|
||||
|
||||
var obj = this.Objects[objectName];
|
||||
var objectHeaders = GenerateObjectResponseHeaders(obj);
|
||||
|
||||
return TestHelper.CreateResponse(HttpStatusCode.OK, objectHeaders, obj.Content);
|
||||
}
|
||||
|
||||
public string GetContainerName(string[] uriSegments)
|
||||
{
|
||||
return uriSegments.Count() < 4 ? null : uriSegments[3].TrimEnd('/');
|
||||
}
|
||||
|
||||
public string GetAccountName(string[] uriSegments)
|
||||
{
|
||||
return uriSegments.Count() < 3 ? null : uriSegments[2].TrimEnd('/');
|
||||
}
|
||||
|
||||
public string GetObjectName(string[] uriSegments)
|
||||
{
|
||||
if (uriSegments.Count() < 5)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
return string.Join("", uriSegments.Skip(4));
|
||||
}
|
||||
|
||||
private string GenerateAccountPayload()
|
||||
{
|
||||
var payload = new StringBuilder();
|
||||
payload.Append("[");
|
||||
var first = true;
|
||||
foreach (var container in this.Containers)
|
||||
{
|
||||
if (!first)
|
||||
{
|
||||
payload.Append(",");
|
||||
first = false;
|
||||
}
|
||||
|
||||
payload.Append("{");
|
||||
payload.Append("\"count\": 42,");
|
||||
payload.Append("\"bytes\": 12345,");
|
||||
payload.Append(string.Format("\"name\": \"{0}\"",container.Value.Name));
|
||||
payload.Append("}");
|
||||
}
|
||||
payload.Append("]");
|
||||
return payload.ToString();
|
||||
}
|
||||
|
||||
private IEnumerable<KeyValuePair<string, string>> GenerateAccountResponseHeaders()
|
||||
{
|
||||
return new Dictionary<string, string>()
|
||||
{
|
||||
{"X-Account-Bytes-Used", "12345"},
|
||||
{"X-Account-Container-Count", this.Containers.Count.ToString()},
|
||||
{"X-Account-Object-Count", this.Objects.Count.ToString()},
|
||||
{"Content-Type", this.ContentType},
|
||||
{"X-Trans-Id", "12345"},
|
||||
{"Date", DateTime.UtcNow.ToShortTimeString()},
|
||||
{"X-Timestamp", "1234567890.98765"}
|
||||
};
|
||||
}
|
||||
|
||||
internal Dictionary<string, string> GenerateObjectResponseHeaders(StorageItem obj)
|
||||
{
|
||||
var etag = Convert.ToBase64String(MD5.Create().ComputeHash(obj.Content));
|
||||
obj.Content.Position = 0;
|
||||
|
||||
return new Dictionary<string, string>(obj.MetaData)
|
||||
{
|
||||
{"ETag", etag},
|
||||
{"Content-Type", this.ContentType},
|
||||
{"X-Trans-Id", "12345"},
|
||||
{"Date", DateTime.UtcNow.ToShortTimeString()},
|
||||
{"X-Timestamp", "1234567890.98765"}
|
||||
};
|
||||
}
|
||||
|
||||
internal Dictionary<string, string> GenerateContainerResponseHeaders(StorageItem obj)
|
||||
{
|
||||
return new Dictionary<string, string>(obj.MetaData)
|
||||
{
|
||||
{"X-Container-Bytes-Used", "0"},
|
||||
{"Content-Type", this.ContentType},
|
||||
{"X-Container-Object-Count", "0"},
|
||||
{"Date", DateTime.UtcNow.ToShortTimeString()},
|
||||
{"X-Container-Read", ".r.*,.rlistings"},
|
||||
{"X-Trans-Id", "12345"},
|
||||
{"X-Timestamp", "1234567890.98765"}
|
||||
};
|
||||
}
|
||||
|
||||
internal Dictionary<string, string> GenerateDeleteHeaders()
|
||||
{
|
||||
return new Dictionary<string, string>()
|
||||
{
|
||||
{"X-Trans-Id", "12345"},
|
||||
{"Date", DateTime.UtcNow.ToShortTimeString()}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
public class StorageRestSimulatorFactory : IHttpAbstractionClientFactory
|
||||
{
|
||||
internal StorageRestSimulator Simulator = null;
|
||||
public StorageRestSimulatorFactory(StorageRestSimulator simulator)
|
||||
{
|
||||
this.Simulator = simulator;
|
||||
}
|
||||
|
||||
public IHttpAbstractionClient Create()
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public IHttpAbstractionClient Create(CancellationToken token)
|
||||
{
|
||||
if (this.Simulator != null)
|
||||
{
|
||||
this.Simulator.Headers.Clear();
|
||||
}
|
||||
return this.Simulator ?? new StorageRestSimulator(token);
|
||||
}
|
||||
|
||||
public IHttpAbstractionClient Create(TimeSpan timeout)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public IHttpAbstractionClient Create(TimeSpan timeout, CancellationToken token)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
}
|
||||
}
|
@ -1,89 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
using OpenStack.Common;
|
||||
using OpenStack.Identity;
|
||||
using OpenStack.Storage;
|
||||
|
||||
namespace OpenStack.Test.Storage
|
||||
{
|
||||
[TestClass]
|
||||
public class StorageServiceClientDefinitionTests
|
||||
{
|
||||
IOpenStackCredential GetValidCreds()
|
||||
{
|
||||
var authId = "12345";
|
||||
var endpoint = "http://teststorageendpoint.com/v1/1234567890";
|
||||
|
||||
var creds = new OpenStackCredential(new Uri(endpoint), "SomeUser", "Password", "SomeTenant");
|
||||
creds.SetAccessTokenId(authId);
|
||||
return creds;
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CanSupportVersion1()
|
||||
{
|
||||
var client = new StorageServiceClientDefinition();
|
||||
var creds = GetValidCreds();
|
||||
var catalog =
|
||||
new OpenStackServiceCatalog
|
||||
{
|
||||
new OpenStackServiceDefinition("Swift", "Test",
|
||||
new List<OpenStackServiceEndpoint>()
|
||||
{
|
||||
new OpenStackServiceEndpoint("http://someplace.com", "somewhere", "1.0",
|
||||
"http://www.someplace.com", "http://www.someplace.com")
|
||||
})
|
||||
};
|
||||
creds.SetServiceCatalog(catalog);
|
||||
Assert.IsTrue(client.IsSupported(creds, "Swift"));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CannotSupportVersion2()
|
||||
{
|
||||
var client = new StorageServiceClientDefinition();
|
||||
var creds = GetValidCreds();
|
||||
var catalog =
|
||||
new OpenStackServiceCatalog
|
||||
{
|
||||
new OpenStackServiceDefinition("Swift", "Test",
|
||||
new List<OpenStackServiceEndpoint>()
|
||||
{
|
||||
new OpenStackServiceEndpoint("http://someplace.com", "somewhere", "2.0.0.0",
|
||||
"http://www.someplace.com", "http://www.someplace.com")
|
||||
})
|
||||
};
|
||||
creds.SetServiceCatalog(catalog);
|
||||
Assert.IsFalse(client.IsSupported(creds, "Swift"));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CannotSupportUnknownServiceName()
|
||||
{
|
||||
var client = new StorageServiceClientDefinition();
|
||||
var creds = GetValidCreds();
|
||||
var catalog =
|
||||
new OpenStackServiceCatalog
|
||||
{
|
||||
new OpenStackServiceDefinition("Swift", "Test",
|
||||
new List<OpenStackServiceEndpoint>()
|
||||
{
|
||||
new OpenStackServiceEndpoint("http://someplace.com", "somewhere", "1.0",
|
||||
"http://www.someplace.com", "http://www.someplace.com")
|
||||
})
|
||||
};
|
||||
creds.SetServiceCatalog(catalog);
|
||||
Assert.IsFalse(client.IsSupported(creds, "BadServiceName"));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Version1Supported()
|
||||
{
|
||||
var client = new StorageServiceClientDefinition();
|
||||
Assert.IsTrue(client.ListSupportedVersions().Contains("1.0"));
|
||||
Assert.IsTrue(client.ListSupportedVersions().Contains("1"));
|
||||
}
|
||||
}
|
||||
}
|
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@ -1,50 +0,0 @@
|
||||
// /* ============================================================================
|
||||
// Copyright 2014 Hewlett Packard
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ============================================================================ */
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Threading.Tasks;
|
||||
using OpenStack.Storage;
|
||||
|
||||
namespace OpenStack.Test.Storage
|
||||
{
|
||||
public class TestLargeStorageObjectCreatorFactory : ILargeStorageObjectCreatorFactory
|
||||
{
|
||||
internal ILargeStorageObjectCreator creator;
|
||||
|
||||
public TestLargeStorageObjectCreatorFactory(ILargeStorageObjectCreator creator)
|
||||
{
|
||||
this.creator = creator;
|
||||
}
|
||||
public ILargeStorageObjectCreator Create(IStorageServiceClient client)
|
||||
{
|
||||
return creator;
|
||||
}
|
||||
}
|
||||
|
||||
public class TestLargeStorageObjectCreator : ILargeStorageObjectCreator
|
||||
{
|
||||
public Func<string, string, IDictionary<string, string>, Stream, int, string, Task<StorageObject>> CreateDelegate { get; set; }
|
||||
|
||||
public async Task<StorageObject> Create(string containerName, string objectName, IDictionary<string, string> metadata, Stream content, int numberOfSegments,
|
||||
string segmentsContainer)
|
||||
{
|
||||
return
|
||||
await CreateDelegate(containerName, objectName, metadata, content, numberOfSegments, segmentsContainer);
|
||||
}
|
||||
}
|
||||
}
|
@ -1,34 +0,0 @@
|
||||
// /* ============================================================================
|
||||
// Copyright 2014 Hewlett Packard
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ============================================================================ */
|
||||
|
||||
using OpenStack.Storage;
|
||||
|
||||
namespace OpenStack.Test.Storage
|
||||
{
|
||||
public class TestStorageManifest : StorageManifest
|
||||
{
|
||||
public new string ContainerName { get; set; }
|
||||
|
||||
public new string FullName { get; set; }
|
||||
|
||||
public TestStorageManifest(string container, string name)
|
||||
: base(container, name)
|
||||
{
|
||||
this.ContainerName = container;
|
||||
this.FullName = name;
|
||||
}
|
||||
}
|
||||
}
|
@ -1,180 +0,0 @@
|
||||
// /* ============================================================================
|
||||
// Copyright 2014 Hewlett Packard
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ============================================================================ */
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Threading.Tasks;
|
||||
using OpenStack.Storage;
|
||||
|
||||
namespace OpenStack.Test.Storage
|
||||
{
|
||||
public class TestStorageServiceClient : IStorageServiceClient
|
||||
{
|
||||
public long LargeObjectThreshold { get; set; }
|
||||
public int LargeObjectSegments { get; set; }
|
||||
public string LargeObjectSegmentContainer { get; set; }
|
||||
|
||||
public Func<string, IDictionary<string, string>, Task> CreateStorageContainerDelegate { get; set; }
|
||||
|
||||
public Func<string, Task<StorageContainer>> GetStorageContainerDelegate { get; set; }
|
||||
|
||||
public Func<string, Task> DeleteContainerDelegate { get; set; }
|
||||
|
||||
public Func<StorageContainer, Task> UpdateStorageContainerDelegate { get; set; }
|
||||
|
||||
public Func<string, Task<IEnumerable<StorageObject>>> ListStorageObjectsDelegate { get; set; }
|
||||
|
||||
public Func<Task<IEnumerable<StorageContainer>>> ListStorageContainersDelegate { get; set; }
|
||||
|
||||
public Func<Task<StorageAccount>> GetStorageAccountDelegate { get; set; }
|
||||
|
||||
public Func<string, string, IDictionary<string, string>, Stream, Task<StorageObject>> CreateStorageObjectDelegate { get; set; }
|
||||
|
||||
public Func<string, string, string, string, Task<StorageObject>> CopyStorageObjectDelegate { get; set; }
|
||||
|
||||
public Func<string, string, IDictionary<string, string>, Stream, int, Task<StorageObject>> CreateLargeStorageObjectDelegate { get; set; }
|
||||
|
||||
public Func<string, string, Task<StorageObject>> GetStorageObjectDelegate { get; set; }
|
||||
|
||||
public Func<string, string, Stream, Task<StorageObject>> DownloadStorageObjectDelegate { get; set; }
|
||||
|
||||
public Func<string, string, Task> DeleteStorageObjectDelegate { get; set; }
|
||||
|
||||
public Func<StorageObject, Task> UpdateStorageObjectDelegate { get; set; }
|
||||
|
||||
public Func<string, string, IDictionary<string, string>, IEnumerable<StorageObject>, Task<StorageManifest>> CreateStaticStorageManifestDelegate { get; set; }
|
||||
|
||||
public Func<string, string, IDictionary<string, string>, string, Task<StorageManifest>> CreateDynamicStorageManifestDelegate { get; set; }
|
||||
|
||||
public Func<string, string, Task<StorageManifest>> GetStorageManifestDelegate { get; set; }
|
||||
|
||||
public Func<string, string, Task<StorageFolder>> GetStorageFolderDelegate { get; set; }
|
||||
|
||||
public Func<string, string, Task> CreateStorageFolderDelegate { get; set; }
|
||||
|
||||
public Func<string, string, Task> DeleteStorageFolderDelegate { get; set; }
|
||||
|
||||
public Func<Uri> GetPublicEndpointDelegate { get; set; }
|
||||
|
||||
public Uri GetPublicEndpoint()
|
||||
{
|
||||
return GetPublicEndpointDelegate();
|
||||
}
|
||||
|
||||
public async Task CreateStorageContainer(string containerName, IDictionary<string, string> metadata)
|
||||
{
|
||||
await CreateStorageContainerDelegate(containerName, metadata);
|
||||
}
|
||||
|
||||
public async Task<StorageContainer> GetStorageContainer(string containerName)
|
||||
{
|
||||
return await GetStorageContainerDelegate(containerName);
|
||||
}
|
||||
|
||||
public async Task DeleteStorageContainer(string containerName)
|
||||
{
|
||||
await DeleteContainerDelegate(containerName);
|
||||
}
|
||||
|
||||
public async Task UpdateStorageContainer(StorageContainer container)
|
||||
{
|
||||
await UpdateStorageContainerDelegate(container);
|
||||
}
|
||||
|
||||
public async Task<IEnumerable<StorageObject>> ListStorageObjects(string containerName)
|
||||
{
|
||||
return await ListStorageObjectsDelegate(containerName);
|
||||
}
|
||||
|
||||
public async Task<IEnumerable<StorageContainer>> ListStorageContainers()
|
||||
{
|
||||
return await ListStorageContainersDelegate();
|
||||
}
|
||||
|
||||
public async Task<StorageAccount> GetStorageAccount()
|
||||
{
|
||||
return await GetStorageAccountDelegate();
|
||||
}
|
||||
|
||||
public async Task<StorageObject> CreateStorageObject(string containerName, string objectName, IDictionary<string, string> metadata, Stream content)
|
||||
{
|
||||
return await CreateStorageObjectDelegate(containerName, objectName, metadata, content);
|
||||
}
|
||||
|
||||
public async Task<StorageObject> CopyStorageObject(string containerName, string objectName, string destinationContainerName, string destinationObjectName = null)
|
||||
{
|
||||
return await CopyStorageObjectDelegate(containerName, objectName, destinationContainerName, destinationObjectName);
|
||||
}
|
||||
|
||||
public async Task<StorageObject> CreateLargeStorageObject(string containerName, string objectName, IDictionary<string, string> metadata, Stream content,
|
||||
int numberOfsegments)
|
||||
{
|
||||
return
|
||||
await CreateLargeStorageObjectDelegate(containerName, objectName, metadata, content, numberOfsegments);
|
||||
}
|
||||
|
||||
public async Task<StorageObject> GetStorageObject(string containerName, string objectName)
|
||||
{
|
||||
return await GetStorageObjectDelegate(containerName, objectName);
|
||||
}
|
||||
|
||||
public async Task<StorageObject> DownloadStorageObject(string containerName, string objectName, Stream outputStream)
|
||||
{
|
||||
return await DownloadStorageObjectDelegate(containerName, objectName, outputStream);
|
||||
}
|
||||
|
||||
public async Task DeleteStorageObject(string containerName, string objectName)
|
||||
{
|
||||
await DeleteStorageObjectDelegate(containerName, objectName);
|
||||
}
|
||||
|
||||
public async Task UpdateStorageObject(StorageObject obj)
|
||||
{
|
||||
await UpdateStorageObject(obj);
|
||||
}
|
||||
|
||||
public async Task<StorageManifest> CreateStorageManifest(string containerName, string manifestName, IDictionary<string, string> metadata, IEnumerable<StorageObject> objects)
|
||||
{
|
||||
return await CreateStaticStorageManifestDelegate(containerName, manifestName, metadata, objects);
|
||||
}
|
||||
|
||||
public async Task<StorageManifest> CreateStorageManifest(string containerName, string manifestName, IDictionary<string, string> metadata, string segmentsPath)
|
||||
{
|
||||
return await CreateDynamicStorageManifestDelegate(containerName, manifestName, metadata, segmentsPath);
|
||||
}
|
||||
|
||||
public async Task<StorageManifest> GetStorageManifest(string containerName, string objectName)
|
||||
{
|
||||
return await GetStorageManifestDelegate(containerName, objectName);
|
||||
}
|
||||
|
||||
public async Task<StorageFolder> GetStorageFolder(string containerName, string folderName)
|
||||
{
|
||||
return await GetStorageFolderDelegate(containerName, folderName);
|
||||
}
|
||||
|
||||
public async Task CreateStorageFolder(string containerName, string folderName)
|
||||
{
|
||||
await this.CreateStorageFolderDelegate(containerName, folderName);
|
||||
}
|
||||
|
||||
public async Task DeleteStorageFolder(string containerName, string folderName)
|
||||
{
|
||||
await DeleteStorageFolderDelegate(containerName, folderName);
|
||||
}
|
||||
}
|
||||
}
|
@ -1,154 +0,0 @@
|
||||
// /* ============================================================================
|
||||
// Copyright 2014 Hewlett Packard
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ============================================================================ */
|
||||
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Threading.Tasks;
|
||||
using OpenStack.Common.ServiceLocation;
|
||||
using OpenStack.Storage;
|
||||
|
||||
namespace OpenStack.Test.Storage
|
||||
{
|
||||
public class TestStorageServicePocoClient : IStorageServicePocoClient
|
||||
{
|
||||
public Func<StorageObject, Stream, Task<StorageObject>> CreateStorageObjectDelegate { get; set; }
|
||||
|
||||
public Func<StorageObject, string, string, Task<StorageObject>> CopyStorageObjectDelegate { get; set; }
|
||||
|
||||
public Func<StorageManifest,Task<StorageManifest>> CreateStorageManifestDelegate { get; set; }
|
||||
|
||||
public Func<StorageContainer, Task<StorageContainer>> CreateStorageContainerDelegate { get; set; }
|
||||
|
||||
public Func<string, string, Task> CreateStorageFolderDelegate { get; set; }
|
||||
|
||||
public Func<string, Task<StorageContainer>> GetStorageContainerDelegate { get; set; }
|
||||
|
||||
public Func<Task<StorageAccount>> GetStorageAccountDelegate { get; set; }
|
||||
|
||||
public Func<string, string, Task<StorageObject>> GetStorageObjectDelegate { get; set; }
|
||||
|
||||
public Func<string, string, Task<StorageManifest>> GetStorageManifestDelegate { get; set; }
|
||||
|
||||
public Func<string, string, Task<StorageFolder>> GetStorageFolderDelegate { get; set; }
|
||||
|
||||
public Func<string, string, Stream, Task<StorageObject>> DownloadStorageObjectDelegate { get; set; }
|
||||
|
||||
public Func<string, string, Task> DeleteStorageObjectDelegate { get; set; }
|
||||
|
||||
public Func<string, string, Task> DeleteStorageFolderDelegate { get; set; }
|
||||
|
||||
public Func<StorageObject, Task> UpdateStorageObjectDelegate { get; set; }
|
||||
|
||||
public Func<string, Task> DeleteStorageConainerDelegate { get; set; }
|
||||
|
||||
public Func<StorageContainer, Task> UpdateStorageContainerDelegate { get; set; }
|
||||
|
||||
public async Task<StorageObject> CreateStorageObject(StorageObject obj, Stream content)
|
||||
{
|
||||
return await this.CreateStorageObjectDelegate(obj, content);
|
||||
}
|
||||
|
||||
public async Task<StorageObject> CopyStorageObject(StorageObject obj, string destinationContainerName, string destinationObjectName = null)
|
||||
{
|
||||
return await this.CopyStorageObjectDelegate(obj, destinationContainerName, destinationObjectName);
|
||||
}
|
||||
|
||||
public async Task<StorageManifest> CreateStorageManifest(StorageManifest manifest)
|
||||
{
|
||||
return await this.CreateStorageManifestDelegate(manifest);
|
||||
}
|
||||
|
||||
public async Task CreateStorageContainer(StorageContainer container)
|
||||
{
|
||||
await this.CreateStorageContainerDelegate(container);
|
||||
}
|
||||
|
||||
public async Task<StorageAccount> GetStorageAccount()
|
||||
{
|
||||
return await this.GetStorageAccountDelegate();
|
||||
}
|
||||
|
||||
public async Task<StorageContainer> GetStorageContainer(string containerName)
|
||||
{
|
||||
return await this.GetStorageContainerDelegate(containerName);
|
||||
}
|
||||
|
||||
public async Task<StorageObject> GetStorageObject(string containerName, string objectName)
|
||||
{
|
||||
return await this.GetStorageObjectDelegate(containerName, objectName);
|
||||
}
|
||||
|
||||
public async Task<StorageManifest> GetStorageManifest(string containerName, string manifestName)
|
||||
{
|
||||
return await this.GetStorageManifestDelegate(containerName, manifestName);
|
||||
}
|
||||
|
||||
public async Task<StorageObject> DownloadStorageObject(string containerName, string objectName, Stream outputStream)
|
||||
{
|
||||
return await this.DownloadStorageObjectDelegate(containerName, objectName, outputStream);
|
||||
}
|
||||
|
||||
public async Task DeleteStorageObject(string containerName, string itemName)
|
||||
{
|
||||
await this.DeleteStorageObjectDelegate(containerName, itemName);
|
||||
}
|
||||
|
||||
public async Task DeleteStorageContainer(string containerName)
|
||||
{
|
||||
await this.DeleteStorageConainerDelegate(containerName);
|
||||
}
|
||||
|
||||
public async Task UpdateStorageContainer(StorageContainer container)
|
||||
{
|
||||
await this.UpdateStorageContainerDelegate(container);
|
||||
}
|
||||
|
||||
public async Task UpdateStorageObject(StorageObject item)
|
||||
{
|
||||
await this.UpdateStorageObjectDelegate(item);
|
||||
}
|
||||
|
||||
public async Task<StorageFolder> GetStorageFolder(string containerName, string folderName)
|
||||
{
|
||||
return await this.GetStorageFolderDelegate(containerName, folderName);
|
||||
}
|
||||
|
||||
public async Task CreateStorageFolder(string containerName, string folderName)
|
||||
{
|
||||
await this.CreateStorageFolderDelegate(containerName, folderName);
|
||||
}
|
||||
|
||||
public async Task DeleteStorageFolder(string containerName, string folderName)
|
||||
{
|
||||
await this.DeleteStorageFolderDelegate(containerName, folderName);
|
||||
}
|
||||
}
|
||||
|
||||
public class TestStorageServicePocoClientFactory : IStorageServicePocoClientFactory
|
||||
{
|
||||
internal IStorageServicePocoClient client;
|
||||
|
||||
public TestStorageServicePocoClientFactory(IStorageServicePocoClient client)
|
||||
{
|
||||
this.client = client;
|
||||
}
|
||||
|
||||
public IStorageServicePocoClient Create(ServiceClientContext context, IServiceLocator serviceLocator)
|
||||
{
|
||||
return client;
|
||||
}
|
||||
}
|
||||
}
|
@ -1,135 +0,0 @@
|
||||
// /* ============================================================================
|
||||
// Copyright 2014 Hewlett Packard
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ============================================================================ */
|
||||
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Threading.Tasks;
|
||||
using OpenStack.Common.Http;
|
||||
using OpenStack.Common.ServiceLocation;
|
||||
using OpenStack.Storage;
|
||||
|
||||
namespace OpenStack.Test.Storage
|
||||
{
|
||||
public class TestStorageServiceRestClient : IStorageServiceRestClient
|
||||
{
|
||||
public bool CreateStaticManifestCalled = false;
|
||||
public bool CreatedDynamicManifestCalled = false;
|
||||
|
||||
public TestStorageServiceRestClient()
|
||||
{
|
||||
this.Responses = new Queue<IHttpResponseAbstraction>();
|
||||
}
|
||||
|
||||
public Queue<IHttpResponseAbstraction> Responses { get; set; }
|
||||
|
||||
public Task<IHttpResponseAbstraction> CreateObject(string containerName, string objectName, IDictionary<string, string> metadata, Stream content)
|
||||
{
|
||||
return Task.Factory.StartNew(() => Responses.Dequeue());
|
||||
}
|
||||
|
||||
public Task<IHttpResponseAbstraction> CreateDynamicManifest(string containerName, string manifestName, IDictionary<string, string> metadata, string segmentsPath)
|
||||
{
|
||||
CreatedDynamicManifestCalled = true;
|
||||
return Task.Factory.StartNew(() => Responses.Dequeue());
|
||||
}
|
||||
|
||||
public Task<IHttpResponseAbstraction> CreateStaticManifest(string containerName, string manifestName, IDictionary<string, string> metadata, Stream content)
|
||||
{
|
||||
CreateStaticManifestCalled = true;
|
||||
return Task.Factory.StartNew(() => Responses.Dequeue());
|
||||
}
|
||||
|
||||
public Task<IHttpResponseAbstraction> CreateContainer(string containerName, IDictionary<string, string> metadata)
|
||||
{
|
||||
return Task.Factory.StartNew(() => Responses.Dequeue());
|
||||
}
|
||||
|
||||
public Task<IHttpResponseAbstraction> GetObject(string containerName, string objectName)
|
||||
{
|
||||
return Task.Factory.StartNew(() => Responses.Dequeue());
|
||||
}
|
||||
|
||||
public Task<IHttpResponseAbstraction> GetFolder(string containerName, string folderName)
|
||||
{
|
||||
return Task.Factory.StartNew(() => Responses.Dequeue());
|
||||
}
|
||||
|
||||
public Task<IHttpResponseAbstraction> GetContainer(string containerName)
|
||||
{
|
||||
return Task.Factory.StartNew(() => Responses.Dequeue());
|
||||
}
|
||||
|
||||
public Task<IHttpResponseAbstraction> DeleteObject(string containerName, string objectName)
|
||||
{
|
||||
return Task.Factory.StartNew(() => Responses.Dequeue());
|
||||
}
|
||||
|
||||
public Task<IHttpResponseAbstraction> DeleteContainer(string containerName)
|
||||
{
|
||||
return Task.Factory.StartNew(() => Responses.Dequeue());
|
||||
}
|
||||
|
||||
public Task<IHttpResponseAbstraction> UpdateObject(string containerName, string objectName, IDictionary<string, string> metadata)
|
||||
{
|
||||
return Task.Factory.StartNew(() => Responses.Dequeue());
|
||||
}
|
||||
|
||||
public Task<IHttpResponseAbstraction> UpdateContainer(string containerName, IDictionary<string, string> metadata)
|
||||
{
|
||||
return Task.Factory.StartNew(() => Responses.Dequeue());
|
||||
}
|
||||
|
||||
public Task<IHttpResponseAbstraction> GetContainerMetadata(string containerName)
|
||||
{
|
||||
return Task.Factory.StartNew(() => Responses.Dequeue());
|
||||
}
|
||||
|
||||
public Task<IHttpResponseAbstraction> GetObjectMetadata(string containerName, string objectName)
|
||||
{
|
||||
return Task.Factory.StartNew(() => Responses.Dequeue());
|
||||
}
|
||||
|
||||
public Task<IHttpResponseAbstraction> GetManifestMetadata(string containerName, string manifestName)
|
||||
{
|
||||
return Task.Factory.StartNew(() => Responses.Dequeue());
|
||||
}
|
||||
|
||||
public Task<IHttpResponseAbstraction> CopyObject(string sourceContainerName, string sourceObjectName, string targetContainerName,
|
||||
string targetObjectName)
|
||||
{
|
||||
return Task.Factory.StartNew(() => Responses.Dequeue());
|
||||
}
|
||||
|
||||
public Task<IHttpResponseAbstraction> GetAccount()
|
||||
{
|
||||
return Task.Factory.StartNew(() => Responses.Dequeue());
|
||||
}
|
||||
}
|
||||
|
||||
public class TestStorageServiceRestClientFactory : IStorageServiceRestClientFactory
|
||||
{
|
||||
internal IStorageServiceRestClient Client;
|
||||
public TestStorageServiceRestClientFactory(IStorageServiceRestClient client)
|
||||
{
|
||||
this.Client = client;
|
||||
}
|
||||
|
||||
public IStorageServiceRestClient Create(ServiceClientContext context, IServiceLocator serviceLocator)
|
||||
{
|
||||
return Client;
|
||||
}
|
||||
}
|
||||
}
|
@ -1,36 +0,0 @@
|
||||
// /* ============================================================================
|
||||
// Copyright 2014 Hewlett Packard
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ============================================================================ */
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using OpenStack.Identity;
|
||||
|
||||
namespace OpenStack.Test
|
||||
{
|
||||
public class TestOpenStackRegionResolver : IOpenStackRegionResolver
|
||||
{
|
||||
internal string region;
|
||||
|
||||
public TestOpenStackRegionResolver(string region)
|
||||
{
|
||||
this.region = region;
|
||||
}
|
||||
public string Resolve(Uri endpoint, IEnumerable<OpenStackServiceDefinition> catalog, string serviceName)
|
||||
{
|
||||
return region;
|
||||
}
|
||||
}
|
||||
}
|
@ -1,4 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<packages>
|
||||
<package id="Newtonsoft.Json" version="6.0.2" targetFramework="net45" />
|
||||
</packages>
|
@ -1,31 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<package xmlns="http://schemas.microsoft.com/packaging/2011/08/nuspec.xsd">
|
||||
<metadata>
|
||||
<id>OpenStack-SDK-DotNet</id>
|
||||
<version>0.9.1.0</version>
|
||||
<title>OpenStack SDK/API for Microsoft .NET</title>
|
||||
<authors>OpenStack.org</authors>
|
||||
<owners>OpenStack.org</owners>
|
||||
<licenseUrl>http://www.apache.org/licenses/LICENSE-2.0.html</licenseUrl>
|
||||
<projectUrl>https://wiki.openstack.org/wiki/OpenStack-SDK-DotNet</projectUrl>
|
||||
<iconUrl>http://www.openstack.org/assets/openstack-logo/openstack-cloud-software-vertical-small.png</iconUrl>
|
||||
<requireLicenseAcceptance>false</requireLicenseAcceptance>
|
||||
<description>OpenStack .NET is an SDK/API for working with OpenStack using the Microsoft .NET Framework.</description>
|
||||
<releaseNotes></releaseNotes>
|
||||
<copyright>Copyright 2014</copyright>
|
||||
<tags>OpenStack</tags>
|
||||
<dependencies>
|
||||
<group>
|
||||
<dependency id="Newtonsoft.Json" version="6.0.2" />
|
||||
</group>
|
||||
<group targetFramework="portable-net45+netcore45+wp8+MonoAndroid1+MonoTouch1">
|
||||
<dependency id="Microsoft.Net.Http" version="2.2.22" />
|
||||
<dependency id="Newtonsoft.Json" version="6.0.2" />
|
||||
</group>
|
||||
</dependencies>
|
||||
</metadata>
|
||||
<files>
|
||||
<file src="Bin\net40\Release\OpenStack.dll" target="lib\net40\OpenStack.dll" />
|
||||
<file src="Bin\net45\Release\OpenStack.dll" target="lib\portable-net45+netcore45+wp8+MonoAndroid1+MonoTouch1\OpenStack.dll" />
|
||||
</files>
|
||||
</package>
|
@ -1,40 +0,0 @@
|
||||
|
||||
Microsoft Visual Studio Solution File, Format Version 12.00
|
||||
# Visual Studio 2013
|
||||
VisualStudioVersion = 12.0.30110.0
|
||||
MinimumVisualStudioVersion = 10.0.40219.1
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "OpenStack.Test", "OpenStack.Test\OpenStack.Test.csproj", "{7AF6DEC5-2257-4A29-BB55-66711DE3055D}"
|
||||
EndProject
|
||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{863F820F-2B49-44FF-A825-A858BFBBD69E}"
|
||||
ProjectSection(SolutionItems) = preProject
|
||||
AssemblyVersionInfo.cs = AssemblyVersionInfo.cs
|
||||
..\README.rst = ..\README.rst
|
||||
EndProjectSection
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "OpenStack40", "OpenStack\OpenStack40.csproj", "{E9F05CCA-2748-4785-9F72-5D3F8893BC28}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "OpenStack45-PCL", "OpenStack45-PCL\OpenStack45-PCL.csproj", "{5660F8AA-14D5-4B3B-ADA0-F79A286EF483}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|Any CPU = Debug|Any CPU
|
||||
Release|Any CPU = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(ProjectConfigurationPlatforms) = postSolution
|
||||
{7AF6DEC5-2257-4A29-BB55-66711DE3055D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{7AF6DEC5-2257-4A29-BB55-66711DE3055D}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{7AF6DEC5-2257-4A29-BB55-66711DE3055D}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{7AF6DEC5-2257-4A29-BB55-66711DE3055D}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{E9F05CCA-2748-4785-9F72-5D3F8893BC28}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{E9F05CCA-2748-4785-9F72-5D3F8893BC28}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{E9F05CCA-2748-4785-9F72-5D3F8893BC28}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{E9F05CCA-2748-4785-9F72-5D3F8893BC28}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{5660F8AA-14D5-4B3B-ADA0-F79A286EF483}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{5660F8AA-14D5-4B3B-ADA0-F79A286EF483}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{5660F8AA-14D5-4B3B-ADA0-F79A286EF483}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{5660F8AA-14D5-4B3B-ADA0-F79A286EF483}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
EndGlobalSection
|
||||
EndGlobal
|
@ -1,51 +0,0 @@
|
||||
// /* ============================================================================
|
||||
// Copyright 2014 Hewlett Packard
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ============================================================================ */
|
||||
|
||||
using System;
|
||||
|
||||
namespace OpenStack.Common.Http
|
||||
{
|
||||
public class DisposableClass : IDisposable
|
||||
{
|
||||
private bool _disposed;
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
Dispose(true);
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
|
||||
~DisposableClass()
|
||||
{
|
||||
Dispose(false);
|
||||
}
|
||||
|
||||
protected virtual void Dispose(bool disposing)
|
||||
{
|
||||
if (_disposed)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
//if (disposing)
|
||||
//{
|
||||
|
||||
//}
|
||||
|
||||
_disposed = true;
|
||||
}
|
||||
}
|
||||
}
|
@ -1,180 +0,0 @@
|
||||
// /* ============================================================================
|
||||
// Copyright 2014 Hewlett Packard
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ============================================================================ */
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace OpenStack.Common.Http
|
||||
{
|
||||
public class HttpAbstractionClient : DisposableClass, IHttpAbstractionClient
|
||||
{
|
||||
private readonly HttpClient _client;
|
||||
private CancellationToken _cancellationToken = CancellationToken.None;
|
||||
private static readonly TimeSpan _defaultTimeout = new TimeSpan(0, 5, 0);
|
||||
|
||||
internal HttpAbstractionClient(TimeSpan timeout, CancellationToken cancellationToken)
|
||||
{
|
||||
this._client = new HttpClient(new HttpClientHandler()) { Timeout = timeout };
|
||||
|
||||
this._cancellationToken = cancellationToken;
|
||||
this.Method = HttpMethod.Get;
|
||||
this.Headers = new Dictionary<string, string>();
|
||||
this.ContentType = string.Empty;
|
||||
}
|
||||
|
||||
public static IHttpAbstractionClient Create()
|
||||
{
|
||||
return new HttpAbstractionClient(_defaultTimeout, CancellationToken.None );
|
||||
}
|
||||
|
||||
public static IHttpAbstractionClient Create(TimeSpan timeout)
|
||||
{
|
||||
return new HttpAbstractionClient(timeout, CancellationToken.None);
|
||||
}
|
||||
|
||||
public static IHttpAbstractionClient Create(CancellationToken cancellationToken)
|
||||
{
|
||||
return new HttpAbstractionClient(_defaultTimeout, cancellationToken);
|
||||
}
|
||||
|
||||
public static IHttpAbstractionClient Create(CancellationToken cancellationToken, TimeSpan timeout)
|
||||
{
|
||||
return new HttpAbstractionClient(timeout, cancellationToken);
|
||||
}
|
||||
|
||||
public HttpMethod Method { get; set; }
|
||||
|
||||
public Uri Uri { get; set; }
|
||||
|
||||
public Stream Content { get; set; }
|
||||
|
||||
public IDictionary<string, string> Headers { get; private set; }
|
||||
|
||||
public string ContentType { get; set; }
|
||||
|
||||
public TimeSpan Timeout { get; set; }
|
||||
|
||||
public async Task<IHttpResponseAbstraction> SendAsync()
|
||||
{
|
||||
var requestMessage = new HttpRequestMessage { Method = this.Method, RequestUri = this.Uri };
|
||||
|
||||
if (this.Method == HttpMethod.Post || this.Method == HttpMethod.Put)
|
||||
{
|
||||
if (this.Content != null)
|
||||
{
|
||||
requestMessage.Content = new StreamContent(this.Content);
|
||||
if (this.ContentType != string.Empty)
|
||||
{
|
||||
requestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(this.ContentType);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
requestMessage.Headers.Clear();
|
||||
foreach (var header in this.Headers)
|
||||
{
|
||||
requestMessage.Headers.Add(header.Key, header.Value);
|
||||
}
|
||||
|
||||
var startTime = DateTime.Now;
|
||||
|
||||
try
|
||||
{
|
||||
|
||||
var result = await this._client.SendAsync(requestMessage, HttpCompletionOption.ResponseHeadersRead, this._cancellationToken);
|
||||
|
||||
var headers = new HttpHeadersAbstraction(result.Headers);
|
||||
|
||||
Stream content = null;
|
||||
if (result.Content != null )
|
||||
{
|
||||
headers.AddRange(result.Content.Headers);
|
||||
content = this.WaitForResult(result.Content.ReadAsStreamAsync(), new TimeSpan(0,0,0,0,int.MaxValue) );
|
||||
}
|
||||
|
||||
var retval = new HttpResponseAbstraction(content, headers, result.StatusCode);
|
||||
|
||||
//TODO: Add logging code
|
||||
|
||||
return retval;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
//TODO: Add logging code
|
||||
|
||||
var tcex = ex as TaskCanceledException;
|
||||
if (tcex == null)
|
||||
{
|
||||
throw;
|
||||
}
|
||||
|
||||
if (this._cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
throw new OperationCanceledException("The operation was canceled by user request.", tcex, this._cancellationToken);
|
||||
}
|
||||
|
||||
if (DateTime.Now - startTime > this.Timeout)
|
||||
{
|
||||
throw new TimeoutException(string.Format(CultureInfo.InvariantCulture, "The task failed to complete in the given timeout period ({0}).", this.Timeout));
|
||||
}
|
||||
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
internal T WaitForResult<T>(Task<T> task, TimeSpan timeout)
|
||||
{
|
||||
if (task == null )
|
||||
{
|
||||
throw new ArgumentNullException("task");
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
task.Wait(timeout);
|
||||
}
|
||||
catch (AggregateException aggregateException)
|
||||
{
|
||||
throw GetInnerException(aggregateException);
|
||||
}
|
||||
|
||||
if (task.Status != TaskStatus.RanToCompletion && task.Status != TaskStatus.Faulted && task.Status != TaskStatus.Canceled)
|
||||
{
|
||||
throw new TimeoutException(string.Format(CultureInfo.InvariantCulture, "The task failed to complete in the given timeout period ({0}).", timeout));
|
||||
}
|
||||
|
||||
return task.Result;
|
||||
}
|
||||
|
||||
internal Exception GetInnerException(AggregateException aggregateException)
|
||||
{
|
||||
//helper function to spool off the layers of aggregate exceptions and get the underlying exception...
|
||||
Exception innerExcception = aggregateException;
|
||||
while (aggregateException != null)
|
||||
{
|
||||
innerExcception = aggregateException.InnerExceptions[0];
|
||||
aggregateException = innerExcception as AggregateException;
|
||||
}
|
||||
return innerExcception;
|
||||
}
|
||||
}
|
||||
}
|
@ -1,44 +0,0 @@
|
||||
// /* ============================================================================
|
||||
// Copyright 2014 Hewlett Packard
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ============================================================================ */
|
||||
|
||||
using System;
|
||||
using System.Threading;
|
||||
|
||||
namespace OpenStack.Common.Http
|
||||
{
|
||||
public class HttpAbstractionClientFactory : IHttpAbstractionClientFactory
|
||||
{
|
||||
public IHttpAbstractionClient Create()
|
||||
{
|
||||
return HttpAbstractionClient.Create();
|
||||
}
|
||||
|
||||
public IHttpAbstractionClient Create(TimeSpan timeout)
|
||||
{
|
||||
return HttpAbstractionClient.Create(timeout);
|
||||
}
|
||||
|
||||
public IHttpAbstractionClient Create(CancellationToken token)
|
||||
{
|
||||
return HttpAbstractionClient.Create(token);
|
||||
}
|
||||
|
||||
public IHttpAbstractionClient Create(TimeSpan timeout, CancellationToken token)
|
||||
{
|
||||
return HttpAbstractionClient.Create(token, timeout);
|
||||
}
|
||||
}
|
||||
}
|
@ -1,106 +0,0 @@
|
||||
// /* ============================================================================
|
||||
// Copyright 2014 Hewlett Packard
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ============================================================================ */
|
||||
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Net.Http.Headers;
|
||||
|
||||
namespace OpenStack.Common.Http
|
||||
{
|
||||
public class HttpHeadersAbstraction : IHttpHeadersAbstraction
|
||||
{
|
||||
private readonly Dictionary<string, IEnumerable<string>> _headers = new Dictionary<string, IEnumerable<string>>();
|
||||
|
||||
public HttpHeadersAbstraction()
|
||||
{
|
||||
}
|
||||
|
||||
public HttpHeadersAbstraction(HttpResponseHeaders headers)
|
||||
{
|
||||
foreach (var header in headers)
|
||||
{
|
||||
this._headers.Add(header.Key,header.Value);
|
||||
}
|
||||
}
|
||||
|
||||
public IEnumerator<KeyValuePair<string, IEnumerable<string>>> GetEnumerator()
|
||||
{
|
||||
return this._headers.GetEnumerator();
|
||||
}
|
||||
|
||||
IEnumerator IEnumerable.GetEnumerator()
|
||||
{
|
||||
return this._headers.GetEnumerator();
|
||||
}
|
||||
|
||||
public void Add(string name, IEnumerable<string> values)
|
||||
{
|
||||
this._headers.Add(name,values);
|
||||
}
|
||||
|
||||
public void AddRange(HttpResponseHeaders headers)
|
||||
{
|
||||
foreach (var header in headers)
|
||||
{
|
||||
this._headers.Add(header.Key, header.Value);
|
||||
}
|
||||
}
|
||||
|
||||
public void AddRange(HttpContentHeaders headers)
|
||||
{
|
||||
foreach (var header in headers)
|
||||
{
|
||||
this._headers.Add(header.Key, header.Value);
|
||||
}
|
||||
}
|
||||
|
||||
public void Add(string name, string value)
|
||||
{
|
||||
this._headers.Add(name, new List<string>() { value });
|
||||
}
|
||||
|
||||
public void Clear()
|
||||
{
|
||||
this._headers.Clear();
|
||||
}
|
||||
|
||||
public bool Contains(string name)
|
||||
{
|
||||
return this._headers.ContainsKey(name);
|
||||
}
|
||||
|
||||
public IEnumerable<string> GetValues(string name)
|
||||
{
|
||||
return this._headers[name];
|
||||
}
|
||||
|
||||
public void Remove(string name)
|
||||
{
|
||||
this._headers.Remove(name);
|
||||
}
|
||||
|
||||
public bool TryGetValue(string name, out IEnumerable<string> values)
|
||||
{
|
||||
return this._headers.TryGetValue(name, out values);
|
||||
}
|
||||
|
||||
public IEnumerable<string> this[string name]
|
||||
{
|
||||
get { return this._headers[name]; }
|
||||
set { this._headers[name] = value; }
|
||||
}
|
||||
}
|
||||
}
|
@ -1,46 +0,0 @@
|
||||
// /* ============================================================================
|
||||
// Copyright 2014 Hewlett Packard
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ============================================================================ */
|
||||
|
||||
using System.IO;
|
||||
using System.Net;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace OpenStack.Common.Http
|
||||
{
|
||||
public class HttpResponseAbstraction : IHttpResponseAbstraction
|
||||
{
|
||||
public HttpResponseAbstraction(Stream content, IHttpHeadersAbstraction headers, HttpStatusCode status)
|
||||
{
|
||||
this.Headers = headers ?? new HttpHeadersAbstraction();
|
||||
this.StatusCode = status;
|
||||
this.Content = content;
|
||||
}
|
||||
|
||||
public Stream Content { get; private set; }
|
||||
|
||||
public IHttpHeadersAbstraction Headers { get; private set; }
|
||||
|
||||
public HttpStatusCode StatusCode { get; private set; }
|
||||
|
||||
public async Task<string> ReadContentAsStringAsync()
|
||||
{
|
||||
using (var sr = new StreamReader(this.Content))
|
||||
{
|
||||
return await sr.ReadToEndAsync();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
@ -1,45 +0,0 @@
|
||||
// /* ============================================================================
|
||||
// Copyright 2014 Hewlett Packard
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
// ============================================================================ */
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Net.Http;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace OpenStack.Common.Http
|
||||
{
|
||||
public interface IHttpAbstractionClient : IDisposable
|
||||
{
|
||||
HttpMethod Method { get; set; }
|
||||
|
||||
Uri Uri { get; set; }
|
||||
|
||||
Stream Content { get; set; }
|
||||
|
||||
IDictionary<string, string> Headers { get; }
|
||||
|
||||
string ContentType { get; set; }
|
||||
|
||||
TimeSpan Timeout { get; set; }
|
||||
|
||||
|
||||
//event EventHandler<HttpProgressEventArgs> HttpReceiveProgress;
|
||||
//event EventHandler<HttpProgressEventArgs> HttpSendProgress;
|
||||
|
||||
Task<IHttpResponseAbstraction> SendAsync();
|
||||
}
|
||||
}
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user