Inheritance: IAzureProfile
        public EnvironmentSetupHelper()
        {
            var datastore = new MemoryDataStore();
            AzureSession.DataStore = datastore;
            var profile = new AzureSMProfile(Path.Combine(AzureSession.ProfileDirectory, AzureSession.ProfileFile));
            var rmprofile = new AzureRMProfile(Path.Combine(AzureSession.ProfileDirectory, AzureSession.ProfileFile));
            rmprofile.Environments.Add("foo", AzureEnvironment.PublicEnvironments.Values.FirstOrDefault());
            rmprofile.Context = new AzureContext(new AzureSubscription(), new AzureAccount(), rmprofile.Environments["foo"], new AzureTenant());
            rmprofile.Context.Subscription.Environment = "foo";
            if (AzureRmProfileProvider.Instance.Profile == null)
            {
                AzureRmProfileProvider.Instance.Profile = rmprofile;
            }

            AzureSession.DataStore = datastore;
            ProfileClient = new ProfileClient(profile);

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

            AdalTokenCache.ClearCookies();

            // Set RunningMocked
            TestMockSupport.RunningMocked = HttpMockServer.GetCurrentMode() == HttpRecorderMode.Playback;
        }
Example #2
0
        /// <summary>
        /// Initialize the necessary environment for the tests.
        /// </summary>
        public void BaseSetup()
        {
            currentProfile = new AzureRMProfile();
            var newGuid = Guid.NewGuid();
            currentProfile.Context = new AzureContext(
                new AzureSubscription { Id = newGuid, Name = "test", Environment = EnvironmentName.AzureCloud, Account = "test" },
                new AzureAccount
                {
                    Id = "test",
                    Type = AzureAccount.AccountType.User,
                    Properties = new Dictionary<AzureAccount.Property, string>
                    {
                            {AzureAccount.Property.Subscriptions, newGuid.ToString()}
                    }
                },
            AzureEnvironment.PublicEnvironments[EnvironmentName.AzureCloud],
            new AzureTenant { Id = Guid.NewGuid(), Domain = "testdomain.onmicrosoft.com" });

            AzureRmProfileProvider.Instance.Profile = currentProfile;

            // Now override AzureSession.DataStore to use the MemoryDataStore
            if (AzureSession.DataStore != null && !(AzureSession.DataStore is MemoryDataStore))
            {
                AzureSession.DataStore = new MemoryDataStore();
            }

            AzureSession.AuthenticationFactory = new MockTokenAuthenticationFactory();
            TestMockSupport.RunningMocked = true;
            //This is needed for AutoRest Authentication
            SynchronizationContext.SetSynchronizationContext(new SynchronizationContext());
        }
 private static RMProfileClient SetupTestEnvironment(List<string> tenants, params List<string>[] subscriptionLists)
 {
     AzureSession.AuthenticationFactory = new MockTokenAuthenticationFactory(DefaultAccount,
         Guid.NewGuid().ToString(), DefaultTenant.ToString());
     var subscriptionList = new Queue<List<string>>(subscriptionLists);
     var clientFactory = new MockSubscriptionClientFactory(tenants, subscriptionList);
     var mock = new MockClientFactory(new List<object>
     {
         clientFactory.GetSubscriptionClient()
     }, true);
     mock.MoqClients = true;
     AzureSession.ClientFactory = mock;
     Context = new AzureContext(new AzureSubscription()
         {
             Account = DefaultAccount,
             Environment = EnvironmentName.AzureCloud,
             Id = DefaultSubscription,
             Name = DefaultSubscriptionName
         },
         new AzureAccount() { Id = DefaultAccount, Type = AzureAccount.AccountType.User },
         AzureEnvironment.PublicEnvironments[EnvironmentName.AzureCloud],
         new AzureTenant() { Domain = DefaultDomain, Id = DefaultTenant });
     var profile = new AzureRMProfile();
     profile.Context = Context;
     return new RMProfileClient(profile);
 }
        public RMProfileClient(AzureRMProfile profile)
        {
            _profile = profile;

            if (_profile != null && _profile.Context != null &&
                _profile.Context.TokenCache != null && _profile.Context.TokenCache.Length > 0)
            {
                TokenCache.DefaultShared.Deserialize(_profile.Context.TokenCache);
            }
        }
        public void ProfileSerializeDeserializeWorks()
        {
            var dataStore = new MockDataStore();
            AzureSession.DataStore = dataStore;
            var profilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, AzureSession.ProfileFile);
            var currentProfile = new AzureRMProfile(profilePath);
            var tenantId = Guid.NewGuid().ToString();
            var environment = new AzureEnvironment
            {
                Name = "testCloud",
                Endpoints = { { AzureEnvironment.Endpoint.ActiveDirectory, "http://contoso.com" } }
            };
            var account = new AzureAccount
            {
                Id = "*****@*****.**",
                Type = AzureAccount.AccountType.User,
                Properties = { { AzureAccount.Property.Tenants, tenantId } }
            };
            var sub = new AzureSubscription
            {
                Account = account.Id,
                Environment = environment.Name,
                Id = new Guid(),
                Name = "Contoso Test Subscription",
                Properties = { { AzureSubscription.Property.Tenants, tenantId } }
            };
            var tenant = new AzureTenant
            {
                Id = new Guid(tenantId),
                Domain = "contoso.com"
            };

            currentProfile.Context = new AzureContext(sub, account, environment, tenant);
            currentProfile.Environments[environment.Name] = environment;
            currentProfile.Context.TokenCache = new byte[] { 1, 2, 3, 4, 5, 6, 8, 9, 0 };

            AzureRMProfile deserializedProfile;
            // Round-trip the exception: Serialize and de-serialize with a BinaryFormatter
            BinaryFormatter bf = new BinaryFormatter();
            using (MemoryStream ms = new MemoryStream())
            {
                // "Save" object state
                bf.Serialize(ms, currentProfile);

                // Re-use the same stream for de-serialization
                ms.Seek(0, 0);

                // Replace the original exception with de-serialized one
                deserializedProfile = (AzureRMProfile)bf.Deserialize(ms);
            }
            Assert.NotNull(deserializedProfile);
            var jCurrentProfile = currentProfile.ToString();
            var jDeserializedProfile = deserializedProfile.ToString();
            Assert.Equal(jCurrentProfile, jDeserializedProfile);
        }
        public void SelectAzureProfileInMemory()
        {
            var profile = new AzureRMProfile();
            profile.Environments.Add("foo", AzureEnvironment.PublicEnvironments.Values.FirstOrDefault());
            SelectAzureRMProfileCommand cmdlt = new SelectAzureRMProfileCommand();
            // Setup
            cmdlt.Profile = profile;
            cmdlt.CommandRuntime = commandRuntimeMock;

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

            // Verify
            Assert.True(AzureRmProfileProvider.Instance.Profile.Environments.ContainsKey("foo"));
        }
Example #7
0
        private void Load(string path)
        {
            this.ProfilePath = path;

            if (!AzureSession.DataStore.DirectoryExists(AzureSession.ProfileDirectory))
            {
                AzureSession.DataStore.CreateDirectory(AzureSession.ProfileDirectory);
            }

            if (AzureSession.DataStore.FileExists(ProfilePath))
            {
                string         contents = AzureSession.DataStore.ReadFileAsText(ProfilePath);
                AzureRMProfile profile  = JsonConvert.DeserializeObject <AzureRMProfile>(contents);
                Debug.Assert(profile != null);
                this.Context      = profile.Context;
                this.Environments = profile.Environments;
            }
        }
 public static void RunDataProfileTest(AzureRMProfile rmProfile, AzureSMProfile smProfile, Action testAction)
 {
     var savedRmProfile = AzureRmProfileProvider.Instance.Profile;
     var savedSmProfile = AzureSMProfileProvider.Instance.Profile;
     try
     {
         AzureRmProfileProvider.Instance.Profile = rmProfile;
         AzureSMProfileProvider.Instance.Profile = smProfile;
         testAction();
     }
     finally
     {
         AzureRmProfileProvider.Instance.Profile = savedRmProfile;
         AzureSMProfileProvider.Instance.Profile = savedSmProfile;
     }
 }
 public void CanClearStorageAccountForEmptyProfile()
 {
     var rmProfile = new AzureRMProfile();
     rmProfile.Context = new AzureContext(null, null, null, null);
     RunDataProfileTest(
          rmProfile,
          new AzureSMProfile(),
          () =>
          {
              GeneralUtilities.ClearCurrentStorageAccount(true);
              Assert.True(string.IsNullOrEmpty(AzureSMProfileProvider.Instance.Profile.Context.GetCurrentStorageAccountName()));
          });
 }
        public void SavingProfileWorks()
        {
            string expected = @"{
  ""Environments"": {
    ""testCloud"": {
      ""Name"": ""testCloud"",
      ""OnPremise"": false,
      ""Endpoints"": {
        ""ActiveDirectory"": ""http://contoso.com""
      }
    }
  },
  ""Context"": {
    ""Account"": {
      ""Id"": ""*****@*****.**"",
      ""Type"": 1,
      ""Properties"": {
        ""Tenants"": ""3c0ff8a7-e8bb-40e8-ae66-271343379af6""
      }
    },
    ""Subscription"": {
      ""Id"": ""00000000-0000-0000-0000-000000000000"",
      ""Name"": ""Contoso Test Subscription"",
      ""Environment"": ""testCloud"",
      ""Account"": ""*****@*****.**"",
      ""State"": ""Enabled"",
      ""Properties"": {
        ""Tenants"": ""3c0ff8a7-e8bb-40e8-ae66-271343379af6""
      }
    },
    ""Environment"": {
      ""Name"": ""testCloud"",
      ""OnPremise"": false,
      ""Endpoints"": {
        ""ActiveDirectory"": ""http://contoso.com""
      }
    },
    ""Tenant"": {
      ""Id"": ""3c0ff8a7-e8bb-40e8-ae66-271343379af6"",
      ""Domain"": ""contoso.com""
    },
    ""TokenCache"": ""AQIDBAUGCAkA""
  }
}";
            var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, AzureSession.ProfileFile);
            var dataStore = new MockDataStore();
            AzureSession.DataStore = dataStore;
            AzureRMProfile profile = new AzureRMProfile(path);
            var tenantId = new Guid("3c0ff8a7-e8bb-40e8-ae66-271343379af6");
            var environment = new AzureEnvironment
            {
                Name = "testCloud",
                Endpoints = { { AzureEnvironment.Endpoint.ActiveDirectory, "http://contoso.com" } }
            };
            var account = new AzureAccount
            {
                Id = "*****@*****.**",
                Type = AzureAccount.AccountType.User,
                Properties = { { AzureAccount.Property.Tenants, tenantId.ToString() } }
            };
            var sub = new AzureSubscription
            {
                Account = account.Id,
                Environment = environment.Name,
                Id = new Guid(),
                Name = "Contoso Test Subscription",
                State = "Enabled",
                Properties = { { AzureSubscription.Property.Tenants, tenantId.ToString() } }
            };
            var tenant = new AzureTenant
            {
                Id = tenantId,
                Domain = "contoso.com"
            };
            profile.Context = new AzureContext(sub, account, environment, tenant);
            profile.Environments[environment.Name] = environment;
            profile.Context.TokenCache = new byte[] { 1, 2, 3, 4, 5, 6, 8, 9, 0 };
            profile.Save();
            string actual = dataStore.ReadFileAsText(path);
            Assert.Equal(expected, actual);
        }
        public void LoadingProfileWorks()
        {
            string contents = @"{
  ""Environments"": {
    ""testCloud"": {
      ""Name"": ""testCloud"",
      ""OnPremise"": false,
      ""Endpoints"": {
        ""ActiveDirectory"": ""http://contoso.com""
      }
    }
  },
  ""Context"": {
    ""TokenCache"": ""AQIDBAUGCAkA"",
    ""Account"": {
      ""Id"": ""*****@*****.**"",
      ""Type"": 1,
      ""Properties"": {
        ""Tenants"": ""3c0ff8a7-e8bb-40e8-ae66-271343379af6""
      }
    },
    ""Subscription"": {
      ""Id"": ""00000000-0000-0000-0000-000000000000"",
      ""Name"": ""Contoso Test Subscription"",
      ""Environment"": ""testCloud"",
      ""Account"": ""*****@*****.**"",
      ""Properties"": {
        ""Tenants"": ""3c0ff8a7-e8bb-40e8-ae66-271343379af6""
      }
    },
    ""Environment"": {
      ""Name"": ""testCloud"",
      ""OnPremise"": false,
      ""Endpoints"": {
        ""ActiveDirectory"": ""http://contoso.com""
      }
    },
    ""Tenant"": {
      ""Id"": ""3c0ff8a7-e8bb-40e8-ae66-271343379af6"",
      ""Domain"": ""contoso.com""
    }
  }
}";
            var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, AzureSession.ProfileFile);
            var dataStore = new MockDataStore();
            AzureSession.DataStore = dataStore;
            dataStore.WriteFile(path, contents);
            var profile = new AzureRMProfile(path);
            Assert.Equal(4, profile.Environments.Count);
            Assert.Equal("3c0ff8a7-e8bb-40e8-ae66-271343379af6", profile.Context.Tenant.Id.ToString());
            Assert.Equal("contoso.com", profile.Context.Tenant.Domain);
            Assert.Equal("00000000-0000-0000-0000-000000000000", profile.Context.Subscription.Id.ToString());
            Assert.Equal("testCloud", profile.Context.Environment.Name);
            Assert.Equal("*****@*****.**", profile.Context.Account.Id);
            Assert.Equal(new byte[] { 1, 2, 3, 4, 5, 6, 8, 9, 0 }, profile.Context.TokenCache);
            Assert.Equal(path, profile.ProfilePath);
        }
        public void GetAzureRmSubscriptionPaginatedResult()
        {
            var tenants = new List<string> { Guid.NewGuid().ToString(), DefaultTenant.ToString() };
            var secondsubscriptionInTheFirstTenant = Guid.NewGuid().ToString();
            var firstList = new List<string> { DefaultSubscription.ToString(), secondsubscriptionInTheFirstTenant };
            var secondList = new List<string> { Guid.NewGuid().ToString() };
            var thirdList = new List<string> { DefaultSubscription.ToString(), secondsubscriptionInTheFirstTenant };
            var fourthList = new List<string> { DefaultSubscription.ToString(), secondsubscriptionInTheFirstTenant };
            var client = SetupTestEnvironment(tenants, firstList, secondList, thirdList, fourthList);

            var dataStore = new MemoryDataStore();
            AzureSession.DataStore = dataStore;
            var commandRuntimeMock = new MockCommandRuntime();
            AzureSession.AuthenticationFactory = new MockTokenAuthenticationFactory();
            var profile = new AzureRMProfile();
            profile.Environments.Add("foo", AzureEnvironment.PublicEnvironments.Values.FirstOrDefault());
            profile.Context = Context;
            var cmdlt = new GetAzureRMSubscriptionCommand();
            // Setup
            cmdlt.DefaultProfile = profile;
            cmdlt.CommandRuntime = commandRuntimeMock;

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

            Assert.True(commandRuntimeMock.OutputPipeline.Count == 7);
            Assert.Equal("Disabled", ((PSAzureSubscription)commandRuntimeMock.OutputPipeline[2]).State);
            Assert.Equal("LinkToNextPage", ((PSAzureSubscription)commandRuntimeMock.OutputPipeline[2]).SubscriptionName);
        }
 public void SetContextPreservesTokenCache()
 {
     AzureRMProfile profile = null;
     AzureContext context = new AzureContext(null, null, null, null);
     Assert.Throws<ArgumentNullException>(() =>profile.SetContextWithCache(context));
     profile = new AzureRMProfile();
     Assert.Throws<ArgumentNullException>(() => profile.SetContextWithCache(null));
     profile.SetContextWithCache(context);
     Assert.Equal(TokenCache.DefaultShared.Serialize(), profile.Context.TokenCache);
 }
        public void SaveAzureProfileFromDefault()
        {
            var profile = new AzureRMProfile();
            profile.Environments.Add("foo", AzureEnvironment.PublicEnvironments.Values.FirstOrDefault());
            profile.Context = new AzureContext(new AzureSubscription(), new AzureAccount(), profile.Environments["foo"]);
            AzureRmProfileProvider.Instance.Profile = profile;
            SaveAzureRMProfileCommand cmdlt = new SaveAzureRMProfileCommand();
            // Setup
            cmdlt.Path = "X:\\foo.json";
            cmdlt.CommandRuntime = commandRuntimeMock;

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

            // Verify
            Assert.True(AzureSession.DataStore.FileExists("X:\\foo.json"));
            var profile2 = new AzureRMProfile("X:\\foo.json");
            Assert.True(profile2.Environments.ContainsKey("foo"));
        }
        public void SaveAzureProfileInMemory()
        {
            var profile = new AzureRMProfile();
            profile.Environments.Add("foo", AzureEnvironment.PublicEnvironments.Values.FirstOrDefault());
            SaveAzureRMProfileCommand cmdlt = new SaveAzureRMProfileCommand();
            // Setup
            cmdlt.Profile = profile;
            cmdlt.Path = "X:\\foo.json";
            cmdlt.CommandRuntime = commandRuntimeMock;

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

            // Verify
            Assert.True(AzureSession.DataStore.FileExists("X:\\foo.json"));
            var profile2 = new AzureRMProfile("X:\\foo.json");
            Assert.True(profile2.Environments.ContainsKey("foo"));
        }