public async Task SubscriptionsList()
        {
            Environment.SetEnvironmentVariable("AZURE_TEST_MODE", "Playback");

            using (MockContext context = MockContext.Start(this.GetType()))
            {
                var testBase = new ApiManagementTestBase(context);
                testBase.TryCreateApiManagementService();

                // get product
                var listProductsResponse = testBase.client.Product.ListByService(
                    testBase.rgName,
                    testBase.serviceName,
                    new Microsoft.Rest.Azure.OData.ODataQuery <ProductContract>
                {
                    Filter = "name eq 'Starter'"
                });

                var product = listProductsResponse.Single();

                // list product's subscriptions
                var listSubscriptionsResponse = await testBase.client.ProductSubscriptions.ListAsync(
                    testBase.rgName,
                    testBase.serviceName,
                    product.Name,
                    null);

                Assert.NotNull(listSubscriptionsResponse);
                Assert.Single(listSubscriptionsResponse);
            }
        }
Esempio n. 2
0
        public async Task TryUpdateQuota()
        {
            Environment.SetEnvironmentVariable("AZURE_TEST_MODE", "Playback");
            using (MockContext context = MockContext.Start(this.GetType()))
            {
                var testBase = new ApiManagementTestBase(context);
                testBase.TryCreateApiManagementService();

                try
                {
                    // try to update quota. should not be 400(bad contract) but 404(quota not found)
                    await testBase.client.QuotaByCounterKeys.UpdateAsync(
                        testBase.rgName,
                        testBase.serviceName,
                        "not_exist",
                        new QuotaCounterValueUpdateContract()
                    {
                        CallsCount = 0, KbTransferred = 0
                    });
                }
                catch (ErrorResponseException ex) when(ex.Body.Code == "ResourceNotFound")
                {
                    //expected, do not raise exception
                }
            }
        }
Esempio n. 3
0
        public void WadlTest()
        {
            Environment.SetEnvironmentVariable("AZURE_TEST_MODE", "Playback");
            using (MockContext context = MockContext.Start(this.GetType().FullName))
            {
                var testBase = new ApiManagementTestBase(context);
                testBase.TryCreateApiManagementService();

                const string wadlPath = "./Resources/WADLYahoo.xml";
                const string path     = "yahooWadl";
                string       wadlApi  = TestUtilities.GenerateName("aid");

                try
                {
                    // import API
                    string wadlApiContent;
                    using (StreamReader reader = File.OpenText(wadlPath))
                    {
                        wadlApiContent = reader.ReadToEnd();
                    }

                    var apiCreateOrUpdate = new ApiCreateOrUpdateParameter()
                    {
                        Path          = path,
                        ContentFormat = ContentFormat.WadlXml,
                        ContentValue  = wadlApiContent
                    };

                    var wadlApiResponse = testBase.client.Api.CreateOrUpdate(
                        testBase.rgName,
                        testBase.serviceName,
                        wadlApi,
                        apiCreateOrUpdate);

                    Assert.NotNull(wadlApiResponse);

                    // get the api to check it was created
                    var getResponse = testBase.client.Api.Get(testBase.rgName, testBase.serviceName, wadlApi);

                    Assert.NotNull(getResponse);
                    Assert.Equal(wadlApi, getResponse.Name);
                    Assert.Equal(path, getResponse.Path);
                    Assert.Equal("Yahoo News Search", getResponse.DisplayName);
                    Assert.Equal("http://api.search.yahoo.com/NewsSearchService/V1/", getResponse.ServiceUrl);
                    Assert.True(getResponse.IsCurrent);
                    Assert.True(getResponse.Protocols.Contains(Protocol.Https));
                    Assert.Equal("1", getResponse.ApiRevision);

                    ApiExportResult wadlExport = testBase.client.ApiExport.Get(testBase.rgName, testBase.serviceName, wadlApi, ExportFormat.Wadl);

                    Assert.NotNull(wadlExport);
                    Assert.NotNull(wadlExport.Link);
                }
                finally
                {
                    // remove the API
                    testBase.client.Api.Delete(testBase.rgName, testBase.serviceName, wadlApi, "*");
                }
            }
        }
        public void OpenApiTest()
        {
            Environment.SetEnvironmentVariable("AZURE_TEST_MODE", "Playback");
            using (MockContext context = MockContext.Start(this.GetType()))
            {
                var testBase = new ApiManagementTestBase(context);
                testBase.TryCreateApiManagementService();

                const string openapiFilePath = "./Resources/petstore.yaml";
                const string path            = "openapi3";
                string       openApiId       = TestUtilities.GenerateName("aid");

                try
                {
                    // import API
                    string openApiContent;
                    using (StreamReader reader = File.OpenText(openapiFilePath))
                    {
                        openApiContent = reader.ReadToEnd();
                    }

                    var apiCreateOrUpdate = new ApiCreateOrUpdateParameter()
                    {
                        Path   = path,
                        Format = ContentFormat.Openapi,
                        Value  = openApiContent
                    };

                    var swaggerApiResponse = testBase.client.Api.CreateOrUpdate(
                        testBase.rgName,
                        testBase.serviceName,
                        openApiId,
                        apiCreateOrUpdate);

                    Assert.NotNull(swaggerApiResponse);

                    // get the api to check it was created
                    var getResponse = testBase.client.Api.Get(testBase.rgName, testBase.serviceName, openApiId);

                    Assert.NotNull(getResponse);
                    Assert.Equal(openApiId, getResponse.Name);
                    Assert.Equal(path, getResponse.Path);
                    Assert.Equal("Swagger Petstore", getResponse.DisplayName);
                    Assert.Equal("http://petstore.swagger.io/v1", getResponse.ServiceUrl);

                    ApiExportResult openApiExport = testBase.client.ApiExport.Get(testBase.rgName, testBase.serviceName, openApiId, ExportFormat.Openapi);

                    Assert.NotNull(openApiExport);
                    Assert.NotNull(openApiExport.Value.Link);
                    Assert.Equal("openapi-link", openApiExport.ExportResultFormat);
                }
                finally
                {
                    // remove the API
                    testBase.client.Api.Delete(testBase.rgName, testBase.serviceName, openApiId, "*");
                }
            }
        }
        public void SwaggerTest()
        {
            Environment.SetEnvironmentVariable("AZURE_TEST_MODE", "Playback");
            using (MockContext context = MockContext.Start(this.GetType()))
            {
                var testBase = new ApiManagementTestBase(context);
                testBase.TryCreateApiManagementService();

                const string swaggerPath = "./Resources/SwaggerPetStoreV2.json";
                const string path        = "swaggerApi";
                string       swaggerApi  = TestUtilities.GenerateName("aid");

                try
                {
                    // import API
                    string swaggerApiContent;
                    using (StreamReader reader = File.OpenText(swaggerPath))
                    {
                        swaggerApiContent = reader.ReadToEnd();
                    }

                    var apiCreateOrUpdate = new ApiCreateOrUpdateParameter()
                    {
                        Path   = path,
                        Format = ContentFormat.SwaggerJson,
                        Value  = swaggerApiContent
                    };

                    var swaggerApiResponse = testBase.client.Api.CreateOrUpdate(
                        testBase.rgName,
                        testBase.serviceName,
                        swaggerApi,
                        apiCreateOrUpdate);

                    Assert.NotNull(swaggerApiResponse);

                    // get the api to check it was created
                    var getResponse = testBase.client.Api.Get(testBase.rgName, testBase.serviceName, swaggerApi);

                    Assert.NotNull(getResponse);
                    Assert.Equal(swaggerApi, getResponse.Name);
                    Assert.Equal(path, getResponse.Path);
                    Assert.Equal("Swagger Petstore Extensive", getResponse.DisplayName);
                    Assert.Equal("http://petstore.swagger.wordnik.com/api", getResponse.ServiceUrl);

                    ApiExportResult swaggerExport = testBase.client.ApiExport.Get(testBase.rgName, testBase.serviceName, swaggerApi, ExportFormat.Swagger);

                    Assert.NotNull(swaggerExport);
                    Assert.NotNull(swaggerExport.Value.Link);
                    Assert.Equal("swagger-link-json", swaggerExport.ExportResultFormat);
                }
                finally
                {
                    // remove the API
                    testBase.client.Api.Delete(testBase.rgName, testBase.serviceName, swaggerApi, "*");
                }
            }
        }
        public async Task CreateListUpdatePortalRevision()
        {
            Environment.SetEnvironmentVariable("AZURE_TEST_MODE", "Playback");
            using (MockContext context = MockContext.Start(this.GetType()))
            {
                var testBase = new ApiManagementTestBase(context);
                testBase.TryCreateApiManagementService();
                var revisionId             = TestUtilities.GenerateName("revisionId");
                var portalRevisionContract = new PortalRevisionContract
                {
                    Description = new string('a', 99),
                    IsCurrent   = true
                };

                // create portal revision
                var portalRevision = await testBase.client.PortalRevision.CreateOrUpdateAsync(
                    testBase.rgName,
                    testBase.serviceName,
                    revisionId,
                    portalRevisionContract);

                Assert.NotNull(portalRevision);
                Assert.True(portalRevision.IsCurrent);
                Assert.Equal("completed", portalRevision.Status);

                //get
                var getPortalRevision = testBase.client.PortalRevision.Get(
                    testBase.rgName,
                    testBase.serviceName,
                    revisionId);

                Assert.NotNull(getPortalRevision);
                Assert.True(portalRevision.IsCurrent);
                Assert.Equal("completed", portalRevision.Status);

                var updateDescription = "Updated " + portalRevisionContract.Description;

                var updatedResult = await testBase.client.PortalRevision.UpdateAsync(
                    testBase.rgName,
                    testBase.serviceName,
                    revisionId,
                    new PortalRevisionContract { Description = updateDescription },
                    "*");

                Assert.NotNull(updatedResult);
                Assert.True(portalRevision.IsCurrent);
                Assert.Equal("completed", updatedResult.Status);
                Assert.Equal(updateDescription, updatedResult.Description);

                //list
                var listPortalRevision = testBase.client.PortalRevision.ListByService(
                    testBase.rgName,
                    testBase.serviceName);

                Assert.NotNull(listPortalRevision);
            }
        }
        public async Task CreateUpdateReset()
        {
            Environment.SetEnvironmentVariable("AZURE_TEST_MODE", "Playback");
            using (MockContext context = MockContext.Start(this.GetType()))
            {
                var testBase = new ApiManagementTestBase(context);
                testBase.TryCreateApiManagementService();

                // get the existing settings on the service
                PortalSignupSettings defaultSignupSettings = await testBase.client.SignUpSettings.GetAsync(
                    testBase.rgName,
                    testBase.serviceName);

                Assert.NotNull(defaultSignupSettings);

                // check settings Etag
                var signUpTag = await testBase.client.SignUpSettings.GetEntityTagAsync(
                    testBase.rgName,
                    testBase.serviceName);

                Assert.NotNull(signUpTag);
                Assert.NotNull(signUpTag.ETag);

                // disable portal signIn
                var portalSignUpSettingParams = new PortalSignupSettings()
                {
                    Enabled        = false,
                    TermsOfService = defaultSignupSettings.TermsOfService
                };
                var portalSignUpSettings = testBase.client.SignUpSettings.CreateOrUpdate(
                    testBase.rgName,
                    testBase.serviceName,
                    portalSignUpSettingParams);
                Assert.NotNull(portalSignUpSettings);
                Assert.False(portalSignUpSettings.Enabled);

                signUpTag = await testBase.client.SignUpSettings.GetEntityTagAsync(
                    testBase.rgName,
                    testBase.serviceName);

                Assert.NotNull(signUpTag);
                Assert.NotNull(signUpTag.ETag);

                // reset the signIn settings
                portalSignUpSettings.Enabled        = defaultSignupSettings.Enabled;
                portalSignUpSettings.TermsOfService = defaultSignupSettings.TermsOfService;
                await testBase.client.SignUpSettings.UpdateAsync(
                    testBase.rgName,
                    testBase.serviceName,
                    portalSignUpSettings,
                    signUpTag.ETag);
            }
        }
Esempio n. 8
0
        public void SubscriptionsList()
        {
            Environment.SetEnvironmentVariable("AZURE_TEST_MODE", "Playback");
            using (MockContext context = MockContext.Start(this.GetType()))
            {
                var testBase = new ApiManagementTestBase(context);
                testBase.TryCreateApiManagementService();

                var usersResponse = testBase.client.User.ListByService(testBase.rgName, testBase.serviceName, null);
                var user          = usersResponse.First();

                // list subscriptions of a user: there should be two by default
                var listResponse = testBase.client.UserSubscription.List(
                    testBase.rgName,
                    testBase.serviceName,
                    user.Name,
                    null);

                Assert.NotNull(listResponse);
                Assert.True(listResponse.Count() >= 2);
                Assert.Null(listResponse.NextPageLink);

                var userSubscription = testBase.client.UserSubscription.Get(
                    testBase.rgName,
                    testBase.serviceName,
                    user.Name,
                    listResponse.First().Name);

                Assert.NotNull(userSubscription);
                Assert.NotNull(userSubscription.Name);

                // list paged
                listResponse = testBase.client.UserSubscription.List(
                    testBase.rgName,
                    testBase.serviceName,
                    user.Name,
                    new Microsoft.Rest.Azure.OData.ODataQuery <SubscriptionContract> {
                    Top = 1
                });

                Assert.NotNull(listResponse);
                Assert.Single(listResponse);
                Assert.NotNull(listResponse.NextPageLink);

                // list next page
                listResponse = testBase.client.UserSubscription.ListNext(listResponse.NextPageLink);

                Assert.NotNull(listResponse);
                Assert.Single(listResponse);
                Assert.Null(listResponse.NextPageLink);
            }
        }
        public async Task GetUpdateKeys()
        {
            Environment.SetEnvironmentVariable("AZURE_TEST_MODE", "Playback");
            using (MockContext context = MockContext.Start(this.GetType()))
            {
                var testBase = new ApiManagementTestBase(context);
                testBase.TryCreateApiManagementService();

                // get settings
                var getResponse = testBase.client.TenantAccessGit.Get(
                    testBase.rgName,
                    testBase.serviceName);

                Assert.NotNull(getResponse);
                Assert.NotNull(getResponse);
                Assert.True(getResponse.Enabled); // git access is always enabled
                Assert.Null(getResponse.PrimaryKey);
                Assert.Null(getResponse.SecondaryKey);

                var secretsResponse = testBase.client.TenantAccessGit.ListSecrets(
                    testBase.rgName,
                    testBase.serviceName);
                Assert.NotNull(secretsResponse.PrimaryKey);
                Assert.NotNull(secretsResponse.SecondaryKey);

                testBase.client.TenantAccessGit.RegeneratePrimaryKey(
                    testBase.rgName,
                    testBase.serviceName);

                var secretsResponse2 = testBase.client.TenantAccessGit.ListSecrets(
                    testBase.rgName,
                    testBase.serviceName);

                Assert.NotNull(secretsResponse2);
                Assert.Equal(secretsResponse.SecondaryKey, secretsResponse2.SecondaryKey);
                Assert.NotEqual(secretsResponse.PrimaryKey, secretsResponse2.PrimaryKey);

                testBase.client.TenantAccessGit.RegenerateSecondaryKey(
                    testBase.rgName,
                    testBase.serviceName);

                var getSecretsHttpResponse = await testBase.client.TenantAccessGit.ListSecretsWithHttpMessagesAsync(
                    testBase.rgName,
                    testBase.serviceName);

                Assert.NotNull(getSecretsHttpResponse);
                Assert.NotNull(getSecretsHttpResponse.Body);
                Assert.NotNull(getSecretsHttpResponse.Headers.ETag);
                Assert.NotEqual(secretsResponse.SecondaryKey, getSecretsHttpResponse.Body.SecondaryKey);
            }
        }
Esempio n. 10
0
        public async Task CreateUpdateReset()
        {
            Environment.SetEnvironmentVariable("AZURE_TEST_MODE", "Playback");
            using (MockContext context = MockContext.Start(this.GetType()))
            {
                var testBase = new ApiManagementTestBase(context);
                testBase.TryCreateApiManagementService();
                // get the existing settings on the service
                var portalSignInSettings = await testBase.client.SignInSettings.GetAsync(
                    testBase.rgName,
                    testBase.serviceName);

                Assert.NotNull(portalSignInSettings);

                // disable portal signIn
                portalSignInSettings.Enabled = false;
                portalSignInSettings         = testBase.client.SignInSettings.CreateOrUpdate(
                    testBase.rgName,
                    testBase.serviceName,
                    portalSignInSettings);

                Assert.NotNull(portalSignInSettings);
                Assert.False(portalSignInSettings.Enabled);

                // check settings
                var signInTag = await testBase.client.SignInSettings.GetEntityTagAsync(
                    testBase.rgName,
                    testBase.serviceName);

                Assert.NotNull(signInTag);
                Assert.NotNull(signInTag.ETag);

                // reset the signIn settings
                portalSignInSettings.Enabled = true;
                await testBase.client.SignInSettings.UpdateAsync(
                    testBase.rgName,
                    testBase.serviceName,
                    portalSignInSettings,
                    signInTag.ETag);

                // get the delegation settings
                portalSignInSettings = await testBase.client.SignInSettings.GetAsync(
                    testBase.rgName,
                    testBase.serviceName);

                Assert.NotNull(portalSignInSettings);
                Assert.True(portalSignInSettings.Enabled);
            }
        }
        public void ListPortalSetting()
        {
            Environment.SetEnvironmentVariable("AZURE_TEST_MODE", "Playback");
            using (MockContext context = MockContext.Start(this.GetType()))
            {
                var testBase = new ApiManagementTestBase(context);
                testBase.TryCreateApiManagementService();

                // get the existing settings on the service
                var portalSettings = testBase.client.PortalSettings.ListByService(
                    testBase.rgName,
                    testBase.serviceName);
                Assert.NotNull(portalSettings);
            }
        }
        public async Task List()
        {
            Environment.SetEnvironmentVariable("AZURE_TEST_MODE", "Playback");
            using (MockContext context = MockContext.Start(this.GetType()))
            {
                var testBase = new ApiManagementTestBase(context);
                testBase.TryCreateApiManagementService();

                var regions = await testBase.client.Region.ListByServiceAsync(
                    testBase.rgName,
                    testBase.serviceName);

                Assert.NotNull(regions);
                Assert.Single(regions);
                Assert.Equal(testBase.location.ToLowerInvariant().Replace(" ", ""), regions.First().Name.ToLowerInvariant().Replace(" ", ""));
                Assert.True(regions.First().IsMasterRegion);
            }
        }
        public async Task ListAndGetSetting()
        {
            Environment.SetEnvironmentVariable("AZURE_TEST_MODE", "Playback");
            using (MockContext context = MockContext.Start(this.GetType()))
            {
                var testBase = new ApiManagementTestBase(context);
                testBase.TryCreateApiManagementService();

                // list tenant access
                var listSettings = testBase.client.TenantSettings.ListByService(
                    testBase.rgName,
                    testBase.serviceName);

                Assert.NotNull(listSettings);

                // there is only one setting `public`
                var getSetting = await testBase.client.TenantSettings.GetAsync(testBase.rgName, testBase.serviceName);

                Assert.NotNull(getSetting.Settings);
                Assert.True(getSetting.Settings.Count > 1);
            }
        }
Esempio n. 14
0
        public void UserIdentities()
        {
            Environment.SetEnvironmentVariable("AZURE_TEST_MODE", "Playback");
            using (MockContext context = MockContext.Start(this.GetType().FullName))
            {
                var testBase = new ApiManagementTestBase(context);
                testBase.TryCreateApiManagementService();

                // there should be 'Echo API' which is created by default for every new instance of API Management and
                // 'Starter' product

                var listUsersResponse = testBase.client.User.ListByService(
                    testBase.rgName,
                    testBase.serviceName,
                    new Microsoft.Rest.Azure.OData.ODataQuery <UserContract> {
                    Filter = "firstName eq 'Administrator'"
                });

                Assert.NotNull(listUsersResponse);
                Assert.Single(listUsersResponse);

                var user = listUsersResponse.Single();

                // list user identities
                var listResponse = testBase.client.UserIdentities.List(
                    testBase.rgName,
                    testBase.serviceName,
                    user.Name);

                Assert.NotNull(listResponse);

                // there should be Azure identification
                Assert.Single(listResponse);
                Assert.Equal(user.Email, listResponse.Single().Id);
                Assert.Equal("Azure", listResponse.Single().Provider);
            }
        }
Esempio n. 15
0
        public async Task CreateListUpdateDelete()
        {
            Environment.SetEnvironmentVariable("AZURE_TEST_MODE", "Playback");
            using (MockContext context = MockContext.Start(this.GetType()))
            {
                var testBase = new ApiManagementTestBase(context);
                testBase.TryCreateApiManagementService();

                // list gateways: there should be none
                var gatewayListResponse = testBase.client.Gateway.ListByService(
                    testBase.rgName,
                    testBase.serviceName,
                    null);

                Assert.NotNull(gatewayListResponse);
                Assert.Empty(gatewayListResponse);

                // list all the APIs
                var apisResponse = testBase.client.Api.ListByService(
                    testBase.rgName,
                    testBase.serviceName,
                    null);

                Assert.NotNull(apisResponse);
                Assert.Single(apisResponse);
                Assert.Null(apisResponse.NextPageLink);
                var echoApi = apisResponse.First();

                string gatewayId        = TestUtilities.GenerateName("gatewayid");;
                string certificateId    = TestUtilities.GenerateName("certificateId");
                string hostnameConfigId = TestUtilities.GenerateName("hostnameConfigId");

                try
                {
                    var gatewayContract = new GatewayContract()
                    {
                        LocationData = new ResourceLocationDataContract()
                        {
                            City            = "Seattle",
                            CountryOrRegion = "USA",
                            District        = "King County",
                            Name            = "Microsoft"
                        },
                        Description = TestUtilities.GenerateName()
                    };

                    var createResponse = await testBase.client.Gateway.CreateOrUpdateAsync(
                        testBase.rgName,
                        testBase.serviceName,
                        gatewayId,
                        gatewayContract);

                    Assert.NotNull(createResponse);
                    Assert.Equal(gatewayId, createResponse.Name);
                    Assert.Equal(gatewayContract.Description, createResponse.Description);
                    Assert.NotNull(createResponse.LocationData);
                    Assert.Equal(gatewayContract.LocationData.City, createResponse.LocationData.City);
                    Assert.Equal(gatewayContract.LocationData.CountryOrRegion, createResponse.LocationData.CountryOrRegion);
                    Assert.Equal(gatewayContract.LocationData.District, createResponse.LocationData.District);
                    Assert.Equal(gatewayContract.LocationData.Name, createResponse.LocationData.Name);

                    // get the gateway to check is was created
                    var getResponse = await testBase.client.Gateway.GetWithHttpMessagesAsync(
                        testBase.rgName,
                        testBase.serviceName,
                        gatewayId);

                    Assert.NotNull(getResponse);
                    Assert.Equal(gatewayId, getResponse.Body.Name);

                    // list gateways
                    gatewayListResponse = testBase.client.Gateway.ListByService(
                        testBase.rgName,
                        testBase.serviceName,
                        null);

                    Assert.NotNull(gatewayListResponse);
                    Assert.Single(gatewayListResponse);


                    var associationContract = new AssociationContract()
                    {
                        ProvisioningState = ProvisioningState.Created
                    };

                    // assign gateway to api
                    var assignResponse = await testBase.client.GatewayApi.CreateOrUpdateAsync(
                        testBase.rgName,
                        testBase.serviceName,
                        gatewayId,
                        echoApi.Name,
                        associationContract);

                    Assert.NotNull(assignResponse);
                    Assert.Equal(echoApi.Name, assignResponse.Name);

                    // list gateway apis
                    var apiGatewaysResponse = await testBase.client.GatewayApi.ListByServiceAsync(
                        testBase.rgName,
                        testBase.serviceName,
                        gatewayId);

                    Assert.NotNull(apiGatewaysResponse);
                    Assert.Single(apiGatewaysResponse);
                    Assert.Equal(echoApi.Name, apiGatewaysResponse.First().Name);

                    //certificate first:
                    var base64ArrayCertificate = Convert.FromBase64String(testBase.base64EncodedTestCertificateData);
                    var cert = new X509Certificate2(base64ArrayCertificate, testBase.testCertificatePassword);

                    var certCreateResponse = testBase.client.Certificate.CreateOrUpdate(
                        testBase.rgName,
                        testBase.serviceName,
                        certificateId,
                        new CertificateCreateOrUpdateParameters
                    {
                        Data     = testBase.base64EncodedTestCertificateData,
                        Password = testBase.testCertificatePassword
                    },
                        null);

                    //GatewayCertificateAuthority:
                    var gatewayCertificateAuthority = new GatewayCertificateAuthorityContract()
                    {
                        IsTrusted = true
                    };

                    var gatewayCertificateAuthorityCreateResponse = await testBase.client.GatewayCertificateAuthority.CreateOrUpdateWithHttpMessagesAsync(
                        testBase.rgName,
                        testBase.serviceName,
                        gatewayId,
                        certificateId,
                        gatewayCertificateAuthority
                        );

                    Assert.NotNull(gatewayCertificateAuthorityCreateResponse);
                    Assert.Equal(certificateId, gatewayCertificateAuthorityCreateResponse.Body.Name);
                    Assert.True(gatewayCertificateAuthorityCreateResponse.Body.IsTrusted);

                    var gatewayCertificateAuthorityResponse = await testBase.client.GatewayCertificateAuthority.GetAsync(
                        testBase.rgName,
                        testBase.serviceName,
                        gatewayId,
                        certificateId
                        );

                    Assert.NotNull(gatewayCertificateAuthorityResponse);
                    Assert.Equal(certificateId, gatewayCertificateAuthorityResponse.Name);
                    Assert.True(gatewayCertificateAuthorityResponse.IsTrusted);

                    //delete
                    testBase.client.GatewayCertificateAuthority.Delete(
                        testBase.rgName,
                        testBase.serviceName,
                        gatewayId,
                        certificateId,
                        "*");

                    //hostnameConfiguration:
                    var hostnameConfig = new GatewayHostnameConfigurationContract()
                    {
                        CertificateId = certCreateResponse.Id,
                        Hostname      = "www.contoso.com",
                        NegotiateClientCertificate = false
                    };

                    var hostnameConfigCreateResponse = await testBase.client.GatewayHostnameConfiguration.CreateOrUpdateAsync(
                        testBase.rgName,
                        testBase.serviceName,
                        gatewayId,
                        hostnameConfigId,
                        hostnameConfig
                        );

                    Assert.NotNull(hostnameConfigCreateResponse);
                    Assert.Equal(hostnameConfigId, hostnameConfigCreateResponse.Name);
                    Assert.Equal(hostnameConfigCreateResponse.CertificateId, hostnameConfigCreateResponse.CertificateId);
                    Assert.Equal("www.contoso.com", hostnameConfigCreateResponse.Hostname);
                    Assert.False(hostnameConfigCreateResponse.NegotiateClientCertificate);

                    var hostnameConfigResponse = await testBase.client.GatewayHostnameConfiguration.GetAsync(
                        testBase.rgName,
                        testBase.serviceName,
                        gatewayId,
                        hostnameConfigId
                        );

                    Assert.NotNull(hostnameConfigCreateResponse);
                    Assert.Equal(hostnameConfigId, hostnameConfigCreateResponse.Name);
                    Assert.Equal(hostnameConfigCreateResponse.CertificateId, hostnameConfigCreateResponse.CertificateId);
                    Assert.Equal("www.contoso.com", hostnameConfigCreateResponse.Hostname);
                    Assert.False(hostnameConfigCreateResponse.NegotiateClientCertificate);

                    //delete hostname config
                    testBase.client.GatewayHostnameConfiguration.Delete(
                        testBase.rgName,
                        testBase.serviceName,
                        gatewayId,
                        hostnameConfigId,
                        "*");

                    //get latest etag for delete
                    getResponse = await testBase.client.Gateway.GetWithHttpMessagesAsync(
                        testBase.rgName,
                        testBase.serviceName,
                        gatewayId);

                    // remove the gateway
                    testBase.client.Gateway.Delete(
                        testBase.rgName,
                        testBase.serviceName,
                        gatewayId,
                        getResponse.Headers.ETag);

                    // list again to see it was removed
                    gatewayListResponse = testBase.client.Gateway.ListByService(
                        testBase.rgName,
                        testBase.serviceName,
                        null);

                    Assert.NotNull(gatewayListResponse);
                    Assert.Empty(gatewayListResponse);
                }
                finally
                {
                    try
                    {
                        testBase.client.GatewayHostnameConfiguration.Delete(testBase.rgName, testBase.serviceName, gatewayId, hostnameConfigId, "*");
                    }
                    catch (ErrorResponseException) { }
                    testBase.client.Gateway.Delete(testBase.rgName, testBase.serviceName, gatewayId, "*");
                    testBase.client.Certificate.Delete(testBase.rgName, testBase.serviceName, certificateId, "*");
                }
            }
        }
Esempio n. 16
0
        public async Task CreateUpdateDelete()
        {
            Environment.SetEnvironmentVariable("AZURE_TEST_MODE", "Playback");

            using (MockContext context = MockContext.Start(this.GetType()))
            {
                var testBase = new ApiManagementTestBase(context);
                testBase.TryCreateApiManagementService();

                // list all the APIs
                var apiListResponse = testBase.client.Api.ListByService(
                    testBase.rgName,
                    testBase.serviceName,
                    null);
                Assert.NotNull(apiListResponse);
                Assert.Single(apiListResponse);
                Assert.Null(apiListResponse.NextPageLink);

                // find the echo api
                var echoApi = apiListResponse.First();

                // list users
                var listUsersResponse = testBase.client.User.ListByService(
                    testBase.rgName,
                    testBase.serviceName,
                    null);

                Assert.NotNull(listUsersResponse);
                Assert.Single(listUsersResponse);

                var adminUser = listUsersResponse.First();

                // there should be now issues initially
                var issuesList = testBase.client.ApiIssue.ListByService(
                    testBase.rgName,
                    testBase.serviceName,
                    echoApi.Name,
                    null);
                Assert.NotNull(issuesList);
                Assert.Empty(issuesList);

                string       newissueId      = TestUtilities.GenerateName("newIssue");
                string       newcommentId    = TestUtilities.GenerateName("newComment");
                string       newattachmentId = TestUtilities.GenerateName("newattachment");
                const string attachmentPath  = "./Resources/apiissueattachment.JPG";

                try
                {
                    // add a recipient to the notification
                    var issueContract = new IssueContract()
                    {
                        Title       = TestUtilities.GenerateName("title"),
                        Description = TestUtilities.GenerateName("description"),
                        UserId      = adminUser.Id,
                        ApiId       = echoApi.Id,
                        CreatedDate = DateTime.UtcNow
                    };
                    var apiIssueContract = await testBase.client.ApiIssue.CreateOrUpdateAsync(
                        testBase.rgName,
                        testBase.serviceName,
                        echoApi.Name,
                        newissueId,
                        issueContract);

                    Assert.NotNull(apiIssueContract);
                    Assert.Equal(echoApi.Id, apiIssueContract.ApiId);
                    Assert.Equal(State.Proposed, apiIssueContract.State);
                    Assert.Equal(issueContract.Title, apiIssueContract.Title);
                    // get the issue
                    var issueData = await testBase.client.ApiIssue.GetAsync(
                        testBase.rgName,
                        testBase.serviceName,
                        echoApi.Name,
                        newissueId);

                    Assert.NotNull(issueData);
                    Assert.Equal(issueData.Name, newissueId);
                    Assert.Equal(adminUser.Id, issueData.UserId);

                    // update the issue
                    var updateTitle       = TestUtilities.GenerateName("updatedTitle");
                    var updateDescription = TestUtilities.GenerateName("updateddescription");

                    var issueUpdateContract = new IssueUpdateContract()
                    {
                        Description = updateDescription,
                        Title       = updateTitle
                    };

                    await testBase.client.ApiIssue.UpdateAsync(
                        testBase.rgName,
                        testBase.serviceName,
                        echoApi.Name,
                        newissueId,
                        issueUpdateContract,
                        "*");

                    // get the issue
                    issueData = await testBase.client.ApiIssue.GetAsync(
                        testBase.rgName,
                        testBase.serviceName,
                        echoApi.Name,
                        newissueId);

                    Assert.NotNull(issueData);
                    Assert.Equal(issueData.Name, newissueId);
                    Assert.Equal(adminUser.Id, issueData.UserId);
                    Assert.Equal(updateTitle, issueData.Title);
                    Assert.Equal(updateDescription, issueData.Description);

                    // get commments on issue. there should be none initially
                    var emptyCommentList = await testBase.client.ApiIssueComment.ListByServiceAsync(
                        testBase.rgName,
                        testBase.serviceName,
                        echoApi.Name,
                        newissueId,
                        null);

                    Assert.Empty(emptyCommentList);

                    // add a comment
                    var issueCommentParameters = new IssueCommentContract()
                    {
                        Text        = TestUtilities.GenerateName("issuecommenttext"),
                        UserId      = adminUser.Id,
                        CreatedDate = DateTime.UtcNow
                    };
                    var addedComment = await testBase.client.ApiIssueComment.CreateOrUpdateAsync(
                        testBase.rgName,
                        testBase.serviceName,
                        echoApi.Name,
                        newissueId,
                        newcommentId,
                        issueCommentParameters);

                    Assert.NotNull(addedComment);
                    Assert.Equal(addedComment.Name, newcommentId);
                    // https://msazure.visualstudio.com/DefaultCollection/One/_workitems/edit/4402087
                    //Assert.Equal(addedComment.UserId, adminUser.Id); //Bug userId is not getting populated
                    Assert.NotNull(addedComment.CreatedDate);

                    // get the comment tag.
                    var commentEntityTag = await testBase.client.ApiIssueComment.GetEntityTagAsync(
                        testBase.rgName,
                        testBase.serviceName,
                        echoApi.Name,
                        newissueId,
                        newcommentId);

                    Assert.NotNull(commentEntityTag);
                    Assert.NotNull(commentEntityTag.ETag);

                    // delete the commment
                    await testBase.client.ApiIssueComment.DeleteAsync(
                        testBase.rgName,
                        testBase.serviceName,
                        echoApi.Name,
                        newissueId,
                        newcommentId,
                        commentEntityTag.ETag);

                    try
                    {
                        // get the apicomment
                        var getComment = await testBase.client.ApiIssueComment.GetAsync(
                            testBase.rgName,
                            testBase.serviceName,
                            echoApi.Name,
                            newissueId,
                            newcommentId);

                        // should not come here
                        throw new Exception("This code should not have been executed.");
                    }
                    catch (ErrorResponseException ex)
                    {
                        Assert.Equal(HttpStatusCode.NotFound, ex.Response.StatusCode);
                    }

                    // get the issue attachments
                    var apiIssueAttachments = await testBase.client.ApiIssueAttachment.ListByServiceAsync(
                        testBase.rgName,
                        testBase.serviceName,
                        echoApi.Name,
                        newissueId,
                        null);

                    Assert.Empty(apiIssueAttachments);

                    // add an attachment to the issue
                    FileInfo fileInfo = new FileInfo(attachmentPath);

                    // The byte[] to save the data in
                    byte[] data = new byte[fileInfo.Length];

                    // Load a filestream and put its content into the byte[]
                    using (FileStream fs = fileInfo.OpenRead())
                    {
                        fs.Read(data, 0, data.Length);
                    }

                    var content = Convert.ToBase64String(data);
                    var issueAttachmentContract = new IssueAttachmentContract()
                    {
                        Content       = content,
                        ContentFormat = "image/jpeg",
                        Title         = TestUtilities.GenerateName("attachment")
                    };
                    var issueAttachment = await testBase.client.ApiIssueAttachment.CreateOrUpdateAsync(
                        testBase.rgName,
                        testBase.serviceName,
                        echoApi.Name,
                        newissueId,
                        newattachmentId,
                        issueAttachmentContract);

                    Assert.NotNull(issueAttachment);
                    Assert.Equal(newattachmentId, issueAttachment.Name);
                    Assert.Equal("link", issueAttachment.ContentFormat);
                    Assert.NotNull(issueAttachment.Content);

                    // get the attachment tag
                    var issueAttachmentTag = await testBase.client.ApiIssueAttachment.GetEntityTagAsync(
                        testBase.rgName,
                        testBase.serviceName,
                        echoApi.Name,
                        newissueId,
                        newattachmentId);

                    Assert.NotNull(issueAttachmentTag);
                    Assert.NotNull(issueAttachmentTag.ETag);

                    // delete the attachment
                    await testBase.client.ApiIssueAttachment.DeleteAsync(
                        testBase.rgName,
                        testBase.serviceName,
                        echoApi.Name,
                        newissueId,
                        newattachmentId,
                        issueAttachmentTag.ETag);

                    try
                    {
                        var issueattachment = await testBase.client.ApiIssueAttachment.GetAsync(
                            testBase.rgName,
                            testBase.serviceName,
                            echoApi.Name,
                            newissueId,
                            newattachmentId);

                        // it should not reach here.
                        throw new Exception("This code should not have been executed.");
                    }
                    catch (ErrorResponseException ex)
                    {
                        Assert.Equal(HttpStatusCode.NotFound, ex.Response.StatusCode);
                    }

                    // get the issue tag
                    var apiIssuetag = await testBase.client.ApiIssue.GetEntityTagAsync(
                        testBase.rgName,
                        testBase.serviceName,
                        echoApi.Name,
                        newissueId);

                    Assert.NotNull(apiIssuetag);

                    // delete the issue
                    await testBase.client.ApiIssue.DeleteAsync(
                        testBase.rgName,
                        testBase.serviceName,
                        echoApi.Name,
                        newissueId,
                        apiIssuetag.ETag);

                    // check the issue exist
                    try
                    {
                        var apiIssue = await testBase.client.ApiIssue.GetAsync(
                            testBase.rgName,
                            testBase.serviceName,
                            echoApi.Name,
                            newissueId);

                        // it should not reach here.
                        throw new Exception("This code should not have been executed.");
                    }
                    catch (ErrorResponseException ex)
                    {
                        Assert.Equal(HttpStatusCode.NotFound, ex.Response.StatusCode);
                    }
                }
                finally
                {
                    // cleanup the api issue attachment, if exists
                    testBase.client.ApiIssueAttachment.Delete(
                        testBase.rgName,
                        testBase.serviceName,
                        echoApi.Name,
                        newissueId,
                        newattachmentId,
                        "*");

                    // cleanup the api issue comment if exists
                    testBase.client.ApiIssueComment.Delete(
                        testBase.rgName,
                        testBase.serviceName,
                        echoApi.Name,
                        newissueId,
                        newcommentId,
                        "*");

                    // cleanup the api issue if exists
                    testBase.client.ApiIssue.Delete(
                        testBase.rgName,
                        testBase.serviceName,
                        echoApi.Name,
                        newissueId,
                        "*");
                }
            }
        }
Esempio n. 17
0
        public async Task CreateListUpdateDelete()
        {
            Environment.SetEnvironmentVariable("AZURE_TEST_MODE", "Playback");
            using (MockContext context = MockContext.Start(this.GetType()))
            {
                var testBase = new ApiManagementTestBase(context);
                testBase.TryCreateApiManagementService();

                var userId     = TestUtilities.GenerateName("sdkUserId");
                var newGroupId = TestUtilities.GenerateName("sdkGroupId");

                try
                {
                    // create a new group
                    var newGroupDisplayName = TestUtilities.GenerateName("sdkGroup");
                    var parameters          = new GroupCreateParameters()
                    {
                        DisplayName = newGroupDisplayName,
                        Description = "Group created from Sdk client"
                    };

                    var groupContract = await testBase.client.Group.CreateOrUpdateAsync(
                        testBase.rgName,
                        testBase.serviceName,
                        newGroupId,
                        parameters);

                    Assert.NotNull(groupContract);
                    Assert.Equal(newGroupDisplayName, groupContract.DisplayName);
                    Assert.False(groupContract.BuiltIn);
                    Assert.NotNull(groupContract.Description);
                    Assert.Equal(GroupType.Custom, groupContract.GroupContractType);

                    // list all group users
                    var listResponse = testBase.client.GroupUser.List(
                        testBase.rgName,
                        testBase.serviceName,
                        newGroupId,
                        null);
                    Assert.NotNull(listResponse);
                    Assert.Empty(listResponse);

                    // create a new user and add to the group
                    var createParameters = new UserCreateParameters()
                    {
                        FirstName = TestUtilities.GenerateName("sdkFirst"),
                        LastName  = TestUtilities.GenerateName("sdkLast"),
                        Email     = TestUtilities.GenerateName("sdkFirst.Last") + "@contoso.com",
                        State     = UserState.Active,
                        Note      = "dummy note"
                    };

                    var userContract = testBase.client.User.CreateOrUpdate(
                        testBase.rgName,
                        testBase.serviceName,
                        userId,
                        createParameters);
                    Assert.NotNull(userContract);

                    // add user to group
                    var addUserContract = testBase.client.GroupUser.Create(
                        testBase.rgName,
                        testBase.serviceName,
                        newGroupId,
                        userId);
                    Assert.NotNull(addUserContract);
                    Assert.Equal(userContract.Email, addUserContract.Email);
                    Assert.Equal(userContract.FirstName, addUserContract.FirstName);

                    // list group user
                    var listgroupResponse = testBase.client.GroupUser.List(
                        testBase.rgName,
                        testBase.serviceName,
                        newGroupId);
                    Assert.NotNull(listgroupResponse);
                    Assert.Single(listgroupResponse);
                    Assert.Equal(addUserContract.Email, listgroupResponse.GetEnumerator().ToIEnumerable().First().Email);

                    // check entity exists
                    var entityStatus = await testBase.client.GroupUser.CheckEntityExistsAsync(
                        testBase.rgName,
                        testBase.serviceName,
                        newGroupId,
                        userId);

                    Assert.True(entityStatus);

                    // remove user from group
                    testBase.client.GroupUser.Delete(
                        testBase.rgName,
                        testBase.serviceName,
                        newGroupId,
                        userId);

                    // make sure user is removed
                    entityStatus = await testBase.client.GroupUser.CheckEntityExistsAsync(
                        testBase.rgName,
                        testBase.serviceName,
                        newGroupId,
                        userId);

                    Assert.False(entityStatus);
                }
                finally
                {
                    // delete the user
                    testBase.client.User.Delete(
                        testBase.rgName,
                        testBase.serviceName,
                        userId,
                        "*",
                        deleteSubscriptions: true);

                    // delete the group
                    testBase.client.Group.Delete(
                        testBase.rgName,
                        testBase.serviceName,
                        newGroupId,
                        "*");
                }
            }
        }
Esempio n. 18
0
        public async Task CreateListUpdateDeleteOperationTags()
        {
            Environment.SetEnvironmentVariable("AZURE_TEST_MODE", "Playback");
            using (MockContext context = MockContext.Start(this.GetType()))
            {
                var testBase = new ApiManagementTestBase(context);
                testBase.TryCreateApiManagementService();

                var tagsResources = await testBase.client.Tag.ListByServiceAsync(
                    testBase.rgName,
                    testBase.serviceName);

                Assert.Empty(tagsResources);

                // there should be 'Echo API' which is created by default for every new instance of API Management
                var apis = testBase.client.Api.ListByService(
                    testBase.rgName,
                    testBase.serviceName);

                Assert.Single(apis);
                var api = apis.Single();

                // list paged
                var listResponse = testBase.client.ApiOperation.ListByApi(
                    testBase.rgName,
                    testBase.serviceName,
                    api.Name,
                    new Microsoft.Rest.Azure.OData.ODataQuery <OperationContract> {
                    Top = 1
                });

                var firstOperation = listResponse.First();

                string tagId = TestUtilities.GenerateName("operationTag");
                try
                {
                    string tagDisplayName   = TestUtilities.GenerateName("opreationTag");
                    var    createParameters = new TagCreateUpdateParameters();
                    createParameters.DisplayName = tagDisplayName;

                    // create a tag
                    var tagContract = testBase.client.Tag.CreateOrUpdate(
                        testBase.rgName,
                        testBase.serviceName,
                        tagId,
                        createParameters);

                    Assert.NotNull(tagContract);
                    Assert.Equal(tagDisplayName, tagContract.DisplayName);

                    // associate the tag with the API Operation
                    tagContract = await testBase.client.Tag.AssignToOperationAsync(
                        testBase.rgName,
                        testBase.serviceName,
                        api.Name,
                        firstOperation.Name,
                        tagId);

                    Assert.NotNull(tagContract);

                    // Tag list by Api Operation
                    var tagsInOperation = await testBase.client.Tag.ListByOperationAsync(
                        testBase.rgName,
                        testBase.serviceName,
                        api.Name,
                        firstOperation.Name);

                    Assert.NotNull(tagsInOperation);
                    Assert.Single(tagsInOperation);
                    Assert.Equal(tagDisplayName, tagsInOperation.First().DisplayName);

                    // get the tag on the api operation
                    var tagOnOperation = await testBase.client.Tag.GetByOperationAsync(
                        testBase.rgName,
                        testBase.serviceName,
                        api.Name,
                        firstOperation.Name,
                        tagId);

                    Assert.NotNull(tagOnOperation);
                    Assert.Equal(tagDisplayName, tagOnOperation.DisplayName);

                    // get the tag resources for the service.
                    var tagResources = await testBase.client.TagResource.ListByServiceAsync(
                        testBase.rgName,
                        testBase.serviceName);

                    Assert.NotNull(tagResources);
                    Assert.Single(tagResources);
                    Assert.Equal(tagDisplayName, tagResources.First().Tag.Name);
                    Assert.Null(tagResources.First().Api);
                    Assert.NotNull(tagResources.First().Operation);
                    Assert.Null(tagResources.First().Product);
                    Assert.Equal(firstOperation.DisplayName, tagResources.GetEnumerator().ToIEnumerable().First().Operation.Name, true);
                    Assert.Equal(firstOperation.Method, tagResources.GetEnumerator().ToIEnumerable().First().Operation.Method);

                    // get the tag Etag
                    var tagEtagByOperation = await testBase.client.Tag.GetEntityStateByOperationAsync(
                        testBase.rgName,
                        testBase.serviceName,
                        api.Name,
                        firstOperation.Name,
                        tagId);

                    Assert.NotNull(tagEtagByOperation);
                    Assert.NotNull(tagEtagByOperation.ETag);

                    // detach the tag
                    await testBase.client.Tag.DetachFromOperationAsync(
                        testBase.rgName,
                        testBase.serviceName,
                        api.Name,
                        firstOperation.Name,
                        tagId);

                    Assert.Throws <ErrorResponseException>(()
                                                           => testBase.client.Tag.GetByOperation(
                                                               testBase.rgName,
                                                               testBase.serviceName,
                                                               api.Name,
                                                               firstOperation.Name,
                                                               tagId));

                    var tagEtag = await testBase.client.Tag.GetEntityStateAsync(
                        testBase.rgName,
                        testBase.serviceName,
                        tagId);

                    Assert.NotNull(tagEtag);
                    Assert.NotNull(tagEtag.ETag);

                    //delete the tag
                    await testBase.client.Tag.DeleteAsync(
                        testBase.rgName,
                        testBase.serviceName,
                        tagId,
                        tagEtag.ETag);

                    Assert.Throws <ErrorResponseException>(()
                                                           => testBase.client.Tag.GetEntityState(
                                                               testBase.rgName,
                                                               testBase.serviceName,
                                                               tagId));
                }
                finally
                {
                    testBase.client.Tag.DetachFromOperation(
                        testBase.rgName,
                        testBase.serviceName,
                        api.Name,
                        firstOperation.Name,
                        tagId);

                    testBase.client.Tag.Delete(
                        testBase.rgName, testBase.serviceName, tagId, "*");
                }
            }
        }
Esempio n. 19
0
        public async Task CreateListUpdateDeleteApiTags()
        {
            Environment.SetEnvironmentVariable("AZURE_TEST_MODE", "Playback");
            using (MockContext context = MockContext.Start(this.GetType()))
            {
                var testBase = new ApiManagementTestBase(context);
                testBase.TryCreateApiManagementService();

                var tagsResources = await testBase.client.Tag.ListByServiceAsync(
                    testBase.rgName,
                    testBase.serviceName);

                Assert.Empty(tagsResources);

                // list all the APIs
                var listResponse = testBase.client.Api.ListByService(
                    testBase.rgName,
                    testBase.serviceName,
                    null);
                Assert.NotNull(listResponse);
                Assert.Single(listResponse);
                Assert.Null(listResponse.NextPageLink);

                var echoApi = listResponse.First();

                string tagId = TestUtilities.GenerateName("apiTag");
                try
                {
                    string tagDisplayName   = TestUtilities.GenerateName("apiTag");
                    var    createParameters = new TagCreateUpdateParameters();
                    createParameters.DisplayName = tagDisplayName;

                    // create a tag
                    var tagContract = testBase.client.Tag.CreateOrUpdate(
                        testBase.rgName,
                        testBase.serviceName,
                        tagId,
                        createParameters);

                    Assert.NotNull(tagContract);
                    Assert.Equal(tagDisplayName, tagContract.DisplayName);

                    // associate the tag with the API
                    tagContract = await testBase.client.Tag.AssignToApiAsync(
                        testBase.rgName,
                        testBase.serviceName,
                        echoApi.Name,
                        tagId);

                    Assert.NotNull(tagContract);

                    // get APIs with Tags
                    var apisWithTags = await testBase.client.Api.ListByTagsAsync(
                        testBase.rgName,
                        testBase.serviceName,
                        new Microsoft.Rest.Azure.OData.ODataQuery <TagResourceContract>
                    {
                        Top = 1
                    });

                    Assert.NotNull(apisWithTags);
                    Assert.Single(apisWithTags);
                    Assert.Equal(tagContract.DisplayName, apisWithTags.GetEnumerator().ToIEnumerable().First().Tag.Name);

                    // Tag list by API
                    var tagsInApi = await testBase.client.Tag.ListByApiAsync(
                        testBase.rgName,
                        testBase.serviceName,
                        echoApi.Name);

                    Assert.NotNull(tagsInApi);
                    Assert.Single(tagsInApi);
                    Assert.Equal(tagDisplayName, tagsInApi.GetEnumerator().ToIEnumerable().First().DisplayName);

                    // get the tag on the api
                    var tagOnApi = await testBase.client.Tag.GetByApiAsync(
                        testBase.rgName,
                        testBase.serviceName,
                        echoApi.Name,
                        tagId);

                    Assert.NotNull(tagOnApi);
                    Assert.Equal(tagDisplayName, tagOnApi.DisplayName);

                    // get the tag Etag
                    var tagEtagByApi = await testBase.client.Tag.GetEntityStateByApiAsync(
                        testBase.rgName,
                        testBase.serviceName,
                        echoApi.Name,
                        tagId);

                    Assert.NotNull(tagEtagByApi);
                    Assert.NotNull(tagEtagByApi.ETag);

                    // get the tag resources for the service.
                    var tagResources = await testBase.client.TagResource.ListByServiceAsync(
                        testBase.rgName,
                        testBase.serviceName);

                    Assert.NotNull(tagResources);
                    Assert.Single(tagResources);
                    Assert.Equal(tagDisplayName, tagResources.GetEnumerator().ToIEnumerable().First().Tag.Name);
                    Assert.NotNull(tagResources.GetEnumerator().ToIEnumerable().First().Api);
                    Assert.Equal(echoApi.DisplayName, tagResources.GetEnumerator().ToIEnumerable().First().Api.Name);

                    // detach the tag
                    await testBase.client.Tag.DetachFromApiAsync(
                        testBase.rgName,
                        testBase.serviceName,
                        echoApi.Name,
                        tagId);

                    Assert.Throws <ErrorResponseException>(()
                                                           => testBase.client.Tag.GetByApi(
                                                               testBase.rgName,
                                                               testBase.serviceName,
                                                               echoApi.Name,
                                                               tagId));

                    var tagEtag = await testBase.client.Tag.GetEntityStateAsync(
                        testBase.rgName,
                        testBase.serviceName,
                        tagId);

                    Assert.NotNull(tagEtag);
                    Assert.NotNull(tagEtag.ETag);

                    //delete the tag
                    await testBase.client.Tag.DeleteAsync(
                        testBase.rgName,
                        testBase.serviceName,
                        tagId,
                        tagEtag.ETag);

                    Assert.Throws <ErrorResponseException>(()
                                                           => testBase.client.Tag.GetEntityState(
                                                               testBase.rgName,
                                                               testBase.serviceName,
                                                               tagId));
                }
                finally
                {
                    testBase.client.Tag.DetachFromApi(
                        testBase.rgName, testBase.serviceName, echoApi.Name, tagId);
                    testBase.client.Tag.Delete(
                        testBase.rgName, testBase.serviceName, tagId, "*");
                }
            }
        }
Esempio n. 20
0
        public async Task CreateListUpdateDeleteProductTags()
        {
            Environment.SetEnvironmentVariable("AZURE_TEST_MODE", "Playback");
            using (MockContext context = MockContext.Start(this.GetType()))
            {
                var testBase = new ApiManagementTestBase(context);
                testBase.TryCreateApiManagementService();

                var tagsResources = await testBase.client.Tag.ListByServiceAsync(
                    testBase.rgName,
                    testBase.serviceName);

                Assert.Empty(tagsResources);

                // list all the Product
                var listResponse = testBase.client.Product.ListByService(
                    testBase.rgName,
                    testBase.serviceName,
                    null);
                Assert.NotNull(listResponse);
                Assert.Equal(2, listResponse.GetEnumerator().ToIEnumerable().Count());
                Assert.Null(listResponse.NextPageLink);

                var starterProduct = listResponse.First();

                string tagId = TestUtilities.GenerateName("productTag");
                try
                {
                    string tagDisplayName   = TestUtilities.GenerateName("productTag");
                    var    createParameters = new TagCreateUpdateParameters();
                    createParameters.DisplayName = tagDisplayName;

                    // create a tag
                    var tagContract = testBase.client.Tag.CreateOrUpdate(
                        testBase.rgName,
                        testBase.serviceName,
                        tagId,
                        createParameters);

                    Assert.NotNull(tagContract);
                    Assert.Equal(tagDisplayName, tagContract.DisplayName);

                    // associate the tag with the API
                    tagContract = await testBase.client.Tag.AssignToProductAsync(
                        testBase.rgName,
                        testBase.serviceName,
                        starterProduct.Name,
                        tagId);

                    Assert.NotNull(tagContract);

                    // Tag list by Prod
                    var tagsInProduct = await testBase.client.Tag.ListByProductAsync(
                        testBase.rgName,
                        testBase.serviceName,
                        starterProduct.Name);

                    Assert.NotNull(tagsInProduct);
                    Assert.Single(tagsInProduct);
                    Assert.Equal(tagDisplayName, tagsInProduct.GetEnumerator().ToIEnumerable().First().DisplayName);

                    // get the tag on the api
                    var tagOnProduct = await testBase.client.Tag.GetByProductAsync(
                        testBase.rgName,
                        testBase.serviceName,
                        starterProduct.Name,
                        tagId);

                    Assert.NotNull(tagOnProduct);
                    Assert.Equal(tagDisplayName, tagOnProduct.DisplayName);

                    // get the tag resources for the service.
                    var tagResources = await testBase.client.TagResource.ListByServiceAsync(
                        testBase.rgName,
                        testBase.serviceName);

                    Assert.NotNull(tagResources);
                    Assert.Single(tagResources);
                    Assert.Equal(tagDisplayName, tagResources.First().Tag.Name);
                    Assert.Null(tagResources.First().Api);
                    Assert.Null(tagResources.First().Operation);
                    Assert.NotNull(tagResources.First().Product);
                    Assert.Equal(starterProduct.DisplayName, tagResources.First().Product.Name);

                    // get the tag Etag
                    var tagEtagByProduct = await testBase.client.Tag.GetEntityStateByProductAsync(
                        testBase.rgName,
                        testBase.serviceName,
                        starterProduct.Name,
                        tagId);

                    Assert.NotNull(tagEtagByProduct);
                    Assert.NotNull(tagEtagByProduct.ETag);

                    // detach the tag
                    await testBase.client.Tag.DetachFromProductAsync(
                        testBase.rgName,
                        testBase.serviceName,
                        starterProduct.Name,
                        tagId);

                    Assert.Throws <ErrorResponseException>(()
                                                           => testBase.client.Tag.GetByProduct(
                                                               testBase.rgName,
                                                               testBase.serviceName,
                                                               starterProduct.Name,
                                                               tagId));

                    var tagEtag = await testBase.client.Tag.GetEntityStateAsync(
                        testBase.rgName,
                        testBase.serviceName,
                        tagId);

                    Assert.NotNull(tagEtag);
                    Assert.NotNull(tagEtag.ETag);

                    //delete the tag
                    await testBase.client.Tag.DeleteAsync(
                        testBase.rgName,
                        testBase.serviceName,
                        tagId,
                        tagEtag.ETag);

                    Assert.Throws <ErrorResponseException>(()
                                                           => testBase.client.Tag.GetEntityState(
                                                               testBase.rgName,
                                                               testBase.serviceName,
                                                               tagId));
                }
                finally
                {
                    testBase.client.Tag.DetachFromProduct(
                        testBase.rgName, testBase.serviceName, starterProduct.Name, tagId);
                    testBase.client.Tag.Delete(
                        testBase.rgName, testBase.serviceName, tagId, "*");
                }
            }
        }
Esempio n. 21
0
        public void GroupsListAddRemove()
        {
            Environment.SetEnvironmentVariable("AZURE_TEST_MODE", "Playback");
            using (MockContext context = MockContext.Start(this.GetType()))
            {
                var testBase = new ApiManagementTestBase(context);
                testBase.TryCreateApiManagementService();

                // there should be 'Administrators', 'Developers' and 'Guests' groups which is created by default for every new instance of API Management and
                // 'Starter' product

                var getProductsResponse = testBase.client.Product.ListByService(
                    testBase.rgName,
                    testBase.serviceName,
                    new Microsoft.Rest.Azure.OData.ODataQuery <ProductContract>
                {
                    Filter = "name eq 'Starter'"
                });

                Assert.NotNull(getProductsResponse);
                Assert.Single(getProductsResponse);

                var product = getProductsResponse.Single();

                // list product groups: there sould be all three
                var listGroupsResponse = testBase.client.ProductGroup.ListByProduct(
                    testBase.rgName,
                    testBase.serviceName,
                    product.Name,
                    null);

                Assert.NotNull(listGroupsResponse);
                Assert.Equal(3, listGroupsResponse.Count());

                // get group
                var getResponse = testBase.client.Group.Get(
                    testBase.rgName,
                    testBase.serviceName,
                    listGroupsResponse.Single(g => g.DisplayName.Equals("Guests")).Name);

                Assert.NotNull(getResponse);

                // remove group from product
                testBase.client.ProductGroup.Delete(
                    testBase.rgName,
                    testBase.serviceName,
                    product.Name,
                    getResponse.Name);

                // list to check it was removed
                listGroupsResponse = testBase.client.ProductGroup.ListByProduct(
                    testBase.rgName,
                    testBase.serviceName,
                    product.Name,
                    null);

                Assert.NotNull(listGroupsResponse);
                Assert.Equal(2, listGroupsResponse.Count());

                // assign the group to the product

                var addResponse = testBase.client.ProductGroup.CreateOrUpdate(
                    testBase.rgName,
                    testBase.serviceName,
                    product.Name,
                    getResponse.Name);

                Assert.NotNull(addResponse);

                // list to check it was added
                listGroupsResponse = testBase.client.ProductGroup.ListByProduct(
                    testBase.rgName,
                    testBase.serviceName,
                    product.Name,
                    null);

                Assert.NotNull(listGroupsResponse);
                Assert.Equal(3, listGroupsResponse.Count());
            }
        }
        public async Task ValidateSaveDeploy()
        {
            Environment.SetEnvironmentVariable("AZURE_TEST_MODE", "Playback");
            using (MockContext context = MockContext.Start(this.GetType()))
            {
                var testBase = new ApiManagementTestBase(context);
                testBase.TryCreateApiManagementService();

                // test git is enabled
                var getResponse = testBase.client.TenantAccessGit.Get(
                    testBase.rgName,
                    testBase.serviceName);

                Assert.NotNull(getResponse);
                Assert.True(getResponse.Enabled);

                // get the sync state of the repository
                var getSyncState = testBase.client.TenantConfiguration.GetSyncState(
                    testBase.rgName,
                    testBase.serviceName);

                Assert.NotNull(getSyncState);
                Assert.NotNull(getSyncState);
                Assert.True(getSyncState.IsGitEnabled);

                // save changes in current database to configuration database
                var saveConfigurationParameters         = new SaveConfigurationParameter("master");
                OperationResultContract getSaveResponse = testBase.client.TenantConfiguration.Save(
                    testBase.rgName,
                    testBase.serviceName,
                    saveConfigurationParameters);

                Assert.NotNull(getSaveResponse);
                Assert.NotNull(getSaveResponse.Status);
                Assert.NotNull(getSaveResponse.ResultInfo);
                Assert.Null(getSaveResponse.Error);
                Assert.Equal(AsyncOperationStatus.Succeeded, getSaveResponse.Status);

                // get the sync state of the repository after Save
                getSyncState = testBase.client.TenantConfiguration.GetSyncState(
                    testBase.rgName,
                    testBase.serviceName);

                Assert.NotNull(getSyncState);
                Assert.True(getSyncState.IsGitEnabled);
                Assert.Equal("master", getSyncState.Branch);

                // validate changes in current database to configuration database
                var deployConfigurationParameters           = new DeployConfigurationParameters("master");
                OperationResultContract getValidateResponse = testBase.client.TenantConfiguration.Validate(
                    testBase.rgName,
                    testBase.serviceName,
                    deployConfigurationParameters);

                Assert.NotNull(getValidateResponse);
                Assert.NotNull(getSaveResponse.ResultInfo);
                Assert.Null(getSaveResponse.Error);
                Assert.Equal(AsyncOperationStatus.Succeeded, getSaveResponse.Status);

                // deploy changes in current database to configuration database
                OperationResultContract getDeployResponse = testBase.client.TenantConfiguration.Deploy(
                    testBase.rgName,
                    testBase.serviceName,
                    deployConfigurationParameters);

                Assert.NotNull(getDeployResponse);
                Assert.NotNull(getDeployResponse.ResultInfo);
                Assert.Null(getSaveResponse.Error);
                Assert.Equal(AsyncOperationStatus.Succeeded, getDeployResponse.Status);

                // get the sync state of the repository
                var getSyncStateResponse = await testBase.client.TenantConfiguration.GetSyncStateWithHttpMessagesAsync(
                    testBase.rgName,
                    testBase.serviceName);

                Assert.NotNull(getSyncStateResponse);
                Assert.NotNull(getSyncStateResponse.Body.CommitId);
                Assert.True(getSyncStateResponse.Body.IsGitEnabled);
                Assert.True(getSyncStateResponse.Body.IsSynced);
                Assert.False(getSyncStateResponse.Body.IsExport);
                Assert.NotNull(getSyncStateResponse.Body.SyncDate);
                Assert.Equal("master", getSyncStateResponse.Body.Branch);
            }
        }
Esempio n. 23
0
        public async Task CreateListUpdateDelete()
        {
            Environment.SetEnvironmentVariable("AZURE_TEST_MODE", "Playback");
            using (MockContext context = MockContext.Start(this.GetType().FullName))
            {
                var testBase = new ApiManagementTestBase(context);
                testBase.TryCreateApiManagementService();

                // test tenant policy
                var globalPolicy = testBase.client.Policy.Get(testBase.rgName, testBase.serviceName);

                // set policy
                var policyDoc = XDocument.Parse(globalPolicy.Value);

                var policyContract = new PolicyContract(policyDoc.ToString());

                try
                {
                    var globalPolicyResponse = testBase.client.Policy.CreateOrUpdate(
                        testBase.rgName,
                        testBase.serviceName,
                        policyContract);
                    Assert.NotNull(globalPolicyResponse);

                    // get policy to check it was added
                    var getPolicyResponse = await testBase.client.Policy.GetAsync(
                        testBase.rgName,
                        testBase.serviceName);

                    Assert.NotNull(getPolicyResponse);
                    Assert.NotNull(getPolicyResponse.Value);

                    // get the policy etag
                    var globalPolicyTag = await testBase.client.Policy.GetEntityTagAsync(
                        testBase.rgName,
                        testBase.serviceName);

                    Assert.NotNull(globalPolicyTag);
                    Assert.NotNull(globalPolicyTag.ETag);

                    // remove policy
                    testBase.client.Policy.Delete(
                        testBase.rgName,
                        testBase.serviceName,
                        globalPolicyTag.ETag);

                    // get policy to check it was removed
                    try
                    {
                        testBase.client.Policy.Get(
                            testBase.rgName,
                            testBase.serviceName);
                    }
                    catch (ErrorResponseException ex)
                    {
                        Assert.Equal(HttpStatusCode.NotFound, ex.Response.StatusCode);
                    }
                }
                finally
                {
                    testBase.client.Policy.CreateOrUpdate(
                        testBase.rgName,
                        testBase.serviceName,
                        policyContract);
                }

                // test api policy

                // there should be 'Echo API' with no policy

                var getApiResponse = testBase.client.Api.ListByService(
                    testBase.rgName,
                    testBase.serviceName,
                    null);

                var api = getApiResponse.Single();

                try
                {
                    testBase.client.ApiPolicy.Get(
                        testBase.rgName,
                        testBase.serviceName,
                        api.Id);
                }
                catch (ErrorResponseException ex)
                {
                    Assert.Equal(HttpStatusCode.NotFound, ex.Response.StatusCode);
                }

                // set policy
                policyDoc = XDocument.Parse(ApiValid);

                var setResponse = testBase.client.ApiPolicy.CreateOrUpdate(
                    testBase.rgName,
                    testBase.serviceName,
                    api.Name,
                    new PolicyContract(policyDoc.ToString()),
                    "*");

                Assert.NotNull(setResponse);

                // get policy to check it was added
                var getApiPolicy = await testBase.client.ApiPolicy.GetAsync(
                    testBase.rgName,
                    testBase.serviceName,
                    api.Name);

                Assert.NotNull(getApiPolicy);
                Assert.NotNull(getApiPolicy.Value);

                // get the api policy tag
                var apiPolicyTag = await testBase.client.ApiPolicy.GetEntityTagAsync(
                    testBase.rgName,
                    testBase.serviceName,
                    api.Name);

                Assert.NotNull(apiPolicyTag);
                Assert.NotNull(apiPolicyTag.ETag);

                // remove policy
                testBase.client.ApiPolicy.Delete(
                    testBase.rgName,
                    testBase.serviceName,
                    api.Name,
                    apiPolicyTag.ETag);

                // get policy to check it was removed
                try
                {
                    testBase.client.ApiPolicy.Get(
                        testBase.rgName,
                        testBase.serviceName,
                        api.Name);
                }
                catch (ErrorResponseException ex)
                {
                    Assert.Equal(HttpStatusCode.NotFound, ex.Response.StatusCode);
                }

                // test api operation policy
                var getOperationResponse = testBase.client.ApiOperation.ListByApi(
                    testBase.rgName,
                    testBase.serviceName,
                    api.Name,
                    null);

                var operation = getOperationResponse.First(op => op.DisplayName.Equals("Modify Resource", StringComparison.OrdinalIgnoreCase));

                try
                {
                    testBase.client.ApiOperationPolicy.Get(
                        testBase.rgName,
                        testBase.serviceName,
                        api.Name,
                        operation.Name);
                }
                catch (ErrorResponseException ex)
                {
                    Assert.Equal(HttpStatusCode.NotFound, ex.Response.StatusCode);
                }

                // set policy
                policyDoc = XDocument.Parse(OperationValid);

                setResponse = testBase.client.ApiOperationPolicy.CreateOrUpdate(
                    testBase.rgName,
                    testBase.serviceName,
                    api.Name,
                    operation.Name,
                    new PolicyContract(policyDoc.ToString()),
                    "*");

                Assert.NotNull(setResponse);

                // get policy to check it was added
                var getOperationPolicy = await testBase.client.ApiOperationPolicy.GetAsync(
                    testBase.rgName,
                    testBase.serviceName,
                    api.Name,
                    operation.Name);

                Assert.NotNull(getOperationPolicy);
                Assert.NotNull(getOperationPolicy.Value);

                // get operation policy tag
                var operationPolicyTag = await testBase.client.ApiOperationPolicy.GetEntityTagAsync(
                    testBase.rgName,
                    testBase.serviceName,
                    api.Name,
                    operation.Name);

                Assert.NotNull(operationPolicyTag);
                Assert.NotNull(operationPolicyTag.ETag);

                // remove policy
                testBase.client.ApiOperationPolicy.Delete(
                    testBase.rgName,
                    testBase.serviceName,
                    api.Name,
                    operation.Name,
                    operationPolicyTag.ETag);

                // get policy to check it was removed
                try
                {
                    testBase.client.ApiOperationPolicy.Get(
                        testBase.rgName,
                        testBase.serviceName,
                        api.Name,
                        operation.Name);
                }
                catch (ErrorResponseException ex)
                {
                    Assert.Equal(HttpStatusCode.NotFound, ex.Response.StatusCode);
                }


                // 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);
                }

                // set policy
                policyDoc = XDocument.Parse(ProductValid);

                setResponse = testBase.client.ProductPolicy.CreateOrUpdate(
                    testBase.rgName,
                    testBase.serviceName,
                    product.Name,
                    new PolicyContract(value: policyDoc.ToString()));

                Assert.NotNull(setResponse);

                // 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.Value);

                // get product policy tag
                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);
                }
            }
        }
Esempio n. 24
0
        public async Task CreateListUpdateDelete()
        {
            Environment.SetEnvironmentVariable("AZURE_TEST_MODE", "Playback");
            using (MockContext context = MockContext.Start(this.GetType()))
            {
                var testBase = new ApiManagementTestBase(context);
                testBase.TryCreateApiManagementService();

                // list diagnostics: there should be none
                var diagnostics = testBase.client.Diagnostic.ListByService(
                    testBase.rgName,
                    testBase.serviceName,
                    null);

                Assert.NotNull(diagnostics);
                Assert.Empty(diagnostics);

                // create new diagnostic, supported Ids are applicationinsights, azuremonitor
                string diagnosticId = "applicationinsights";
                string loggerId     = TestUtilities.GenerateName("appInsights");

                try
                {
                    // create a logger
                    Guid applicationInsightsGuid = TestUtilities.GenerateGuid("appInsights");
                    var  credentials             = new Dictionary <string, string>();
                    credentials.Add("instrumentationKey", applicationInsightsGuid.ToString());

                    var loggerCreateParameters = new LoggerContract(LoggerType.ApplicationInsights, credentials: credentials);
                    var loggerContract         = await testBase.client.Logger.CreateOrUpdateAsync(
                        testBase.rgName,
                        testBase.serviceName,
                        loggerId,
                        loggerCreateParameters);

                    Assert.NotNull(loggerContract);
                    Assert.Equal(loggerId, loggerContract.Name);
                    Assert.Equal(LoggerType.ApplicationInsights, loggerContract.LoggerType);
                    Assert.NotNull(loggerContract.Credentials);
                    Assert.Equal(1, loggerContract.Credentials.Keys.Count);

                    // create a diagnostic entity with just loggerId
                    var diagnosticContractParams = new DiagnosticContract()
                    {
                        LoggerId = loggerContract.Id
                    };
                    var diagnosticContract = await testBase.client.Diagnostic.CreateOrUpdateAsync(
                        testBase.rgName,
                        testBase.serviceName,
                        diagnosticId,
                        diagnosticContractParams);

                    Assert.NotNull(diagnosticContract);
                    Assert.Equal(diagnosticId, diagnosticContract.Name);

                    // check the diagnostic entity etag
                    var diagnosticTag = await testBase.client.Diagnostic.GetEntityTagAsync(
                        testBase.rgName,
                        testBase.serviceName,
                        diagnosticId);

                    Assert.NotNull(diagnosticTag);
                    Assert.NotNull(diagnosticTag.ETag);

                    // now update the sampling and other settings of the diagnostic
                    diagnosticContractParams.AlwaysLog = "allErrors";
                    diagnosticContractParams.Sampling  = new SamplingSettings("fixed", 50);
                    var listOfHeaders = new List <string> {
                        "Content-type"
                    };
                    var bodyDiagnostic = new BodyDiagnosticSettings(512);
                    diagnosticContractParams.Frontend = new PipelineDiagnosticSettings
                    {
                        Request = new HttpMessageDiagnostic()
                        {
                            Body    = bodyDiagnostic,
                            Headers = listOfHeaders
                        },
                        Response = new HttpMessageDiagnostic()
                        {
                            Body    = bodyDiagnostic,
                            Headers = listOfHeaders
                        }
                    };
                    diagnosticContractParams.Backend = new PipelineDiagnosticSettings
                    {
                        Request = new HttpMessageDiagnostic()
                        {
                            Body    = bodyDiagnostic,
                            Headers = listOfHeaders
                        },
                        Response = new HttpMessageDiagnostic()
                        {
                            Body    = bodyDiagnostic,
                            Headers = listOfHeaders
                        }
                    };

                    var updatedDiagnostic = await testBase.client.Diagnostic.CreateOrUpdateWithHttpMessagesAsync(
                        testBase.rgName,
                        testBase.serviceName,
                        diagnosticId,
                        diagnosticContractParams,
                        diagnosticTag.ETag);

                    Assert.NotNull(updatedDiagnostic);
                    Assert.Equal("allErrors", updatedDiagnostic.Body.AlwaysLog);
                    Assert.NotNull(updatedDiagnostic.Body.Sampling);
                    Assert.NotNull(updatedDiagnostic.Body.Frontend);
                    Assert.NotNull(updatedDiagnostic.Body.Backend);
                    Assert.NotNull(updatedDiagnostic.Body.HttpCorrelationProtocol);
                    Assert.Equal(HttpCorrelationProtocol.Legacy, updatedDiagnostic.Body.HttpCorrelationProtocol);

                    // delete the diagnostic entity
                    await testBase.client.Diagnostic.DeleteAsync(
                        testBase.rgName,
                        testBase.serviceName,
                        diagnosticId,
                        updatedDiagnostic.Headers.ETag);

                    Assert.Throws <ErrorResponseException>(()
                                                           => testBase.client.Diagnostic.GetEntityTag(testBase.rgName, testBase.serviceName, diagnosticId));

                    // check the logger entity etag
                    var loggerTag = await testBase.client.Logger.GetEntityTagAsync(
                        testBase.rgName,
                        testBase.serviceName,
                        loggerId);

                    Assert.NotNull(loggerTag);
                    Assert.NotNull(loggerTag.ETag);

                    // delete the logger entity
                    await testBase.client.Logger.DeleteAsync(
                        testBase.rgName,
                        testBase.serviceName,
                        loggerId,
                        loggerTag.ETag);

                    Assert.Throws <ErrorResponseException>(()
                                                           => testBase.client.Logger.GetEntityTag(testBase.rgName, testBase.serviceName, loggerId));
                }
                finally
                {
                    testBase.client.Diagnostic.Delete(testBase.rgName, testBase.serviceName, diagnosticId, "*");
                    testBase.client.Logger.Delete(testBase.rgName, testBase.serviceName, loggerId, "*");

                    // clean up all properties
                    var listOfProperties = testBase.client.NamedValue.ListByService(
                        testBase.rgName,
                        testBase.serviceName);
                    foreach (var property in listOfProperties)
                    {
                        testBase.client.NamedValue.Delete(
                            testBase.rgName,
                            testBase.serviceName,
                            property.Name,
                            "*");
                    }
                }
            }
        }
Esempio n. 25
0
        public async Task CreateUpdateReset()
        {
            Environment.SetEnvironmentVariable("AZURE_TEST_MODE", "Playback");
            using (MockContext context = MockContext.Start(this.GetType().FullName))
            {
                var testBase = new ApiManagementTestBase(context);
                testBase.TryCreateApiManagementService();

                var intialPortalDelegationSettings = await testBase.client.DelegationSettings.GetAsync(
                    testBase.rgName,
                    testBase.serviceName);

                try
                {
                    string delegationServer = TestUtilities.GenerateName("delegationServer");
                    string urlParameter     = new UriBuilder("https", delegationServer, 443).Uri.ToString();

                    var portalDelegationSettingsParams = new PortalDelegationSettings()
                    {
                        Subscriptions    = new SubscriptionsDelegationSettingsProperties(true),
                        UserRegistration = new RegistrationDelegationSettingsProperties(true),
                        Url           = urlParameter,
                        ValidationKey = PortalDelegationSettings.GenerateValidationKey()
                    };
                    var portalDelegationSettings = testBase.client.DelegationSettings.CreateOrUpdate(
                        testBase.rgName,
                        testBase.serviceName,
                        portalDelegationSettingsParams);
                    Assert.NotNull(portalDelegationSettings);
                    Assert.Equal(urlParameter, portalDelegationSettings.Url);
                    // this is bug in the api, where the validation key is coming out as encrypted.
                    // https://msazure.visualstudio.com/DefaultCollection/One/_workitems/edit/2202008
                    //Assert.Equal(testBase.base64EncodedTestCertificateData, portalDelegationSettings.ValidationKey);
                    Assert.True(portalDelegationSettings.UserRegistration.Enabled);
                    Assert.True(portalDelegationSettings.Subscriptions.Enabled);

                    // check settings
                    var delegationsTag = await testBase.client.DelegationSettings.GetEntityTagAsync(
                        testBase.rgName,
                        testBase.serviceName);

                    Assert.NotNull(delegationsTag);
                    Assert.NotNull(delegationsTag.ETag);

                    // update the delegation settings
                    portalDelegationSettings.Subscriptions.Enabled    = false;
                    portalDelegationSettings.UserRegistration.Enabled = false;
                    portalDelegationSettings.Url           = null;
                    portalDelegationSettings.ValidationKey = null;

                    await testBase.client.DelegationSettings.UpdateAsync(
                        testBase.rgName,
                        testBase.serviceName,
                        portalDelegationSettings,
                        delegationsTag.ETag);

                    // get the delegation settings
                    portalDelegationSettings = await testBase.client.DelegationSettings.GetAsync(
                        testBase.rgName,
                        testBase.serviceName);

                    Assert.NotNull(portalDelegationSettings);
                    //Assert.Null(portalDelegationSettings.Url);
                    //Assert.Null(portalDelegationSettings.ValidationKey);
                    Assert.False(portalDelegationSettings.UserRegistration.Enabled);
                    Assert.False(portalDelegationSettings.Subscriptions.Enabled);
                }
                finally
                {
                    // due to bug in the api
                    intialPortalDelegationSettings.ValidationKey = null;
                    testBase.client.DelegationSettings.Update(
                        testBase.rgName,
                        testBase.serviceName,
                        intialPortalDelegationSettings,
                        "*");
                }
            }
        }
Esempio n. 26
0
        public void ApisListAddRemove()
        {
            Environment.SetEnvironmentVariable("AZURE_TEST_MODE", "Playback");
            using (MockContext context = MockContext.Start(this.GetType()))
            {
                var testBase = new ApiManagementTestBase(context);
                testBase.TryCreateApiManagementService();

                // there should be 'Echo API' which is created by default for every new instance of API Management and
                // 'Starter' product

                var getProductsResponse = testBase.client.Product.ListByService(
                    testBase.rgName,
                    testBase.serviceName,
                    new Microsoft.Rest.Azure.OData.ODataQuery <ProductContract>
                {
                    Filter = "name eq 'Starter'"
                });

                Assert.NotNull(getProductsResponse);
                Assert.Single(getProductsResponse);

                var product = getProductsResponse.Single();

                // list product apis: there sHould be 1
                var listApisResponse = testBase.client.ProductApi.ListByProduct(
                    testBase.rgName,
                    testBase.serviceName,
                    product.Name,
                    null);

                Assert.NotNull(listApisResponse);
                Assert.Single(listApisResponse);

                // get api
                var getResponse = testBase.client.Api.Get(
                    testBase.rgName,
                    testBase.serviceName,
                    listApisResponse.Single().Name);

                Assert.NotNull(getResponse);

                // remove api from product
                testBase.client.ProductApi.Delete(
                    testBase.rgName,
                    testBase.serviceName,
                    product.Name,
                    listApisResponse.Single().Name);

                // list to check it was removed
                listApisResponse = testBase.client.ProductApi.ListByProduct(
                    testBase.rgName,
                    testBase.serviceName,
                    product.Name,
                    null);

                Assert.NotNull(listApisResponse);
                Assert.Empty(listApisResponse);

                // add the api to product
                var addResponse = testBase.client.ProductApi.CreateOrUpdate(
                    testBase.rgName,
                    testBase.serviceName,
                    product.Name,
                    getResponse.Name);

                Assert.NotNull(addResponse);

                // list to check it was added
                listApisResponse = testBase.client.ProductApi.ListByProduct(
                    testBase.rgName,
                    testBase.serviceName,
                    product.Name,
                    null);

                Assert.NotNull(listApisResponse);
                Assert.Single(listApisResponse);
            }
        }
Esempio n. 27
0
        public async Task GetRegenerateKeys()
        {
            Environment.SetEnvironmentVariable("AZURE_TEST_MODE", "Playback");
            using (MockContext context = MockContext.Start(this.GetType()))
            {
                var testBase = new ApiManagementTestBase(context);
                testBase.TryCreateApiManagementService();

                // list gateways: there should be none
                var gatewayListResponse = testBase.client.Gateway.ListByService(
                    testBase.rgName,
                    testBase.serviceName,
                    null);

                Assert.NotNull(gatewayListResponse);
                Assert.Empty(gatewayListResponse);

                string gatewayId = TestUtilities.GenerateName("gatewayid");;

                try
                {
                    var gatewayContract = new GatewayContract()
                    {
                        LocationData = new ResourceLocationDataContract()
                        {
                            City            = "Seattle",
                            CountryOrRegion = "USA",
                            District        = "King County",
                            Name            = "Microsoft"
                        },
                        Description = TestUtilities.GenerateName()
                    };

                    var createResponse = await testBase.client.Gateway.CreateOrUpdateAsync(
                        testBase.rgName,
                        testBase.serviceName,
                        gatewayId,
                        gatewayContract);

                    Assert.NotNull(createResponse);
                    Assert.Equal(gatewayId, createResponse.Name);
                    Assert.Equal(gatewayContract.Description, createResponse.Description);
                    Assert.NotNull(createResponse.LocationData);
                    Assert.Equal(gatewayContract.LocationData.City, createResponse.LocationData.City);
                    Assert.Equal(gatewayContract.LocationData.CountryOrRegion, createResponse.LocationData.CountryOrRegion);
                    Assert.Equal(gatewayContract.LocationData.District, createResponse.LocationData.District);
                    Assert.Equal(gatewayContract.LocationData.Name, createResponse.LocationData.Name);

                    // get keys
                    var getResponse = await testBase.client.Gateway.ListKeysAsync(
                        testBase.rgName,
                        testBase.serviceName,
                        gatewayId);

                    Assert.NotNull(getResponse);
                    Assert.NotNull(getResponse.Primary);
                    Assert.NotNull(getResponse.Secondary);

                    var primaryKey   = getResponse.Primary;
                    var secondaryKey = getResponse.Secondary;
                    Assert.NotEqual(primaryKey, secondaryKey);

                    var expiry = DateTime.UtcNow;

                    // generate token
                    var tokenResponse = await testBase.client.Gateway.GenerateTokenAsync(
                        testBase.rgName,
                        testBase.serviceName,
                        gatewayId,
                        new GatewayTokenRequestContract()
                    {
                        Expiry = expiry, KeyType = KeyType.Primary
                    });

                    Assert.NotNull(tokenResponse);
                    Assert.NotNull(tokenResponse.Value);
                    var primaryToken = tokenResponse.Value;

                    //check the same token stays
                    tokenResponse = await testBase.client.Gateway.GenerateTokenAsync(
                        testBase.rgName,
                        testBase.serviceName,
                        gatewayId,
                        new GatewayTokenRequestContract()
                    {
                        Expiry = expiry, KeyType = KeyType.Primary
                    });

                    Assert.NotNull(tokenResponse);
                    Assert.NotNull(tokenResponse.Value);
                    Assert.Equal(primaryToken, tokenResponse.Value);

                    // generate secondary token
                    tokenResponse = await testBase.client.Gateway.GenerateTokenAsync(
                        testBase.rgName,
                        testBase.serviceName,
                        gatewayId,
                        new GatewayTokenRequestContract()
                    {
                        Expiry = expiry, KeyType = KeyType.Secondary
                    });

                    Assert.NotNull(tokenResponse);
                    Assert.NotNull(tokenResponse.Value);
                    var secondaryToken = tokenResponse.Value;

                    Assert.NotEqual(primaryToken, secondaryToken);

                    //change keys
                    await testBase.client.Gateway.RegenerateKeyAsync(
                        testBase.rgName,
                        testBase.serviceName,
                        gatewayId,
                        new GatewayKeyRegenerationRequestContract()
                    {
                        KeyType = KeyType.Primary
                    });

                    await testBase.client.Gateway.RegenerateKeyAsync(
                        testBase.rgName,
                        testBase.serviceName,
                        gatewayId,
                        new GatewayKeyRegenerationRequestContract()
                    {
                        KeyType = KeyType.Secondary
                    });

                    // get keys
                    getResponse = await testBase.client.Gateway.ListKeysAsync(
                        testBase.rgName,
                        testBase.serviceName,
                        gatewayId);

                    Assert.NotNull(getResponse);
                    Assert.NotNull(getResponse.Primary);
                    Assert.NotNull(getResponse.Secondary);

                    Assert.NotEqual(primaryKey, getResponse.Primary);
                    Assert.NotEqual(secondaryKey, getResponse.Secondary);

                    // generate token
                    tokenResponse = await testBase.client.Gateway.GenerateTokenAsync(
                        testBase.rgName,
                        testBase.serviceName,
                        gatewayId,
                        new GatewayTokenRequestContract()
                    {
                        Expiry = expiry, KeyType = KeyType.Primary
                    });

                    Assert.NotNull(tokenResponse);
                    Assert.NotNull(tokenResponse.Value);
                    Assert.NotEqual(primaryToken, tokenResponse.Value);

                    // generate secondary token
                    tokenResponse = await testBase.client.Gateway.GenerateTokenAsync(
                        testBase.rgName,
                        testBase.serviceName,
                        gatewayId,
                        new GatewayTokenRequestContract()
                    {
                        Expiry = expiry, KeyType = KeyType.Secondary
                    });

                    Assert.NotNull(tokenResponse);
                    Assert.NotNull(tokenResponse.Value);
                    Assert.NotEqual(secondaryToken, tokenResponse.Value);
                }
                finally
                {
                    testBase.client.Gateway.Delete(testBase.rgName, testBase.serviceName, gatewayId, "*");
                }
            }
        }
Esempio n. 28
0
        public async Task CreateListUpdateDelete()
        {
            Environment.SetEnvironmentVariable("AZURE_TEST_MODE", "Playback");
            using (MockContext context = MockContext.Start(this.GetType().FullName))
            {
                var testBase = new ApiManagementTestBase(context);
                testBase.TryCreateApiManagementService();

                // list all the APIs
                var listResponse = testBase.client.Api.ListByService(
                    testBase.rgName,
                    testBase.serviceName,
                    null);
                Assert.NotNull(listResponse);
                Assert.Single(listResponse);
                Assert.Null(listResponse.NextPageLink);

                var echoApi = listResponse.First();

                string tagId = TestUtilities.GenerateName("apiTag");
                try
                {
                    string tagDisplayName   = TestUtilities.GenerateName("apiTag");
                    var    createParameters = new TagCreateUpdateParameters();
                    createParameters.DisplayName = tagDisplayName;

                    // create a tag
                    var tagContract = testBase.client.Tag.CreateOrUpdate(
                        testBase.rgName,
                        testBase.serviceName,
                        tagId,
                        createParameters);

                    Assert.NotNull(tagContract);
                    Assert.Equal(tagDisplayName, tagContract.DisplayName);

                    // associate the tag with the API
                    tagContract = await testBase.client.Tag.AssignToApiAsync(
                        testBase.rgName,
                        testBase.serviceName,
                        echoApi.Name,
                        tagId);

                    Assert.NotNull(tagContract);

                    // list tag description
                    var tagDescriptionList = await testBase.client.TagDescription.ListByApiAsync(
                        testBase.rgName,
                        testBase.serviceName,
                        echoApi.Name);

                    Assert.NotNull(tagDescriptionList);
                    Assert.Empty(tagDescriptionList);

                    // create a tag description
                    var tagDescriptionCreateParams = new TagDescriptionCreateParameters()
                    {
                        Description     = TestUtilities.GenerateName("somedescription"),
                        ExternalDocsUrl = "http://somelog.content"
                    };
                    var tagDescriptionContract = await testBase.client.TagDescription.CreateOrUpdateAsync(
                        testBase.rgName,
                        testBase.serviceName,
                        echoApi.Name,
                        tagId,
                        tagDescriptionCreateParams);

                    Assert.NotNull(tagDescriptionContract);
                    Assert.Equal(tagDisplayName, tagDescriptionContract.DisplayName);
                    Assert.Equal(tagDescriptionCreateParams.Description, tagDescriptionContract.Description);

                    // get the tagdescription etag
                    var tagDescriptionTag = await testBase.client.TagDescription.GetEntityStateAsync(
                        testBase.rgName,
                        testBase.serviceName,
                        echoApi.Name,
                        tagId);

                    Assert.NotNull(tagDescriptionTag);
                    Assert.NotNull(tagDescriptionTag.ETag);

                    // update the tag description
                    tagDescriptionCreateParams.Description = TestUtilities.GenerateName("tag_update");
                    tagDescriptionContract = await testBase.client.TagDescription.CreateOrUpdateAsync(
                        testBase.rgName,
                        testBase.serviceName,
                        echoApi.Name,
                        tagId,
                        tagDescriptionCreateParams,
                        tagDescriptionTag.ETag);

                    Assert.NotNull(tagDescriptionContract);
                    Assert.Equal(tagDisplayName, tagDescriptionContract.DisplayName);
                    Assert.Equal(tagDescriptionCreateParams.Description, tagDescriptionContract.Description);

                    // get the entity
                    tagDescriptionTag = await testBase.client.TagDescription.GetEntityStateAsync(
                        testBase.rgName,
                        testBase.serviceName,
                        echoApi.Name,
                        tagId);

                    Assert.NotNull(tagDescriptionTag);
                    Assert.NotNull(tagDescriptionTag.ETag);

                    // delete the tag description
                    await testBase.client.TagDescription.DeleteAsync(
                        testBase.rgName,
                        testBase.serviceName,
                        echoApi.Name,
                        tagId,
                        tagDescriptionTag.ETag);

                    // get the entity tag
                    var tagTag = await testBase.client.Tag.GetEntityStateAsync(
                        testBase.rgName,
                        testBase.serviceName,
                        tagId);

                    Assert.NotNull(tagTag);
                    Assert.NotNull(tagTag.ETag);

                    // detach from Api
                    await testBase.client.Tag.DetachFromApiAsync(
                        testBase.rgName,
                        testBase.serviceName,
                        echoApi.Name,
                        tagId,
                        tagTag.ETag);

                    // get the entity tag
                    tagTag = await testBase.client.Tag.GetEntityStateAsync(
                        testBase.rgName,
                        testBase.serviceName,
                        tagId);

                    Assert.NotNull(tagTag);
                    Assert.NotNull(tagTag.ETag);

                    // delete the tag
                    await testBase.client.Tag.DeleteAsync(
                        testBase.rgName,
                        testBase.serviceName,
                        tagId,
                        tagTag.ETag);

                    // delete the tag description
                    Assert.Throws <ErrorResponseException>(()
                                                           => testBase.client.Tag.Get(
                                                               testBase.rgName,
                                                               testBase.serviceName,
                                                               tagId));
                }
                finally
                {
                    // detach from api
                    testBase.client.Tag.DetachFromApi(
                        testBase.rgName,
                        testBase.serviceName,
                        echoApi.Name,
                        tagId,
                        "*");

                    // delete the tag description
                    testBase.client.TagDescription.Delete(
                        testBase.rgName,
                        testBase.serviceName,
                        echoApi.Name,
                        tagId,
                        "*");

                    // delete the tag
                    testBase.client.Tag.Delete(
                        testBase.rgName,
                        testBase.serviceName,
                        tagId,
                        "*");
                }
            }
        }
Esempio n. 29
0
        public async Task CreateListUpdateDelete()
        {
            Environment.SetEnvironmentVariable("AZURE_TEST_MODE", "Playback");
            using (MockContext context = MockContext.Start(this.GetType().FullName))
            {
                var testBase = new ApiManagementTestBase(context);
                testBase.TryCreateApiManagementService();

                // list subscriptions: there should be two by default
                var listResponse = testBase.client.Subscription.List(
                    testBase.rgName,
                    testBase.serviceName,
                    null);

                Assert.NotNull(listResponse);
                Assert.True(listResponse.Count() >= 2);
                Assert.NotNull(listResponse.NextPageLink);

                // list paged
                listResponse = testBase.client.Subscription.List(
                    testBase.rgName,
                    testBase.serviceName,
                    new Microsoft.Rest.Azure.OData.ODataQuery <SubscriptionContract> {
                    Top = 1
                });

                Assert.NotNull(listResponse);
                Assert.Single(listResponse);
                Assert.NotNull(listResponse.NextPageLink);

                // get first subscription
                var firstSubscription = listResponse.First();

                var getResponse = testBase.client.Subscription.Get(
                    testBase.rgName,
                    testBase.serviceName,
                    firstSubscription.Name);

                Assert.NotNull(getResponse);
                Assert.Equal(firstSubscription.Name, getResponse.Name);
                Assert.Equal(firstSubscription.NotificationDate, getResponse.NotificationDate);
                Assert.Equal(firstSubscription.PrimaryKey, getResponse.PrimaryKey);
                Assert.Equal(firstSubscription.ProductId, getResponse.ProductId);
                Assert.Equal(firstSubscription.SecondaryKey, getResponse.SecondaryKey);
                Assert.Equal(firstSubscription.StartDate, getResponse.StartDate);
                Assert.Equal(firstSubscription.State, getResponse.State);
                Assert.Equal(firstSubscription.StateComment, getResponse.StateComment);
                Assert.Equal(firstSubscription.UserId, getResponse.UserId);
                Assert.Equal(firstSubscription.CreatedDate, getResponse.CreatedDate);
                Assert.Equal(firstSubscription.EndDate, getResponse.EndDate);
                Assert.Equal(firstSubscription.ExpirationDate, getResponse.ExpirationDate);

                // update product to accept unlimited number or subscriptions
                testBase.client.Product.Update(
                    testBase.rgName,
                    testBase.serviceName,
                    firstSubscription.ProductIdentifier,
                    new ProductUpdateParameters
                {
                    SubscriptionsLimit = int.MaxValue
                },
                    "*");

                // add new subscription
                string newSubscriptionId = TestUtilities.GenerateName("newSubscriptionId");

                try
                {
                    string newSubscriptionName  = TestUtilities.GenerateName("newSubscriptionName");
                    string newSubscriptionPk    = TestUtilities.GenerateName("newSubscriptionPK");
                    string newSubscriptionSk    = TestUtilities.GenerateName("newSubscriptionSK");
                    var    newSubscriptionState = SubscriptionState.Active;

                    var newSubscriptionCreate = new SubscriptionCreateParameters(
                        firstSubscription.UserId,
                        firstSubscription.ProductId,
                        newSubscriptionName)
                    {
                        PrimaryKey   = newSubscriptionPk,
                        SecondaryKey = newSubscriptionSk,
                        State        = newSubscriptionState,
                    };

                    var subscriptionContract = testBase.client.Subscription.CreateOrUpdate(
                        testBase.rgName,
                        testBase.serviceName,
                        newSubscriptionId,
                        newSubscriptionCreate);

                    Assert.NotNull(subscriptionContract);
                    Assert.Equal(firstSubscription.ProductId, subscriptionContract.ProductId);
                    Assert.Equal(firstSubscription.UserId, subscriptionContract.UserId);
                    Assert.Equal(newSubscriptionState, subscriptionContract.State);
                    Assert.Equal(newSubscriptionSk, subscriptionContract.SecondaryKey);
                    Assert.Equal(newSubscriptionPk, subscriptionContract.PrimaryKey);
                    Assert.Equal(newSubscriptionName, subscriptionContract.DisplayName);

                    var subscriptionResponse = await testBase.client.Subscription.GetWithHttpMessagesAsync(
                        testBase.rgName,
                        testBase.serviceName,
                        newSubscriptionId);

                    Assert.NotNull(subscriptionResponse);
                    Assert.NotNull(subscriptionResponse.Headers.ETag);

                    // patch the subscription
                    string patchedName           = TestUtilities.GenerateName("patchedName");
                    string patchedPk             = TestUtilities.GenerateName("patchedPk");
                    string patchedSk             = TestUtilities.GenerateName("patchedSk");
                    var    patchedExpirationDate = new DateTime(2025, 5 + 2, 20);

                    testBase.client.Subscription.Update(
                        testBase.rgName,
                        testBase.serviceName,
                        newSubscriptionId,
                        new SubscriptionUpdateParameters
                    {
                        DisplayName    = patchedName,
                        PrimaryKey     = patchedPk,
                        SecondaryKey   = patchedSk,
                        ExpirationDate = patchedExpirationDate
                    },
                        subscriptionResponse.Headers.ETag);

                    // get patched subscription to check it was actually patched
                    getResponse = testBase.client.Subscription.Get(
                        testBase.rgName,
                        testBase.serviceName,
                        newSubscriptionId);

                    Assert.NotNull(getResponse);
                    Assert.Equal(newSubscriptionId, getResponse.Name);
                    Assert.Equal(patchedName, getResponse.DisplayName);
                    Assert.Equal(patchedPk, getResponse.PrimaryKey);
                    Assert.Equal(patchedSk, getResponse.SecondaryKey);
                    Assert.Equal(newSubscriptionState, getResponse.State);
                    Assert.Equal(patchedExpirationDate, getResponse.ExpirationDate);

                    // regenerate primary key
                    testBase.client.Subscription.RegeneratePrimaryKey(
                        testBase.rgName,
                        testBase.serviceName,
                        newSubscriptionId);

                    // get the subscription to check the key
                    getResponse = testBase.client.Subscription.Get(
                        testBase.rgName,
                        testBase.serviceName,
                        newSubscriptionId);

                    Assert.NotNull(getResponse);
                    Assert.NotEqual(patchedPk, getResponse.PrimaryKey);
                    Assert.Equal(patchedSk, getResponse.SecondaryKey);

                    // regenerate secondary key
                    testBase.client.Subscription.RegenerateSecondaryKey(
                        testBase.rgName,
                        testBase.serviceName,
                        newSubscriptionId);

                    // get the subscription to check the key
                    subscriptionResponse = await testBase.client.Subscription.GetWithHttpMessagesAsync(
                        testBase.rgName,
                        testBase.serviceName,
                        newSubscriptionId);

                    Assert.NotNull(subscriptionResponse);
                    Assert.NotNull(subscriptionResponse.Headers.ETag);
                    Assert.NotEqual(patchedPk, subscriptionResponse.Body.PrimaryKey);
                    Assert.NotEqual(patchedSk, subscriptionResponse.Body.SecondaryKey);

                    // delete the subscription
                    testBase.client.Subscription.Delete(
                        testBase.rgName,
                        testBase.serviceName,
                        newSubscriptionId,
                        subscriptionResponse.Headers.ETag);

                    // get the deleted subscription to make sure it was deleted
                    try
                    {
                        testBase.client.Subscription.Get(testBase.rgName, testBase.serviceName, newSubscriptionId);
                        throw new Exception("This code should not have been executed.");
                    }
                    catch (ErrorResponseException ex)
                    {
                        Assert.Equal((int)HttpStatusCode.NotFound, (int)ex.Response.StatusCode);
                    }
                }
                finally
                {
                    testBase.client.Subscription.Delete(
                        testBase.rgName,
                        testBase.serviceName,
                        newSubscriptionId,
                        "*");
                }
            }
        }
Esempio n. 30
0
        public async Task CreateListUpdateDelete()
        {
            Environment.SetEnvironmentVariable("AZURE_TEST_MODE", "Playback");
            using (MockContext context = MockContext.Start(this.GetType()))
            {
                var testBase = new ApiManagementTestBase(context);
                testBase.TryCreateApiManagementService();

                var listResponse = testBase.client.Product.ListByService(
                    testBase.rgName,
                    testBase.serviceName,
                    null);

                Assert.NotNull(listResponse);
                Assert.Equal(2, listResponse.Count());// there are 2 product Starter and Unlimited created by default
                Assert.Null(listResponse.NextPageLink);

                string productId = TestUtilities.GenerateName("newproduct");

                try
                {
                    string       productName                 = TestUtilities.GenerateName("productName");
                    bool?        productApprovalRequired     = true;
                    string       productDescription          = TestUtilities.GenerateName("productDescription");
                    ProductState productState                = ProductState.NotPublished;
                    bool?        productSubscriptionRequired = true;
                    int?         productSubscriptionsLimit   = 10;
                    string       productTerms                = TestUtilities.GenerateName("productTerms");

                    var createParameters = new ProductContract(productName)
                    {
                        ApprovalRequired     = productApprovalRequired,
                        Description          = productDescription,
                        State                = productState,
                        SubscriptionRequired = productSubscriptionRequired,
                        SubscriptionsLimit   = productSubscriptionsLimit,
                        Terms                = productTerms
                    };

                    var createResponse = testBase.client.Product.CreateOrUpdate(
                        testBase.rgName,
                        testBase.serviceName,
                        productId,
                        createParameters);

                    Assert.NotNull(createResponse);
                    Assert.Equal(productName, createResponse.DisplayName);
                    Assert.Equal(productApprovalRequired, createResponse.ApprovalRequired);
                    Assert.Equal(productDescription, createResponse.Description);
                    Assert.Equal(productState, createResponse.State);
                    Assert.Equal(productSubscriptionRequired, createResponse.SubscriptionRequired);
                    Assert.Equal(productSubscriptionsLimit, createResponse.SubscriptionsLimit);
                    Assert.Equal(productTerms, createResponse.Terms);

                    //get async
                    var productTag = await testBase.client.Product.GetEntityTagAsync(
                        testBase.rgName,
                        testBase.serviceName,
                        productId);

                    Assert.NotNull(productTag);

                    // update product
                    string patchedName        = TestUtilities.GenerateName("productName");
                    string patchedDescription = TestUtilities.GenerateName("productDescription");
                    string patchedTerms       = TestUtilities.GenerateName("productTerms");
                    var    updateParameters   = new ProductUpdateParameters
                    {
                        DisplayName = patchedName,
                        Description = patchedDescription,
                        Terms       = patchedTerms
                    };
                    testBase.client.Product.Update(
                        testBase.rgName,
                        testBase.serviceName,
                        productId,
                        updateParameters,
                        productTag.ETag);

                    // get to check it was updated
                    var getUpdatedResponse = testBase.client.Product.Get(
                        testBase.rgName,
                        testBase.serviceName,
                        productId);

                    Assert.NotNull(getUpdatedResponse);

                    Assert.Equal(patchedName, getUpdatedResponse.DisplayName);
                    Assert.Equal(productApprovalRequired, getUpdatedResponse.ApprovalRequired);
                    Assert.Equal(patchedDescription, getUpdatedResponse.Description);
                    Assert.Equal(productState, getUpdatedResponse.State);
                    Assert.Equal(productSubscriptionRequired, getUpdatedResponse.SubscriptionRequired);
                    Assert.Equal(productSubscriptionsLimit, getUpdatedResponse.SubscriptionsLimit);
                    Assert.Equal(patchedTerms, getUpdatedResponse.Terms);

                    // check product listing works
                    // list paged
                    var productList = await testBase.client.Product.ListByServiceAsync(
                        testBase.rgName,
                        testBase.serviceName,
                        new Microsoft.Rest.Azure.OData.ODataQuery <ProductContract> {
                        Top = 1
                    });

                    Assert.NotNull(productList);
                    Assert.Single(productList);
                    // first is the product in Test due to alphabetical order of name
                    Assert.Equal(patchedName, productList.First().DisplayName);
                    Assert.NotEmpty(productList.NextPageLink);

                    // check the next link returned from above query works
                    var pagedProducts = await testBase.client.Product.ListByServiceNextAsync(productList.NextPageLink);

                    Assert.NotNull(pagedProducts);
                    Assert.Single(pagedProducts);
                    // next is the Starter product due to alphabetical order of name
                    Assert.Equal("Starter", pagedProducts.First().DisplayName);

                    // check the nextlink to the next page link query works
                    pagedProducts = await testBase.client.Product.ListByServiceNextAsync(pagedProducts.NextPageLink);

                    Assert.NotNull(pagedProducts);
                    Assert.Single(pagedProducts);
                    // finally the Unlimited product due to alphabetical order of name
                    Assert.Equal("Unlimited", pagedProducts.First().DisplayName);
                    Assert.Null(pagedProducts.NextPageLink); // it should be empty now.

                    // get the entity tag
                    productTag = await testBase.client.Product.GetEntityTagAsync(
                        testBase.rgName,
                        testBase.serviceName,
                        productId);

                    Assert.NotNull(productTag);

                    // delete the product
                    testBase.client.Product.Delete(
                        testBase.rgName,
                        testBase.serviceName,
                        productId,
                        productTag.ETag,
                        deleteSubscriptions: true);

                    // get the deleted product to make sure it was deleted
                    Assert.Throws <ErrorResponseException>(()
                                                           => testBase.client.Product.Get(
                                                               testBase.rgName,
                                                               testBase.serviceName,
                                                               productId));
                }
                finally
                {
                    testBase.client.Product.Delete(
                        testBase.rgName,
                        testBase.serviceName,
                        productId,
                        "*",
                        true);
                }
            }
        }