public void InitializerCreatesTokenCacheFile()
        {
            AzureSessionInitializer.InitializeAzureSession();
            IAzureSession oldSession = null;

            try
            {
                oldSession = AzureSession.Instance;
            }
            catch { }
            try
            {
                var store    = new MemoryDataStore();
                var path     = Path.Combine(AzureSession.Instance.ARMProfileDirectory, ContextAutosaveSettings.AutoSaveSettingsFile);
                var settings = new ContextAutosaveSettings {
                    Mode = ContextSaveMode.CurrentUser
                };
                var content = JsonConvert.SerializeObject(settings);
                store.VirtualStore[path] = content;
                AzureSessionInitializer.CreateOrReplaceSession(store);
                var session        = AzureSession.Instance;
                var tokenCacheFile = Path.Combine(session.ProfileDirectory, session.TokenCacheFile);
                Assert.True(store.FileExists(tokenCacheFile));
            }
            finally
            {
                AzureSession.Initialize(() => oldSession, true);
            }
        }
        public void CanCreateStorageContextNameAndKey()
        {
            AzureSessionInitializer.InitializeAzureSession();
            var smProvider = AzureSMProfileProvider.Instance;
            var rmProvider = AzureRmProfileProvider.Instance;

            AzureRmProfileProvider.SetInstance(() => new TestProfileProvider(), true);
            AzureSMProfileProvider.SetInstance(() => new TestSMProfileProvider(), true);
            try
            {
                var mock = new MockCommandRuntime();

                AzureSMProfileProvider.Instance.Profile = null;
                AzureRmProfileProvider.Instance.Profile = new TestContextContainer();
                var cmdlet = new NewAzureStorageContext
                {
                    CommandRuntime     = mock,
                    StorageAccountName = "contosostorage",
                    StorageAccountKey  = "AAAAAAAA",
                };

                cmdlet.SetParameterSet("AccountNameAndKey");
                cmdlet.ExecuteCmdlet();
                var output = mock.OutputPipeline;
                Assert.NotNull(output);
                var storageContext = output.First() as AzureStorageContext;
                Assert.NotNull(storageContext);
                Assert.Equal(cmdlet.StorageAccountName, storageContext.StorageAccountName);
            }
            finally
            {
                AzureSMProfileProvider.SetInstance(() => smProvider, true);
                AzureRmProfileProvider.SetInstance(() => rmProvider, true);
            }
        }
        protected void RunPowerShellTest(params string[] scripts)
        {
            AzureSessionInitializer.InitializeAzureSession();
            ServiceManagementProfileProvider.InitializeServiceManagementProfile();
            using (UndoContext context = UndoContext.Current)
            {
                context.Start(TestUtilities.GetCallingClass(1), TestUtilities.GetCurrentMethodName(2));

                SetupManagementClients();

                List <string> modules = new List <string>();

                modules.Add(Path.Combine(EnvironmentSetupHelper.PackageDirectory, @"ServiceManagement\Azure\Compute\AzurePreview.psd1"));
                modules.Add(Path.Combine(EnvironmentSetupHelper.PackageDirectory, @"ServiceManagement\Azure\Compute\PIR.psd1"));
                modules.AddRange(Directory.GetFiles(@"Resources\ServiceManagement".AsAbsoluteLocation(), "*.ps1").ToList());

                helper.SetupEnvironment(AzureModule.AzureServiceManagement);
                helper.SetupModules(AzureModule.AzureServiceManagement, modules.ToArray());

                var scriptEnvPath = new List <string>();
                scriptEnvPath.Add(
                    string.Format(
                        "$env:PSModulePath=\"{0};$env:PSModulePath\"",
                        Path.Combine(EnvironmentSetupHelper.PackageDirectory, @"ServiceManagement\Azure\Compute").AsAbsoluteLocation()));

                helper.RunPowerShellTest(scriptEnvPath.ToArray(), scripts);
            }
        }
        public void DisableAutoSaveWhenSettingFileBreaks()
        {
            string faker = Path.Combine(Directory.GetParent(profileBasePath).ToString(), "faker");

            faker = Path.Combine(faker, Resources.AzureDirectoryName);
            var backupPath = HookSettingFile(faker);

            try
            {
                AzureSessionInitializer.CreateOrReplaceSession(dataStore);
                TestMockSupport.RunningMocked = true;
                var cmdlet = new ConnectAzureRmAccountCommand();
                cmdlet.OnImport();
                Assert.Equal(ContextSaveMode.Process, AzureSession.Instance.ARMContextSaveMode);
                Assert.Equal(typeof(ResourceManagerProfileProvider), AzureRmProfileProvider.Instance.GetType());
                var afterModified = dataStore.ReadFileAsText(settingsPath);
                var newSetting    = JsonConvert.DeserializeObject <ContextAutosaveSettings>(afterModified) as ContextAutosaveSettings;
                Assert.NotNull(newSetting);
                Assert.Equal(ContextSaveMode.CurrentUser, newSetting.Mode);
                //Assert.Equal(typeof(AzureTokenCache), AzureSession.Instance.TokenCache.GetType());
            }
            finally
            {
                RestoreSetting(backupPath);
            }
        }
Beispiel #5
0
        /// <summary>
        /// Load global aliases for ARM
        /// </summary>
        public void OnImport()
        {
#if DEBUG
            try
            {
#endif
            AzureSessionInitializer.InitializeAzureSession();
            ResourceManagerProfileProvider.InitializeResourceManagerProfile();
#if DEBUG
            if (!TestMockSupport.RunningMocked)
            {
#endif
            AzureSession.Instance.DataStore = new DiskDataStore();
#if DEBUG
        }
#endif
            System.Management.Automation.PowerShell invoker = null;
            invoker = System.Management.Automation.PowerShell.Create(RunspaceMode.CurrentRunspace);
            invoker.AddScript(File.ReadAllText(FileUtilities.GetContentFilePath(
                                                   Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location),
                                                   "AzureRmProfileStartup.ps1")));
            invoker.Invoke();
#if DEBUG
        }
        catch (Exception) when(TestMockSupport.RunningMocked)
        {
            // This will throw exception for tests, ignore.
        }
#endif
        }
 public SMTestBase()
 {
     AzureSessionInitializer.InitializeAzureSession();
     ServiceManagementProfileProvider.InitializeServiceManagementProfile();
     System.Environment.CurrentDirectory = AppDomain.CurrentDomain.BaseDirectory;
     BaseSetup();
 }
 public AddAzureEnvironmentTests()
 {
     AzureSessionInitializer.InitializeAzureSession();
     ServiceManagementProfileProvider.InitializeServiceManagementProfile();
     dataStore = new MemoryDataStore();
     AzureSession.Instance.DataStore = dataStore;
 }
Beispiel #8
0
 public void DataCollectionSettingPreventsFileWrite()
 {
     try
     {
         Environment.SetEnvironmentVariable("Azure_PS_Data_Collection", "true");
         var store = SetupStore();
         store.Setup(f => f.FileExists(It.IsAny <string>())).Returns(false);
         store.Setup(f => f.WriteFile(It.IsAny <string>(), It.IsAny <string>())).Throws(new IOException("Cannot access file"));
         store.Setup(f => f.WriteFile(It.IsAny <string>(), It.IsAny <byte[]>())).Throws(new IOException("Cannot access file"));
         store.Setup(f => f.WriteFile(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <Encoding>())).Throws(new IOException("Cannot access file"));
         AzureSessionInitializer.CreateOrReplaceSession(store.Object);
         var session = AzureSession.Instance;
         Assert.NotNull(session);
         Assert.Equal(ContextSaveMode.Process, session.ARMContextSaveMode);
         Assert.NotNull(session.TokenCache);
         Assert.Equal(typeof(AuthenticationStoreTokenCache), session.TokenCache.GetType());
         Assert.NotNull(AzureRmProfileProvider.Instance);
         Assert.Equal(typeof(ResourceManagerProfileProvider), AzureRmProfileProvider.Instance.GetType());
         store.Verify(f => f.WriteFile(It.IsAny <string>(), It.IsAny <string>()), Times.Once);
     }
     finally
     {
         ResetState();
     }
 }
Beispiel #9
0
        /// <summary>
        /// Load global aliases for ARM
        /// </summary>
        public void OnImport()
        {
#if DEBUG
            try
            {
#endif
            AzureSessionInitializer.InitializeAzureSession();
#if DEBUG
            if (!TestMockSupport.RunningMocked)
            {
#endif
            AzureSession.Instance.DataStore = new DiskDataStore();
#if DEBUG
        }
#endif

            bool autoSaveEnabled = AzureSession.Instance.ARMContextSaveMode == ContextSaveMode.CurrentUser;
            var autosaveVariable = System.Environment.GetEnvironmentVariable(AzureProfileConstants.AzureAutosaveVariable);
            bool localAutosave;
            if (bool.TryParse(autosaveVariable, out localAutosave))
            {
                autoSaveEnabled = localAutosave;
            }

            InitializeProfileProvider(autoSaveEnabled);
#if DEBUG
        }
        catch (Exception) when(TestMockSupport.RunningMocked)
        {
            // This will throw exception for tests, ignore.
        }
#endif
        }
Beispiel #10
0
        public void CanConvertProfieWithCustomEnvironment()
        {
            AzureSessionInitializer.InitializeAzureSession();
            IAzureContext context         = new AzureContext(new AzureSubscription(), new AzureAccount(), new AzureEnvironment(), new AzureTenant(), new byte[0]);
            var           testContext     = new PSAzureContext(context);
            var           testEnvironment = new PSAzureEnvironment(AzureEnvironment.PublicEnvironments["AzureCloud"]);

            testEnvironment.Name = "ExtraEnvironment";
            var testProfile = new PSAzureProfile();

            testProfile.Context = testContext;
            testProfile.Environments.Add("ExtraEnvironment", testEnvironment);
            ConvertAndTestProfile(testProfile, (profile) =>
            {
                Assert.NotEmpty(profile.EnvironmentTable);
                Assert.True(profile.EnvironmentTable.ContainsKey("ExtraEnvironment"));
                Assert.NotEmpty(profile.Contexts);
                Assert.NotNull(profile.DefaultContext);
                Assert.NotEmpty(profile.DefaultContextKey);
                Assert.Equal("Default", profile.DefaultContextKey);
                Assert.Collection(profile.Environments.OrderBy(e => e.Name),
                                  (e) => Assert.Equal(e, AzureEnvironment.PublicEnvironments[EnvironmentName.AzureChinaCloud]),
                                  (e) => Assert.Equal(e, AzureEnvironment.PublicEnvironments[EnvironmentName.AzureCloud]),
                                  (e) => Assert.Equal(e, AzureEnvironment.PublicEnvironments[EnvironmentName.AzureGermanCloud]),
                                  (e) => Assert.Equal(e, AzureEnvironment.PublicEnvironments[EnvironmentName.AzureUSGovernment]),
                                  (e) => Assert.Equal(e, testEnvironment));
            });
        }
Beispiel #11
0
        public void VerifySubscriptionTokenCacheRemove()
        {
            AzureSessionInitializer.InitializeAzureSession();
            var authFactory = new AuthenticationFactory
            {
                TokenProvider = new MockAccessTokenProvider("testtoken", "testuser")
            };

            var subscriptionId = Guid.NewGuid();
            var account        = new AzureAccount
            {
                Id   = "testuser",
                Type = AzureAccount.AccountType.User,
            };

            account.SetTenants("123");
            var sub = new AzureSubscription
            {
                Id = subscriptionId.ToString(),
            };

            sub.SetTenant("123");
            var credential = authFactory.GetSubscriptionCloudCredentials(new AzureContext
                                                                         (
                                                                             sub,
                                                                             account,
                                                                             AzureEnvironment.PublicEnvironments["AzureCloud"]
                                                                         ));

            Assert.True(credential is AccessTokenCredential);
            Assert.Equal(subscriptionId, new Guid(((AccessTokenCredential)credential).SubscriptionId));
        }
 public void InitMock()
 {
     AzureSessionInitializer.InitializeAzureSession();
     BlobMock       = new MockStorageBlobManagement();
     MockCmdRunTime = new MockCommandRuntime();
     AzureSession.Instance.DataStore = new MemoryDataStore();
 }
        public void BaseSetup()
        {
            AzureSessionInitializer.InitializeAzureSession();
            ServiceManagementProfileProvider.InitializeServiceManagementProfile();
            if (AzureSession.Instance.DataStore == null || (AzureSession.Instance.DataStore != null && !(AzureSession.Instance.DataStore is MemoryDataStore)))
            {
                AzureSession.Instance.DataStore = new MemoryDataStore();
            }
            currentProfile = new AzureSMProfile();

            if (currentProfile.Context.Subscription == null)
            {
                var newGuid = Guid.NewGuid();
                var client  = new ProfileClient(currentProfile);
                var account = new AzureAccount
                {
                    Id   = "test",
                    Type = AzureAccount.AccountType.User,
                };
                account.SetSubscriptions(newGuid.ToString());
                client.AddOrSetAccount(account);
                var sub = new AzureSubscription {
                    Id = newGuid.ToString(), Name = "test"
                };
                sub.SetEnvironment(EnvironmentName.AzureCloud);
                sub.SetAccount("test");
                client.AddOrSetSubscription(sub);
                client.SetSubscriptionAsDefault(newGuid, "test");
            }
            AzureSession.Instance.AuthenticationFactory = new MockTokenAuthenticationFactory();
        }
        public ClientFactoryTests()
        {
            // Example of environment variable: TEST_AZURE_CREDENTIALS=<subscription-id-value>;<*****@*****.**>;<email-password>"
            AzureSessionInitializer.InitializeAzureSession();
            string credsEnvironmentVariable = Environment.GetEnvironmentVariable("TEST_AZURE_CREDENTIALS") ?? "";

            string[] creds = credsEnvironmentVariable.Split(';');

            if (creds.Length != 3)
            {
                // The test is not configured to run.
                runTest = false;
                return;
            }

            subscriptionId = creds[0];
            userAccount    = creds[1];
            password       = new SecureString();
            foreach (char letter in creds[2])
            {
                password.AppendChar(letter);
            }
            password = password.Length == 0 ? null : password;
            runTest  = true;
            if (runTest)
            {
                return;
            }
        }
        protected void RunPowerShellTest(params string[] scripts)
        {
            AzureSessionInitializer.InitializeAzureSession();
            ServiceManagementProfileProvider.InitializeServiceManagementProfile();
            using (UndoContext context = UndoContext.Current)
            {
                context.Start(TestUtilities.GetCallingClass(1), TestUtilities.GetCurrentMethodName(2));

                SetupManagementClients();

                var modules = new List <string>
                {
                    "Resources\\SqlIaaSExtension\\SqlIaaSExtensionTests.ps1",
                    "Resources\\ServiceManagement\\Common.ps1",
                    ".\\Assert.ps1",
                    @"..\..\..\..\..\Package\Debug\ServiceManagement\Azure\Compute\AzurePreview.psd1"
                };

                helper.SetupEnvironment(AzureModule.AzureServiceManagement);
                helper.SetupModules(AzureModule.AzureServiceManagement, modules.ToArray());


                var scriptEnvPath = new List <string>();
                scriptEnvPath.Add(
                    string.Format(
                        "$env:PSModulePath=\"{0};$env:PSModulePath\"",
                        @"..\..\..\..\..\Package\Debug\ServiceManagement\Azure\Compute".AsAbsoluteLocation()));

                helper.RunPowerShellTest(scriptEnvPath, scripts);
            }
        }
        private void NewShareAndValidate(string name, string expectedErrorId)
        {
            try
            {
                AzureSessionInitializer.InitializeAzureSession();
                this.CmdletInstance.RunCmdlet(
                    Constants.ShareNameParameterSetName,
                    new KeyValuePair <string, object>("Name", name));
            }
            catch (TargetInvocationException exception)
            {
                Trace.WriteLine(string.Format("Creating a share with name '{0}'", name));
                if (exception.InnerException != null)
                {
                    Trace.WriteLine(string.Format("Exception:"));
                    Trace.WriteLine(string.Format("{0}: {1}", exception.InnerException.GetType(), exception.InnerException.Message));
                    if (exception.InnerException.GetType().ToString().Contains(expectedErrorId))
                    {
                        return;
                    }
                }
            }

            throw new InvalidOperationException("Did not receive expected exception");
        }
Beispiel #17
0
        public EnvironmentSetupHelper()
        {
            AzureSessionInitializer.InitializeAzureSession();
            var datastore = new MemoryDataStore();

            AzureSession.Instance.DataStore = datastore;
            var profile = new AzureSMProfile(Path.Combine(AzureSession.Instance.ProfileDirectory, AzureSession.Instance.ProfileFile));

            AzureSMCmdlet.CurrentProfile    = profile;
            AzureSession.Instance.DataStore = datastore;
            ProfileClient = new ProfileClient(profile);

            // Ignore SSL errors
            System.Net.ServicePointManager.ServerCertificateValidationCallback += (se, cert, chain, sslerror) => true;

            // Set RunningMocked
            if (HttpMockServer.GetCurrentMode() == HttpRecorderMode.Playback)
            {
                TestMockSupport.RunningMocked = true;
            }
            else
            {
                TestMockSupport.RunningMocked = false;
            }
        }
Beispiel #18
0
 public void SetupTest()
 {
     AzureSessionInitializer.InitializeAzureSession();
     ServiceManagementProfileProvider.InitializeServiceManagementProfile();
     AzureSMProfileProvider.Instance.Profile = new AzureSMProfile();
     // Create 2 test databases
     NewAzureSqlDatabaseTests.CreateTestDatabasesWithSqlAuth();
 }
Beispiel #19
0
        public virtual void SetupTest()
        {
            AzureSessionInitializer.InitializeAzureSession();
            ServiceManagementProfileProvider.InitializeServiceManagementProfile();
            new FileSystemHelper(this).CreateAzureSdkDirectoryAndImportPublishSettings();

            currentProfile = new AzureSMProfile(Path.Combine(AzureSession.Instance.ProfileDirectory, AzureSession.Instance.ProfileFile));
        }
 private void InitSession()
 {
     AzureSessionInitializer.InitializeAzureSession();
     smProvider = AzureSMProfileProvider.Instance;
     rmProvider = AzureRmProfileProvider.Instance;
     AzureRmProfileProvider.SetInstance(() => new TestProfileProvider(), true);
     AzureSMProfileProvider.SetInstance(() => new TestSMProfileProvider(), true);
 }
Beispiel #21
0
        public void CanAuthenticateUsingMSIObjectId()
        {
            AzureSessionInitializer.InitializeAzureSession();
            string expectedAccessToken = Guid.NewGuid().ToString();

            _output.WriteLine("Expected access token for ARM URI: {0}", expectedAccessToken);
            string expectedToken2 = Guid.NewGuid().ToString();
            string tenant         = Guid.NewGuid().ToString();

            _output.WriteLine("Expected access token for graph URI: {0}", expectedToken2);
            string userId  = Guid.NewGuid().ToString();
            var    account = new AzureAccount
            {
                Id   = userId,
                Type = AzureAccount.AccountType.ManagedService
            };
            var environment      = AzureEnvironment.PublicEnvironments["AzureCloud"];
            var expectedResource = environment.ActiveDirectoryServiceEndpointResourceId;
            var builder          = new UriBuilder(AuthenticationFactory.DefaultMSILoginUri);

            builder.Query = $"resource={Uri.EscapeDataString(environment.ActiveDirectoryServiceEndpointResourceId)}&object_id={userId}&api-version=2018-02-01";
            var defaultUri = builder.Uri.ToString();

            var customBuilder = new UriBuilder(AuthenticationFactory.DefaultMSILoginUri);

            customBuilder.Query = $"resource={Uri.EscapeDataString(environment.GraphEndpointResourceId)}&object_id={userId}&api-version=2018-02-01";
            var customUri = customBuilder.Uri.ToString();

            var responses = new Dictionary <string, ManagedServiceTokenInfo>(StringComparer.OrdinalIgnoreCase)
            {
                { defaultUri, new ManagedServiceTokenInfo {
                      AccessToken = expectedAccessToken, ExpiresIn = 3600, Resource = expectedResource
                  } },
                { customUri, new ManagedServiceTokenInfo {
                      AccessToken = expectedToken2, ExpiresIn = 3600, Resource = environment.GraphEndpointResourceId
                  } }
            };

            AzureSession.Instance.RegisterComponent(HttpClientOperationsFactory.Name, () => TestHttpOperationsFactory.Create(responses, _output), true);
            var             authFactory = new AuthenticationFactory();
            IRenewableToken token       = (IRenewableToken)authFactory.Authenticate(account, environment, tenant, null, null, null);

            _output.WriteLine($"Received access token for default Uri ${token.AccessToken}");
            Assert.Equal(expectedAccessToken, token.AccessToken);
            var account2 = new AzureAccount
            {
                Id   = userId,
                Type = AzureAccount.AccountType.ManagedService
            };
            var token2 = authFactory.Authenticate(account2, environment, tenant, null, null, null, AzureEnvironment.Endpoint.GraphEndpointResourceId);

            _output.WriteLine($"Received access token for custom Uri ${token2.AccessToken}");
            Assert.Equal(expectedToken2, token2.AccessToken);
            Assert.Equal(3600, Math.Round(token.ExpiresOn.DateTime.Subtract(DateTime.UtcNow).TotalSeconds));
            var token3 = authFactory.Authenticate(account, environment, tenant, null, null, null, "bar");

            Assert.Throws <InvalidOperationException>(() => token3.AccessToken);
        }
Beispiel #22
0
 public void ConConvertEmptyProfile()
 {
     AzureSessionInitializer.InitializeAzureSession();
     ConvertAndTestProfile(new PSAzureProfile(), (profile) =>
     {
         AssertStandardEnvironments(profile);
         Assert.Null(profile.DefaultContext);
     });
 }
Beispiel #23
0
        public void SilentReauthenticateSuccess()
        {
            try
            {
                // Setup
                InitializeSession();
                cmdlet.TenantId = Guid.NewGuid().ToString();
                var mockAzureCredentialFactory = new Mock <AzureCredentialFactory>();
                mockAzureCredentialFactory.Setup(f => f.CreateSharedTokenCacheCredentials(It.IsAny <SharedTokenCacheCredentialOptions>())).Returns(() => new TokenCredentialMock(
                                                                                                                                                       (firstTime) =>
                {
                    return(new ValueTask <AccessToken>(new AccessToken(fakeToken, DateTimeOffset.Now.AddHours(1))));
                }));

                AzureSession.Instance.RegisterComponent(nameof(AzureCredentialFactory), () => mockAzureCredentialFactory.Object, true);
                AzureSession.Instance.ClientFactory.AddHandler(new HttpMockHandler(
                                                                   (times) =>
                {
                    HttpResponseMessage response = null;
                    if (times == 0)
                    {
                        response = new HttpResponseMessage(HttpStatusCode.Unauthorized)
                        {
                            Content = new StringContent(body401, Encoding.UTF8, "application/json"),
                        };
                        response.Headers.Add("WWW-Authenticate", WwwAuthenticateIP);
                    }
                    else
                    {
                        response = new HttpResponseMessage(HttpStatusCode.OK)
                        {
                            Content = new StringContent(string.Format(body200, cmdlet.TenantId), Encoding.UTF8, "application/json"),
                        };
                    }
                    return(response);
                }));

                // Act
                cmdlet.InvokeBeginProcessing();
                cmdlet.ExecuteCmdlet();
                cmdlet.InvokeEndProcessing();

                //Verify
                Assert.Single(OutputPipeline);
                Assert.True(OutputPipeline.First() is PSAzureTenant);
                Assert.Equal(cmdlet.TenantId, ((PSAzureTenant)OutputPipeline.First()).Id.ToString());
                Assert.Equal(2, ((PSAzureTenant)OutputPipeline.First()).Domains.Length);
                Assert.Equal("AzureSDKTeam.onmicrosoft.com,azdevextest.com", string.Join(",", ((PSAzureTenant)OutputPipeline.First()).Domains));
                Assert.Equal("Home", ((PSAzureTenant)OutputPipeline.First()).TenantCategory);
            }
            finally
            {
                //Dispose
                AzureSessionInitializer.CreateOrReplaceSession(new MemoryDataStore());
            }
        }
Beispiel #24
0
 protected void SetupSessionAndProfile()
 {
     AzureSessionInitializer.InitializeAzureSession();
     AzureSession.Instance.ARMContextSaveMode = ContextSaveMode.Process;
     ResourceManagerProfileProvider.InitializeResourceManagerProfile();
     if (!(AzureSession.Instance?.DataStore is MemoryDataStore))
     {
         AzureSession.Instance.DataStore = new MemoryDataStore();
     }
 }
Beispiel #25
0
        public void CanAuthenticateUsingMSIDefault()
        {
            AzureSessionInitializer.InitializeAzureSession();
            string expectedAccessToken = Guid.NewGuid().ToString();

            _output.WriteLine("Expected access token for default URI: {0}", expectedAccessToken);
            string expectedToken2 = Guid.NewGuid().ToString();
            string tenant         = Guid.NewGuid().ToString();

            _output.WriteLine("Expected access token for custom URI: {0}", expectedToken2);
            string userId  = "*****@*****.**";
            var    account = new AzureAccount
            {
                Id   = userId,
                Type = AzureAccount.AccountType.ManagedService
            };
            var environment      = AzureEnvironment.PublicEnvironments["AzureCloud"];
            var expectedResource = environment.ActiveDirectoryServiceEndpointResourceId;
            var builder          = new UriBuilder(AuthenticationFactory.DefaultBackupMSILoginUri);

            builder.Query = $"resource={Uri.EscapeDataString(environment.ActiveDirectoryServiceEndpointResourceId)}&api-version=2018-02-01";
            var defaultUri = builder.Uri.ToString();

            var responses = new Dictionary <string, ManagedServiceTokenInfo>(StringComparer.OrdinalIgnoreCase)
            {
                { defaultUri, new ManagedServiceTokenInfo {
                      AccessToken = expectedAccessToken, ExpiresIn = 3600, Resource = expectedResource
                  } },
                { "http://myfunkyurl:10432/oauth2/token?resource=foo&api-version=2018-02-01", new ManagedServiceTokenInfo {
                      AccessToken = expectedToken2, ExpiresIn = 3600, Resource = "foo"
                  } }
            };

            AzureSession.Instance.RegisterComponent(HttpClientOperationsFactory.Name, () => TestHttpOperationsFactory.Create(responses, _output), true);
            var authFactory = new AuthenticationFactory();
            var token       = authFactory.Authenticate(account, environment, tenant, null, null, null);

            _output.WriteLine($"Received access token for default Uri ${token.AccessToken}");
            Assert.Equal(expectedAccessToken, token.AccessToken);
            var account2 = new AzureAccount
            {
                Id   = userId,
                Type = AzureAccount.AccountType.ManagedService
            };

            account2.SetProperty(AzureAccount.Property.MSILoginUri, "http://myfunkyurl:10432/oauth2/token");
            var token2 = authFactory.Authenticate(account2, environment, tenant, null, null, null, "foo");

            _output.WriteLine($"Received access token for custom Uri ${token2.AccessToken}");
            Assert.Equal(expectedToken2, token2.AccessToken);
            var token3 = authFactory.Authenticate(account, environment, tenant, null, null, null, "bar");

            Assert.Throws <InvalidOperationException>(() => token3.AccessToken);
        }
Beispiel #26
0
        public static void InitializeClass(TestContext context)
        {
            AzureSessionInitializer.InitializeAzureSession();
            ServiceManagementProfileProvider.InitializeServiceManagementProfile();
            AzureSMProfileProvider.Instance.Profile = new AzureSMProfile();
            // Create atleast two test databases
            NewAzureSqlDatabaseTests.CreateTestDatabasesWithSqlAuth();

            // Remove the test databases
            NewAzureSqlDatabaseTests.RemoveTestDatabasesWithSqlAuth();
        }
Beispiel #27
0
        public void GetsSlots()
        {
            AzureSessionInitializer.InitializeAzureSession();
            ServiceManagementProfileProvider.InitializeServiceManagementProfile();
            // Setup
            string slot       = "staging";
            var    clientMock = new Mock <IWebsitesClient>();

            clientMock.Setup(c => c.ListWebsites(slot))
            .Returns(new List <Site> {
                new Site
                {
                    Name     = "website1(stage)",
                    WebSpace = "webspace1"
                }, new Site
                {
                    Name     = "website2(stage)",
                    WebSpace = "webspace1"
                }
            });

            clientMock.Setup(c => c.GetWebsiteConfiguration(It.IsAny <string>(), slot))
            .Returns(new SiteConfig
            {
                PublishingUsername = "******"
            });

            SetupProfile(null);

            // Test
            var getAzureWebsiteCommand = new GetAzureWebsiteCommand
            {
                CommandRuntime = new MockCommandRuntime(),
                WebsitesClient = clientMock.Object,
                Slot           = slot
            };

            getAzureWebsiteCommand.ExecuteWithProcessing();

            IEnumerable <Site> sites = System.Management.Automation.LanguagePrimitives.GetEnumerable(((MockCommandRuntime)getAzureWebsiteCommand.CommandRuntime).OutputPipeline).Cast <Site>();

            Assert.NotNull(sites);
            Assert.NotEmpty(sites);
            Assert.Equal(2, sites.Count());
            var website1 = sites.ElementAt(0);
            var website2 = sites.ElementAt(1);

            Assert.NotNull(website1);
            Assert.NotNull(website2);
            Assert.Equal("website1(stage)", website1.Name);
            Assert.Equal("website2(stage)", website2.Name);
        }
Beispiel #28
0
        public void CanConvertFullProfilet()
        {
            AzureSessionInitializer.InitializeAzureSession();
            var context = GetDefaultContext();
            var prof    = new PSAzureProfile();

            prof.Context = new PSAzureContext(context);
            ConvertAndTestProfile(prof, (profile) =>
            {
                AssertStandardEnvironments(profile);
                Assert.True(context.IsEqual(profile.DefaultContext));
            });
        }
Beispiel #29
0
        public void InitializeTest()
        {
            AzureSessionInitializer.InitializeAzureSession();
            ServiceManagementProfileProvider.InitializeServiceManagementProfile();
            powershell = System.Management.Automation.PowerShell.Create();

            MockHttpServer.SetupCertificates();

            UnitTestHelper.SetupUnitTestSubscription(powershell);

            serverName = SqlDatabaseTestSettings.Instance.ServerName;
            powershell.Runspace.SessionStateProxy.SetVariable("serverName", serverName);
        }
Beispiel #30
0
        public virtual void Initialize()
        {
            if (!IsInitialized)
            {
                AzureSessionInitializer.InitializeAzureSession();
                ServiceManagementProfileProvider.InitializeServiceManagementProfile();
                TestRunSetup();
                IsInitialized = true;
            }

            this.ApplyFullMocking();
            this.ResetIndividualMocks();
        }