mirror of
https://github.com/ckaczor/sqltoolsservice.git
synced 2026-01-28 01:25:44 -05:00
Port Azure code from SSDT to the tools service (#477)
Porting of the vast majority of Azure-related code from SSDT. This is very large, so I want to put this out as one large "lift and shift" PR before I do the tools-service specific JSON-RPC service handlers, connect a new account handler (as the code to get necessary info from accounts and subscriptions isn't fully complete) and add tests over these **What's in this PR**: - Created 3 new projects: - Microsoft.SqlTools.ResourceProvider will host the executable that accepts requests for Azure-related actions over the JSON-RPC protocol. This must be separate from other DLLs since a direct dependency on the Azure SDK DLLs fails (they're NetStandard 1.4 and you can't reference them if you have RuntimeIdentifiers in your .csproj file) - Microsoft.SqlTools.ResourceProvider.Core is where all the main business logic is, including definitions and logic on how to navigate over resources and create firewall rules, etc. - Microsoft.SqlTools.ResourceProvider.DefaultImpl is the actual Azure implementation of the resource provider APIs. The reason for separating this is to support eventual integration back into other tools (since their Azure and Identity services will be different). - Implemented the AzureResourceManager that connects to Azure via ARM APIs and handles creating firewall rule and querying databases. The dependent DLLs have had major breaking changes, so will need additional verification to ensure this works as expected - Ported the unit tests for all code that was not a viewmodel. Viewmodel test code will be ported in a future update as we plumb through a service-equivalent to these. Also, the DependencyManager code which has overlap with our service provider code is commented out. Will work to uncomment in a future update as it has value to test some scenarios **What's not in this PR**: - Identity Services. We currently just have a stub for the interface, and even that will likely change a little - anything JSON-RPC or registered service related. These will be adapted from the viewmodels and added in a separate PR
This commit is contained in:
@@ -0,0 +1,204 @@
|
||||
//
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.SqlTools.ResourceProvider.Core;
|
||||
using Microsoft.SqlTools.ServiceLayer.UnitTests.ResourceProvider.Fakes;
|
||||
using Xunit;
|
||||
|
||||
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ResourceProvider.Azure
|
||||
{
|
||||
/// <summary>
|
||||
/// Tests for AzureDatabaseDiscoveryProvider to verify getting azure databases using azure resource manager
|
||||
/// </summary>
|
||||
public class AzureDatabaseDiscoveryProviderTest
|
||||
{
|
||||
[Fact]
|
||||
public async Task GetShouldReturnDatabasesSuccessfully()
|
||||
{
|
||||
string databaseName1 = "server/db1";
|
||||
string databaseName2 = "db2";
|
||||
string databaseName3 = "server/";
|
||||
string databaseName4 = "/db4";
|
||||
List<string> databasesForSubscription = new List<string>()
|
||||
{
|
||||
databaseName1,
|
||||
databaseName2
|
||||
};
|
||||
|
||||
Dictionary<string, List<string>> subscriptionToDatabaseMap = new Dictionary<string, List<string>>();
|
||||
subscriptionToDatabaseMap.Add(Guid.NewGuid().ToString(), databasesForSubscription);
|
||||
subscriptionToDatabaseMap.Add(Guid.NewGuid().ToString(), new List<string>()
|
||||
{
|
||||
databaseName3,
|
||||
databaseName4,
|
||||
});
|
||||
|
||||
AzureDatabaseDiscoveryProvider databaseDiscoveryProvider = FakeDataFactory.CreateAzureDatabaseDiscoveryProvider(subscriptionToDatabaseMap);
|
||||
ServiceResponse<DatabaseInstanceInfo> response = await databaseDiscoveryProvider.GetDatabaseInstancesAsync(serverName: null, cancellationToken: new CancellationToken());
|
||||
List<DatabaseInstanceInfo> list = response.Data.ToList();
|
||||
Assert.NotNull(list);
|
||||
Assert.True(list.Any(x => x.Name == "db1" && x.ServerInstanceInfo.Name == "server"));
|
||||
Assert.False(list.Any(x => x.Name == "db2" && x.ServerInstanceInfo.Name == ""));
|
||||
Assert.True(list.Any(x => x.Name == "" && x.ServerInstanceInfo.Name == "server"));
|
||||
Assert.False(list.Any(x => x.Name == "db4" && x.ServerInstanceInfo.Name == ""));
|
||||
Assert.True(list.Count() == 2);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetShouldReturnDatabasesEvenIfFailsForOneServer()
|
||||
{
|
||||
string databaseName1 = "server1/db1";
|
||||
string databaseName2 = "server1/db2";
|
||||
string databaseName3 = "error/db3";
|
||||
string databaseName4 = "server2/db4";
|
||||
List<string> databasesForSubscription = new List<string>()
|
||||
{
|
||||
databaseName1,
|
||||
databaseName2
|
||||
};
|
||||
|
||||
Dictionary<string, List<string>> subscriptionToDatabaseMap = new Dictionary<string, List<string>>();
|
||||
subscriptionToDatabaseMap.Add(Guid.NewGuid().ToString(), databasesForSubscription);
|
||||
subscriptionToDatabaseMap.Add(Guid.NewGuid().ToString(), new List<string>()
|
||||
{
|
||||
databaseName3,
|
||||
databaseName4,
|
||||
});
|
||||
|
||||
AzureDatabaseDiscoveryProvider databaseDiscoveryProvider = FakeDataFactory.CreateAzureDatabaseDiscoveryProvider(subscriptionToDatabaseMap);
|
||||
ServiceResponse<DatabaseInstanceInfo> response = await databaseDiscoveryProvider.GetDatabaseInstancesAsync(serverName: null, cancellationToken: new CancellationToken());
|
||||
List<DatabaseInstanceInfo> list = response.Data.ToList();
|
||||
Assert.NotNull(list);
|
||||
Assert.True(list.Any(x => x.Name == "db1" && x.ServerInstanceInfo.Name == "server1"));
|
||||
Assert.True(list.Any(x => x.Name == "db2" && x.ServerInstanceInfo.Name == "server1"));
|
||||
Assert.True(list.Any(x => x.Name == "db4" && x.ServerInstanceInfo.Name == "server2"));
|
||||
Assert.False(list.Any(x => x.Name == "db3" && x.ServerInstanceInfo.Name == "error"));
|
||||
Assert.True(list.Count() == 3);
|
||||
Assert.NotNull(response.Errors);
|
||||
Assert.True(response.Errors.Count() == 1);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetShouldReturnDatabasesFromCacheIfGetCalledTwice()
|
||||
{
|
||||
Dictionary<string, List<string>> subscriptionToDatabaseMap = CreateSubscriptonMap(2);
|
||||
AddDatabases(subscriptionToDatabaseMap, 3);
|
||||
|
||||
AzureDatabaseDiscoveryProvider databaseDiscoveryProvider = FakeDataFactory.CreateAzureDatabaseDiscoveryProvider(subscriptionToDatabaseMap);
|
||||
ServiceResponse<DatabaseInstanceInfo> response = await databaseDiscoveryProvider.GetDatabaseInstancesAsync(serverName: null, cancellationToken: new CancellationToken());
|
||||
List<DatabaseInstanceInfo> list = response.Data.ToList();
|
||||
ValidateResult(subscriptionToDatabaseMap, list);
|
||||
|
||||
Dictionary<string, List<string>> subscriptionToDatabaseMap2 = CopySubscriptonMap(subscriptionToDatabaseMap);
|
||||
AddDatabases(subscriptionToDatabaseMap2, 5);
|
||||
AzureTestContext testContext = new AzureTestContext(subscriptionToDatabaseMap2);
|
||||
databaseDiscoveryProvider.AccountManager = testContext.AzureAccountManager;
|
||||
databaseDiscoveryProvider.AzureResourceManager = testContext.AzureResourceManager;
|
||||
response = await databaseDiscoveryProvider.GetDatabaseInstancesAsync(serverName: null, cancellationToken: new CancellationToken());
|
||||
list = response.Data.ToList();
|
||||
//the provider should get the databases from cache for the list should match the first created data
|
||||
ValidateResult(subscriptionToDatabaseMap, list);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetShouldReturnDatabasesFromServiceIfGetCalledTwiceButRefreshed()
|
||||
{
|
||||
Dictionary<string, List<string>> subscriptionToDatabaseMap = CreateSubscriptonMap(2);
|
||||
AddDatabases(subscriptionToDatabaseMap, 3);
|
||||
|
||||
AzureDatabaseDiscoveryProvider databaseDiscoveryProvider = FakeDataFactory.CreateAzureDatabaseDiscoveryProvider(subscriptionToDatabaseMap);
|
||||
ServiceResponse<DatabaseInstanceInfo> response = await databaseDiscoveryProvider.GetDatabaseInstancesAsync(serverName: null, cancellationToken: new CancellationToken());
|
||||
List<DatabaseInstanceInfo> list = response.Data.ToList();
|
||||
ValidateResult(subscriptionToDatabaseMap, list);
|
||||
|
||||
Dictionary<string, List<string>> subscriptionToDatabaseMap2 = CopySubscriptonMap(subscriptionToDatabaseMap);
|
||||
AddDatabases(subscriptionToDatabaseMap2, 5);
|
||||
AzureTestContext testContext = new AzureTestContext(subscriptionToDatabaseMap2);
|
||||
databaseDiscoveryProvider.AccountManager = testContext.AzureAccountManager;
|
||||
databaseDiscoveryProvider.AzureResourceManager = testContext.AzureResourceManager;
|
||||
await databaseDiscoveryProvider.ClearCacheAsync();
|
||||
response = await databaseDiscoveryProvider.GetDatabaseInstancesAsync(serverName: null, cancellationToken: new CancellationToken());
|
||||
list = response.Data.ToList();
|
||||
//the provider should get the databases from cache for the list should match the first created data
|
||||
ValidateResult(subscriptionToDatabaseMap2, list);
|
||||
}
|
||||
|
||||
private void ValidateResult(Dictionary<string, List<string>> subscriptionToDatabaseMap, List<DatabaseInstanceInfo> result)
|
||||
{
|
||||
Assert.NotNull(result);
|
||||
int numberOfDatabases = 0;
|
||||
foreach (KeyValuePair<string, List<string>> item in subscriptionToDatabaseMap)
|
||||
{
|
||||
numberOfDatabases += item.Value.Count;
|
||||
foreach (string databaseFullName in item.Value)
|
||||
{
|
||||
string serverName = AzureTestContext.GetServerName(databaseFullName);
|
||||
string databaseName = databaseFullName.Replace(serverName + @"/", "");
|
||||
Assert.True(result.Any(x => x.Name == databaseName && x.ServerInstanceInfo.Name == serverName));
|
||||
}
|
||||
}
|
||||
Assert.True(result.Count() == numberOfDatabases);
|
||||
}
|
||||
|
||||
private void AddDatabases(Dictionary<string, List<string>> subscriptionToDatabaseMap, int numberOfDatabases)
|
||||
{
|
||||
foreach (string key in subscriptionToDatabaseMap.Keys.ToList())
|
||||
{
|
||||
List<string> databases = CreateDatabases(numberOfDatabases);
|
||||
subscriptionToDatabaseMap[key] = databases;
|
||||
}
|
||||
}
|
||||
|
||||
private List<string> CreateDatabases(int numberOfDatabases)
|
||||
{
|
||||
List<string> databases = new List<string>();
|
||||
for (int j = 0; j < numberOfDatabases; j++)
|
||||
{
|
||||
databases.Add(string.Format(CultureInfo.InvariantCulture, @"{0}/{1}", Guid.NewGuid().ToString(), Guid.NewGuid().ToString()));
|
||||
}
|
||||
return databases;
|
||||
}
|
||||
|
||||
private Dictionary<string, List<string>> CreateSubscriptonMap(int numberOfSubscriptions)
|
||||
{
|
||||
Dictionary<string, List<string>> subscriptionToDatabaseMap = new Dictionary<string, List<string>>();
|
||||
for (int i = 0; i < numberOfSubscriptions; i++)
|
||||
{
|
||||
string id = Guid.NewGuid().ToString();
|
||||
subscriptionToDatabaseMap.Add(id, null);
|
||||
}
|
||||
return subscriptionToDatabaseMap;
|
||||
}
|
||||
|
||||
private Dictionary<string, List<string>> CopySubscriptonMap(Dictionary<string, List<string>> subscriptionToDatabaseMap)
|
||||
{
|
||||
Dictionary<string, List<string>> subscriptionToDatabaseMapCopy = new Dictionary<string, List<string>>();
|
||||
foreach (KeyValuePair<string, List<string>> pair in subscriptionToDatabaseMap)
|
||||
{
|
||||
subscriptionToDatabaseMapCopy.Add(pair.Key, null);
|
||||
}
|
||||
return subscriptionToDatabaseMapCopy;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetShouldReturnEmptyGivenNotSubscriptionFound()
|
||||
{
|
||||
Dictionary<string, List<string>> subscriptionToDatabaseMap = new Dictionary<string, List<string>>();
|
||||
|
||||
AzureDatabaseDiscoveryProvider databaseDiscoveryProvider =
|
||||
FakeDataFactory.CreateAzureDatabaseDiscoveryProvider(subscriptionToDatabaseMap);
|
||||
ServiceResponse<DatabaseInstanceInfo> response =
|
||||
await databaseDiscoveryProvider.GetDatabaseInstancesAsync(serverName: null, cancellationToken: new CancellationToken());
|
||||
Assert.NotNull(response);
|
||||
Assert.NotNull(response.Data);
|
||||
Assert.False(response.Data.Any());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
//
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.SqlTools.ResourceProvider.Core;
|
||||
using Microsoft.SqlTools.ServiceLayer.UnitTests.ResourceProvider.Fakes;
|
||||
using Xunit;
|
||||
|
||||
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ResourceProvider.Azure
|
||||
{
|
||||
/// <summary>
|
||||
/// Tests for AzureServerDiscoveryProvider to verify getting azure servers using azure resource manager
|
||||
/// </summary>
|
||||
public class AzureSqlServerDiscoveryProviderTest
|
||||
{
|
||||
[Fact]
|
||||
public async Task GetShouldReturnServersSuccessfully()
|
||||
{
|
||||
string serverName = "server";
|
||||
List<string> serversForSubscription = new List<string>()
|
||||
{
|
||||
Guid.NewGuid().ToString(),
|
||||
serverName
|
||||
};
|
||||
|
||||
Dictionary<string, List<string>> subscriptionToDatabaseMap = new Dictionary<string, List<string>>();
|
||||
subscriptionToDatabaseMap.Add(Guid.NewGuid().ToString(), serversForSubscription);
|
||||
subscriptionToDatabaseMap.Add(Guid.NewGuid().ToString(), new List<string>()
|
||||
{
|
||||
Guid.NewGuid().ToString(),
|
||||
Guid.NewGuid().ToString(),
|
||||
});
|
||||
|
||||
AzureSqlServerDiscoveryProvider discoveryProvider =
|
||||
FakeDataFactory.CreateAzureServerDiscoveryProvider(subscriptionToDatabaseMap);
|
||||
ServiceResponse<ServerInstanceInfo> response = await discoveryProvider.GetServerInstancesAsync();
|
||||
IEnumerable<ServerInstanceInfo> servers = response.Data;
|
||||
Assert.NotNull(servers);
|
||||
Assert.True(servers.Any(x => x.Name == serverName));
|
||||
Assert.True(servers.Count() == 4);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetShouldReturnEmptyGivenNotSubscriptionFound()
|
||||
{
|
||||
Dictionary<string, List<string>> subscriptionToDatabaseMap = new Dictionary<string, List<string>>();
|
||||
|
||||
AzureSqlServerDiscoveryProvider discoveryProvider =
|
||||
FakeDataFactory.CreateAzureServerDiscoveryProvider(subscriptionToDatabaseMap);
|
||||
ServiceResponse<ServerInstanceInfo> response = await discoveryProvider.GetServerInstancesAsync();
|
||||
IEnumerable<ServerInstanceInfo> servers = response.Data;
|
||||
Assert.NotNull(servers);
|
||||
Assert.False(servers.Any());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
//
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
|
||||
|
||||
using System;
|
||||
using Microsoft.SqlTools.ResourceProvider.DefaultImpl;
|
||||
using Xunit;
|
||||
|
||||
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ResourceProvider.Azure
|
||||
{
|
||||
/// <summary>
|
||||
/// Tests for AzureSubscriptionContextWrapper to verify the wrapper on azure subscription class
|
||||
/// </summary>
|
||||
public class AzureSubscriptionContextTest
|
||||
{
|
||||
[Fact]
|
||||
public void SubscriptionNameShouldReturnNullGivenNullSubscription()
|
||||
{
|
||||
AzureSubscriptionContext subscriptionContext = new AzureSubscriptionContext(null);
|
||||
Assert.True(subscriptionContext.SubscriptionName == String.Empty);
|
||||
Assert.True(subscriptionContext.Subscription == null);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SubscriptionNameShouldReturnCorrectValueGivenValidSubscription()
|
||||
{
|
||||
string name = Guid.NewGuid().ToString();
|
||||
|
||||
AzureSubscriptionContext subscriptionContext = new AzureSubscriptionContext(new AzureSubscriptionIdentifier(null, name, null));
|
||||
Assert.True(subscriptionContext.SubscriptionName == name);
|
||||
Assert.True(subscriptionContext.Subscription != null);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
//
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.Azure.Management.Sql.Models;
|
||||
using Microsoft.Rest;
|
||||
using Microsoft.SqlTools.ResourceProvider.Core;
|
||||
using Microsoft.SqlTools.ResourceProvider.Core.Authentication;
|
||||
using Microsoft.SqlTools.ResourceProvider.DefaultImpl;
|
||||
using Moq;
|
||||
|
||||
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ResourceProvider.Azure
|
||||
{
|
||||
/// <summary>
|
||||
/// A container to create test data and mock classes to test azure services and providers
|
||||
/// </summary>
|
||||
internal class AzureTestContext
|
||||
{
|
||||
public AzureTestContext(Dictionary<string, List<string>> subscriptionToDatabaseMap)
|
||||
{
|
||||
AzureAccountManagerMock = new Mock<IAzureAuthenticationManager>();
|
||||
List<IAzureUserAccountSubscriptionContext> accountSubscriptions = new List
|
||||
<IAzureUserAccountSubscriptionContext>();
|
||||
AzureResourceManagerMock = new Mock<IAzureResourceManager>();
|
||||
|
||||
foreach (string subscriptionName in subscriptionToDatabaseMap.Keys)
|
||||
{
|
||||
var azureAccount = new AzureUserAccount();
|
||||
AzureSubscriptionIdentifier subId = new AzureSubscriptionIdentifier(azureAccount, subscriptionName, null);
|
||||
var subscription = new AzureUserAccountSubscriptionContext(subId, new TokenCredentials("dummy"));
|
||||
accountSubscriptions.Add(subscription);
|
||||
|
||||
var sessionMock = new Mock<IAzureResourceManagementSession>();
|
||||
IAzureResourceManagementSession session = sessionMock.Object;
|
||||
sessionMock.Setup(x => x.SubscriptionContext).Returns(subscription);
|
||||
AzureResourceManagerMock.Setup(x => x.CreateSessionAsync(subscription)).Returns(Task.FromResult(session));
|
||||
MockServersAndDatabases(subscriptionToDatabaseMap[subscriptionName], session);
|
||||
}
|
||||
AzureAccountManagerMock.Setup(x => x.GetSelectedSubscriptionsAsync()).Returns
|
||||
(Task.FromResult(accountSubscriptions as IEnumerable<IAzureUserAccountSubscriptionContext>));
|
||||
}
|
||||
|
||||
private void MockServersAndDatabases(List<string> resourceNames, IAzureResourceManagementSession session)
|
||||
{
|
||||
IEnumerable<IAzureResource> azureResources = resourceNames.Select(
|
||||
x => new AzureResourceWrapper(new TrackedResource(Guid.NewGuid().ToString(), "id", x, "type")) { ResourceGroupName = Guid.NewGuid().ToString()}
|
||||
).ToList();
|
||||
|
||||
List<IAzureSqlServerResource> servers = new List<IAzureSqlServerResource>();
|
||||
foreach (var azureResourceWrapper in azureResources.ToList())
|
||||
{
|
||||
var serverName = GetServerName(azureResourceWrapper.Name);
|
||||
if (string.IsNullOrEmpty(serverName) || servers.Any(x => x.Name == serverName))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var databases = azureResources.Where(x => x.Name.StartsWith(serverName + "/"));
|
||||
if (serverName.Equals("error", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
AzureResourceManagerMock.Setup(x => x.GetAzureDatabasesAsync(session, azureResourceWrapper.ResourceGroupName, serverName))
|
||||
.Throws(new ApplicationException(serverName));
|
||||
}
|
||||
else
|
||||
{
|
||||
AzureResourceManagerMock.Setup(x => x.GetAzureDatabasesAsync(session, azureResourceWrapper.ResourceGroupName, serverName))
|
||||
.Returns(Task.FromResult(databases));
|
||||
}
|
||||
|
||||
Server azureSqlServer = new Server(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), serverName, null, null, null, null, null, null, null, null, fullyQualifiedDomainName: serverName + ".database.windows.net");
|
||||
servers.Add(new SqlAzureResource(azureSqlServer)
|
||||
{
|
||||
ResourceGroupName = azureResourceWrapper.ResourceGroupName
|
||||
});
|
||||
}
|
||||
AzureResourceManagerMock.Setup(x => x.GetSqlServerAzureResourcesAsync(session))
|
||||
.Returns(Task.FromResult(servers as IEnumerable<IAzureSqlServerResource>));
|
||||
}
|
||||
|
||||
internal static string GetServerName(string name)
|
||||
{
|
||||
string azureResourceName = name;
|
||||
int separatorIndex = azureResourceName.IndexOf("/", StringComparison.OrdinalIgnoreCase);
|
||||
if (separatorIndex >= 0)
|
||||
{
|
||||
return azureResourceName.Substring(0, separatorIndex);
|
||||
}
|
||||
else
|
||||
{
|
||||
return azureResourceName;
|
||||
}
|
||||
}
|
||||
|
||||
public Mock<IAzureAuthenticationManager> AzureAccountManagerMock
|
||||
{
|
||||
get;
|
||||
set;
|
||||
}
|
||||
|
||||
public IAzureAuthenticationManager AzureAccountManager
|
||||
{
|
||||
get { return AzureAccountManagerMock.Object; }
|
||||
}
|
||||
|
||||
public IAzureResourceManager AzureResourceManager
|
||||
{
|
||||
get { return AzureResourceManagerMock.Object; }
|
||||
}
|
||||
|
||||
public Mock<IAzureResourceManager> AzureResourceManagerMock
|
||||
{
|
||||
get;
|
||||
set;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
//
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
|
||||
|
||||
using System;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.SqlTools.ResourceProvider.Core;
|
||||
using Microsoft.SqlTools.ResourceProvider.Core.Authentication;
|
||||
using Microsoft.SqlTools.ResourceProvider.Core.Extensibility;
|
||||
|
||||
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ResourceProvider.Azure
|
||||
{
|
||||
/// <summary>
|
||||
/// A fake server discovery class
|
||||
/// </summary>
|
||||
[Exportable(ServerTypes.SqlServer, Categories.Azure
|
||||
, typeof(IServerDiscoveryProvider),
|
||||
"Microsoft.SqlTools.ServiceLayer.UnitTests.ResourceProvider.Azure.FakeAzureServerDiscoveryProvider", 1)]
|
||||
public class FakeAzureServerDiscoveryProvider : ExportableBase, IServerDiscoveryProvider, ISecureService
|
||||
{
|
||||
public FakeAzureServerDiscoveryProvider()
|
||||
{
|
||||
Metadata = new ExportableMetadata(ServerTypes.SqlServer, Categories.Azure,
|
||||
"Microsoft.SqlTools.ServiceLayer.UnitTests.ResourceProvider.Azure.FakeAzureServerDiscoveryProvider", 1);
|
||||
}
|
||||
public Task<ServiceResponse<ServerInstanceInfo>> GetServerInstancesAsync()
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public IAccountManager AccountManager
|
||||
{
|
||||
get;
|
||||
set;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// This should always return null otherwise there's going to be a infinite loop
|
||||
/// </summary>
|
||||
public IServerDiscoveryProvider ServerDiscoveryProvider
|
||||
{
|
||||
get
|
||||
{
|
||||
return GetService<IServerDiscoveryProvider>();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,295 @@
|
||||
//
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
|
||||
|
||||
// TODO Ideally would reenable these but using ExtensionServiceProvider
|
||||
|
||||
//using System;
|
||||
//using System.Collections.Generic;
|
||||
//using System.Linq;
|
||||
//using System.Threading.Tasks;
|
||||
//using Microsoft.SqlTools.ResourceProvider.Core;
|
||||
//using Microsoft.SqlTools.ResourceProvider.Core.Extensibility;
|
||||
//using Microsoft.SqlTools.ServiceLayer.UnitTests.ResourceProvider.Fakes;
|
||||
//using Moq;
|
||||
//using Xunit;
|
||||
|
||||
//namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ResourceProvider
|
||||
//{
|
||||
// /// <summary>
|
||||
// /// Tests for DependencyManager to verify the services and providers can be created given different types of catalogs
|
||||
// /// </summary>
|
||||
// public class DependencyManagerTest
|
||||
// {
|
||||
// private ExtensionProperties _serviceProperties;
|
||||
// private DependencyManager _dependencyManager;
|
||||
// private IList<Lazy<IServerDiscoveryProvider, IExportableMetadata>> _providers;
|
||||
|
||||
// private readonly List<ServerInstanceInfo> _localSqlServers = new List<ServerInstanceInfo>()
|
||||
// {
|
||||
// new ServerInstanceInfo(),
|
||||
// new ServerInstanceInfo(),
|
||||
// };
|
||||
|
||||
// public DependencyManagerTest()
|
||||
// {
|
||||
// var provider1 = new Mock<IServerDiscoveryProvider>();
|
||||
// var provider2 = new Mock<IServerDiscoveryProvider>();
|
||||
// provider1.Setup(x => x.GetServerInstancesAsync()).Returns(Task.FromResult(new ServiceResponse<ServerInstanceInfo>(_localSqlServers.AsEnumerable())));
|
||||
// _providers = new List<Lazy<IServerDiscoveryProvider, IExportableMetadata>>()
|
||||
// {
|
||||
// new Lazy<IServerDiscoveryProvider, IExportableMetadata>(() => provider1.Object,
|
||||
// new ExportableAttribute("SqlServer", "Local", typeof(IServerDiscoveryProvider), Guid.NewGuid().ToString())),
|
||||
// new Lazy<IServerDiscoveryProvider, IExportableMetadata>(() => provider2.Object,
|
||||
// new ExportableAttribute("SqlServer", "Network", typeof(IServerDiscoveryProvider), Guid.NewGuid().ToString())),
|
||||
// };
|
||||
|
||||
// _serviceProperties = FakeDataFactory.CreateServiceProperties(_providers);
|
||||
// _dependencyManager = new DependencyManager(_serviceProperties);
|
||||
// }
|
||||
|
||||
// [Fact]
|
||||
// public void GetShouldReturnProvidersFromTheCatalog()
|
||||
// {
|
||||
// IEnumerable<ExportableDescriptor<IServerDiscoveryProvider>> providers =
|
||||
// _dependencyManager.GetServiceDescriptors<IServerDiscoveryProvider>();
|
||||
// Assert.NotNull(providers);
|
||||
// }
|
||||
|
||||
// [Fact]
|
||||
// public void GetShouldReturnEmptyListGivenInvalidCategory()
|
||||
// {
|
||||
// Assert.False(_dependencyManager.GetServiceDescriptors<IServerDiscoveryProvider>(new ServerDefinition(null, "invalid category")).Any());
|
||||
// }
|
||||
|
||||
// [Fact]
|
||||
// public void GetShouldReturnEmptyListGivenInvalidServerType()
|
||||
// {
|
||||
// Assert.False(_dependencyManager.GetServiceDescriptors<IServerDiscoveryProvider>(new ServerDefinition("invalid server type", null)).Any());
|
||||
// }
|
||||
|
||||
// [Fact]
|
||||
// public void GetShouldReturnAllProvidersGivenNoParameter()
|
||||
// {
|
||||
// IEnumerable<ExportableDescriptor<IServerDiscoveryProvider>> providers =
|
||||
// _dependencyManager.GetServiceDescriptors<IServerDiscoveryProvider>();
|
||||
// Assert.NotNull(providers);
|
||||
// Assert.True(providers.Count() == _providers.Count());
|
||||
// }
|
||||
|
||||
// [Fact]
|
||||
// public void GetShouldReturnProvidersGivenServerType()
|
||||
// {
|
||||
// var serverType = "sqlServer";
|
||||
// IEnumerable<ExportableDescriptor<IServerDiscoveryProvider>> providers =
|
||||
// _dependencyManager.GetServiceDescriptors<IServerDiscoveryProvider>(new ServerDefinition(serverType, null));
|
||||
// Assert.NotNull(providers);
|
||||
// Assert.True(providers.Any());
|
||||
// Assert.True(providers.Count() == _providers.Count(x => x.Metadata.ServerType.Equals(serverType, StringComparison.OrdinalIgnoreCase)));
|
||||
// }
|
||||
|
||||
// [Fact]
|
||||
// public void GetShouldReturnProvidersGivenCategory()
|
||||
// {
|
||||
// IEnumerable<ExportableDescriptor<IServerDiscoveryProvider>> providers =
|
||||
// _dependencyManager.GetServiceDescriptors<IServerDiscoveryProvider>(new ServerDefinition(null, "local"));
|
||||
// Assert.NotNull(providers);
|
||||
// Assert.True(providers.Count() == 1);
|
||||
// }
|
||||
|
||||
// [Fact]
|
||||
// public void GetShouldReturnProviderForEmptyCategoryGivenEmptyCategory()
|
||||
// {
|
||||
// // Given choice of 2 providers, one with empty category and other with specified one
|
||||
|
||||
// IServerDiscoveryProvider provider1 = new Mock<IServerDiscoveryProvider>();
|
||||
// IServerDiscoveryProvider provider2 = new Mock<IServerDiscoveryProvider>();
|
||||
// provider1.Setup(x => x.GetServerInstancesAsync()).Returns(Task.FromResult(new ServiceResponse<ServerInstanceInfo>(_localSqlServers.AsEnumerable())));
|
||||
// var providers = new List<Lazy<IServerDiscoveryProvider, IExportableMetadata>>()
|
||||
// {
|
||||
// new Lazy<IServerDiscoveryProvider, IExportableMetadata>(() => provider1,
|
||||
// new ExportableAttribute("SqlServer", "Azure", typeof(IServerDiscoveryProvider), Guid.NewGuid().ToString())),
|
||||
// new Lazy<IServerDiscoveryProvider, IExportableMetadata>(() => provider2,
|
||||
// new ExportableAttribute("SqlServer", "", typeof(IServerDiscoveryProvider), Guid.NewGuid().ToString())),
|
||||
// };
|
||||
|
||||
// var serviceProperties = FakeDataFactory.CreateServiceProperties(providers);
|
||||
// var dependencyManager = new DependencyManager(serviceProperties);
|
||||
|
||||
// // When getting the correct descriptor
|
||||
|
||||
// IEnumerable<ExportableDescriptor<IServerDiscoveryProvider>> foundProviders =
|
||||
// dependencyManager.GetServiceDescriptors<IServerDiscoveryProvider>(new ServerDefinition("SqlServer", ""));
|
||||
|
||||
// // Then expect only the provider with the empty categorty to be returned
|
||||
// Assert.NotNull(foundProviders);
|
||||
// Assert.True(foundProviders.Count() == 1);
|
||||
// }
|
||||
|
||||
// [Fact]
|
||||
// public void GetShouldReturnProviderGivenServerTypeAndLocationWithValidProvider()
|
||||
// {
|
||||
// IEnumerable<ExportableDescriptor<IServerDiscoveryProvider>> providers =
|
||||
// _dependencyManager.GetServiceDescriptors<IServerDiscoveryProvider>(new ServerDefinition("SqlServer", "local"));
|
||||
// Assert.NotNull(providers);
|
||||
// Assert.True(providers.Count() == 1);
|
||||
// }
|
||||
|
||||
// [Fact]
|
||||
|
||||
// public void GetShouldReturnTheServiceWithTheHighestPriorityIdMultipleFound()
|
||||
// {
|
||||
// IServerDiscoveryProvider expectedProvider = new Mock<IServerDiscoveryProvider>();
|
||||
// List<Lazy<IServerDiscoveryProvider, IExportableMetadata>> providers = new List<Lazy<IServerDiscoveryProvider, IExportableMetadata>>()
|
||||
// {
|
||||
// new Lazy<IServerDiscoveryProvider, IExportableMetadata>(() => new Mock<IServerDiscoveryProvider>(),
|
||||
// new ExportableAttribute("SqlServer", "Local", typeof(IServerDiscoveryProvider), Guid.NewGuid().ToString())),
|
||||
// new Lazy<IServerDiscoveryProvider, IExportableMetadata>(() => new Mock<IServerDiscoveryProvider>(),
|
||||
// new ExportableAttribute("SqlServer", "Network", typeof(IServerDiscoveryProvider), Guid.NewGuid().ToString(), 1)),
|
||||
// new Lazy<IServerDiscoveryProvider, IExportableMetadata>(() => expectedProvider,
|
||||
// new ExportableAttribute("SqlServer", "Network", typeof(IServerDiscoveryProvider), Guid.NewGuid().ToString(), 2))
|
||||
// };
|
||||
|
||||
// ExtensionProperties serviceProperties = FakeDataFactory.CreateServiceProperties(providers);
|
||||
// DependencyManager dependencyManager = new DependencyManager(serviceProperties);
|
||||
|
||||
// IEnumerable<ExportableDescriptor<IServerDiscoveryProvider>> descriptors =
|
||||
// dependencyManager.GetServiceDescriptors<IServerDiscoveryProvider>();
|
||||
// Assert.NotNull(descriptors);
|
||||
|
||||
// ExportableDescriptor<IServerDiscoveryProvider> descriptor = descriptors.FindMatchedDescriptor(new ServerDefinition("SqlServer", "network"));
|
||||
// Assert.NotNull(descriptor);
|
||||
// Assert.True(descriptor.Exportable == expectedProvider);
|
||||
// }
|
||||
|
||||
// [Fact]
|
||||
// public void GetShouldReturnTheServiceEvenIfTheServerTypeNotSet()
|
||||
// {
|
||||
// IServerDiscoveryProvider expectedProvider = new Mock<IServerDiscoveryProvider>();
|
||||
// List<Lazy<IServerDiscoveryProvider, IExportableMetadata>> providers = new List<Lazy<IServerDiscoveryProvider, IExportableMetadata>>()
|
||||
// {
|
||||
// new Lazy<IServerDiscoveryProvider, IExportableMetadata>(() => new Mock<IServerDiscoveryProvider>(),
|
||||
// new ExportableAttribute("SqlServer", "", typeof(IServerDiscoveryProvider), Guid.NewGuid().ToString())),
|
||||
// new Lazy<IServerDiscoveryProvider, IExportableMetadata>(() => new Mock<IServerDiscoveryProvider>(),
|
||||
// new ExportableAttribute("SqlServer", "Network", typeof(IServerDiscoveryProvider), Guid.NewGuid().ToString(), 1)),
|
||||
// new Lazy<IServerDiscoveryProvider, IExportableMetadata>(() => expectedProvider,
|
||||
// new ExportableAttribute("", "Network", typeof(IServerDiscoveryProvider), Guid.NewGuid().ToString(), 2))
|
||||
// };
|
||||
|
||||
// ExtensionProperties serviceProperties = FakeDataFactory.CreateServiceProperties(providers);
|
||||
// DependencyManager dependencyManager = new DependencyManager(serviceProperties);
|
||||
|
||||
// IEnumerable<ExportableDescriptor<IServerDiscoveryProvider>> descriptors =
|
||||
// dependencyManager.GetServiceDescriptors<IServerDiscoveryProvider>();
|
||||
// Assert.NotNull(descriptors);
|
||||
|
||||
// ExportableDescriptor<IServerDiscoveryProvider> descriptor = descriptors.FindMatchedDescriptor(new ServerDefinition("", "network"));
|
||||
// Assert.NotNull(descriptor);
|
||||
// Assert.True(descriptor.Exportable == expectedProvider);
|
||||
// }
|
||||
|
||||
// [Fact]
|
||||
// public void GetShouldReturnTheServiceThatMatchedExactlyIfServerTypeSpecified()
|
||||
// {
|
||||
// IServerDiscoveryProvider expectedProvider = new Mock<IServerDiscoveryProvider>();
|
||||
// List<Lazy<IServerDiscoveryProvider, IExportableMetadata>> providers = new List<Lazy<IServerDiscoveryProvider, IExportableMetadata>>()
|
||||
// {
|
||||
// new Lazy<IServerDiscoveryProvider, IExportableMetadata>(() => new Mock<IServerDiscoveryProvider>(),
|
||||
// new ExportableAttribute("SqlServer", "", typeof(IServerDiscoveryProvider), Guid.NewGuid().ToString())),
|
||||
// new Lazy<IServerDiscoveryProvider, IExportableMetadata>(() => expectedProvider,
|
||||
// new ExportableAttribute("SqlServer", "Network", typeof(IServerDiscoveryProvider), Guid.NewGuid().ToString(), 1)),
|
||||
// new Lazy<IServerDiscoveryProvider, IExportableMetadata>(() => new Mock<IServerDiscoveryProvider>(),
|
||||
// new ExportableAttribute("", "Network", typeof(IServerDiscoveryProvider), Guid.NewGuid().ToString(), 2))
|
||||
// };
|
||||
|
||||
// ExtensionProperties serviceProperties = FakeDataFactory.CreateServiceProperties(providers);
|
||||
// DependencyManager dependencyManager = new DependencyManager(serviceProperties);
|
||||
|
||||
// IEnumerable<ExportableDescriptor<IServerDiscoveryProvider>> descriptors =
|
||||
// dependencyManager.GetServiceDescriptors<IServerDiscoveryProvider>();
|
||||
// Assert.NotNull(descriptors);
|
||||
|
||||
// ExportableDescriptor<IServerDiscoveryProvider> descriptor = descriptors.FindMatchedDescriptor(new ServerDefinition("SqlServer", "network"));
|
||||
// Assert.NotNull(descriptor);
|
||||
// Assert.True(descriptor.Exportable == expectedProvider);
|
||||
// }
|
||||
|
||||
// [Fact]
|
||||
// public void GetShouldReturnTheServiceThatMatchedExactlyIfCategorySpecified()
|
||||
// {
|
||||
// IServerDiscoveryProvider expectedProvider = new Mock<IServerDiscoveryProvider>();
|
||||
// List<Lazy<IServerDiscoveryProvider, IExportableMetadata>> providers = new List<Lazy<IServerDiscoveryProvider, IExportableMetadata>>()
|
||||
// {
|
||||
// new Lazy<IServerDiscoveryProvider, IExportableMetadata>(() => new Mock<IServerDiscoveryProvider>(),
|
||||
// new ExportableAttribute("SqlServer", "", typeof(IServerDiscoveryProvider), Guid.NewGuid().ToString())),
|
||||
// new Lazy<IServerDiscoveryProvider, IExportableMetadata>(() => expectedProvider,
|
||||
// new ExportableAttribute("SqlServer", "Network", typeof(IServerDiscoveryProvider), Guid.NewGuid().ToString(), 1)),
|
||||
// new Lazy<IServerDiscoveryProvider, IExportableMetadata>(() => new Mock<IServerDiscoveryProvider>(),
|
||||
// new ExportableAttribute("", "Network", typeof(IServerDiscoveryProvider), Guid.NewGuid().ToString(), 2))
|
||||
// };
|
||||
|
||||
// ExtensionProperties serviceProperties = FakeDataFactory.CreateServiceProperties(providers);
|
||||
// DependencyManager dependencyManager = new DependencyManager(serviceProperties);
|
||||
|
||||
// IEnumerable<ExportableDescriptor<IServerDiscoveryProvider>> descriptors =
|
||||
// dependencyManager.GetServiceDescriptors<IServerDiscoveryProvider>();
|
||||
// Assert.NotNull(descriptors);
|
||||
|
||||
// ExportableDescriptor<IServerDiscoveryProvider> descriptor = descriptors.FindMatchedDescriptor(new ServerDefinition("SqlServer", "network"));
|
||||
// Assert.NotNull(descriptor);
|
||||
// Assert.True(descriptor.Exportable == expectedProvider);
|
||||
// }
|
||||
|
||||
// [Fact]
|
||||
|
||||
// public void GetShouldReturnTheServiceEvenIfTheCategoryNotSet()
|
||||
// {
|
||||
// IServerDiscoveryProvider expectedProvider = new Mock<IServerDiscoveryProvider>();
|
||||
// List<Lazy<IServerDiscoveryProvider, IExportableMetadata>> providers = new List<Lazy<IServerDiscoveryProvider, IExportableMetadata>>()
|
||||
// {
|
||||
// new Lazy<IServerDiscoveryProvider, IExportableMetadata>(() => new Mock<IServerDiscoveryProvider>(),
|
||||
// new ExportableAttribute("SqlServer", "Local", typeof(IServerDiscoveryProvider), Guid.NewGuid().ToString())),
|
||||
// new Lazy<IServerDiscoveryProvider, IExportableMetadata>(() => new Mock<IServerDiscoveryProvider>(),
|
||||
// new ExportableAttribute("SqlServer", "Network", typeof(IServerDiscoveryProvider), Guid.NewGuid().ToString(), 1)),
|
||||
// new Lazy<IServerDiscoveryProvider, IExportableMetadata>(() => expectedProvider,
|
||||
// new ExportableAttribute("SqlServer", "", typeof(IServerDiscoveryProvider), Guid.NewGuid().ToString(), 2))
|
||||
// };
|
||||
|
||||
// ExtensionProperties serviceProperties = FakeDataFactory.CreateServiceProperties(providers);
|
||||
// DependencyManager dependencyManager = new DependencyManager(serviceProperties);
|
||||
|
||||
// IEnumerable<ExportableDescriptor<IServerDiscoveryProvider>> descriptors =
|
||||
// dependencyManager.GetServiceDescriptors<IServerDiscoveryProvider>();
|
||||
// Assert.NotNull(descriptors);
|
||||
|
||||
// ExportableDescriptor<IServerDiscoveryProvider> descriptor = descriptors.FindMatchedDescriptor(new ServerDefinition("SqlServer", ""));
|
||||
// Assert.NotNull(descriptor);
|
||||
// Assert.True(descriptor.Exportable == expectedProvider);
|
||||
// }
|
||||
|
||||
// [Fact]
|
||||
// public void GetShouldReturnProvidersGivenServerTypeAndMoreThanOneLocation()
|
||||
// {
|
||||
// var serverType = "sqlServer";
|
||||
// IEnumerable<ExportableDescriptor<IServerDiscoveryProvider>> providers =
|
||||
// _dependencyManager.GetServiceDescriptors<IServerDiscoveryProvider>(new ServerDefinition(serverType, null));
|
||||
// Assert.NotNull(providers);
|
||||
// Assert.True(providers.Count() == _providers.Count(x => x.Metadata.ServerType.Equals(serverType, StringComparison.OrdinalIgnoreCase)));
|
||||
// }
|
||||
|
||||
// [Fact]
|
||||
// public async Task ProviderCreatedByFactoryShouldReturnServersSuccessfully()
|
||||
// {
|
||||
// List<ServerInstanceInfo> expectedServers = _localSqlServers;
|
||||
// IEnumerable<ExportableDescriptor<IServerDiscoveryProvider>> providers =
|
||||
// _dependencyManager.GetServiceDescriptors<IServerDiscoveryProvider>(new ServerDefinition("SqlServer",
|
||||
// "local"));
|
||||
// ExportableDescriptor<IServerDiscoveryProvider> provider = providers.First();
|
||||
// Assert.NotNull(provider);
|
||||
// ServiceResponse<ServerInstanceInfo> result = await provider.Exportable.GetServerInstancesAsync();
|
||||
// var servers = result.Data;
|
||||
// Assert.NotNull(servers);
|
||||
// Assert.Equal(expectedServers, servers);
|
||||
// }
|
||||
// }
|
||||
//}
|
||||
@@ -0,0 +1,72 @@
|
||||
//
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
|
||||
|
||||
using System;
|
||||
using System.Data.Common;
|
||||
using Microsoft.SqlTools.ResourceProvider.Core;
|
||||
using Moq;
|
||||
using Xunit;
|
||||
|
||||
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ResourceProvider
|
||||
{
|
||||
/// <summary>
|
||||
/// Tests for ExceptionUtil to verify the helper and extension methods
|
||||
/// </summary>
|
||||
public class ExceptionUtilTest
|
||||
{
|
||||
[Fact]
|
||||
public void IsSqlExceptionShouldReturnFalseGivenNullException()
|
||||
{
|
||||
Exception exception = null;
|
||||
bool expected = false;
|
||||
bool actual = exception.IsDbException();
|
||||
Assert.Equal(expected, actual);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void IsSqlExceptionShouldReturnFalseGivenNonSqlException()
|
||||
{
|
||||
Exception exception = new ApplicationException();
|
||||
bool expected = false;
|
||||
bool actual = exception.IsDbException();
|
||||
Assert.Equal(expected, actual);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void IsSqlExceptionShouldReturnFalseGivenNonSqlExceptionWithInternalException()
|
||||
{
|
||||
Exception exception = new ApplicationException("Exception message", new ServiceFailedException());
|
||||
bool expected = false;
|
||||
bool actual = exception.IsDbException();
|
||||
Assert.Equal(expected, actual);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void IsSqlExceptionShouldReturnTrueGivenSqlException()
|
||||
{
|
||||
Exception exception = CreateDbException();
|
||||
Assert.NotNull(exception);
|
||||
|
||||
bool expected = true;
|
||||
bool actual = exception.IsDbException();
|
||||
Assert.Equal(expected, actual);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void IsSqlExceptionShouldReturnTrueGivenExceptionWithInnerSqlException()
|
||||
{
|
||||
Exception exception = new ApplicationException("", CreateDbException());
|
||||
Assert.NotNull(exception);
|
||||
|
||||
bool expected = true;
|
||||
bool actual = exception.IsDbException();
|
||||
Assert.Equal(expected, actual);
|
||||
}
|
||||
|
||||
private Exception CreateDbException()
|
||||
{
|
||||
return new Mock<DbException>().Object;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
//
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
|
||||
|
||||
using System;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.SqlTools.Extensibility;
|
||||
using Microsoft.SqlTools.ResourceProvider.Core;
|
||||
using Microsoft.SqlTools.ResourceProvider.Core.Authentication;
|
||||
using Microsoft.SqlTools.ResourceProvider.Core.Extensibility;
|
||||
|
||||
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ResourceProvider.Fakes
|
||||
{
|
||||
[Exportable(ServerTypes.SqlServer, Categories.Azure,
|
||||
typeof(IAccountManager),
|
||||
"Microsoft.SqlTools.ServiceLayer.UnitTests.ResourceProvider.Fakes.FakeAccountManager", 1)]
|
||||
public class FakeAccountManager : IAccountManager
|
||||
{
|
||||
public FakeAccountManager(IExportableMetadata metadata)
|
||||
{
|
||||
Metadata = metadata;
|
||||
}
|
||||
|
||||
public ITrace Trace { get; set; }
|
||||
public Task<bool> GetUserNeedsReauthenticationAsync()
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public Task<IUserAccount> AuthenticateAsync()
|
||||
{
|
||||
throw new System.NotImplementedException();
|
||||
}
|
||||
|
||||
public bool IsCachExpired { get; private set; }
|
||||
public bool SessionIsCached { get; private set; }
|
||||
public void ResetSession()
|
||||
{
|
||||
throw new System.NotImplementedException();
|
||||
}
|
||||
|
||||
public Task<IUserAccount> AddUserAccountAsync()
|
||||
{
|
||||
throw new System.NotImplementedException();
|
||||
}
|
||||
|
||||
public Task<IUserAccount> SetCurrentAccountAsync(object account)
|
||||
{
|
||||
throw new System.NotImplementedException();
|
||||
}
|
||||
|
||||
public Task<IUserAccount> SetCurrentAccountFromLoginDialogAsync()
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public Task<IUserAccount> GetCurrentAccountAsync()
|
||||
{
|
||||
throw new System.NotImplementedException();
|
||||
}
|
||||
|
||||
public bool HasLoginDialog { get; }
|
||||
|
||||
public event EventHandler CurrentAccountChanged;
|
||||
|
||||
public IUserAccount SetCurrentAccount(object account)
|
||||
{
|
||||
if (CurrentAccountChanged != null)
|
||||
{
|
||||
CurrentAccountChanged(this, null);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public void SetServiceProvider(IMultiServiceProvider provider)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public IExportableMetadata Metadata { get; set; }
|
||||
public ExportableStatus Status { get; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
//
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
|
||||
|
||||
using System;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.SqlTools.Extensibility;
|
||||
using Microsoft.SqlTools.ResourceProvider.Core.Authentication;
|
||||
using Microsoft.SqlTools.ResourceProvider.Core.Extensibility;
|
||||
|
||||
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ResourceProvider.Fakes
|
||||
{
|
||||
[Exportable("SqlServer", "Network",
|
||||
typeof(IAccountManager), "Microsoft.SqlTools.ServiceLayer.UnitTests.ResourceProvider.Fakes.FakeAccountManager2", 2)]
|
||||
public class FakeAccountManager2 : IAccountManager
|
||||
{
|
||||
public FakeAccountManager2(IExportableMetadata metadata)
|
||||
{
|
||||
Metadata = metadata;
|
||||
}
|
||||
|
||||
public ITrace Trace { get; set; }
|
||||
public Task<bool> GetUserNeedsReauthenticationAsync()
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public Task<IUserAccount> AuthenticateAsync()
|
||||
{
|
||||
throw new System.NotImplementedException();
|
||||
}
|
||||
|
||||
public bool IsCachExpired { get; private set; }
|
||||
public bool SessionIsCached { get; private set; }
|
||||
public void ResetSession()
|
||||
{
|
||||
throw new System.NotImplementedException();
|
||||
}
|
||||
|
||||
public Task<IUserAccount> AddUserAccountAsync()
|
||||
{
|
||||
throw new System.NotImplementedException();
|
||||
}
|
||||
|
||||
public Task<IUserAccount> SetCurrentAccountAsync(object account)
|
||||
{
|
||||
throw new System.NotImplementedException();
|
||||
}
|
||||
|
||||
public Task<IUserAccount> SetCurrentAccountFromLoginDialogAsync()
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public Task<IUserAccount> GetCurrentAccountAsync()
|
||||
{
|
||||
throw new System.NotImplementedException();
|
||||
}
|
||||
|
||||
public bool HasLoginDialog { get; }
|
||||
|
||||
public event EventHandler CurrentAccountChanged;
|
||||
|
||||
public IUserAccount SetCurrentAccount(object account)
|
||||
{
|
||||
if (CurrentAccountChanged != null)
|
||||
{
|
||||
CurrentAccountChanged(this, null);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public void SetServiceProvider(IMultiServiceProvider provider)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public IExportableMetadata Metadata { get; set; }
|
||||
public ExportableStatus Status { get; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,193 @@
|
||||
//
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Data.SqlClient;
|
||||
using System.Diagnostics;
|
||||
using System.Linq;
|
||||
using Microsoft.SqlTools.ResourceProvider.Core;
|
||||
using Microsoft.SqlTools.ResourceProvider.Core.Extensibility;
|
||||
using Microsoft.SqlTools.ServiceLayer.UnitTests.ResourceProvider.Azure;
|
||||
using Moq;
|
||||
|
||||
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ResourceProvider.Fakes
|
||||
{
|
||||
internal static class FakeDataFactory
|
||||
{
|
||||
//public static ExtensionProperties CreateServiceProperties(IList<Lazy<IServerDiscoveryProvider, IExportableMetadata>> exports)
|
||||
//{
|
||||
// FakeExportProvider fakeProvider = new FakeExportProvider(f => ((FakeInstanceExportDefinition)f).Instance);
|
||||
// foreach (var export in exports)
|
||||
// {
|
||||
// var metadata = new Dictionary<string, object>()
|
||||
// {
|
||||
// {"ServerType", export.Metadata.ServerType},
|
||||
// {"Category", export.Metadata.Category},
|
||||
// {"Id", export.Metadata.Id },
|
||||
// {"Priority", export.Metadata.Priority}
|
||||
// };
|
||||
|
||||
// var definition = new FakeInstanceExportDefinition(typeof(IServerDiscoveryProvider), export.Value, metadata);
|
||||
// fakeProvider.AddExportDefinitions(definition);
|
||||
// }
|
||||
// var trace = new Mock<ITrace>();
|
||||
// trace.Setup(x => x.TraceEvent(It.IsAny<TraceEventType>(), It.IsAny<int>(), It.IsAny<string>(), It.IsAny<object[]>()))
|
||||
// .Returns(true);
|
||||
|
||||
// var metadata2 = new Dictionary<string, object>()
|
||||
// {
|
||||
// {"Id", Guid.NewGuid().ToString()},
|
||||
// {"Priority", 0}
|
||||
// };
|
||||
// var traceDefinition = new FakeInstanceExportDefinition(typeof(ITrace), trace, metadata2);
|
||||
// fakeProvider.AddExportDefinitions(traceDefinition);
|
||||
|
||||
// ExtensionProperties serviceProperties = new ExtensionProperties(false);
|
||||
// serviceProperties.Providers = new ExportProvider[] { fakeProvider };
|
||||
// TypeCatalog typeCatalog = new TypeCatalog(typeof(FakeTrace));
|
||||
// serviceProperties.AddCatalog(typeCatalog);
|
||||
// return serviceProperties;
|
||||
//}
|
||||
|
||||
internal static AzureDatabaseDiscoveryProvider CreateAzureDatabaseDiscoveryProvider(
|
||||
Dictionary<string, List<string>> subscriptionToDatabaseMap)
|
||||
{
|
||||
AzureTestContext testContext = new AzureTestContext(subscriptionToDatabaseMap);
|
||||
|
||||
AzureDatabaseDiscoveryProvider databaseDiscoveryProvider = new AzureDatabaseDiscoveryProvider();
|
||||
databaseDiscoveryProvider.AccountManager = testContext.AzureAccountManager;
|
||||
databaseDiscoveryProvider.AzureResourceManager = testContext.AzureResourceManager;
|
||||
|
||||
return databaseDiscoveryProvider;
|
||||
}
|
||||
|
||||
internal static AzureSqlServerDiscoveryProvider CreateAzureServerDiscoveryProvider(Dictionary<string, List<string>> subscriptionToDatabaseMap)
|
||||
{
|
||||
AzureTestContext testContext = new AzureTestContext(subscriptionToDatabaseMap);
|
||||
|
||||
AzureSqlServerDiscoveryProvider serverDiscoveryProvider = new AzureSqlServerDiscoveryProvider();
|
||||
serverDiscoveryProvider.AccountManager = testContext.AzureAccountManager;
|
||||
serverDiscoveryProvider.AzureResourceManager = testContext.AzureResourceManager;
|
||||
|
||||
return serverDiscoveryProvider;
|
||||
}
|
||||
|
||||
//internal static IDependencyManager AddDependencyProvider<T>(T provider,
|
||||
// ServerDefinition serverDefinition, IDependencyManager existingDependencyManager = null)
|
||||
// where T : IExportable
|
||||
//{
|
||||
// return AddDependencyProviders(new Dictionary<T,ServerDefinition>() {{ provider, serverDefinition}}, existingDependencyManager);
|
||||
//}
|
||||
|
||||
//internal static IDependencyManager AddDependencyProviders<T>(Dictionary<T, ServerDefinition> providers, IDependencyManager existingDependencyManager = null)
|
||||
// where T : IExportable
|
||||
//{
|
||||
// IDependencyManager dependencyManager = existingDependencyManager ?? new Mock<IDependencyManager>();
|
||||
|
||||
// IEnumerable<ExportableDescriptor<T>> exportableDescriptors =
|
||||
// providers.Select(x => new ExportableDescriptorImpl<T>(
|
||||
// new ExtensionDescriptor<T, IExportableMetadata>(
|
||||
// new Lazy<T, IExportableMetadata>(
|
||||
// () => x.Key,
|
||||
// new ExportableAttribute(x.Value.ServerType, x.Value.Category,
|
||||
// typeof (T), Guid.NewGuid().ToString())))));
|
||||
|
||||
// dependencyManager.Setup(x => x.GetServiceDescriptors<T>()).Returns(exportableDescriptors);
|
||||
|
||||
// return dependencyManager;
|
||||
//}
|
||||
|
||||
internal static ServiceResponse<ServerInstanceInfo> CreateServerInstanceResponse(int numberOfServers, ServerDefinition serverDefinition, Exception exception = null)
|
||||
{
|
||||
List<ServerInstanceInfo> servers = new List<ServerInstanceInfo>();
|
||||
for (int i = 0; i < numberOfServers; i++)
|
||||
{
|
||||
servers.Add(new ServerInstanceInfo(serverDefinition)
|
||||
{
|
||||
Name = Guid.NewGuid().ToString(),
|
||||
FullyQualifiedDomainName = Guid.NewGuid().ToString()
|
||||
});
|
||||
}
|
||||
ServiceResponse<ServerInstanceInfo> response;
|
||||
if (exception != null)
|
||||
{
|
||||
response = new ServiceResponse<ServerInstanceInfo>(servers, new List<Exception> { exception });
|
||||
}
|
||||
else
|
||||
{
|
||||
response = new ServiceResponse<ServerInstanceInfo>(servers);
|
||||
}
|
||||
|
||||
return response;
|
||||
}
|
||||
|
||||
internal static ServiceResponse<DatabaseInstanceInfo> CreateDatabaseInstanceResponse(int numberOfServers, ServerDefinition serverDefinition = null,
|
||||
string serverName = "", Exception exception = null)
|
||||
{
|
||||
serverDefinition = serverDefinition ?? ServerDefinition.Default;
|
||||
List<DatabaseInstanceInfo> databases = new List<DatabaseInstanceInfo>();
|
||||
for (int i = 0; i < numberOfServers; i++)
|
||||
{
|
||||
databases.Add(new DatabaseInstanceInfo(serverDefinition, serverName, Guid.NewGuid().ToString()));
|
||||
}
|
||||
ServiceResponse<DatabaseInstanceInfo> response;
|
||||
if (exception != null)
|
||||
{
|
||||
response = new ServiceResponse<DatabaseInstanceInfo>(databases, new List<Exception> { exception });
|
||||
}
|
||||
else
|
||||
{
|
||||
response = new ServiceResponse<DatabaseInstanceInfo>(databases);
|
||||
}
|
||||
|
||||
return response;
|
||||
}
|
||||
|
||||
//internal static UIConnectionInfo CreateUiConnectionInfo(string baseDbName)
|
||||
//{
|
||||
// SqlConnectionStringBuilder connectionStringBuilder = CreateConnectionStringBuilder(baseDbName);
|
||||
// return CreateUiConnectionInfo(connectionStringBuilder);
|
||||
//}
|
||||
//internal static UIConnectionInfo CreateUiConnectionInfo(SqlConnectionStringBuilder connectionStringBuilder)
|
||||
//{
|
||||
// UIConnectionInfo ci = UIConnectionInfoUtil.GetUIConnectionInfoFromConnectionString(connectionStringBuilder.ConnectionString, (new SqlServerType()));
|
||||
// ci.PersistPassword = connectionStringBuilder.PersistSecurityInfo;
|
||||
// return ci;
|
||||
//}
|
||||
|
||||
|
||||
//internal static SqlConnectionStringBuilder CreateConnectionStringBuilder(string baseDbName)
|
||||
//{
|
||||
// return CreateConnectionStringBuilder(baseDbName, InstanceManager.DefaultSql2011);
|
||||
//}
|
||||
|
||||
|
||||
//internal static SqlConnectionStringBuilder CreateConnectionStringBuilder(string baseDbName, InstanceInfo dbInstance)
|
||||
//{
|
||||
// string dbName = ConnectionDialogHelper.CreateTestDatabase(baseDbName, dbInstance);
|
||||
// string dbConnectionString = dbInstance.BuildConnectionString(dbName);
|
||||
// SqlConnectionStringBuilder connectionStringBuilder = new SqlConnectionStringBuilder(dbConnectionString);
|
||||
// connectionStringBuilder.ApplicationName = Guid.NewGuid().ToString();
|
||||
// connectionStringBuilder.ConnectTimeout = 123;
|
||||
// connectionStringBuilder.Encrypt = true;
|
||||
// connectionStringBuilder.ApplicationIntent = ApplicationIntent.ReadWrite;
|
||||
// connectionStringBuilder.AsynchronousProcessing = true;
|
||||
// connectionStringBuilder.MaxPoolSize = 45;
|
||||
// connectionStringBuilder.MinPoolSize = 3;
|
||||
// connectionStringBuilder.PacketSize = 600;
|
||||
// connectionStringBuilder.Pooling = true;
|
||||
// connectionStringBuilder.TrustServerCertificate = false;
|
||||
// return connectionStringBuilder;
|
||||
//}
|
||||
|
||||
//internal static ConnectionInfo CreateConnectionInfo(string baseDbName, IEventsChannel eventsChannel = null)
|
||||
//{
|
||||
// ConnectionInfo connectionInfo = new ConnectionInfo(eventsChannel);
|
||||
// UIConnectionInfo uiConnectionInfo = CreateUiConnectionInfo(baseDbName);
|
||||
// connectionInfo.UpdateConnectionInfo(uiConnectionInfo);
|
||||
// return connectionInfo;
|
||||
//}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
//
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
|
||||
|
||||
using System;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.SqlTools.Extensibility;
|
||||
using Microsoft.SqlTools.ResourceProvider.Core;
|
||||
using Microsoft.SqlTools.ResourceProvider.Core.Extensibility;
|
||||
|
||||
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ResourceProvider.Fakes
|
||||
{
|
||||
/// <summary>
|
||||
/// A fake database discovery class which generates db names for 5 seconds or until it gets canceled
|
||||
/// </summary>
|
||||
public class FakeDatabaseDiscoveryProvider : IDatabaseDiscoveryProvider
|
||||
{
|
||||
private TimeSpan _timeout = TimeSpan.FromSeconds(5);
|
||||
|
||||
public IExportableMetadata Metadata { get; set; }
|
||||
public ExportableStatus Status { get; }
|
||||
IExportableMetadata IExportable.Metadata { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }
|
||||
|
||||
ExportableStatus IExportable.Status => throw new NotImplementedException();
|
||||
|
||||
public Task<ServiceResponse<DatabaseInstanceInfo>> GetDatabaseInstancesAsync(string serverName, CancellationToken cancellationToken)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
//public Task<ServiceResponse<DatabaseInstanceInfo>> GetDatabaseInstancesAsync(UIConnectionInfo uiConnectionInfo, CancellationToken cancellationToken)
|
||||
//{
|
||||
// return Task.Factory.StartNew(() => GetDatabaseInstances(uiConnectionInfo, cancellationToken), cancellationToken);
|
||||
//}
|
||||
|
||||
//private ServiceResponse<DatabaseInstanceInfo> GetDatabaseInstances(UIConnectionInfo uiConnectionInfo, CancellationToken cancellationToken)
|
||||
//{
|
||||
// List<DatabaseInstanceInfo> databases = new List<DatabaseInstanceInfo>();
|
||||
// DateTime startTime = DateTime.UtcNow;
|
||||
// while (!cancellationToken.IsCancellationRequested)
|
||||
// {
|
||||
// DateTime now = DateTime.UtcNow;
|
||||
// if (now.Subtract(startTime).TotalMilliseconds >= _timeout.TotalMilliseconds)
|
||||
// {
|
||||
// break;
|
||||
// }
|
||||
// databases.Add(new DatabaseInstanceInfo(ServerDefinition.Default, uiConnectionInfo.ServerName, uiConnectionInfo.ServerName + "" + Guid.NewGuid().ToString()));
|
||||
// }
|
||||
|
||||
// return new ServiceResponse<DatabaseInstanceInfo>(databases);
|
||||
//}
|
||||
|
||||
private static void TimerCallback(object state)
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
private void OnDatabaseFound(DatabaseInstanceInfo databaseInfo)
|
||||
{
|
||||
if (DatabaseFound != null)
|
||||
{
|
||||
DatabaseFound(this, new DatabaseInfoEventArgs() { Database = databaseInfo });
|
||||
}
|
||||
}
|
||||
|
||||
public void SetServiceProvider(IMultiServiceProvider provider)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public event EventHandler<DatabaseInfoEventArgs> DatabaseFound;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
//
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
|
||||
|
||||
using Microsoft.SqlTools.ResourceProvider.Core.Extensibility;
|
||||
|
||||
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ResourceProvider.Fakes
|
||||
{
|
||||
public interface IDatabaseResourceManager
|
||||
{
|
||||
}
|
||||
|
||||
[Exportable(FakeServerDiscoveryProvider.ServerTypeValue, FakeServerDiscoveryProvider.CategoryValue
|
||||
, typeof(IDatabaseResourceManager), "Microsoft.SqlTools.ServiceLayer.UnitTests.ResourceProvider.Fakes.FakeDatabaseResourceManager")]
|
||||
public class FakeDatabaseResourceManager : IDatabaseResourceManager
|
||||
{
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
//
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
|
||||
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.SqlTools.ResourceProvider.Core;
|
||||
using Microsoft.SqlTools.ResourceProvider.Core.Authentication;
|
||||
using Microsoft.SqlTools.ResourceProvider.Core.Extensibility;
|
||||
|
||||
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ResourceProvider.Fakes
|
||||
{
|
||||
[Exportable("SqlServer", "azure", typeof(IServerDiscoveryProvider),
|
||||
"Microsoft.SqlTools.ServiceLayer.UnitTests.ResourceProvider.Fakes.FakeSecureServerDiscoveryProvider")]
|
||||
public class FakeSecureServerDiscoveryProvider : ExportableBase, IServerDiscoveryProvider, ISecureService
|
||||
{
|
||||
public FakeSecureServerDiscoveryProvider(IExportableMetadata metadata)
|
||||
{
|
||||
Metadata = metadata;
|
||||
}
|
||||
|
||||
public async Task<ServiceResponse<ServerInstanceInfo>> GetServerInstancesAsync()
|
||||
{
|
||||
return await Task.Run(() => new ServiceResponse<ServerInstanceInfo>());
|
||||
}
|
||||
|
||||
public IDatabaseResourceManager DatabaseResourceManager
|
||||
{
|
||||
get;
|
||||
set;
|
||||
}
|
||||
|
||||
public IAccountManager AccountManager
|
||||
{
|
||||
get
|
||||
{
|
||||
return GetService<IAccountManager>();
|
||||
}
|
||||
set
|
||||
{
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
//
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
|
||||
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.SqlTools.ResourceProvider.Core;
|
||||
using Microsoft.SqlTools.ResourceProvider.Core.Extensibility;
|
||||
|
||||
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ResourceProvider.Fakes
|
||||
{
|
||||
[Exportable(ServerTypeValue, CategoryValue
|
||||
, typeof(IServerDiscoveryProvider),
|
||||
"Microsoft.SqlTools.ServiceLayer.UnitTests.ResourceProvider.Fakes.FakeServerDiscoveryProvider")]
|
||||
public class FakeServerDiscoveryProvider : ExportableBase, IServerDiscoveryProvider
|
||||
{
|
||||
public FakeServerDiscoveryProvider(IExportableMetadata metadata)
|
||||
{
|
||||
Metadata = metadata;
|
||||
}
|
||||
|
||||
public async Task<ServiceResponse<ServerInstanceInfo>> GetServerInstancesAsync()
|
||||
{
|
||||
return await Task.Run(() => new ServiceResponse<ServerInstanceInfo>());
|
||||
}
|
||||
|
||||
|
||||
public IDatabaseResourceManager DatabaseResourceManager
|
||||
{
|
||||
get;
|
||||
set;
|
||||
}
|
||||
|
||||
public const string ServerTypeValue = "FakeServerType";
|
||||
public const string CategoryValue = "FakeCategory";
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
//
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
|
||||
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.SqlTools.ResourceProvider.Core;
|
||||
using Microsoft.SqlTools.ResourceProvider.Core.Extensibility;
|
||||
|
||||
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ResourceProvider.Fakes
|
||||
{
|
||||
public class FakeServerDiscoveryProvider2 : ExportableBase, IServerDiscoveryProvider
|
||||
{
|
||||
public FakeServerDiscoveryProvider2(IExportableMetadata metadata)
|
||||
{
|
||||
Metadata = metadata;
|
||||
}
|
||||
|
||||
public async Task<ServiceResponse<ServerInstanceInfo>> GetServerInstancesAsync()
|
||||
{
|
||||
return await Task.Run(() => new ServiceResponse<ServerInstanceInfo>());
|
||||
}
|
||||
|
||||
|
||||
public IDatabaseResourceManager DatabaseResourceManager
|
||||
{
|
||||
get;
|
||||
set;
|
||||
}
|
||||
|
||||
public const string ServerTypeValue = "FakeServerType";
|
||||
public const string CategoryValue = "FakeCategory";
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
//
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using Microsoft.SqlTools.Extensibility;
|
||||
using Microsoft.SqlTools.ResourceProvider.Core.Extensibility;
|
||||
|
||||
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ResourceProvider.Fakes
|
||||
{
|
||||
[Exportable(typeof(ITrace), "Microsoft.SqlTools.ServiceLayer.UnitTests.ResourceProvider.Fakes.FakeTrace")
|
||||
]
|
||||
public class FakeTrace : ITrace
|
||||
{
|
||||
private readonly List<string> _traces = new List<string>();
|
||||
public bool TraceEvent(TraceEventType eventType, int traceId, string message, params object[] args)
|
||||
{
|
||||
_traces.Add(message);
|
||||
return true;
|
||||
}
|
||||
|
||||
public bool TraceException(TraceEventType eventType, int traceId, Exception exception, string message, int lineNumber = 0,
|
||||
string fileName = "", string memberName = "")
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
public void SetServiceProvider(IMultiServiceProvider provider)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public IEnumerable<string> Traces
|
||||
{
|
||||
get
|
||||
{
|
||||
return _traces;
|
||||
}
|
||||
}
|
||||
|
||||
public IExportableMetadata Metadata { get; set; }
|
||||
public ExportableStatus Status { get; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
//
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
|
||||
|
||||
using System;
|
||||
using Microsoft.SqlTools.ResourceProvider.Core.FirewallRule;
|
||||
using Xunit;
|
||||
|
||||
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ResourceProvider
|
||||
{
|
||||
/// <summary>
|
||||
/// Tests to verify FirewallErrorParser
|
||||
/// </summary>
|
||||
public class FirewallErrorParserTest
|
||||
{
|
||||
private const int SqlAzureFirewallBlockedErrorNumber = 40615;
|
||||
private const int SqlAzureLoginFailedErrorNumber = 18456;
|
||||
private string _errorMessage = "error Message with 1.2.3.4 as IP address";
|
||||
private FirewallErrorParser _firewallErrorParser = new FirewallErrorParser();
|
||||
|
||||
|
||||
[Fact]
|
||||
public void ParseExceptionShouldThrowExceptionGivenNullErrorMessage()
|
||||
{
|
||||
string errorMessage = null;
|
||||
int errorCode = SqlAzureFirewallBlockedErrorNumber;
|
||||
|
||||
Assert.Throws<ArgumentNullException>("errorMessage", () =>
|
||||
{
|
||||
FirewallParserResponse response = _firewallErrorParser.ParseErrorMessage(errorMessage, errorCode);
|
||||
Assert.False(response.FirewallRuleErrorDetected);
|
||||
});
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ParseExceptionShouldReturnFireWallRuleNotDetectedGivenDifferentError()
|
||||
{
|
||||
int errorCode = 123;
|
||||
|
||||
FirewallParserResponse response = _firewallErrorParser.ParseErrorMessage(_errorMessage, errorCode);
|
||||
Assert.False(response.FirewallRuleErrorDetected);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ParseExceptionShouldReturnFireWallRuleNotDetectedGivenLoginFailedError()
|
||||
{
|
||||
int errorCode = SqlAzureLoginFailedErrorNumber;
|
||||
|
||||
FirewallParserResponse response = _firewallErrorParser.ParseErrorMessage(_errorMessage, errorCode);
|
||||
Assert.False(response.FirewallRuleErrorDetected);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ParseExceptionShouldReturnFireWallRuleNotDetectedGivenInvalidErrorMessage()
|
||||
{
|
||||
int errorCode = SqlAzureFirewallBlockedErrorNumber;
|
||||
string errorMessage = "error Message with no IP address";
|
||||
FirewallParserResponse response = _firewallErrorParser.ParseErrorMessage(errorMessage, errorCode);
|
||||
Assert.False(response.FirewallRuleErrorDetected);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ParseExceptionShouldReturnFireWallRuleDetectedGivenValidErrorMessage()
|
||||
{
|
||||
int errorCode = SqlAzureFirewallBlockedErrorNumber;
|
||||
FirewallParserResponse response = _firewallErrorParser.ParseErrorMessage(_errorMessage, errorCode);
|
||||
Assert.True(response.FirewallRuleErrorDetected);
|
||||
Assert.Equal(response.BlockedIpAddress.ToString(), "1.2.3.4");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,527 @@
|
||||
//
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.SqlTools.ResourceProvider.Core;
|
||||
using Microsoft.SqlTools.ResourceProvider.Core.Authentication;
|
||||
using Microsoft.SqlTools.ResourceProvider.Core.FirewallRule;
|
||||
using Moq;
|
||||
using Xunit;
|
||||
|
||||
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ResourceProvider
|
||||
{
|
||||
/// <summary>
|
||||
/// Tests to verify FirewallRuleService by mocking the azure authentication and resource managers
|
||||
/// </summary>
|
||||
public class FirewallRuleServiceTest
|
||||
{
|
||||
[Fact]
|
||||
public async Task CreateShouldThrowExceptionGivenNullServerName()
|
||||
{
|
||||
string serverName = null;
|
||||
|
||||
ServiceTestContext testContext = new ServiceTestContext();
|
||||
|
||||
await Assert.ThrowsAsync<FirewallRuleException>(() => VerifyCreateAsync(testContext, serverName));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CreateShouldThrowExceptionGivenNullStartIp()
|
||||
{
|
||||
string serverName = "serverName";
|
||||
|
||||
ServiceTestContext testContext = new ServiceTestContext();
|
||||
testContext.StartIpAddress = null;
|
||||
await Assert.ThrowsAsync<FirewallRuleException>(() => VerifyCreateAsync(testContext, serverName));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CreateShouldThrowExceptionGivenInvalidEndIp()
|
||||
{
|
||||
string serverName = "serverName";
|
||||
|
||||
ServiceTestContext testContext = new ServiceTestContext();
|
||||
testContext.EndIpAddress = "invalid ip";
|
||||
await Assert.ThrowsAsync<FirewallRuleException>(() => VerifyCreateAsync(testContext, serverName));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CreateShouldThrowExceptionGivenInvalidStartIp()
|
||||
{
|
||||
string serverName = "serverName";
|
||||
|
||||
ServiceTestContext testContext = new ServiceTestContext();
|
||||
testContext.StartIpAddress = "invalid ip";
|
||||
await Assert.ThrowsAsync<FirewallRuleException>(() => VerifyCreateAsync(testContext, serverName));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CreateShouldThrowExceptionGivenNullEndIp()
|
||||
{
|
||||
ServiceTestContext testContext = new ServiceTestContext();
|
||||
testContext.EndIpAddress = null;
|
||||
await Assert.ThrowsAsync<FirewallRuleException>(() => VerifyCreateAsync(testContext, testContext.ServerName));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CreateShouldThrowExceptionIfUserIsNotLoggedIn()
|
||||
{
|
||||
var applicationAuthenticationManagerMock = new Mock<IAzureAuthenticationManager>();
|
||||
applicationAuthenticationManagerMock.Setup(x => x.GetUserNeedsReauthenticationAsync()).Throws(new ApplicationException());
|
||||
var azureResourceManagerMock = new Mock<IAzureResourceManager>();
|
||||
|
||||
ServiceTestContext testContext = new ServiceTestContext();
|
||||
testContext.ApplicationAuthenticationManagerMock = applicationAuthenticationManagerMock;
|
||||
testContext.AzureResourceManagerMock = azureResourceManagerMock;
|
||||
|
||||
await Assert.ThrowsAsync<FirewallRuleException>(() => VerifyCreateAsync(testContext, testContext.ServerName));
|
||||
azureResourceManagerMock.Verify(x => x.CreateFirewallRuleAsync(
|
||||
It.IsAny<IAzureResourceManagementSession>(), It.IsAny<IAzureSqlServerResource>(), It.IsAny<FirewallRuleRequest>()),
|
||||
Times.Never);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CreateShouldThrowExceptionIfUserDoesNotHaveSubscriptions()
|
||||
{
|
||||
var applicationAuthenticationManagerMock =
|
||||
new Mock<IAzureAuthenticationManager>();
|
||||
applicationAuthenticationManagerMock.Setup(x => x.GetUserNeedsReauthenticationAsync()).Returns(Task.FromResult(false));
|
||||
applicationAuthenticationManagerMock.Setup(x => x.GetSubscriptionsAsync())
|
||||
.Returns(Task.FromResult(Enumerable.Empty<IAzureUserAccountSubscriptionContext>()));
|
||||
var azureResourceManagerMock = new Mock<IAzureResourceManager>();
|
||||
|
||||
ServiceTestContext testContext = new ServiceTestContext();
|
||||
testContext.ApplicationAuthenticationManagerMock = applicationAuthenticationManagerMock;
|
||||
testContext.AzureResourceManagerMock = azureResourceManagerMock;
|
||||
|
||||
await Assert.ThrowsAsync<FirewallRuleException>(() => VerifyCreateAsync(testContext, testContext.ServerName));
|
||||
azureResourceManagerMock.Verify(x => x.CreateFirewallRuleAsync(
|
||||
It.IsAny<IAzureResourceManagementSession>(), It.IsAny<IAzureSqlServerResource>(), It.IsAny<FirewallRuleRequest>()),
|
||||
Times.Never);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CreateShouldThrowExceptionIfAuthenticationManagerFailsToReturnSubscription()
|
||||
{
|
||||
var applicationAuthenticationManagerMock = new Mock<IAzureAuthenticationManager>();
|
||||
applicationAuthenticationManagerMock.Setup(x => x.GetUserNeedsReauthenticationAsync()).Returns(Task.FromResult(false));
|
||||
applicationAuthenticationManagerMock.Setup(x => x.GetSubscriptionsAsync()).Throws(new Exception());
|
||||
var azureResourceManagerMock = new Mock<IAzureResourceManager>();
|
||||
|
||||
ServiceTestContext testContext = new ServiceTestContext();
|
||||
testContext.ApplicationAuthenticationManagerMock = applicationAuthenticationManagerMock;
|
||||
testContext.AzureResourceManagerMock = azureResourceManagerMock;
|
||||
await Assert.ThrowsAsync<FirewallRuleException>(() => VerifyCreateAsync(testContext, "invalid server"));
|
||||
|
||||
azureResourceManagerMock.Verify(x => x.CreateFirewallRuleAsync(
|
||||
It.IsAny<IAzureResourceManagementSession>(), It.IsAny<IAzureSqlServerResource>(), It.IsAny<FirewallRuleRequest>()),
|
||||
Times.Never);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CreateShouldThrowExceptionGivenNoSubscriptionFound()
|
||||
{
|
||||
ServiceTestContext testContext = new ServiceTestContext();
|
||||
testContext = CreateMocks(testContext);
|
||||
await Assert.ThrowsAsync<FirewallRuleException>(() => VerifyCreateAsync(testContext, "invalid server"));
|
||||
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CreateShouldCreateFirewallSuccessfullyGivenValidUserAccount()
|
||||
{
|
||||
ServiceTestContext testContext = new ServiceTestContext();
|
||||
testContext = CreateMocks(testContext);
|
||||
|
||||
await VerifyCreateAsync(testContext, testContext.ServerName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CreateShouldFindTheRightSubscriptionGivenValidSubscriptionInFirstPlace()
|
||||
{
|
||||
ServiceTestContext testContext = new ServiceTestContext();
|
||||
testContext.Subscriptions = new List<IAzureUserAccountSubscriptionContext>
|
||||
{
|
||||
testContext.ValidSubscription,
|
||||
ServiceTestContext.CreateSubscriptionContext(),
|
||||
ServiceTestContext.CreateSubscriptionContext(),
|
||||
};
|
||||
|
||||
testContext = CreateMocks(testContext);
|
||||
|
||||
await VerifyCreateAsync(testContext, testContext.ServerName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CreateShouldFindTheRightSubscriptionGivenValidSubscriptionInSecondPlace()
|
||||
{
|
||||
ServiceTestContext testContext = new ServiceTestContext();
|
||||
testContext.Subscriptions = new List<IAzureUserAccountSubscriptionContext>
|
||||
{
|
||||
ServiceTestContext.CreateSubscriptionContext(),
|
||||
testContext.ValidSubscription,
|
||||
ServiceTestContext.CreateSubscriptionContext(),
|
||||
};
|
||||
testContext.Initialize();
|
||||
testContext = CreateMocks(testContext);
|
||||
await VerifyCreateAsync(testContext, testContext.ServerName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CreateShouldFindTheRightSubscriptionGivenValidSubscriptionInLastPlace()
|
||||
{
|
||||
ServiceTestContext testContext = new ServiceTestContext();
|
||||
testContext.Subscriptions = new List<IAzureUserAccountSubscriptionContext>
|
||||
{
|
||||
ServiceTestContext.CreateSubscriptionContext(),
|
||||
ServiceTestContext.CreateSubscriptionContext(),
|
||||
testContext.ValidSubscription
|
||||
};
|
||||
testContext.Initialize();
|
||||
|
||||
testContext = CreateMocks(testContext);
|
||||
|
||||
await VerifyCreateAsync(testContext, testContext.ServerName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CreateShouldFindTheRightResourceGivenValidResourceInLastPlace()
|
||||
{
|
||||
ServiceTestContext testContext = new ServiceTestContext();
|
||||
var resources = new List<IAzureSqlServerResource>
|
||||
{
|
||||
ServiceTestContext.CreateAzureSqlServer(Guid.NewGuid().ToString()),
|
||||
ServiceTestContext.CreateAzureSqlServer(testContext.ServerName),
|
||||
};
|
||||
testContext.SubscriptionToResourcesMap[testContext.ValidSubscription.Subscription.SubscriptionId] = resources;
|
||||
|
||||
testContext = CreateMocks(testContext);
|
||||
|
||||
await VerifyCreateAsync(testContext, testContext.ServerName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CreateShouldFindTheRightResourceGivenValidResourceInFirstPlace()
|
||||
{
|
||||
ServiceTestContext testContext = new ServiceTestContext();
|
||||
var resources = new List<IAzureSqlServerResource>
|
||||
{
|
||||
ServiceTestContext.CreateAzureSqlServer(testContext.ServerName),
|
||||
ServiceTestContext.CreateAzureSqlServer(Guid.NewGuid().ToString()),
|
||||
};
|
||||
testContext.SubscriptionToResourcesMap[testContext.ValidSubscription.Subscription.SubscriptionId] = resources;
|
||||
|
||||
testContext = CreateMocks(testContext);
|
||||
|
||||
await VerifyCreateAsync(testContext, testContext.ServerName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CreateShouldFindTheRightResourceGivenValidResourceInMiddle()
|
||||
{
|
||||
ServiceTestContext testContext = new ServiceTestContext();
|
||||
var resources = new List<IAzureSqlServerResource>
|
||||
{
|
||||
ServiceTestContext.CreateAzureSqlServer(Guid.NewGuid().ToString()),
|
||||
ServiceTestContext.CreateAzureSqlServer(testContext.ServerName),
|
||||
ServiceTestContext.CreateAzureSqlServer(Guid.NewGuid().ToString())
|
||||
};
|
||||
testContext.SubscriptionToResourcesMap[testContext.ValidSubscription.Subscription.SubscriptionId] = resources;
|
||||
|
||||
testContext = CreateMocks(testContext);
|
||||
|
||||
await VerifyCreateAsync(testContext, testContext.ServerName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CreateThrowExceptionIfResourceNotFound()
|
||||
{
|
||||
ServiceTestContext testContext = new ServiceTestContext();
|
||||
var resources = new List<IAzureSqlServerResource>
|
||||
{
|
||||
ServiceTestContext.CreateAzureSqlServer(Guid.NewGuid().ToString()),
|
||||
ServiceTestContext.CreateAzureSqlServer(Guid.NewGuid().ToString()),
|
||||
};
|
||||
testContext.SubscriptionToResourcesMap[testContext.ValidSubscription.Subscription.SubscriptionId] = resources;
|
||||
|
||||
testContext = CreateMocks(testContext);
|
||||
|
||||
await Assert.ThrowsAsync<FirewallRuleException>(() => VerifyCreateAsync(testContext, testContext.ServerName));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CreateThrowExceptionIfResourcesIsEmpty()
|
||||
{
|
||||
ServiceTestContext testContext = new ServiceTestContext();
|
||||
|
||||
testContext.SubscriptionToResourcesMap[testContext.ValidSubscription.Subscription.SubscriptionId] = new List<IAzureSqlServerResource>();
|
||||
testContext = CreateMocks(testContext);
|
||||
|
||||
await Assert.ThrowsAsync<FirewallRuleException>(() => VerifyCreateAsync(testContext, testContext.ServerName, false));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CreateShouldThrowExceptionIfThereIsNoSubscriptionForUser()
|
||||
{
|
||||
ServiceTestContext testContext = new ServiceTestContext();
|
||||
testContext.Subscriptions = new List<IAzureUserAccountSubscriptionContext>();
|
||||
|
||||
testContext = CreateMocks(testContext);
|
||||
|
||||
await Assert.ThrowsAsync<FirewallRuleException>(() => VerifyCreateAsync(testContext, testContext.ServerName, false));
|
||||
}
|
||||
|
||||
|
||||
[Fact]
|
||||
public async Task CreateShouldThrowExceptionIfSubscriptionIsInAnotherAccount()
|
||||
{
|
||||
ServiceTestContext testContext = new ServiceTestContext();
|
||||
testContext.Subscriptions = new List<IAzureUserAccountSubscriptionContext>
|
||||
{
|
||||
ServiceTestContext.CreateSubscriptionContext(),
|
||||
ServiceTestContext.CreateSubscriptionContext(),
|
||||
};
|
||||
|
||||
testContext = CreateMocks(testContext);
|
||||
await Assert.ThrowsAsync<FirewallRuleException>(() => VerifyCreateAsync(testContext, testContext.ServerName, false));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CreateShouldCreateFirewallForTheRightServerFullyQualifiedName()
|
||||
{
|
||||
ServiceTestContext testContext = new ServiceTestContext();
|
||||
string serverNameWithDifferentDomain = testContext.ServerNameWithoutDomain + ".myaliased.domain.name";
|
||||
|
||||
testContext.ServerName = serverNameWithDifferentDomain;
|
||||
testContext.Initialize();
|
||||
testContext = CreateMocks(testContext);
|
||||
|
||||
await VerifyCreateAsync(testContext, testContext.ServerName);
|
||||
}
|
||||
|
||||
private async Task<FirewallRuleResponse> VerifyCreateAsync(ServiceTestContext testContext, string serverName, bool verifyFirewallRuleCreated = true)
|
||||
{
|
||||
try
|
||||
{
|
||||
FirewallRuleService service = new FirewallRuleService();
|
||||
service.AuthenticationManager = testContext.ApplicationAuthenticationManager;
|
||||
service.ResourceManager = testContext.AzureResourceManager;
|
||||
FirewallRuleResponse response = await service.CreateFirewallRuleAsync(serverName, testContext.StartIpAddress, testContext.EndIpAddress);
|
||||
if (verifyFirewallRuleCreated)
|
||||
{
|
||||
testContext.AzureResourceManagerMock.Verify(x => x.CreateFirewallRuleAsync(
|
||||
It.Is<IAzureResourceManagementSession>(s => s.SubscriptionContext.Subscription.SubscriptionId == testContext.ValidSubscription.Subscription.SubscriptionId),
|
||||
It.Is<IAzureSqlServerResource>(r => r.FullyQualifiedDomainName == serverName),
|
||||
It.Is<FirewallRuleRequest>(y => y.EndIpAddress.ToString().Equals(testContext.EndIpAddress) && y.StartIpAddress.ToString().Equals(testContext.StartIpAddress))),
|
||||
Times.AtLeastOnce);
|
||||
}
|
||||
else
|
||||
{
|
||||
testContext.AzureResourceManagerMock.Verify(x => x.CreateFirewallRuleAsync(
|
||||
It.Is<IAzureResourceManagementSession>(s => s.SubscriptionContext.Subscription.SubscriptionId == testContext.ValidSubscription.Subscription.SubscriptionId),
|
||||
It.Is<IAzureSqlServerResource>(r => r.FullyQualifiedDomainName == serverName),
|
||||
It.Is<FirewallRuleRequest>(y => y.EndIpAddress.ToString().Equals(testContext.EndIpAddress) && y.StartIpAddress.ToString().Equals(testContext.StartIpAddress))),
|
||||
Times.Never);
|
||||
}
|
||||
|
||||
return response;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
if (ex is FirewallRuleException)
|
||||
{
|
||||
Assert.True(ex.InnerException == null || !(ex.InnerException is FirewallRuleException));
|
||||
}
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
private ServiceTestContext CreateMocks(ServiceTestContext testContext)
|
||||
{
|
||||
var accountMock = new Mock<IUserAccount>();
|
||||
accountMock.Setup(x => x.UniqueId).Returns(Guid.NewGuid().ToString());
|
||||
var applicationAuthenticationManagerMock = new Mock<IAzureAuthenticationManager>();
|
||||
applicationAuthenticationManagerMock.Setup(x => x.GetUserNeedsReauthenticationAsync())
|
||||
.Returns(Task.FromResult(false));
|
||||
applicationAuthenticationManagerMock.Setup(x => x.GetCurrentAccountAsync()).Returns(Task.FromResult(accountMock.Object));
|
||||
applicationAuthenticationManagerMock.Setup(x => x.GetSubscriptionsAsync()).Returns(Task.FromResult(testContext.Subscriptions as IEnumerable<IAzureUserAccountSubscriptionContext>));
|
||||
|
||||
var azureResourceManagerMock = new Mock<IAzureResourceManager>();
|
||||
|
||||
CreateMocksForResources(testContext, azureResourceManagerMock);
|
||||
|
||||
testContext.ApplicationAuthenticationManagerMock = applicationAuthenticationManagerMock;
|
||||
testContext.AzureResourceManagerMock = azureResourceManagerMock;
|
||||
return testContext;
|
||||
}
|
||||
|
||||
private void CreateMocksForResources(
|
||||
ServiceTestContext testContext,
|
||||
Mock<IAzureResourceManager> azureResourceManagerMock)
|
||||
{
|
||||
foreach (IAzureUserAccountSubscriptionContext subscription in testContext.Subscriptions)
|
||||
{
|
||||
var sessionMock = new Mock<IAzureResourceManagementSession>();
|
||||
sessionMock.Setup(x => x.SubscriptionContext).Returns(subscription);
|
||||
azureResourceManagerMock.Setup(x => x.CreateSessionAsync(subscription)).Returns(Task.FromResult(sessionMock.Object));
|
||||
|
||||
List<IAzureSqlServerResource> resources;
|
||||
if (testContext.SubscriptionToResourcesMap.TryGetValue(subscription.Subscription.SubscriptionId,
|
||||
out resources))
|
||||
{
|
||||
azureResourceManagerMock.Setup(x => x.GetSqlServerAzureResourcesAsync(It.Is<IAzureResourceManagementSession>(
|
||||
m => m.SubscriptionContext.Subscription.SubscriptionId == subscription.Subscription.SubscriptionId)))
|
||||
.Returns(Task.FromResult(resources as IEnumerable<IAzureSqlServerResource>));
|
||||
}
|
||||
else
|
||||
{
|
||||
azureResourceManagerMock.Setup(x => x.GetSqlServerAzureResourcesAsync(
|
||||
It.Is<IAzureResourceManagementSession>(m => m.SubscriptionContext.Subscription.SubscriptionId == subscription.Subscription.SubscriptionId)))
|
||||
.Returns(Task.FromResult<IEnumerable<IAzureSqlServerResource>>(null));
|
||||
}
|
||||
}
|
||||
|
||||
azureResourceManagerMock
|
||||
.Setup(x => x.CreateFirewallRuleAsync(
|
||||
It.IsAny<IAzureResourceManagementSession>(),
|
||||
It.IsAny<IAzureSqlServerResource>(),
|
||||
It.Is<FirewallRuleRequest>(
|
||||
y => y.EndIpAddress.ToString().Equals(testContext.EndIpAddress)
|
||||
&& y.StartIpAddress.ToString().Equals(testContext.StartIpAddress))))
|
||||
.Returns(Task.FromResult(new FirewallRuleResponse() {Created = true}));
|
||||
}
|
||||
}
|
||||
|
||||
internal class ServiceTestContext
|
||||
{
|
||||
private string _validServerName = "validServerName.database.windows.net";
|
||||
private string _startIpAddressValue = "1.2.3.6";
|
||||
private string _endIpAddressValue = "1.2.3.6";
|
||||
private Dictionary<string, List<IAzureSqlServerResource>> _subscriptionToResourcesMap;
|
||||
|
||||
public ServiceTestContext()
|
||||
{
|
||||
StartIpAddress = _startIpAddressValue;
|
||||
EndIpAddress = _endIpAddressValue;
|
||||
ServerName = _validServerName;
|
||||
Initialize();
|
||||
}
|
||||
|
||||
internal void Initialize()
|
||||
{
|
||||
CreateSubscriptions();
|
||||
CreateAzureResources();
|
||||
}
|
||||
|
||||
internal static IAzureUserAccountSubscriptionContext CreateSubscriptionContext()
|
||||
{
|
||||
var subscriptionContext = new Mock<IAzureUserAccountSubscriptionContext>();
|
||||
var subscriptionMock = new Mock<IAzureSubscriptionIdentifier>();
|
||||
subscriptionMock.Setup(x => x.SubscriptionId).Returns(Guid.NewGuid().ToString());
|
||||
subscriptionContext.Setup(x => x.Subscription).Returns(subscriptionMock.Object);
|
||||
return subscriptionContext.Object;
|
||||
}
|
||||
|
||||
private void CreateSubscriptions()
|
||||
{
|
||||
if (Subscriptions == null || Subscriptions.Count == 0)
|
||||
{
|
||||
|
||||
ValidSubscriptionMock = new Mock<IAzureUserAccountSubscriptionContext>();
|
||||
var subscriptionMock = new Mock<IAzureSubscriptionIdentifier>();
|
||||
subscriptionMock.Setup(x => x.SubscriptionId).Returns(Guid.NewGuid().ToString());
|
||||
ValidSubscriptionMock.Setup(x => x.Subscription).Returns(subscriptionMock.Object);
|
||||
|
||||
Subscriptions = new List<IAzureUserAccountSubscriptionContext>
|
||||
{
|
||||
ValidSubscription,
|
||||
CreateSubscriptionContext(),
|
||||
CreateSubscriptionContext()
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
internal void CreateAzureResources(Dictionary<string, List<IAzureSqlServerResource>> subscriptionToResourcesMap = null)
|
||||
{
|
||||
_subscriptionToResourcesMap = new Dictionary<string, List<IAzureSqlServerResource>>();
|
||||
|
||||
if (subscriptionToResourcesMap == null)
|
||||
{
|
||||
foreach (var subscriptionDetails in Subscriptions)
|
||||
{
|
||||
if (subscriptionDetails.Subscription.SubscriptionId == ValidSubscription.Subscription.SubscriptionId)
|
||||
{
|
||||
var resources = new List<IAzureSqlServerResource>();
|
||||
resources.Add(CreateAzureSqlServer(Guid.NewGuid().ToString()));
|
||||
resources.Add(CreateAzureSqlServer(Guid.NewGuid().ToString()));
|
||||
resources.Add(CreateAzureSqlServer(ServerName));
|
||||
_subscriptionToResourcesMap.Add(ValidSubscription.Subscription.SubscriptionId, resources);
|
||||
}
|
||||
else
|
||||
{
|
||||
var resources = new List<IAzureSqlServerResource>();
|
||||
resources.Add(CreateAzureSqlServer(Guid.NewGuid().ToString()));
|
||||
resources.Add(CreateAzureSqlServer(Guid.NewGuid().ToString()));
|
||||
_subscriptionToResourcesMap.Add(subscriptionDetails.Subscription.SubscriptionId, resources);
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
_subscriptionToResourcesMap = subscriptionToResourcesMap;
|
||||
}
|
||||
}
|
||||
|
||||
internal static IAzureSqlServerResource CreateAzureSqlServer(string serverName)
|
||||
{
|
||||
var azureSqlServer =
|
||||
new Mock<IAzureSqlServerResource>();
|
||||
azureSqlServer.Setup(x => x.Name).Returns(GetServerNameWithoutDomain(serverName));
|
||||
azureSqlServer.Setup(x => x.FullyQualifiedDomainName).Returns(serverName);
|
||||
return azureSqlServer.Object;
|
||||
}
|
||||
|
||||
internal Dictionary<string, List<IAzureSqlServerResource>> SubscriptionToResourcesMap
|
||||
{
|
||||
get { return _subscriptionToResourcesMap; }
|
||||
}
|
||||
|
||||
internal static string GetServerNameWithoutDomain(string serverName)
|
||||
{
|
||||
int index = serverName.IndexOf('.');
|
||||
if (index > 0)
|
||||
{
|
||||
return serverName.Substring(0, index);
|
||||
}
|
||||
return serverName;
|
||||
}
|
||||
|
||||
internal string StartIpAddress { get; set; }
|
||||
|
||||
internal string EndIpAddress { get; set; }
|
||||
|
||||
internal IList<IAzureUserAccountSubscriptionContext> Subscriptions { get; set; }
|
||||
|
||||
internal Mock<IAzureUserAccountSubscriptionContext> ValidSubscriptionMock { get; set; }
|
||||
internal IAzureUserAccountSubscriptionContext ValidSubscription { get { return ValidSubscriptionMock.Object; } }
|
||||
|
||||
internal string ServerName { get; set; }
|
||||
|
||||
internal string ServerNameWithoutDomain
|
||||
{
|
||||
get { return GetServerNameWithoutDomain(ServerName); }
|
||||
}
|
||||
|
||||
internal Mock<IAzureAuthenticationManager> ApplicationAuthenticationManagerMock { get; set; }
|
||||
internal IAzureAuthenticationManager ApplicationAuthenticationManager { get { return ApplicationAuthenticationManagerMock?.Object; } }
|
||||
|
||||
internal Mock<IAzureResourceManager> AzureResourceManagerMock { get; set; }
|
||||
|
||||
internal IAzureResourceManager AzureResourceManager { get { return AzureResourceManagerMock?.Object; } }
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
//
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Reflection;
|
||||
using Microsoft.SqlTools.Extensibility;
|
||||
using Microsoft.SqlTools.ResourceProvider.Core;
|
||||
using Microsoft.SqlTools.ResourceProvider.Core.Authentication;
|
||||
using Microsoft.SqlTools.ResourceProvider.Core.Extensibility;
|
||||
using Microsoft.SqlTools.ServiceLayer.UnitTests.ResourceProvider.Azure;
|
||||
using Microsoft.SqlTools.ServiceLayer.UnitTests.ResourceProvider.Fakes;
|
||||
using Moq;
|
||||
using Xunit;
|
||||
|
||||
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ResourceProvider
|
||||
{
|
||||
/// <summary>
|
||||
/// Tests for ServiceManager to verify finding services and providers for specific type correctly
|
||||
/// </summary>
|
||||
public class ServiceManagerTest
|
||||
{
|
||||
private IList<IServerDiscoveryProvider> _providers;
|
||||
private IList<IAccountManager> _accountManagers;
|
||||
|
||||
public ServiceManagerTest()
|
||||
{
|
||||
_providers = new List<IServerDiscoveryProvider>()
|
||||
{
|
||||
new FakeServerDiscoveryProvider2(new ExportableMetadata("SqlServer", "Local", Guid.NewGuid().ToString())),
|
||||
new FakeSecureServerDiscoveryProvider(new ExportableMetadata("SqlServer", "Azure", Guid.NewGuid().ToString())),
|
||||
new FakeServerDiscoveryProvider(new ExportableMetadata("SqlServer", "Network", Guid.NewGuid().ToString()))
|
||||
};
|
||||
|
||||
_accountManagers = new List<IAccountManager>()
|
||||
{
|
||||
new FakeAccountManager(new ExportableMetadata("SqlServer", "Azure", Guid.NewGuid().ToString())),
|
||||
new FakeAccountManager2(new ExportableMetadata("SqlServer", "Network", Guid.NewGuid().ToString()))
|
||||
};
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetServiceShouldReturnTheServiceThatHasGivenMetadataCorrectly()
|
||||
{
|
||||
//given
|
||||
var serverDefinition = new ServerDefinition("SqlServer", "Azure");
|
||||
IMultiServiceProvider provider = CreateServiceProvider();
|
||||
|
||||
//when
|
||||
IServerDiscoveryProvider service = ExtensionUtils.GetService<IServerDiscoveryProvider>(provider, serverDefinition);
|
||||
|
||||
//then
|
||||
Assert.NotNull(service);
|
||||
Assert.True(service.GetType() == typeof(FakeSecureServerDiscoveryProvider));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetServiceShouldReturnNullGivenInvalidMetadata()
|
||||
{
|
||||
//given
|
||||
var serverDefinition = new ServerDefinition(Guid.NewGuid().ToString(), Guid.NewGuid().ToString());
|
||||
IMultiServiceProvider provider = CreateServiceProvider();
|
||||
|
||||
//when
|
||||
IServerDiscoveryProvider service = ExtensionUtils.GetService<IServerDiscoveryProvider>(provider, serverDefinition);
|
||||
|
||||
//then
|
||||
Assert.Null(service);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetServiceShouldReturnNullGivenUnSupportedMetadata()
|
||||
{
|
||||
//given
|
||||
var serverDefinition = new ServerDefinition("SqlServer", "Local");
|
||||
IMultiServiceProvider provider = CreateServiceProvider();
|
||||
|
||||
//when
|
||||
IAccountManager service = ExtensionUtils.GetService<IAccountManager>(provider, serverDefinition);
|
||||
|
||||
//then
|
||||
Assert.Null(service);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RequiresUserAccountShouldReturnFalseGivenNotSecuredService()
|
||||
{
|
||||
//given
|
||||
var serverDefinition = new ServerDefinition("SqlServer", "Local");
|
||||
IMultiServiceProvider provider = CreateServiceProvider();
|
||||
|
||||
//when
|
||||
IServerDiscoveryProvider service = ExtensionUtils.GetService<IServerDiscoveryProvider>(provider, serverDefinition);
|
||||
|
||||
//then
|
||||
Assert.NotNull(service);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetShouldReturnDefaultAzureServiceGivenDefaultCatalog()
|
||||
{
|
||||
// given
|
||||
ExtensionServiceProvider provider = ExtensionServiceProvider.Create(new Assembly[]
|
||||
{
|
||||
typeof(IAccountManager).Assembly,
|
||||
typeof(IAzureResourceManager).Assembly
|
||||
});
|
||||
var serverDefinition = new ServerDefinition("sqlserver", "azure");
|
||||
|
||||
// when I query each provider
|
||||
IServerDiscoveryProvider serverDiscoveryProvider = ExtensionUtils.GetService<IServerDiscoveryProvider>(provider, serverDefinition);
|
||||
// Then I get a valid provider back
|
||||
Assert.NotNull(serverDiscoveryProvider);
|
||||
Assert.True(serverDiscoveryProvider is AzureSqlServerDiscoveryProvider);
|
||||
|
||||
IDatabaseDiscoveryProvider databaseDiscoveryProvider =
|
||||
ExtensionUtils.GetService<IDatabaseDiscoveryProvider>(provider, serverDefinition);
|
||||
|
||||
// TODO Verify account manager is detected as soon as the account manager has a real implementation
|
||||
//IAccountManager accountManager = ((AzureSqlServerDiscoveryProvider)serverDiscoveryProvider).AccountManager;
|
||||
//Assert.NotNull(accountManager);
|
||||
//Assert.True(accountManager is IAzureAuthenticationManager);
|
||||
|
||||
Assert.NotNull(databaseDiscoveryProvider);
|
||||
Assert.True(databaseDiscoveryProvider is AzureDatabaseDiscoveryProvider);
|
||||
}
|
||||
|
||||
|
||||
[Fact]
|
||||
public void GetShouldReturnImplementedAzureServiceIfFoundInCatalog()
|
||||
{
|
||||
//given
|
||||
ExtensionServiceProvider provider = ExtensionServiceProvider.Create(typeof(FakeAzureServerDiscoveryProvider).SingleItemAsEnumerable());
|
||||
|
||||
//when
|
||||
IServerDiscoveryProvider serverDiscoveryProvider = ExtensionUtils.GetService<IServerDiscoveryProvider>(provider, new ServerDefinition("sqlserver", "azure"));
|
||||
|
||||
Assert.NotNull(serverDiscoveryProvider);
|
||||
Assert.True(serverDiscoveryProvider is FakeAzureServerDiscoveryProvider);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetGetServiceOfExportableShouldReturnNullGivenSameTypeAsExportable()
|
||||
{
|
||||
//given
|
||||
ExtensionServiceProvider provider = ExtensionServiceProvider.Create(typeof(FakeAzureServerDiscoveryProvider).SingleItemAsEnumerable());
|
||||
|
||||
//when
|
||||
IServerDiscoveryProvider serverDiscoveryProvider = ExtensionUtils.GetService<IServerDiscoveryProvider>(provider, new ServerDefinition("sqlserver", "azure"));
|
||||
|
||||
Assert.NotNull(serverDiscoveryProvider);
|
||||
FakeAzureServerDiscoveryProvider fakeAzureServerDiscovery = serverDiscoveryProvider as FakeAzureServerDiscoveryProvider;
|
||||
Assert.NotNull(fakeAzureServerDiscovery);
|
||||
Assert.Null(fakeAzureServerDiscovery.ServerDiscoveryProvider);
|
||||
}
|
||||
|
||||
private IMultiServiceProvider CreateServiceProvider()
|
||||
{
|
||||
var providerMock = new Mock<IMultiServiceProvider>();
|
||||
|
||||
providerMock.Setup(x => x.GetServices<IServerDiscoveryProvider>()).Returns(_providers);
|
||||
providerMock.Setup(x => x.GetServices<IAccountManager>()).Returns(_accountManagers);
|
||||
|
||||
return providerMock.Object;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user