public void CurrentProjectIsFirstIfNotSetInSettings() { // Arrange var context = new MockContext(); context.SettingsRepoMock.Setup( s => s.GetById( SettingKeys.LastProject ) ).Returns( new Config { Value = "-1" } ); var projects = new[] { new Project {Name = "One", Id = 1}, new Project {Name = "Two", Id = 2}, new Project {Name = "Three", Id = 3} }; context.ProjectRepoMock.Setup( p => p.GetAll() ).Returns( projects ); // Act var vm = new ProjectListViewModel( context.ViewServiceRepo, context.SettingsRepo, context.ProjectRepo ); // Assert Assert.IsNotNull( vm.CurrentProject ); Assert.AreSame( projects[0], vm.CurrentProject.Model ); context.SettingsRepoMock.VerifyAll(); context.ProjectRepoMock.VerifyAll(); }
public void ResolverReturnsProperNamedObject() { string expected = "We want this one"; string notExpected = "Not this one"; var expectedKey = NamedTypeBuildKey.Make<string>("expected"); var notExpectedKey = NamedTypeBuildKey.Make<string>(); var mainContext = new MockContext(); mainContext.NewBuildupCallback = (k) => { if (k == expectedKey) { return expected; } if (k == notExpectedKey) { return notExpected; } return null; }; var resolver = new OptionalDependencyResolverPolicy(typeof(string), "expected"); object result = resolver.Resolve(mainContext); Assert.Same(expected, result); }
public void Assert_Once_IsVerified() { var mockContext = new MockContext<IFoo>(); var fooMock = new FooMock(mockContext); fooMock.Execute("SomeValue"); mockContext.Assert(f => f.Execute("SomeValue")); }
public void _BeforeTest() { MockContext = new MockContext(); Settings = SettingKeys.DefaultValues.ToDictionary( kvp => kvp.Key, kvp => new Config { Id = kvp.Key, Value = kvp.Value } ); MockContext.SettingsRepoMock.Setup( x => x.Set( It.IsAny<string>(), It.IsAny<string>() ) ).Callback<string, string>( ( key, value ) => { Settings[key] = new Config { Id = key, Value = value }; } ); MockContext.SettingsRepoMock.Setup( x => x.GetById( It.IsAny<string>() ) ).Returns<string>( cfg => Settings[cfg] ); MockContext.AppThemesMock.SetupGet( x => x.Accents ).Returns( new[] { new ColorItem {Name = "Red"}, new ColorItem {Name = "Blue"}, new ColorItem {Name = "Green"} } ); MockContext.AppThemesMock.SetupGet( x => x.Themes ).Returns( new[] { new ColorItem {Name = "BaseDark"}, new ColorItem {Name = "None"}, new ColorItem {Name = "BaseLight"} } ); }
public void ListChangedEventIsAlwaysOnTheThreadThatCreatedTheList() { try { //convince the threadsafebindinglist we are using a synchronization context //by providing a synchronization context var context = new MockContext(); SynchronizationContext.SetSynchronizationContext(context); var list = new ThreadsafeBindingList<int>(context); //create a new thread adding something to the list //use an anonymous lambda expression delegate :) var addFiveThread = new Thread(() => { list.Add(5); }); //action! run the thread adding 5 addFiveThread.Start(); //wait for the other thread to finish while (addFiveThread.IsAlive) Thread.Sleep(10); //assert the list used the context. Assert.AreEqual(1, context.SendWasCalled, "The list did not use the send method the current context!"); } finally { //always reset the synchronizationcontext SynchronizationContext.SetSynchronizationContext(null); } }
public void Assert_InvokedOnceExpectedOnce_IsVerified() { var mockContext = new MockContext<IFoo>(); var fooMock = new FooMock(mockContext); fooMock.Execute("SomeValue"); mockContext.Assert(f => f.Execute("SomeValue"), Invoked.Once); }
public void Assert_WithValidMatchPredicate_IsVerified() { var mockContext = new MockContext<IFoo>(); var fooMock = new FooMock(mockContext); fooMock.Execute("SomeValue"); mockContext.Assert(f => f.Execute(The<string>.Is(s => s.StartsWith("Some"))), Invoked.Once); }
public void Assert_NeverWhenInvoked_ThrowsException() { var mockContext = new MockContext<IFoo>(); var fooMock = new FooMock(mockContext); fooMock.Execute("SomeValue"); mockContext.Assert(f => f.Execute("SomeValue"), Invoked.Never); }
protected void InitializeContext() { var contextMappings = new EntityMappingStore(); var rmp = new ReflectionMappingProvider(); rmp.AddMappingsForAssembly(contextMappings, typeof(LinqToSparqlTests).Assembly); Context = new MockContext(contextMappings); }
public void Arrange_CallBackFourArguments_InvokesCallback() { var mockContext = new MockContext<IFoo>(); var fooMock = new FooMock(mockContext); int firstResult = 0; int secondResult = 0; int thirdResult = 0; int fourthResult = 0; mockContext.Arrange( f => f.Execute(The<int>.IsAnyValue, The<int>.IsAnyValue, The<int>.IsAnyValue, The<int>.IsAnyValue)) .Callback<int, int, int, int>( (i1, i2, i3, i4) => { firstResult = i1; secondResult = i2; thirdResult = i3; fourthResult = i4; }); fooMock.Execute(1, 2, 3, 4); Assert.AreEqual(1, firstResult); Assert.AreEqual(2, secondResult); Assert.AreEqual(3, thirdResult); Assert.AreEqual(4, fourthResult); }
public void Setup() { context = new MockContext(); var contextProvider = MockRepository.GenerateStub<IDataContextProvider>(); contextProvider.Expect(x => x.DataContext).Return(context); filter = new UnitOfWorkFilter(contextProvider); }
public void Assert_InvokedTwiceWithExpectedOnce_ThrowsException() { var mockContext = new MockContext<IFoo>(); var fooMock = new FooMock(mockContext); fooMock.Execute("SomeValue"); fooMock.Execute("SomeValue"); mockContext.Assert(f => f.Execute("SomeValue"), Invoked.Once); }
public void InitTestContext() { ruleT1 = new TestRuleT1(); ruleDependent = new OtherRuleT1(); transformation = new MockTransformation(ruleT1, ruleDependent); transformation.Initialize(); context = new MockContext(transformation); }
private MockContext<IServiceContainer> GetContainerMock(Func<ILifetime> lifetimeFactory, Func<Type, Type, bool> shouldRegister) { var mockContext = new MockContext<IServiceContainer>(); var containerMock = new ContainerMock(mockContext); var assemblyScanner = new AssemblyScanner(new ConcreteTypeExtractor(), new CompositionRootTypeExtractor(), new CompositionRootExecutor(containerMock)); assemblyScanner.Scan(typeof(IFoo).Assembly, containerMock, lifetimeFactory, shouldRegister); return mockContext; }
public void Arrange_CallBackOneArgument_InvokesCallback() { var mockContext = new MockContext<IFoo>(); var fooMock = new FooMock(mockContext); int callBackResult = 0; mockContext.Arrange(f => f.Execute(The<int>.IsAnyValue)).Callback<int>(s => callBackResult = s); fooMock.Execute(1); Assert.AreEqual(1, callBackResult); }
/// <summary> /// Create a Splunk <see cref="Service" /> and login using the settings /// provided in .splunkrc. /// </summary> /// <param name="ns"> /// </param> /// <returns> /// The service created. /// </returns> public static async Task<Service> CreateService(Namespace ns = null) { var context = new MockContext(Splunk.Scheme, Splunk.Host, Splunk.Port); var service = new Service(context, ns); await service.LogOnAsync(Splunk.Username, Splunk.Password); return service; }
public void Arrange_CallBackNoArguments_InvokesCallback() { var mockContext = new MockContext<IFoo>(); var fooMock = new FooMock(mockContext); bool isCalled = false; mockContext.Arrange(f => f.Execute()).Callback(() => isCalled = true); fooMock.Execute(); Assert.IsTrue(isCalled); }
public void Setup() { _sendEmailServiceMock = new MockContext<ISendEmailService> (); _stringResource = new StringResourceMock(); _sendEmailService = new SendEmailServiceMock (_sendEmailServiceMock); _service = new EvaluationService (_stringResource, _sendEmailService); }
public void Move_Line_RelativeVerticalLine() { StreamGeometry geometry = new StreamGeometry(); MockContext context = new MockContext(); PathMarkupParser target = new PathMarkupParser(geometry, context); target.Parse("M3,4 L5,6 v7"); Assert.AreEqual("M3,4 L5,6 L5,13 ", context.Trace); }
public void Move_RelativeLine_RelativeLine() { StreamGeometry geometry = new StreamGeometry(); MockContext context = new MockContext(); PathMarkupParser target = new PathMarkupParser(geometry, context); target.Parse("M3,4 l5,6 7,8"); Assert.AreEqual("M3,4 L8,10 L15,18 ", context.Trace); }
private void SetupManagementClients(MockContext context) { RedisManagementClient = GetRedisManagementClient(context); InsightsManagementClient = GetInsightsManagementClient(); ResourceManagementClient = GetResourceManagementClient(); helper.SetupManagementClients(ResourceManagementClient, InsightsManagementClient, RedisManagementClient ); }
public void Move_Line_HorizontalLine() { StreamGeometry geometry = new StreamGeometry(); MockContext context = new MockContext(); PathMarkupParser target = new PathMarkupParser(geometry, context); target.Parse("M3,4 L5,6 H7"); Assert.AreEqual("M3,4 L5,6 L7,6 ", context.Trace); }
protected void SetupManagementClients(MockContext context) { var nhManagementClient = GetNotificationHubsManagementClient(context); var resourceManagementClient = GetResourceManagementClient(); var gallaryClient = GetGalleryClient(); var authorizationManagementClient = GetAuthorizationManagementClient(); var managementClient = GetManagementClient(); helper.SetupManagementClients(nhManagementClient, resourceManagementClient, gallaryClient, authorizationManagementClient, managementClient); }
public void Cloud_auth_object_returns_project_id() { var mockContext = new MockContext<CloudAuthenticator>(); mockContext.Arrange(f => f.GetProjectId()).Returns("ProjectId"); var cloudAuthMock = new CloudAuthenticatorMock(mockContext); var result = cloudAuthMock.GetProjectId(); mockContext.Assert(f => f.GetProjectId(), Invoked.Once); Assert.Equal("ProjectId", result); }
public void Cloud_auth_object_returns_initializer() { var initializer = new BaseClientService.Initializer(); var mockContext = new MockContext<CloudAuthenticator>(); mockContext.Arrange(f => f.GetInitializer()).Returns(initializer); var cloudAuthMock = new CloudAuthenticatorMock(mockContext); var result = cloudAuthMock.GetInitializer(); mockContext.Assert(f => f.GetInitializer(), Invoked.Once); Assert.Equal(initializer, result); }
public MessageControllerTest(ITestOutputHelper output) { this.output = output; lookupRepo = new FakeLookupRepository(); logger = new DivineLogger<FakeDataStore>(new FakeDataStore()); cache = new MemoryCache(new MemoryCacheOptions()); msgService = new FakeCommunicationService(); var mockContext = new MockContext<IRepository<Member>>(); membersRepo = new FakeMemberRepository(mockContext); var repositories = new DivineRepositories(attendanceRepo, lookupRepo, membersRepo, msgRepo); //divineBot = new TextDivineBot(repositories, msgService); mockContext.Arrange(x => (x.GetAllAsync())).Returns(Task.FromResult(membersList.AsQueryable())); messageCtrl = new MessageController(repositories, msgService, cache, logger, null); }
protected void SetupManagementClients(MockContext context) { ResourceManagementClient = GetResourceManagementClient(); SubscriptionClient = GetSubscriptionClient(); GalleryClient = GetGalleryClient(); AuthorizationManagementClient = GetAuthorizationManagementClient(); CdnManagementClient = GetCdnManagementClient(context); _helper.SetupManagementClients( ResourceManagementClient, SubscriptionClient, GalleryClient, AuthorizationManagementClient, CdnManagementClient); }
public void Arrange_CallBackTwoArguments_InvokesCallback() { var mockContext = new MockContext<IFoo>(); var fooMock = new FooMock(mockContext); int firstResult = 0; int secondResult = 0; mockContext.Arrange(f => f.Execute(The<int>.IsAnyValue, The<int>.IsAnyValue)).Callback<int, int>( (i, i1) => { firstResult = i; secondResult = i1; }); fooMock.Execute(1, 2); Assert.AreEqual(1, firstResult); Assert.AreEqual(2, secondResult); }
protected void SetupManagementClients(MockContext context) { this.ResourceManagementClient = this.GetResourceManagementClient(); this.SubscriptionClient = this.GetSubscriptionClient(); this.GalleryClient = this.GetGalleryClient(); this.AuthorizationManagementClient = this.GetAuthorizationManagementClient(); this.DnsClient = this.GetFeatureClient(context); this.helper.SetupManagementClients( this.ResourceManagementClient, this.SubscriptionClient, this.GalleryClient, this.AuthorizationManagementClient, this.DnsClient); }
public void ChangingCurrentProjectSavesToSettings() { // Arrange var context = new MockContext(); context.SettingsRepoMock.Setup( s => s.Set( SettingKeys.LastProject, "1" ) ).Verifiable(); context.SettingsRepoMock.Setup( x => x.GetById( SettingKeys.LastProject ) ).Returns( new Config {Id = SettingKeys.LastProject, Value = "-1"} ); context.ProjectRepoMock.Setup( x => x.GetAll() ).Returns( new[] { new Project {Id = 1} } ); var vm = new ProjectListViewModel( context.ViewServiceRepo, context.SettingsRepo, context.ProjectRepo ); vm.Reset(); // Act vm.Projects[0].IsCurrent = true; // Assert context.SettingsRepoMock.VerifyAll(); }
public async Task CreateListUpdateDelete() { Environment.SetEnvironmentVariable("AZURE_TEST_MODE", "Playback"); using (MockContext context = MockContext.Start(this.GetType())) { var testBase = new ApiManagementTestBase(context); testBase.TryCreateApiManagementService(); // test tenant policy var globalPolicy = testBase.client.Policy.Get(testBase.rgName, testBase.serviceName); Assert.NotNull(globalPolicy); // test api policy string newApiId = TestUtilities.GenerateName("policyapi"); try { var createdApiContract = testBase.client.Api.CreateOrUpdate( testBase.rgName, testBase.serviceName, newApiId, new ApiCreateOrUpdateParameter { DisplayName = TestUtilities.GenerateName("display"), Description = TestUtilities.GenerateName("description"), Path = TestUtilities.GenerateName("path"), ServiceUrl = "https://echoapi.cloudapp.net/echo", Protocols = new List <Protocol?> { Protocol.Https, Protocol.Http } }); Assert.NotNull(createdApiContract); var policyContract = new PolicyContract(); policyContract.Value = ApiValid; policyContract.Format = PolicyContentFormat.XmlLink; var apiPolicyContract = await testBase.client.ApiPolicy.CreateOrUpdateAsync( testBase.rgName, testBase.serviceName, newApiId, policyContract); Assert.NotNull(apiPolicyContract); Assert.NotNull(apiPolicyContract.Value); // get policy tag var apiPolicyTag = await testBase.client.ApiPolicy.GetEntityTagAsync( testBase.rgName, testBase.serviceName, newApiId); Assert.NotNull(apiPolicyTag); Assert.NotNull(apiPolicyTag.ETag); // delete policy await testBase.client.ApiPolicy.DeleteAsync( testBase.rgName, testBase.serviceName, newApiId, apiPolicyTag.ETag); Assert.Throws <ErrorResponseException>(() => testBase.client.ApiPolicy.Get(testBase.rgName, testBase.serviceName, newApiId)); } finally { await testBase.client.Api.DeleteAsync( testBase.rgName, testBase.serviceName, newApiId, "*", deleteRevisions : true); } // test product policy // get 'Unlimited' product var getProductResponse = testBase.client.Product.ListByService( testBase.rgName, testBase.serviceName, new Microsoft.Rest.Azure.OData.ODataQuery <ProductContract> { Filter = "name eq 'Unlimited'" }); var product = getProductResponse.Single(); // get product policy try { testBase.client.ProductPolicy.Get( testBase.rgName, testBase.serviceName, product.Name); } catch (ErrorResponseException ex) { Assert.Equal(HttpStatusCode.NotFound, ex.Response.StatusCode); } // create product policy contract var productPolicyContract = new PolicyContract(); productPolicyContract.Value = ProductValid; productPolicyContract.Format = PolicyContentFormat.XmlLink; var productPolicyResponse = testBase.client.ProductPolicy.CreateOrUpdate( testBase.rgName, testBase.serviceName, product.Name, productPolicyContract); Assert.NotNull(productPolicyResponse); Assert.NotNull(productPolicyResponse.Value); Assert.Equal("policy", productPolicyResponse.Name); // there can be only one policy per product // get policy to check it was added var getProductPolicy = await testBase.client.ProductPolicy.GetAsync( testBase.rgName, testBase.serviceName, product.Name); Assert.NotNull(getProductPolicy); Assert.NotNull(getProductPolicy.Format); // get product policy etag var productPolicyTag = await testBase.client.ProductPolicy.GetEntityTagAsync( testBase.rgName, testBase.serviceName, product.Name); Assert.NotNull(productPolicyTag); Assert.NotNull(productPolicyTag.ETag); // remove policy testBase.client.ProductPolicy.Delete( testBase.rgName, testBase.serviceName, product.Name, productPolicyTag.ETag); // get policy to check it was removed try { testBase.client.ProductPolicy.Get( testBase.rgName, testBase.serviceName, product.Name); } catch (ErrorResponseException ex) { Assert.Equal(HttpStatusCode.NotFound, ex.Response.StatusCode); } } }
public void CreatePeeringService() { using (MockContext context = MockContext.Start(this.GetType().FullName)) { this.MockClients(context); // Create a Resource Group var rgname = TestUtilities.GenerateName("res"); var resourceGroup = this.ResourcesClient.ResourceGroups.CreateOrUpdate( rgname, new ResourceGroup { Location = "centralus" }); // List Locations var peeringServiceLocations = this.Client.PeeringServiceLocations.List().ToList(); Assert.NotNull(peeringServiceLocations); var location = peeringServiceLocations.Find(s => s.Name == "Washington"); Assert.NotNull(location); // List Providers var listProviders = this.Client.PeeringServiceProviders.List().ToList(); Assert.NotNull(listProviders); PeeringServiceProvider myProvider = null; foreach (var provider in listProviders) { var isAvailable = this.Client.CheckServiceProviderAvailability( location.State, provider.Name); if (isAvailable == "Available") { myProvider = provider; break; } } // Create Peering Service var peeringService = new PeeringService { Location = location.AzureRegion, PeeringServiceLocation = location.Name, PeeringServiceProvider = myProvider?.Name, }; var name = TestUtilities.GenerateName("myPeeringService"); var prefixName = "AS54733Prefix"; try { var result = this.Client.PeeringServices.CreateOrUpdate(rgname, name, peeringService); Assert.NotNull(result); Assert.Equal(name, result.Name); } catch (Exception ex) { Assert.True(this.DeletePeeringService(name, rgname)); Assert.Contains("NotFound", ex.Message); } try { var prefix = new PeeringServicePrefix { Prefix = "10.10.10.0/24", PeeringServicePrefixKey = TestUtilities.GenerateGuid().ToString() }; var peeringServicePrefix = this.Client.Prefixes.CreateOrUpdate(rgname, name, prefixName, prefix.Prefix, prefix.PeeringServicePrefixKey); Assert.NotNull(peeringServicePrefix); Assert.Equal(prefixName, peeringServicePrefix.Name); // var servicePrefix = this.client.PeeringServicePrefixes.Get(rgname, name, prefixName); // Assert.NotNull(servicePrefix); } catch (Exception ex) { Assert.Contains("NotFound", ex.Message); } finally { } } }
public static StorageManagementClient GetStorageManagementClient(MockContext context, RecordedDelegatingHandler handler) { handler.IsPassThrough = true; return(context.GetServiceClient <StorageManagementClient>(handlers: handler)); }
public void CreateUpdateDeleteTest() { using (var context = MockContext.Start(this.GetType())) { RedisEnterpriseManagementClient _client = RedisEnterpriseCacheManagementTestUtilities.GetRedisEnterpriseManagementClient(this, context); Cluster responseCreate = _client.RedisEnterprise.Create(resourceGroupName: fixture.ResourceGroupName, clusterName: fixture.RedisEnterpriseCacheName, parameters: new Cluster { Location = RedisEnterpriseCacheManagementHelper.Location, Sku = new Sku() { Name = SkuName.EnterpriseFlashF300, Capacity = 3 }, Zones = new List <string> { "1", "2", "3" }, }); Assert.Contains(fixture.RedisEnterpriseCacheName, responseCreate.Id); Assert.Equal(RedisEnterpriseCacheManagementHelper.Location, responseCreate.Location); Assert.Equal(fixture.RedisEnterpriseCacheName, responseCreate.Name); Assert.Equal("Microsoft.Cache/redisEnterprise", responseCreate.Type); Assert.Equal(ProvisioningState.Succeeded, responseCreate.ProvisioningState, ignoreCase: true); Assert.Equal(ResourceState.Running, responseCreate.ResourceState, ignoreCase: true); Assert.Equal(SkuName.EnterpriseFlashF300, responseCreate.Sku.Name); Assert.Equal(3, responseCreate.Sku.Capacity); Assert.Equal(3, responseCreate.Zones.Count); Assert.Equal(0, responseCreate.PrivateEndpointConnections.Count); Assert.Equal(0, responseCreate.Tags.Count); Database responseCreateDatabase = _client.Databases.Create(resourceGroupName: fixture.ResourceGroupName, clusterName: fixture.RedisEnterpriseCacheName, databaseName: fixture.DatabaseName, parameters: new Database { ClientProtocol = Protocol.Plaintext, ClusteringPolicy = ClusteringPolicy.EnterpriseCluster, EvictionPolicy = EvictionPolicy.VolatileLRU, }); Assert.Contains(fixture.DatabaseName, responseCreateDatabase.Id); Assert.Equal(fixture.DatabaseName, responseCreateDatabase.Name); Assert.Equal("Microsoft.Cache/redisEnterprise/databases", responseCreateDatabase.Type); Assert.Equal(ProvisioningState.Succeeded, responseCreateDatabase.ProvisioningState, ignoreCase: true); Assert.Equal(ResourceState.Running, responseCreateDatabase.ResourceState, ignoreCase: true); Assert.Equal(Protocol.Plaintext, responseCreateDatabase.ClientProtocol); Assert.Equal(ClusteringPolicy.EnterpriseCluster, responseCreateDatabase.ClusteringPolicy); Assert.Equal(EvictionPolicy.VolatileLRU, responseCreateDatabase.EvictionPolicy); // Database update operations are not currently supported /* * Database responseUpdateDatabase = _client.Databases.Update(resourceGroupName: fixture.ResourceGroupName, clusterName: fixture.RedisEnterpriseCacheName, databaseName: fixture.DatabaseName, * parameters: new DatabaseUpdate * { * ClientProtocol = Protocol.Encrypted, * }); * * Assert.Contains(fixture.DatabaseName, responseUpdateDatabase.Id); * Assert.Equal(fixture.DatabaseName, responseUpdateDatabase.Name); * Assert.Equal("Microsoft.Cache/redisEnterprise/databases", responseUpdateDatabase.Type); * Assert.Equal(ProvisioningState.Succeeded, responseUpdateDatabase.ProvisioningState, ignoreCase: true); * Assert.Equal(ResourceState.Running, responseUpdateDatabase.ResourceState, ignoreCase: true); * Assert.Equal(Protocol.Encrypted, responseUpdateDatabase.ClientProtocol); * Assert.Equal(ClusteringPolicy.EnterpriseCluster, responseUpdateDatabase.ClusteringPolicy); * Assert.Equal(EvictionPolicy.VolatileLRU, responseUpdateDatabase.EvictionPolicy); */ _client.RedisEnterprise.Delete(resourceGroupName: fixture.ResourceGroupName, clusterName: fixture.RedisEnterpriseCacheName); } }
/// <summary> /// The register subscription. /// </summary> /// <param name="subscriptionId"> /// The subscription id. /// </param> private void RegisterSubscription(string subscriptionId) { using (MockContext context = MockContext.Start(this.GetType().FullName)) { var cert = GetClientCertificate(); var url = new Uri($"{LocalEdgeRpUri}api/v1/subscriptions/{subscriptionId}?api-version=2.0"); ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; ServicePointManager.Expect100Continue = true; var request = (HttpWebRequest)WebRequest.Create(url); request.Method = HttpMethod.Put.ToString(); request.ClientCertificates = new X509Certificate2Collection(cert); request.ServerCertificateValidationCallback = (a, b, c, d) => true; request.ContentLength = 0; var postData = @"{ 'state': 'Registered', 'registrationDate': '2019-03-01T23:57:05.644Z', 'properties': { 'tenantId': 'string', 'locationPlacementId': 'string', 'quotaId': 'string', 'registeredFeatures': [ { 'name': 'Microsoft.Peering/AllowExchangePeering', 'state': 'Registered' }, { 'name': 'Microsoft.Peering/AllowDirectPeering', 'state': 'Registered' }, { 'name': 'Microsoft.Peering/AllowPeeringService', 'state': 'Registered' } ] } }"; var data = Encoding.UTF8.GetBytes(postData); request.ContentType = "application/json"; request.ContentLength = data.Length; request.GetRequestStream().Write(data, 0, data.Length); var responseString = string.Empty; using (var response = request.GetResponse()) { using (var responseStream = response.GetResponseStream()) { if (responseStream != null) { using (var sr = new StreamReader(responseStream, Encoding.UTF8)) { responseString = sr.ReadToEnd(); sr.Close(); } } } } Assert.NotNull(responseString); } }
private ProviderHubClient GetProviderHubManagementClient(MockContext context) { return(context.GetServiceClient <ProviderHubClient>()); }
private static SiteRecoveryManagementClient GetSiteRecoveryManagementClient(MockContext context) { return(context.GetServiceClient <SiteRecoveryManagementClient>(TestEnvironmentFactory.GetTestEnvironment())); }
public void GetImageUploadUrl() { using (var context = MockContext.Start(this.GetType())) { var aciClient = context.GetServiceClient <CustomerInsightsManagementClient>(); var profileName = "Contact"; var interactionName = "BankWithdrawal"; var entityprofileimagerelativepath = "images/profile1.png"; var entityinteractionimagerelativepath = "images/interacation1.png"; var dataprofileimagerelativepath = "images/profile1.png"; var datainteractionimagerelativepath = "images/interacation2.png"; var entityTypeImageUploadUrlProfile = new GetImageUploadUrlInput { EntityType = "Profile", EntityTypeName = profileName, RelativePath = entityprofileimagerelativepath }; var entityTypeImageUploadUrlInteraction = new GetImageUploadUrlInput { EntityType = "Interaction", EntityTypeName = interactionName, RelativePath = entityinteractionimagerelativepath }; var dataImageUploadUrlProfile = new GetImageUploadUrlInput { EntityType = "Profile", EntityTypeName = profileName, RelativePath = dataprofileimagerelativepath }; var dataImageUploadUrlInteraction = new GetImageUploadUrlInput { EntityType = "Interaction", EntityTypeName = interactionName, RelativePath = datainteractionimagerelativepath }; var returnentityTypeImageUploadUrlProfile = aciClient.Images.GetUploadUrlForEntityType( ResourceGroupName, HubName, entityTypeImageUploadUrlProfile); Assert.Equal(returnentityTypeImageUploadUrlProfile.RelativePath, entityprofileimagerelativepath); Assert.NotNull(returnentityTypeImageUploadUrlProfile.ContentUrl); var returnentityTypeImageUploadUrlInteraction = aciClient.Images.GetUploadUrlForEntityType( ResourceGroupName, HubName, entityTypeImageUploadUrlInteraction); Assert.Equal(returnentityTypeImageUploadUrlInteraction.RelativePath, entityinteractionimagerelativepath); Assert.NotNull(returnentityTypeImageUploadUrlInteraction.ContentUrl); var returndataImageUploadUrlProfile = aciClient.Images.GetUploadUrlForData( ResourceGroupName, HubName, dataImageUploadUrlProfile); Assert.Equal(returndataImageUploadUrlProfile.RelativePath, dataprofileimagerelativepath); Assert.NotNull(returndataImageUploadUrlProfile.ContentUrl); var returndataImageUploadUrlInteraction = aciClient.Images.GetUploadUrlForData( ResourceGroupName, HubName, dataImageUploadUrlInteraction); Assert.Equal(returndataImageUploadUrlInteraction.RelativePath, datainteractionimagerelativepath); Assert.NotNull(returndataImageUploadUrlInteraction.ContentUrl); } }
public void ResourceTypeRegistrationsCRUDTests() { using (var context = MockContext.Start(GetType())) { string providerNamespace = "Microsoft.Contoso"; string resourceType = "employees"; var employeesResourceTypeProperties = new ResourceTypeRegistrationProperties { RoutingType = "Default", Regionality = "Regional", Endpoints = new ResourceTypeEndpoint[] { new ResourceTypeEndpoint { ApiVersions = new List <string> { "2018-11-01-preview", "2020-01-01-preview", "2019-01-01" }, Locations = new string[] { "West US", "West Central US", "West Europe", "Southeast Asia", "West US 2", "East US 2 EUAP", "North Europe", "East US", "East Asia" }, RequiredFeatures = new string[] { "Microsoft.Contoso/RPaaSSampleApp" } } }, SwaggerSpecifications = new SwaggerSpecification[] { new SwaggerSpecification { ApiVersions = new List <string> { "2018-11-01-preview", "2020-01-01-preview", "2019-01-01" }, SwaggerSpecFolderUri = "https://github.com/Azure/azure-rest-api-specs-pr/blob/RPSaaSMaster/specification/rpsaas/resource-manager/Microsoft.Contoso/" } }, EnableAsyncOperation = true, EnableThirdPartyS2S = false, ResourceMovePolicy = new ResourceTypeRegistrationPropertiesResourceMovePolicy { ValidationRequired = false, CrossResourceGroupMoveEnabled = true, CrossSubscriptionMoveEnabled = true } }; var resourceTypeRegistration = CreateResourceTypeRegistration(context, providerNamespace, resourceType, employeesResourceTypeProperties); Assert.NotNull(resourceTypeRegistration); resourceTypeRegistration = GetResourceTypeRegistration(context, providerNamespace, resourceType); Assert.NotNull(resourceTypeRegistration); var resourceTypeRegistrationsList = ListResourceTypeRegistration(context, providerNamespace); Assert.NotNull(resourceTypeRegistrationsList); DeleteResourceTypeRegistration(context, providerNamespace, resourceType); var exception = Assert.Throws <ErrorResponseException>(() => GetResourceTypeRegistration(context, providerNamespace, resourceType)); Assert.True(exception.Response.StatusCode == System.Net.HttpStatusCode.NotFound); resourceTypeRegistration = CreateResourceTypeRegistration(context, providerNamespace, resourceType, employeesResourceTypeProperties); Assert.NotNull(resourceTypeRegistration); } }
private AuthorizationManagementClient GetAuthorizationManagementClient(MockContext context) { return(context.GetServiceClient <AuthorizationManagementClient>(TestEnvironmentFactory.GetTestEnvironment())); }
public void VirtualNetworkPeeringApiTest() { var handler1 = new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK }; var handler2 = new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK }; using (MockContext context = MockContext.Start(this.GetType().FullName)) { var resourcesClient = ResourcesManagementTestUtilities.GetResourceManagementClientWithHandler(context, handler1); var networkManagementClient = NetworkManagementTestUtilities.GetNetworkManagementClientWithHandler(context, handler2); // var location = NetworkManagementTestUtilities.GetResourceLocation(resourcesClient, "Microsoft.Network/virtualNetworks"); var location = "westus"; string resourceGroupName = TestUtilities.GenerateName("csmrg"); resourcesClient.ResourceGroups.CreateOrUpdate(resourceGroupName, new ResourceGroup { Location = location }); string vnetName = TestUtilities.GenerateName(); string remoteVirtualNetworkName = TestUtilities.GenerateName(); string vnetPeeringName = TestUtilities.GenerateName(); string subnet1Name = TestUtilities.GenerateName(); string subnet2Name = TestUtilities.GenerateName(); var vnet = new VirtualNetwork() { Location = location, AddressSpace = new AddressSpace() { AddressPrefixes = new List <string>() { "10.0.0.0/16", } }, DhcpOptions = new DhcpOptions() { DnsServers = new List <string>() { "10.1.1.1", "10.1.2.4" } }, Subnets = new List <Subnet>() { new Subnet() { Name = subnet1Name, AddressPrefix = "10.0.1.0/24", }, new Subnet() { Name = subnet2Name, AddressPrefix = "10.0.2.0/24", } } }; // Put Vnet var putVnetResponse = networkManagementClient.VirtualNetworks.CreateOrUpdate(resourceGroupName, vnetName, vnet); Assert.Equal("Succeeded", putVnetResponse.ProvisioningState); // Get Vnet var getVnetResponse = networkManagementClient.VirtualNetworks.Get(resourceGroupName, vnetName); Assert.Equal(vnetName, getVnetResponse.Name); Assert.NotNull(getVnetResponse.ResourceGuid); Assert.Equal("Succeeded", getVnetResponse.ProvisioningState); // Get all Vnets var getAllVnets = networkManagementClient.VirtualNetworks.List(resourceGroupName); vnet.AddressSpace.AddressPrefixes[0] = "10.1.0.0/16"; vnet.Subnets[0].AddressPrefix = "10.1.1.0/24"; vnet.Subnets[1].AddressPrefix = "10.1.2.0/24"; var remoteVirtualNetwork = networkManagementClient.VirtualNetworks.CreateOrUpdate(resourceGroupName, remoteVirtualNetworkName, vnet); // Get Peerings in the vnet var listPeering = networkManagementClient.VirtualNetworkPeerings.List(resourceGroupName, vnetName); Assert.Equal(0, listPeering.Count()); var peering = new VirtualNetworkPeering(); peering.Name = vnetPeeringName; peering.RemoteVirtualNetwork = new Microsoft.Azure.Management.Network.Models.SubResource(); peering.RemoteVirtualNetwork.Id = remoteVirtualNetwork.Id; peering.AllowForwardedTraffic = true; peering.AllowVirtualNetworkAccess = false; // Put peering in the vnet var putPeering = networkManagementClient.VirtualNetworkPeerings.CreateOrUpdate(resourceGroupName, vnetName, vnetPeeringName, peering); Assert.NotNull(putPeering.Etag); Assert.Equal(vnetPeeringName, putPeering.Name); Assert.Equal(remoteVirtualNetwork.Id, putPeering.RemoteVirtualNetwork.Id); Assert.Equal(peering.AllowForwardedTraffic, putPeering.AllowForwardedTraffic); Assert.Equal(peering.AllowVirtualNetworkAccess, putPeering.AllowVirtualNetworkAccess); Assert.Equal(false, putPeering.UseRemoteGateways); Assert.Equal(false, putPeering.AllowGatewayTransit); Assert.Equal(VirtualNetworkPeeringState.Initiated, putPeering.PeeringState); // get peering var getPeering = networkManagementClient.VirtualNetworkPeerings.Get(resourceGroupName, vnetName, vnetPeeringName); Assert.Equal(getPeering.Etag, putPeering.Etag); Assert.Equal(vnetPeeringName, getPeering.Name); Assert.Equal(remoteVirtualNetwork.Id, getPeering.RemoteVirtualNetwork.Id); Assert.Equal(peering.AllowForwardedTraffic, getPeering.AllowForwardedTraffic); Assert.Equal(peering.AllowVirtualNetworkAccess, getPeering.AllowVirtualNetworkAccess); Assert.Equal(false, getPeering.UseRemoteGateways); Assert.Equal(false, getPeering.AllowGatewayTransit); Assert.Equal(VirtualNetworkPeeringState.Initiated, getPeering.PeeringState); // list peering listPeering = networkManagementClient.VirtualNetworkPeerings.List(resourceGroupName, vnetName); Assert.Equal(1, listPeering.Count()); Assert.Equal(listPeering.ElementAt(0).Etag, putPeering.Etag); Assert.Equal(vnetPeeringName, listPeering.ElementAt(0).Name); Assert.Equal(remoteVirtualNetwork.Id, listPeering.ElementAt(0).RemoteVirtualNetwork.Id); Assert.Equal(peering.AllowForwardedTraffic, listPeering.ElementAt(0).AllowForwardedTraffic); Assert.Equal(peering.AllowVirtualNetworkAccess, listPeering.ElementAt(0).AllowVirtualNetworkAccess); Assert.Equal(false, listPeering.ElementAt(0).UseRemoteGateways); Assert.Equal(false, listPeering.ElementAt(0).AllowGatewayTransit); Assert.Equal(VirtualNetworkPeeringState.Initiated, listPeering.ElementAt(0).PeeringState); // delete peering networkManagementClient.VirtualNetworkPeerings.Delete(resourceGroupName, vnetName, vnetPeeringName); listPeering = networkManagementClient.VirtualNetworkPeerings.List(resourceGroupName, vnetName); Assert.Equal(0, listPeering.Count()); // Delete Vnet networkManagementClient.VirtualNetworks.Delete(resourceGroupName, vnetName); networkManagementClient.VirtualNetworks.Delete(resourceGroupName, remoteVirtualNetworkName); // Get all Vnets getAllVnets = networkManagementClient.VirtualNetworks.List(resourceGroupName); Assert.Equal(0, getAllVnets.Count()); } }
protected StorageManagementClient GetArmStorageManagementClient(MockContext context) { return(context.GetServiceClient <StorageManagementClient>(TestEnvironmentFactory.GetTestEnvironment())); }
public void RunPsTestWorkflow( string scenario, Func <string[]> scriptBuilder, Action cleanup, string callingClassType, string mockName) { var providers = new Dictionary <string, string> { { "Microsoft.Resources", null }, { "Microsoft.Features", null }, { "Microsoft.Authorization", null }, { "Microsoft.Compute", null }, { "Microsoft.Storage", null }, { "Microsoft.Network", null } }; var providersToIgnore = new Dictionary <string, string> { { "Microsoft.Azure.Management.Internal.Resources.ResourceManagementClient", "2016-09-01" } }; HttpMockServer.Matcher = new PermissiveRecordMatcherWithApiExclusion(true, providers, providersToIgnore); HttpMockServer.RecordsDirectory = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "SessionRecords"); using (var context = MockContext.Start(callingClassType, mockName)) { SetupManagementClients(context); _helper.SetupEnvironment(AzureModule.AzureResourceManager); var rmProfileModule = _helper.RMProfileModule; _helper.SetupModules( AzureModule.AzureResourceManager, PowershellFile, PowershellHelperFile, rmProfileModule, _helper.GetRMModulePath("AzureRM.Network.psd1"), "AzureRM.Storage.ps1", _helper.GetRMModulePath("AzureRM.Compute.psd1"), _helper.GetRMModulePath("AzureRM.RecoveryServices.psd1"), #if !NETSTANDARD _helper.GetRMModulePath("AzureRM.RecoveryServices.SiteRecovery.psd1"), #endif "AzureRM.Resources.ps1"); try { var psScripts = scriptBuilder?.Invoke(); if (psScripts != null) { _helper.RunPowerShellTest(psScripts); } } finally { cleanup?.Invoke(); } } }
private static RecoveryServicesBackupClient GetRecoveryServicesBackupClient(MockContext context) { return(context.GetServiceClient <RecoveryServicesBackupClient>(TestEnvironmentFactory.GetTestEnvironment())); }
private ResourceTypeRegistration GetResourceTypeRegistration(MockContext context, string providerNamespace, string resourceType) { ProviderHubClient client = GetProviderHubManagementClient(context); return(client.ResourceTypeRegistrations.Get(providerNamespace, resourceType)); }
private static NetworkManagementClient GetNetworkManagementClientRestClient(MockContext context) { return(context.GetServiceClient <NetworkManagementClient>(TestEnvironmentFactory.GetTestEnvironment())); }
private ResourceTypeRegistration CreateResourceTypeRegistration(MockContext context, string providerNamespace, string resourceType, ResourceTypeRegistrationProperties properties) { ProviderHubClient client = GetProviderHubManagementClient(context); return(client.ResourceTypeRegistrations.CreateOrUpdate(providerNamespace, resourceType, properties)); }
private static RelayManagementClient GetRelayManagementClient(MockContext context) { return(context.GetServiceClient <RelayManagementClient>(TestEnvironmentFactory.GetTestEnvironment())); }
public void ListRecommendationsRoundTrip() { using (var context = MockContext.Start(this.GetType().FullName)) { var webSitesClient = this.GetWebSiteManagementClient(context); var resourcesClient = this.GetResourceManagementClient(context); string farmName = TestUtilities.GenerateName("csmsf"); string resourceGroupName = TestUtilities.GenerateName("csmrg"); string locationName = "West US"; string siteName = TestUtilities.GenerateName("csmws"); resourcesClient.ResourceGroups.CreateOrUpdate(resourceGroupName, new ResourceGroup { Location = locationName }); webSitesClient.AppServicePlans.CreateOrUpdate(resourceGroupName, farmName, new AppServicePlan { Location = locationName, Sku = new SkuDescription { Name = "S1", Tier = "Standard", Capacity = 1 } }); var serverfarmId = ResourceGroupHelper.GetServerFarmId(webSitesClient.SubscriptionId, resourceGroupName, farmName); webSitesClient.WebApps.CreateOrUpdate(resourceGroupName, siteName, new Site { Location = locationName, ServerFarmId = serverfarmId }); var recommendationResponse = webSitesClient.Recommendations.ListRecommendedRulesForWebApp(resourceGroupName, siteName); Assert.Equal("0", recommendationResponse.AsEnumerable().Count().ToString()); Assert.Null(recommendationResponse.NextPageLink); var rec = recommendationResponse.FirstOrDefault(); if (rec != null) { Assert.Equal("PaidSiteSlots", rec.RuleName); Assert.False(rec.IsDynamic); Assert.True(rec.NextNotificationTime.HasValue); Assert.True(rec.NotificationExpirationTime.HasValue); Assert.True(rec.RecommendationId.HasValue); Assert.Equal("WebSite", rec.ResourceScope); Assert.Equal(1000, rec.Score); } webSitesClient.WebApps.Delete(resourceGroupName, siteName, deleteMetrics: true); webSitesClient.AppServicePlans.Delete(resourceGroupName, farmName); var serverFarmResponse = webSitesClient.AppServicePlans.ListByResourceGroup(resourceGroupName); Assert.Equal("0", serverFarmResponse.AsEnumerable().Count().ToString()); Assert.Null(serverFarmResponse.NextPageLink); } }
public void TestExtImgListVersionsFilters() { string existingVersionPrefix = existingVersion.Substring(0, existingVersion.LastIndexOf('.')); using (MockContext context = MockContext.Start(this.GetType())) { ComputeManagementClient _pirClient = ComputeManagementTestUtilities.GetComputeManagementClient(context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK }); // Filter: startswith - Positive Test parameters.FilterExpression = null; var extImages = _pirClient.VirtualMachineExtensionImages.ListVersions( parameters.Location, parameters.PublisherName, parameters.Type); Assert.True(extImages.Count > 0); string ver = extImages.First().Name; var query = new Microsoft.Rest.Azure.OData.ODataQuery <Microsoft.Azure.Management.Compute.Models.VirtualMachineExtensionImage>(); query.SetFilter(f => f.Name.StartsWith(ver)); parameters.FilterExpression = "$filter=startswith(name,'" + ver + "')"; var vmextimg = _pirClient.VirtualMachineExtensionImages.ListVersions( parameters.Location, parameters.PublisherName, parameters.Type, query); Assert.True(vmextimg.Count > 0); Assert.True(vmextimg.Count(vmi => vmi.Name != existingVersionPrefix) != 0); // Filter: startswith - Negative Test query.SetFilter(f => f.Name.StartsWith(existingVersionPrefix)); parameters.FilterExpression = string.Format("$filter=startswith(name,'{0}')", existingVersionPrefix); vmextimg = _pirClient.VirtualMachineExtensionImages.ListVersions( parameters.Location, parameters.PublisherName, parameters.Type, query); Assert.True(vmextimg.Count > 0); // Filter: top - Positive Test query.Filter = null; query.Top = 1; parameters.FilterExpression = "$top=1"; vmextimg = _pirClient.VirtualMachineExtensionImages.ListVersions( parameters.Location, parameters.PublisherName, parameters.Type, query); Assert.True(vmextimg.Count == 1); // Filter: top - Negative Test query.Top = 0; parameters.FilterExpression = "$top=0"; vmextimg = _pirClient.VirtualMachineExtensionImages.ListVersions( parameters.Location, parameters.PublisherName, parameters.Type, query); Assert.True(vmextimg.Count == 0); } }
private void DeleteResourceTypeRegistration(MockContext context, string providerNamespace, string resourceType) { ProviderHubClient client = GetProviderHubManagementClient(context); client.ResourceTypeRegistrations.Delete(providerNamespace, resourceType); }
public void TestDedicatedHostOperations() { string originalTestLocation = Environment.GetEnvironmentVariable("AZURE_VM_TEST_LOCATION"); using (MockContext context = MockContext.Start(this.GetType())) { Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", "eastus2"); EnsureClientsInitialized(context); string baseRGName = ComputeManagementTestUtilities.GenerateName(TestPrefix); string rgName = baseRGName + "DH"; string dhgName = "DHG-1"; string dhName = "DH-1"; try { // Create a dedicated host group, then get the dedicated host group and validate that they match DedicatedHostGroup createdDHG = CreateDedicatedHostGroup(rgName, dhgName); DedicatedHostGroup returnedDHG = m_CrpClient.DedicatedHostGroups.Get(rgName, dhgName); ValidateDedicatedHostGroup(createdDHG, returnedDHG); // Update existing dedicated host group DedicatedHostGroupUpdate updateDHGInput = new DedicatedHostGroupUpdate() { Tags = new Dictionary <string, string>() { { "testKey", "testValue" } } }; createdDHG.Tags = updateDHGInput.Tags; updateDHGInput.PlatformFaultDomainCount = returnedDHG.PlatformFaultDomainCount; // There is a bug in PATCH. PlatformFaultDomainCount is a required property now. returnedDHG = m_CrpClient.DedicatedHostGroups.Update(rgName, dhgName, updateDHGInput); ValidateDedicatedHostGroup(createdDHG, returnedDHG); //List DedicatedHostGroups by subscription and by resourceGroup var listDHGsResponse = m_CrpClient.DedicatedHostGroups.ListByResourceGroup(rgName); Assert.Single(listDHGsResponse); ValidateDedicatedHostGroup(createdDHG, listDHGsResponse.First()); listDHGsResponse = m_CrpClient.DedicatedHostGroups.ListBySubscription(); //There might be multiple dedicated host groups in the subscription, we only care about the one that we created. returnedDHG = listDHGsResponse.First(dhg => dhg.Id == createdDHG.Id); Assert.NotNull(returnedDHG); ValidateDedicatedHostGroup(createdDHG, returnedDHG); //Create DedicatedHost within the DedicatedHostGroup and validate var createdDH = CreateDedicatedHost(rgName, dhgName, dhName, "ESv3-Type1"); var returnedDH = m_CrpClient.DedicatedHosts.Get(rgName, dhgName, dhName); ValidateDedicatedHost(createdDH, returnedDH); //List DedicatedHosts var listDHsResponse = m_CrpClient.DedicatedHosts.ListByHostGroup(rgName, dhgName); Assert.Single(listDHsResponse); ValidateDedicatedHost(createdDH, listDHsResponse.First()); //Delete DedicatedHosts and DedicatedHostGroups m_CrpClient.DedicatedHosts.Delete(rgName, dhgName, dhName); m_CrpClient.DedicatedHostGroups.Delete(rgName, dhgName); } finally { m_ResourcesClient.ResourceGroups.Delete(rgName); Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", originalTestLocation); } } }
private IPage <ResourceTypeRegistration> ListResourceTypeRegistration(MockContext context, string providerNamespace) { ProviderHubClient client = GetProviderHubManagementClient(context); return(client.ResourceTypeRegistrations.ListByProviderRegistration(providerNamespace)); }
public void NamespaceCreateGetUpdateDeleteAuthorizationRules() { using (MockContext context = MockContext.Start(this.GetType())) { InitializeClients(context); var location = this.ResourceManagementClient.GetLocationFromProvider(); var resourceGroup = this.ResourceManagementClient.TryGetResourceGroup(location); if (string.IsNullOrWhiteSpace(resourceGroup)) { resourceGroup = TestUtilities.GenerateName(ServiceBusManagementHelper.ResourceGroupPrefix); this.ResourceManagementClient.TryRegisterResourceGroup(location, resourceGroup); } // Create a namespace var namespaceName = TestUtilities.GenerateName(ServiceBusManagementHelper.NamespacePrefix); var createNamespaceResponse = ServiceBusManagementClient.Namespaces.CreateOrUpdate(resourceGroup, namespaceName, new SBNamespace() { Location = location, Tags = new Dictionary <string, string>() { { "tag1", "value1" }, { "tag2", "value2" } } }); Assert.NotNull(createNamespaceResponse); Assert.Equal(createNamespaceResponse.Name, namespaceName); TestUtilities.Wait(TimeSpan.FromSeconds(5)); // Get the created namespace var getNamespaceResponse = ServiceBusManagementClient.Namespaces.Get(resourceGroup, namespaceName); if (string.Compare(getNamespaceResponse.ProvisioningState, "Succeeded", true) != 0) { TestUtilities.Wait(TimeSpan.FromSeconds(5)); } getNamespaceResponse = ServiceBusManagementClient.Namespaces.Get(resourceGroup, namespaceName); Assert.NotNull(getNamespaceResponse); Assert.Equal("Succeeded", getNamespaceResponse.ProvisioningState, StringComparer.CurrentCultureIgnoreCase); Assert.Equal(location, getNamespaceResponse.Location, StringComparer.CurrentCultureIgnoreCase); // Create a namespace AuthorizationRule var authorizationRuleName = TestUtilities.GenerateName(ServiceBusManagementHelper.AuthorizationRulesPrefix); string createPrimaryKey = HttpMockServer.GetVariable("CreatePrimaryKey", ServiceBusManagementHelper.GenerateRandomKey()); var createAutorizationRuleParameter = new SBAuthorizationRule() { Rights = new List <AccessRights?>() { AccessRights.Listen, AccessRights.Send } }; var jsonStr = ServiceBusManagementHelper.ConvertObjectToJSon(createAutorizationRuleParameter); var createNamespaceAuthorizationRuleResponse = ServiceBusManagementClient.Namespaces.CreateOrUpdateAuthorizationRule(resourceGroup, namespaceName, authorizationRuleName, createAutorizationRuleParameter); Assert.NotNull(createNamespaceAuthorizationRuleResponse); Assert.True(createNamespaceAuthorizationRuleResponse.Rights.Count == createAutorizationRuleParameter.Rights.Count); foreach (var right in createAutorizationRuleParameter.Rights) { Assert.Contains(createNamespaceAuthorizationRuleResponse.Rights, r => r == right); } // Get default namespace AuthorizationRules var getNamespaceAuthorizationRulesResponse = ServiceBusManagementClient.Namespaces.GetAuthorizationRule(resourceGroup, namespaceName, ServiceBusManagementHelper.DefaultNamespaceAuthorizationRule); Assert.NotNull(getNamespaceAuthorizationRulesResponse); Assert.Equal(getNamespaceAuthorizationRulesResponse.Name, ServiceBusManagementHelper.DefaultNamespaceAuthorizationRule); Assert.Contains(getNamespaceAuthorizationRulesResponse.Rights, r => r == AccessRights.Listen); Assert.Contains(getNamespaceAuthorizationRulesResponse.Rights, r => r == AccessRights.Send); Assert.Contains(getNamespaceAuthorizationRulesResponse.Rights, r => r == AccessRights.Manage); // Get created namespace AuthorizationRules getNamespaceAuthorizationRulesResponse = ServiceBusManagementClient.Namespaces.GetAuthorizationRule(resourceGroup, namespaceName, authorizationRuleName); Assert.NotNull(getNamespaceAuthorizationRulesResponse); Assert.True(getNamespaceAuthorizationRulesResponse.Rights.Count == createAutorizationRuleParameter.Rights.Count); foreach (var right in createAutorizationRuleParameter.Rights) { Assert.Contains(getNamespaceAuthorizationRulesResponse.Rights, r => r == right); } // Get all namespaces AuthorizationRules var getAllNamespaceAuthorizationRulesResponse = ServiceBusManagementClient.Namespaces.ListAuthorizationRules(resourceGroup, namespaceName); Assert.NotNull(getAllNamespaceAuthorizationRulesResponse); Assert.True(getAllNamespaceAuthorizationRulesResponse.Count() > 1); Assert.Contains(getAllNamespaceAuthorizationRulesResponse, ns => ns.Name == authorizationRuleName); Assert.Contains(getAllNamespaceAuthorizationRulesResponse, auth => auth.Name == ServiceBusManagementHelper.DefaultNamespaceAuthorizationRule); // Update namespace authorizationRule string updatePrimaryKey = HttpMockServer.GetVariable("UpdatePrimaryKey", ServiceBusManagementHelper.GenerateRandomKey()); SBAuthorizationRule updateNamespaceAuthorizationRuleParameter = new SBAuthorizationRule(); updateNamespaceAuthorizationRuleParameter.Rights = new List <AccessRights?>() { AccessRights.Listen }; var updateNamespaceAuthorizationRuleResponse = ServiceBusManagementClient.Namespaces.CreateOrUpdateAuthorizationRule(resourceGroup, namespaceName, authorizationRuleName, updateNamespaceAuthorizationRuleParameter); Assert.NotNull(updateNamespaceAuthorizationRuleResponse); Assert.Equal(authorizationRuleName, updateNamespaceAuthorizationRuleResponse.Name); Assert.True(updateNamespaceAuthorizationRuleResponse.Rights.Count == updateNamespaceAuthorizationRuleParameter.Rights.Count); foreach (var right in updateNamespaceAuthorizationRuleParameter.Rights) { Assert.Contains(updateNamespaceAuthorizationRuleResponse.Rights, r => r.Equals(right)); } // Get the updated namespace AuthorizationRule var getNamespaceAuthorizationRuleResponse = ServiceBusManagementClient.Namespaces.GetAuthorizationRule(resourceGroup, namespaceName, authorizationRuleName); Assert.NotNull(getNamespaceAuthorizationRuleResponse); Assert.Equal(authorizationRuleName, getNamespaceAuthorizationRuleResponse.Name); Assert.True(getNamespaceAuthorizationRuleResponse.Rights.Count == updateNamespaceAuthorizationRuleParameter.Rights.Count); foreach (var right in updateNamespaceAuthorizationRuleParameter.Rights) { Assert.Contains(getNamespaceAuthorizationRuleResponse.Rights, r => r.Equals(right)); } // Get the connectionString to the namespace for a Authorization rule created var listKeysResponse = ServiceBusManagementClient.Namespaces.ListKeys(resourceGroup, namespaceName, authorizationRuleName); Assert.NotNull(listKeysResponse); Assert.NotNull(listKeysResponse.PrimaryConnectionString); Assert.NotNull(listKeysResponse.SecondaryConnectionString); // Regenerate AuthorizationRules //Primary var regenerateKeysParameters = new RegenerateAccessKeyParameters(); regenerateKeysParameters.KeyType = KeyType.PrimaryKey; var regenerateKeysResponse = ServiceBusManagementClient.Namespaces.RegenerateKeys(resourceGroup, namespaceName, authorizationRuleName, regenerateKeysParameters); Assert.NotNull(regenerateKeysResponse); Assert.NotEqual(regenerateKeysResponse.PrimaryKey, listKeysResponse.PrimaryKey); Assert.Equal(regenerateKeysResponse.SecondaryKey, listKeysResponse.SecondaryKey); //Secondary regenerateKeysParameters.KeyType = KeyType.SecondaryKey; var regenerateSecondaryKeyResponse = ServiceBusManagementClient.Namespaces.RegenerateKeys(resourceGroup, namespaceName, authorizationRuleName, regenerateKeysParameters); Assert.NotNull(regenerateSecondaryKeyResponse); Assert.NotEqual(regenerateSecondaryKeyResponse.SecondaryKey, listKeysResponse.SecondaryKey); Assert.Equal(regenerateSecondaryKeyResponse.PrimaryKey, regenerateKeysResponse.PrimaryKey); // Delete namespace authorizationRule ServiceBusManagementClient.Namespaces.DeleteAuthorizationRule(resourceGroup, namespaceName, authorizationRuleName); TestUtilities.Wait(TimeSpan.FromSeconds(5)); // Delete namespace ServiceBusManagementClient.Namespaces.Delete(resourceGroup, namespaceName); } }
private static EventHubManagementClient GetEHClient(MockContext context) { return(context.GetServiceClient <EventHubManagementClient>(TestEnvironmentFactory.GetTestEnvironment())); }
public void CredentialCRUDTest() { using (var context = MockContext.Start(this.GetType())) { commonData = new CommonTestFixture(context); commonData.HostUrl = commonData.DataLakeAnalyticsManagementHelper.TryCreateDataLakeAnalyticsAccount( commonData.ResourceGroupName, commonData.Location, commonData.DataLakeStoreAccountName, commonData.SecondDataLakeAnalyticsAccountName ); // Wait 5 minutes for the account setup TestUtilities.Wait(300000); commonData.DataLakeAnalyticsManagementHelper.CreateCatalog( commonData.ResourceGroupName, commonData.SecondDataLakeAnalyticsAccountName, commonData.DatabaseName, commonData.TableName, commonData.TvfName, commonData.ViewName, commonData.ProcName ); using (var clientToUse = commonData.GetDataLakeAnalyticsCatalogManagementClient(context)) { // Create the credential clientToUse.Catalog.CreateCredential( commonData.SecondDataLakeAnalyticsAccountName, commonData.DatabaseName, commonData.SecretName, new DataLakeAnalyticsCatalogCredentialCreateParameters { UserId = TestUtilities.GenerateGuid("fakeUserId01").ToString(), Password = commonData.SecretPwd, Uri = "https://adlasecrettest.contoso.com:443", } ); // Attempt to create the secret again, which should throw Assert.Throws <CloudException>( () => clientToUse.Catalog.CreateCredential( commonData.SecondDataLakeAnalyticsAccountName, commonData.DatabaseName, commonData.SecretName, new DataLakeAnalyticsCatalogCredentialCreateParameters { UserId = TestUtilities.GenerateGuid("fakeUserId02").ToString(), Password = commonData.SecretPwd, Uri = "https://adlasecrettest.contoso.com:443", } ) ); // Create another credential var secondSecretName = commonData.SecretName + "dup"; clientToUse.Catalog.CreateCredential( commonData.SecondDataLakeAnalyticsAccountName, commonData.DatabaseName, secondSecretName, new DataLakeAnalyticsCatalogCredentialCreateParameters { UserId = TestUtilities.GenerateGuid("fakeUserId03").ToString(), Password = commonData.SecretPwd, Uri = "https://adlasecrettest.contoso.com:443", } ); // Get the credential and ensure the response contains a date. var secretGetResponse = clientToUse.Catalog.GetCredential( commonData.SecondDataLakeAnalyticsAccountName, commonData.DatabaseName, commonData.SecretName); Assert.NotNull(secretGetResponse); Assert.NotNull(secretGetResponse.Name); // Get the Credential list var credListResponse = clientToUse.Catalog.ListCredentials( commonData.SecondDataLakeAnalyticsAccountName, commonData.DatabaseName); Assert.True(credListResponse.Count() >= 1); // Look for the credential we created Assert.Contains(credListResponse, cred => cred.Name.Equals(commonData.SecretName)); // Get the specific credential as well var credGetResponse = clientToUse.Catalog.GetCredential( commonData.SecondDataLakeAnalyticsAccountName, commonData.DatabaseName, commonData.SecretName); Assert.Equal(commonData.SecretName, credGetResponse.Name); // Delete the credential clientToUse.Catalog.DeleteCredential( commonData.SecondDataLakeAnalyticsAccountName, commonData.DatabaseName, commonData.SecretName, new DataLakeAnalyticsCatalogCredentialDeleteParameters(commonData.SecretPwd)); // Try to get the credential which should throw Assert.Throws <CloudException>(() => clientToUse.Catalog.GetCredential( commonData.SecondDataLakeAnalyticsAccountName, commonData.DatabaseName, commonData.SecretName)); // Re-create and delete the credential using cascade = true, which should still succeed. clientToUse.Catalog.CreateCredential( commonData.SecondDataLakeAnalyticsAccountName, commonData.DatabaseName, commonData.SecretName, new DataLakeAnalyticsCatalogCredentialCreateParameters { Password = commonData.SecretPwd, Uri = "https://adlasecrettest.contoso.com:443", UserId = TestUtilities.GenerateGuid("fakeUserId01").ToString() }); clientToUse.Catalog.DeleteCredential( commonData.SecondDataLakeAnalyticsAccountName, commonData.DatabaseName, commonData.SecretName, new DataLakeAnalyticsCatalogCredentialDeleteParameters(commonData.SecretPwd), cascade: true); // Try to get the credential which should throw Assert.Throws <CloudException>(() => clientToUse.Catalog.GetCredential( commonData.SecondDataLakeAnalyticsAccountName, commonData.DatabaseName, commonData.SecretName)); // TODO: once support is available for delete all credentials add tests here for that. } } }
public void CreateGetListUpdateDeleteLogProfile() { // The second argument in the call to Start (missing in this case) controls the name of the output file. // By default the system will use the name of the current method as file for the output (when recording.) using (MockContext context = MockContext.Start(this.GetType())) { LogProfileResource expResponse = CreateLogProfile(); var insightsClient = GetMonitorManagementClient(context, handler); var parameters = CreateLogProfileParams(); LogProfileResource actualResponse = insightsClient.LogProfiles.CreateOrUpdate( logProfileName: DefaultName, parameters: parameters); if (!this.IsRecording) { // TODO: Create a check and use it here Assert.False(string.IsNullOrWhiteSpace(actualResponse.Id)); Assert.Equal(DefaultName, actualResponse.Name); Assert.NotNull(actualResponse.Categories); Assert.NotNull(actualResponse.Locations); Assert.True(actualResponse.Categories.Count > 0); Assert.True(actualResponse.Locations.Count > 0); // AreEqual(expResponse, actualResponse); } LogProfileResource retrievedSingleResponse = insightsClient.LogProfiles.Get(logProfileName: DefaultName); if (!this.IsRecording) { Utilities.AreEqual(actualResponse, retrievedSingleResponse); } IEnumerable <LogProfileResource> actualProfiles = insightsClient.LogProfiles.List(); if (!this.IsRecording) { var listActualProfiles = actualProfiles.ToList(); Assert.NotNull(listActualProfiles); Assert.True(listActualProfiles.Count > 0); var selected = listActualProfiles.FirstOrDefault(p => string.Equals(p.Id, retrievedSingleResponse.Id, StringComparison.OrdinalIgnoreCase)); Assert.NotNull(selected); Utilities.AreEqual(retrievedSingleResponse, selected); } LogProfileResourcePatch patchResource = new LogProfileResourcePatch( locations: retrievedSingleResponse.Locations, categories: retrievedSingleResponse.Categories, retentionPolicy: retrievedSingleResponse.RetentionPolicy, tags: retrievedSingleResponse.Tags, serviceBusRuleId: retrievedSingleResponse.ServiceBusRuleId, storageAccountId: retrievedSingleResponse.StorageAccountId); // TODO: Fails with 'MethodNotAllowed' LogProfileResource updatedResponse = null; Assert.Throws <ErrorResponseException>( () => updatedResponse = insightsClient.LogProfiles.Update( logProfileName: DefaultName, logProfilesResource: patchResource)); if (!this.IsRecording && updatedResponse != null) { Utilities.AreEqual(retrievedSingleResponse, updatedResponse); } LogProfileResource secondRetrievedactualResponse = insightsClient.LogProfiles.Get(logProfileName: DefaultName); if (!this.IsRecording && updatedResponse != null) { Utilities.AreEqual(updatedResponse, secondRetrievedactualResponse); } AzureOperationResponse deleteResponse = insightsClient.LogProfiles.DeleteWithHttpMessagesAsync(logProfileName: DefaultName).Result; if (!this.IsRecording) { Assert.Equal(HttpStatusCode.OK, deleteResponse.Response.StatusCode); } } }
public void GetCatalogItemsTest() { // This test currently tests for Database, table TVF, view, types and procedure, and ACLs using (var context = MockContext.Start(this.GetType())) { commonData = new CommonTestFixture(context); commonData.HostUrl = commonData.DataLakeAnalyticsManagementHelper.TryCreateDataLakeAnalyticsAccount( commonData.ResourceGroupName, commonData.Location, commonData.DataLakeStoreAccountName, commonData.SecondDataLakeAnalyticsAccountName ); // Wait 5 minutes for the account setup TestUtilities.Wait(300000); commonData.DataLakeAnalyticsManagementHelper.CreateCatalog( commonData.ResourceGroupName, commonData.SecondDataLakeAnalyticsAccountName, commonData.DatabaseName, commonData.TableName, commonData.TvfName, commonData.ViewName, commonData.ProcName); using (var clientToUse = commonData.GetDataLakeAnalyticsCatalogManagementClient(context)) { var dbListResponse = clientToUse.Catalog.ListDatabases( commonData.SecondDataLakeAnalyticsAccountName ); Assert.True(dbListResponse.Count() >= 1); // Look for the db we created Assert.Contains(dbListResponse, db => db.Name.Equals(commonData.DatabaseName)); // Get the specific Database as well var dbGetResponse = clientToUse.Catalog.GetDatabase( commonData.SecondDataLakeAnalyticsAccountName, commonData.DatabaseName ); Assert.Equal(commonData.DatabaseName, dbGetResponse.Name); // Get the table list var tableListResponse = clientToUse.Catalog.ListTables( commonData.SecondDataLakeAnalyticsAccountName, commonData.DatabaseName, CommonTestFixture.SchemaName ); Assert.True(tableListResponse.Count() >= 1); Assert.True(tableListResponse.ElementAt(0).ColumnList != null && tableListResponse.ElementAt(0).ColumnList.Count() > 0); // Look for the table we created Assert.Contains(tableListResponse, table => table.Name.Equals(commonData.TableName)); // Get the table list with only basic info tableListResponse = clientToUse.Catalog.ListTables( commonData.SecondDataLakeAnalyticsAccountName, commonData.DatabaseName, CommonTestFixture.SchemaName, basic: true ); Assert.True(tableListResponse.Count() >= 1); Assert.True(tableListResponse.ElementAt(0).ColumnList == null || tableListResponse.ElementAt(0).ColumnList.Count() == 0); // Get the table list in just the db tableListResponse = clientToUse.Catalog.ListTablesByDatabase( commonData.SecondDataLakeAnalyticsAccountName, commonData.DatabaseName ); Assert.True(tableListResponse.Count() >= 1); Assert.True(tableListResponse.ElementAt(0).ColumnList != null && tableListResponse.ElementAt(0).ColumnList.Count > 0); // Look for the table we created Assert.Contains(tableListResponse, table => table.Name.Equals(commonData.TableName)); // Get the table list in the db with only basic info tableListResponse = clientToUse.Catalog.ListTablesByDatabase( commonData.SecondDataLakeAnalyticsAccountName, commonData.DatabaseName, basic: true ); Assert.True(tableListResponse.Count() >= 1); Assert.True(tableListResponse.ElementAt(0).ColumnList == null || tableListResponse.ElementAt(0).ColumnList.Count() == 0); // Get preview of the specific table var tablePreviewGetResponse = clientToUse.Catalog.PreviewTable( commonData.SecondDataLakeAnalyticsAccountName, commonData.DatabaseName, CommonTestFixture.SchemaName, commonData.TableName ); Assert.True(tablePreviewGetResponse.TotalRowCount > 0); Assert.True(tablePreviewGetResponse.TotalColumnCount > 0); Assert.True(tablePreviewGetResponse.Rows != null && tablePreviewGetResponse.Rows.Count() > 0); Assert.True(tablePreviewGetResponse.Schema != null && tablePreviewGetResponse.Schema.Count() > 0); Assert.NotNull(tablePreviewGetResponse.Schema[0].Name); Assert.NotNull(tablePreviewGetResponse.Schema[0].Type); // Get the specific table as well var tableGetResponse = clientToUse.Catalog.GetTable( commonData.SecondDataLakeAnalyticsAccountName, commonData.DatabaseName, CommonTestFixture.SchemaName, commonData.TableName ); Assert.Equal(commonData.TableName, tableGetResponse.Name); // Get the tvf list var tvfListResponse = clientToUse.Catalog.ListTableValuedFunctions( commonData.SecondDataLakeAnalyticsAccountName, commonData.DatabaseName, CommonTestFixture.SchemaName ); Assert.True(tvfListResponse.Count() >= 1); // Look for the tvf we created Assert.Contains(tvfListResponse, tvf => tvf.Name.Equals(commonData.TvfName)); // Get tvf list in the database tvfListResponse = clientToUse.Catalog.ListTableValuedFunctionsByDatabase( commonData.SecondDataLakeAnalyticsAccountName, commonData.DatabaseName ); Assert.True(tvfListResponse.Count() >= 1); // look for the tvf we created Assert.Contains(tvfListResponse, tvf => tvf.Name.Equals(commonData.TvfName)); // Get the specific tvf as well var tvfGetResponse = clientToUse.Catalog.GetTableValuedFunction( commonData.SecondDataLakeAnalyticsAccountName, commonData.DatabaseName, CommonTestFixture.SchemaName, commonData.TvfName ); Assert.Equal(commonData.TvfName, tvfGetResponse.Name); // Get the view list var viewListResponse = clientToUse.Catalog.ListViews( commonData.SecondDataLakeAnalyticsAccountName, commonData.DatabaseName, CommonTestFixture.SchemaName ); Assert.True(viewListResponse.Count() >= 1); // Look for the view we created Assert.Contains(viewListResponse, view => view.Name.Equals(commonData.ViewName)); // Get the view list from just the database viewListResponse = clientToUse.Catalog.ListViewsByDatabase( commonData.SecondDataLakeAnalyticsAccountName, commonData.DatabaseName ); Assert.True(viewListResponse.Count() >= 1); // Look for the view we created Assert.Contains(viewListResponse, view => view.Name.Equals(commonData.ViewName)); // Get the specific view as well var viewGetResponse = clientToUse.Catalog.GetView( commonData.SecondDataLakeAnalyticsAccountName, commonData.DatabaseName, CommonTestFixture.SchemaName, commonData.ViewName ); Assert.Equal(commonData.ViewName, viewGetResponse.Name); // Get the procedure list var procListResponse = clientToUse.Catalog.ListProcedures( commonData.SecondDataLakeAnalyticsAccountName, commonData.DatabaseName, CommonTestFixture.SchemaName ); Assert.True(procListResponse.Count() >= 1); // Look for the procedure we created Assert.Contains(procListResponse, proc => proc.Name.Equals(commonData.ProcName)); // Get the specific procedure as well var procGetResponse = clientToUse.Catalog.GetProcedure( commonData.SecondDataLakeAnalyticsAccountName, commonData.DatabaseName, CommonTestFixture.SchemaName, commonData.ProcName ); Assert.Equal(commonData.ProcName, procGetResponse.Name); // Get the partition list var partitionList = clientToUse.Catalog.ListTablePartitions( commonData.SecondDataLakeAnalyticsAccountName, commonData.DatabaseName, CommonTestFixture.SchemaName, commonData.TableName ); Assert.True(partitionList.Count() >= 1); var specificPartition = partitionList.First(); // Get preview of the specific partition var partitionPreviewGetResponse = clientToUse.Catalog.PreviewTablePartition( commonData.SecondDataLakeAnalyticsAccountName, commonData.DatabaseName, CommonTestFixture.SchemaName, commonData.TableName, specificPartition.Name ); Assert.True(partitionPreviewGetResponse.TotalRowCount > 0); Assert.True(partitionPreviewGetResponse.TotalColumnCount > 0); Assert.True(partitionPreviewGetResponse.Rows != null && partitionPreviewGetResponse.Rows.Count() > 0); Assert.True(partitionPreviewGetResponse.Schema != null && partitionPreviewGetResponse.Schema.Count() > 0); Assert.NotNull(tablePreviewGetResponse.Schema[0].Name); Assert.NotNull(tablePreviewGetResponse.Schema[0].Type); // Get the specific partition as well var partitionGetResponse = clientToUse.Catalog.GetTablePartition( commonData.SecondDataLakeAnalyticsAccountName, commonData.DatabaseName, CommonTestFixture.SchemaName, commonData.TableName, specificPartition.Name ); Assert.Equal(specificPartition.Name, partitionGetResponse.Name); // Get the fragment list var fragmentList = clientToUse.Catalog.ListTableFragments( commonData.SecondDataLakeAnalyticsAccountName, commonData.DatabaseName, CommonTestFixture.SchemaName, commonData.TableName ); Assert.NotNull(fragmentList); Assert.NotEmpty(fragmentList); // Get all the types var typeGetResponse = clientToUse.Catalog.ListTypes( commonData.SecondDataLakeAnalyticsAccountName, commonData.DatabaseName, CommonTestFixture.SchemaName ); Assert.NotNull(typeGetResponse); Assert.NotEmpty(typeGetResponse); // Get all the types that are not complex typeGetResponse = clientToUse.Catalog.ListTypes( commonData.SecondDataLakeAnalyticsAccountName, commonData.DatabaseName, CommonTestFixture.SchemaName, new Microsoft.Rest.Azure.OData.ODataQuery <USqlType> { Filter = "isComplexType eq false" } ); Assert.NotNull(typeGetResponse); Assert.NotEmpty(typeGetResponse); Assert.DoesNotContain(typeGetResponse, type => type.IsComplexType.Value); // Prepare to grant/revoke ACLs var principalId = TestUtilities.GenerateGuid(); var grantAclParam = new AclCreateOrUpdateParameters { AceType = AclType.User, PrincipalId = principalId, Permission = PermissionType.Use }; var revokeAclParam = new AclDeleteParameters { AceType = AclType.User, PrincipalId = principalId }; // Get the initial number of ACLs by db var aclByDbListResponse = clientToUse.Catalog.ListAclsByDatabase( commonData.SecondDataLakeAnalyticsAccountName, commonData.DatabaseName ); var aclByDbCount = aclByDbListResponse.Count(); // Get the initial number of ACLs by catalog var aclListResponse = clientToUse.Catalog.ListAcls( commonData.SecondDataLakeAnalyticsAccountName ); var aclCount = aclListResponse.Count(); // Grant ACL to the db clientToUse.Catalog.GrantAclToDatabase( commonData.SecondDataLakeAnalyticsAccountName, commonData.DatabaseName, grantAclParam ); aclByDbListResponse = clientToUse.Catalog.ListAclsByDatabase( commonData.SecondDataLakeAnalyticsAccountName, commonData.DatabaseName ); var acl = aclByDbListResponse.Last(); // Confirm the ACL's information Assert.Equal(aclByDbCount + 1, aclByDbListResponse.Count()); Assert.Equal(AclType.User, acl.AceType); Assert.Equal(principalId, acl.PrincipalId); Assert.Equal(PermissionType.Use, acl.Permission); // Revoke ACL from the db clientToUse.Catalog.RevokeAclFromDatabase( commonData.SecondDataLakeAnalyticsAccountName, commonData.DatabaseName, revokeAclParam ); aclByDbListResponse = clientToUse.Catalog.ListAclsByDatabase( commonData.SecondDataLakeAnalyticsAccountName, commonData.DatabaseName ); Assert.Equal(aclByDbCount, aclByDbListResponse.Count()); // Grant ACL to the catalog clientToUse.Catalog.GrantAcl( commonData.SecondDataLakeAnalyticsAccountName, grantAclParam ); aclListResponse = clientToUse.Catalog.ListAcls( commonData.SecondDataLakeAnalyticsAccountName ); acl = aclListResponse.Last(); // Confirm the ACL's information Assert.Equal(aclCount + 1, aclListResponse.Count()); Assert.Equal(AclType.User, acl.AceType); Assert.Equal(principalId, acl.PrincipalId); Assert.Equal(PermissionType.Use, acl.Permission); // Revoke ACL from the catalog clientToUse.Catalog.RevokeAcl( commonData.SecondDataLakeAnalyticsAccountName, revokeAclParam ); aclListResponse = clientToUse.Catalog.ListAcls( commonData.SecondDataLakeAnalyticsAccountName ); Assert.Equal(aclCount, aclListResponse.Count()); } } }
private static ComputeManagementClient GetComputeManagementClientRestClient(MockContext context) { return(context.GetServiceClient <ComputeManagementClient>(TestEnvironmentFactory.GetTestEnvironment())); }
public void CreateDirectPeering() { using (MockContext context = MockContext.Start(this.GetType().FullName)) { this.MockClients(context); //Create a Resource Group var rgname = TestUtilities.GenerateName("res"); var resourceGroup = this.ResourcesClient.ResourceGroups.CreateOrUpdate( rgname, new ResourceGroup { Location = "centralus" }); //Create Direct Peering var directConnection = new DirectConnection { ConnectionIdentifier = Guid.NewGuid().ToString(), BandwidthInMbps = 10000, PeeringDBFacilityId = 99999, SessionAddressProvider = SessionAddressProvider.Peer, UseForPeeringService = false, BgpSession = new Microsoft.Azure.Management.Peering.Models.BgpSession() { SessionPrefixV4 = this.CreateIpv4Address(true), MaxPrefixesAdvertisedV4 = 20000 } }; // Create Asn int asn = 65003; var subId = this.CreatePeerAsn(asn, $"AS{asn}", isApproved: true); SubResource asnReference = new SubResource(subId); var directPeeringProperties = new PeeringPropertiesDirect( new List <DirectConnection>(), false, asnReference, DirectPeeringType.Edge); directPeeringProperties.Connections.Add(directConnection); var peeringModel = new PeeringModel { PeeringLocation = "Seattle", Sku = new PeeringSku("Basic_Direct_Free"), Direct = directPeeringProperties, Location = "centralus", Kind = "Direct" }; var name = $"directpeering3103"; try { var result = this.Client.Peerings.CreateOrUpdate(rgname, name, peeringModel); var peering = this.Client.Peerings.Get(rgname, name); Assert.NotNull(peering); } catch (Exception ex) { Assert.Contains("NotFound", ex.Message); } finally { Assert.True(this.DeletePeering(name, rgname)); Assert.True(this.DeletePeerAsn($"AS{asn}")); // Assert.True(this.DeleteResourceGroup(context, rgname)); } } }