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

            // Set RunningMocked
            TestMockSupport.RunningMocked = HttpMockServer.GetCurrentMode() == HttpRecorderMode.Playback;
        }
        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"));
        }
        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 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 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 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);
        }