public void RecoverAzureSqlDatabaseWithDatabaseName()
        {
            var testSession = MockServerHelper.DefaultSessionCollection.GetSession(
                "UnitTests.RecoverAzureSqlDatabaseWithDatabaseName");
            ServerTestHelper.SetDefaultTestSessionSettings(testSession);

            testSession.RequestValidator =
                new Action<HttpMessage, HttpMessage.Request>(
                    (expected, actual) =>
                    {
                        Assert.AreEqual(expected.RequestInfo.Method, actual.Method);
                        Assert.IsTrue(
                            actual.UserAgent.Contains(ApiConstants.UserAgentHeaderValue),
                            "Missing proper UserAgent string.");
                    });

            using (var exceptionManager = new AsyncExceptionManager())
            {
                Collection<PSObject> operation;
                using (new MockHttpServer(
                    exceptionManager, MockHttpServer.DefaultHttpsServerPrefixUri, testSession))
                {
                    operation = powershell.InvokeBatchScript(
                        @"Start-AzureSqlDatabaseRecovery " +
                        @"-SourceServerName $serverName " +
                        @"-SourceDatabaseName testdb1 " +
                        @"-TargetDatabaseName testdb1-restored");
                }

                Assert.AreEqual(0, powershell.Streams.Error.Count, "Errors during run!");
                Assert.AreEqual(0, powershell.Streams.Warning.Count, "Warnings during run!");
                powershell.Streams.ClearStreams();

                // Expecting one operation object
                Assert.AreEqual(1, operation.Count, "Expecting one operation object");

                Assert.IsInstanceOfType(
                    operation[0].BaseObject, typeof(RecoverDatabaseOperation),
                    "Expecting a RecoverDatabaseOperation object");

                var operationObject = (RecoverDatabaseOperation)operation[0].BaseObject;
                Guid operationId;
                Assert.IsTrue(
                    Guid.TryParse(operationObject.Id, out operationId),
                    "Expecting a operation ID that's a GUID");
                Assert.AreNotEqual(
                    Guid.Empty, operationId,
                    "Expecting an operation ID that's not an empty GUID");
                Assert.AreEqual(
                    operationObject.SourceDatabaseName, "testdb1",
                    "Source database name mismatch");
                Assert.AreEqual(
                    operationObject.TargetServerName, serverName,
                    "Target server name mismatch");
                Assert.AreEqual(
                    operationObject.TargetDatabaseName, "testdb1-restored",
                    "Target database name mismatch");
            }
        }
        public void RecoverAzureSqlDatabaseWithDatabaseNameWithCertAuth()
        {
            var testSession = MockServerHelper.DefaultSessionCollection.GetSession(
                "UnitTests.RecoverAzureSqlDatabaseWithDatabaseNameWithCertAuth");
            ServerTestHelper.SetDefaultTestSessionSettings(testSession);

            testSession.RequestValidator =
                new Action<HttpMessage, HttpMessage.Request>(
                    (expected, actual) =>
                    {
                        Assert.AreEqual(expected.RequestInfo.Method, actual.Method);
                        Assert.IsTrue(
                            actual.UserAgent.Contains(ApiConstants.UserAgentHeaderValue),
                            "Missing proper UserAgent string.");
                        Assert.IsTrue(
                            UnitTestHelper.GetUnitTestClientCertificate().Equals(actual.Certificate),
                            "Expected correct client certificate");
                    });

            using (var exceptionManager = new AsyncExceptionManager())
            {
                Collection<PSObject> operation;
                using (new MockHttpServer(
                    exceptionManager, MockHttpServer.DefaultHttpsServerPrefixUri, testSession))
                {
                    operation = powershell.InvokeBatchScript(
                        @"Start-AzureSqlDatabaseRecovery " +
                        @"-TargetServerName $serverName " +
                        @"-SourceDatabaseName testdb1 " +
                        @"-TargetDatabaseName testdb1-restored");
                }

                Assert.AreEqual(0, powershell.Streams.Error.Count, "Errors during run!");
                Assert.AreEqual(0, powershell.Streams.Warning.Count, "Warnings during run!");
                powershell.Streams.ClearStreams();

                // Expecting one operation object
                Assert.AreEqual(1, operation.Count, "Expecting one operation object");

                Assert.IsTrue(
                    operation[0].BaseObject is RecoverDatabaseOperation,
                    "Expecting a RecoverDatabaseOperation object");

                var operationObject = (RecoverDatabaseOperation)operation[0].BaseObject;
                Assert.IsTrue(
                    operationObject.RequestID != Guid.Empty,
                    "Expecting a non-empty operation ID");
                Assert.AreEqual(
                    operationObject.TargetDatabaseName, "testdb1-restored",
                    "Target database name mismatch");
            }
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="MockHttpServer" /> class that record or
 /// playback responses for requests in a session.
 /// </summary>
 /// <param name="exceptionManager">
 /// The exception manager that captures all async exceptions.
 /// </param>
 /// <param name="baseUri">The server prefix to use.</param>
 /// <param name="session">The object that stores request/response information.</param>
 public MockHttpServer(
     AsyncExceptionManager exceptionManager,
     Uri baseUri,
     HttpSession session)
     : this(exceptionManager, baseUri)
 {
     this.stopListenerUri = new Uri(baseUri, Guid.NewGuid().ToString());
     this.listener = this.CreateListener(
         context => HandleMockRequest(
             context,
             this.baseUri,
             session),
         int.MaxValue);
 }
        /// <summary>
        /// Common helper method for other tests to create a context for ESA server.
        /// </summary>
        /// <param name="contextVariable">The variable name that will hold the new context.</param>
        public static void CreateServerContextSqlAuthV12(
            System.Management.Automation.PowerShell powershell,
            string manageUrl,
            string username,
            string password,
            string contextVariable)
        {
            UnitTestHelper.ImportAzureModule(powershell);
            UnitTestHelper.CreateTestCredential(
                powershell,
                username,
                password);

            // Tell the sql auth factory to create a v22 context (skip checking sql version using select query).
            //
            SqlAuthContextFactory.sqlVersion = SqlAuthContextFactory.SqlVersion.v12;
            
            Collection<PSObject> serverContext;
            using (AsyncExceptionManager exceptionManager = new AsyncExceptionManager())
            {
                serverContext = powershell.InvokeBatchScript(
                    string.Format(
                        CultureInfo.InvariantCulture,
                        @"{1} = New-AzureSqlDatabaseServerContext " +
                        @"-ManageUrl {0} " +
                        @"-Credential $credential ",
                        manageUrl,
                        contextVariable),
                    contextVariable);
            }

            Assert.AreEqual(0, powershell.Streams.Error.Count, "Errors during run!");
            Assert.AreEqual(0, powershell.Streams.Warning.Count, "Warnings during run!");
            powershell.Streams.ClearStreams();

            PSObject contextPsObject = serverContext.Single();
            Assert.IsTrue(
                contextPsObject.BaseObject is TSqlConnectionContext,
                "Expecting a TSqlConnectionContext object");
        }
        public void CreatePremiumDatabasesWithSqlAuth()
        {
            using (System.Management.Automation.PowerShell powershell =
                       System.Management.Automation.PowerShell.Create())
            {
                NewAzureSqlDatabaseServerContextTests.CreateServerContextSqlAuth(
                    powershell,
                    "$context");
                HttpSession testSession = MockServerHelper.DefaultSessionCollection.GetSession(
                    "UnitTest.Common.CreatePremiumDatabasesWithSqlAuth");
                DatabaseTestHelper.SetDefaultTestSessionSettings(testSession);
                testSession.RequestValidator =
                    new Action <HttpMessage, HttpMessage.Request>(
                        (expected, actual) =>
                {
                    Assert.AreEqual(expected.RequestInfo.Method, actual.Method);
                    Assert.AreEqual(expected.RequestInfo.UserAgent, actual.UserAgent);
                });

                using (AsyncExceptionManager exceptionManager = new AsyncExceptionManager())
                {
                    Collection <PSObject> premiumDB_P1, PremiumDB_P2;
                    using (new MockHttpServer(
                               exceptionManager,
                               MockHttpServer.DefaultServerPrefixUri,
                               testSession))
                    {
                        powershell.InvokeBatchScript(
                            @"$P1 = Get-AzureSqlDatabaseServiceObjective" +
                            @" -Context $context" +
                            @" -ServiceObjectiveName ""P1""");

                        powershell.InvokeBatchScript(
                            @"$P2 = Get-AzureSqlDatabaseServiceObjective " +
                            @"-Context $context" +
                            @" -ServiceObjectiveName ""P2""");

                        premiumDB_P1 = powershell.InvokeBatchScript(
                            @"$premiumDB_P1 = New-AzureSqlDatabase " +
                            @"-Context $context " +
                            @"-DatabaseName NewAzureSqlPremiumDatabaseTests_P1 " +
                            @"-Edition Premium " +
                            @"-ServiceObjective $P1 ");
                        premiumDB_P1 = powershell.InvokeBatchScript("$PremiumDB_P1");

                        powershell.InvokeBatchScript(
                            @"$PremiumDB_P2 = New-AzureSqlDatabase " +
                            @"-Context $context " +
                            @"-DatabaseName NewAzureSqlPremiumDatabaseTests_P2 " +
                            @"-Collation Japanese_CI_AS " +
                            @"-Edition Premium " +
                            @"-ServiceObjective $P2 " +
                            @"-MaxSizeGB 10 " +
                            @"-Force");
                        PremiumDB_P2 = powershell.InvokeBatchScript("$PremiumDB_P2");
                    }

                    Assert.AreEqual(0, powershell.Streams.Error.Count, "Errors during run!");
                    Assert.AreEqual(0, powershell.Streams.Warning.Count, "Warnings during run!");
                    powershell.Streams.ClearStreams();

                    Assert.IsTrue(
                        premiumDB_P1.Single().BaseObject is Services.Server.Database,
                        "Expecting a Database object");
                    Services.Server.Database databaseP1 =
                        (Services.Server.Database)premiumDB_P1.Single().BaseObject;
                    Assert.AreEqual("NewAzureSqlPremiumDatabaseTests_P1", databaseP1.Name, "Expected db name to be NewAzureSqlPremiumDatabaseTests_P1");

                    Assert.IsTrue(
                        PremiumDB_P2.Single().BaseObject is Services.Server.Database,
                        "Expecting a Database object");
                    Services.Server.Database databaseP2 =
                        (Services.Server.Database)PremiumDB_P2.Single().BaseObject;
                    Assert.AreEqual("NewAzureSqlPremiumDatabaseTests_P2", databaseP2.Name, "Expected db name to be NewAzureSqlPremiumDatabaseTests_P2");

                    Assert.AreEqual(
                        "Japanese_CI_AS",
                        databaseP2.CollationName,
                        "Expected collation to be Japanese_CI_AS");
                    Assert.AreEqual("Premium", databaseP2.Edition, "Expected edition to be Premium");
                    Assert.AreEqual(10, databaseP2.MaxSizeGB, "Expected max size to be 10 GB");
                }
            }
        }
Exemple #6
0
        public void GetRestorableDroppedDatabaseWithSqlAuth()
        {
            using (var powershell = System.Management.Automation.PowerShell.Create())
            {
                // Create a context
                NewAzureSqlDatabaseServerContextTests.CreateServerContextSqlAuth(powershell, "$context");

                var testSession = MockServerHelper.DefaultSessionCollection.GetSession(
                    "UnitTests.GetRestorableDroppedDatabaseWithSqlAuth");
                DatabaseTestHelper.SetDefaultTestSessionSettings(testSession);
                testSession.RequestValidator =
                    new Action <HttpMessage, HttpMessage.Request>(
                        (expected, actual) =>
                {
                    Assert.AreEqual(expected.RequestInfo.Method, actual.Method);
                    Assert.AreEqual(expected.RequestInfo.UserAgent, actual.UserAgent);
                    if (expected.Index < 3)
                    {
                        DatabaseTestHelper.ValidateHeadersForODataRequest(expected.RequestInfo, actual);
                    }
                    else
                    {
                        Assert.Fail("No more requests expected.");
                    }
                });

                using (var exceptionManager = new AsyncExceptionManager())
                {
                    Collection <PSObject> databases, database1, database2;
                    using (new MockHttpServer(exceptionManager, MockHttpServer.DefaultServerPrefixUri, testSession))
                    {
                        databases = powershell.InvokeBatchScript(
                            @"Get-AzureSqlDatabase -RestorableDropped " +
                            @"-Context $context");
                    }

                    Assert.AreEqual(0, powershell.Streams.Error.Count, "Errors during run!");
                    Assert.AreEqual(0, powershell.Streams.Warning.Count, "Warnings during run!");
                    powershell.Streams.ClearStreams();

                    // Expecting testdb1, testdb2, possibly dropped databases from previous runs
                    Assert.IsTrue(
                        databases.Count >= 2,
                        "Expecting at-least two RestorableDroppedDatabase objects");

                    Assert.IsTrue(
                        databases[0].BaseObject is RestorableDroppedDatabase,
                        "Expecting a RestorableDroppedDatabase object");

                    Assert.IsTrue(
                        databases[1].BaseObject is RestorableDroppedDatabase,
                        "Expecting a RestorableDroppedDatabase object");

                    var database1Object       = (RestorableDroppedDatabase)databases[0].BaseObject;
                    var database1DeletionDate = database1Object.DeletionDate.ToUniversalTime().ToString(deletionDateStringFormat);

                    var database2Object       = (RestorableDroppedDatabase)databases[1].BaseObject;
                    var database2DeletionDate = database2Object.DeletionDate.ToUniversalTime().ToString(deletionDateStringFormat);

                    using (new MockHttpServer(
                               exceptionManager, MockHttpServer.DefaultServerPrefixUri, testSession))
                    {
                        database1 = powershell.InvokeBatchScript(
                            @"Get-AzureSqlDatabase -RestorableDropped " +
                            @"-Context $context " +
                            @"-DatabaseName " + database1Object.Name + @" " +
                            @"-DatabaseDeletionDate " + database1DeletionDate);
                        database2 = powershell.InvokeBatchScript(
                            @"Get-AzureSqlDatabase -RestorableDropped " +
                            @"-Context $context " +
                            @"-DatabaseName " + database2Object.Name + @" " +
                            @"-DatabaseDeletionDate " + database2DeletionDate);
                    }

                    Assert.IsTrue(
                        database1.Single().BaseObject is RestorableDroppedDatabase,
                        "Expecting a RestorableDroppedDatabase object");
                    var refreshedDatabase1Object = (RestorableDroppedDatabase)database1.Single().BaseObject;
                    Assert.AreEqual(
                        database1Object.Name, refreshedDatabase1Object.Name,
                        "Expected db name to be " + database1Object.Name);

                    Assert.IsTrue(
                        database2.Single().BaseObject is RestorableDroppedDatabase,
                        "Expecting a RestorableDroppedDatabase object");
                    var refreshedDatabase2Object = (RestorableDroppedDatabase)database2.Single().BaseObject;
                    Assert.AreEqual(
                        database2Object.Name, refreshedDatabase2Object.Name,
                        "Expected db name to be " + database2Object.Name);
                    Assert.AreEqual(
                        database2Object.Edition, refreshedDatabase2Object.Edition,
                        "Expected edition to be " + database2Object.Edition);
                    Assert.AreEqual(
                        database2Object.MaxSizeBytes, refreshedDatabase2Object.MaxSizeBytes,
                        "Expected max size to be " + database2Object.MaxSizeBytes);
                }
            }
        }
        /// <summary>
        /// Create a <see cref="WebException"/> with the specified content.
        /// </summary>
        /// <param name="status">The status code to use in the exception.</param>
        /// <param name="content">A <see cref="MemoryStream"/> of the exception content.</param>
        /// <param name="contextHandler">An action that adds extra info to the response.</param>
        /// <returns>An <see cref="WebException"/> with the specified content.</returns>
        public static WebException CreateWebException(
            HttpStatusCode status,
            MemoryStream content,
            Action<HttpListenerContext> contextHandler)
        {
            HttpListener server = null;
            try
            {
                // Create a mock server that always returns the response code and exception stream
                // specified in the parameter.
                using (AsyncExceptionManager exceptionManager = new AsyncExceptionManager())
                {
                    MockHttpServer mockServer = new MockHttpServer(
                        exceptionManager,
                        MockHttpServer.DefaultServerPrefixUri);
                    server = mockServer.CreateListener(
                        (context) =>
                        {
                            contextHandler(context);
                            context.Response.StatusCode = (int)status;
                            content.Position = 0;
                            content.CopyTo(context.Response.OutputStream);
                            context.Response.Close();
                        },
                        1);
                }

                WebClient client = new WebClient();
                try
                {
                    client.OpenRead(new Uri(DefaultServerPrefixUri, "exception.htm"));
                }
                catch (WebException ex)
                {
                    return ex;
                }
            }
            finally
            {
                server.Stop();
            }

            return null;
        }
        public void NewAzureSqlDatabaseServerContextWithSqlAuthNegativeCases()
        {
            HttpSession testSession = DatabaseTestHelper.DefaultSessionCollection.GetSession(
                "UnitTests.NewAzureSqlDatabaseServerContextWithSqlAuthNegativeCases");

            using (System.Management.Automation.PowerShell powershell =
                System.Management.Automation.PowerShell.Create())
            {
                UnitTestHelper.ImportSqlDatabaseModule(powershell);
                UnitTestHelper.CreateTestCredential(powershell);

                using (AsyncExceptionManager exceptionManager = new AsyncExceptionManager())
                {
                    // Test warning when different $metadata is received.
                    Collection<PSObject> serverContext;
                    using (new MockHttpServer(
                        exceptionManager,
                        MockHttpServer.DefaultServerPrefixUri,
                        testSession))
                    {
                        serverContext = powershell.InvokeBatchScript(
                            string.Format(
                                CultureInfo.InvariantCulture,
                                @"$context = New-AzureSqlDatabaseServerContext " +
                                @"-ServerName testserver " +
                                @"-ManageUrl {0} " +
                                @"-Credential $credential",
                                MockHttpServer.DefaultServerPrefixUri.AbsoluteUri),
                            @"$context");
                    }

                    Assert.AreEqual(0, powershell.Streams.Error.Count, "Errors during run!");
                    Assert.AreEqual(1, powershell.Streams.Warning.Count, "Should have warning!");
                    Assert.AreEqual(
                        Resources.WarningModelOutOfDate,
                        powershell.Streams.Warning.First().Message);
                    powershell.Streams.ClearStreams();

                    PSObject contextPsObject = serverContext.Single();
                    Assert.IsTrue(
                        contextPsObject.BaseObject is ServerDataServiceSqlAuth,
                        "Expecting a ServerDataServiceSqlAuth object");

                    // Test error case
                    using (new MockHttpServer(
                        exceptionManager,
                        MockHttpServer.DefaultServerPrefixUri,
                        testSession))
                    {
                        powershell.InvokeBatchScript(
                            string.Format(
                                CultureInfo.InvariantCulture,
                                @"$context = New-AzureSqlDatabaseServerContext " +
                                @"-ServerName testserver " +
                                @"-ManageUrl {0} " +
                                @"-Credential $credential",
                                MockHttpServer.DefaultServerPrefixUri.AbsoluteUri),
                            @"$context");
                    }

                    Assert.AreEqual(1, powershell.Streams.Error.Count, "Should have errors!");
                    Assert.AreEqual(2, powershell.Streams.Warning.Count, "Should have warning!");
                    Assert.AreEqual(
                        "Test error message",
                        powershell.Streams.Error.First().Exception.Message);
                    Assert.IsTrue(
                        powershell.Streams.Warning.Any(
                            (w) => w.Message.StartsWith("Client Session Id:")),
                        "Client session Id not written to warning");
                    Assert.IsTrue(
                        powershell.Streams.Warning.Any(
                            (w) => w.Message.StartsWith("Client Request Id:")),
                        "Client request Id not written to warning");
                    powershell.Streams.ClearStreams();
                }
            }
        }
        public void GetRestorableDroppedDatabaseWithSqlAuthNonExistentDb()
        {
            using (var powershell = System.Management.Automation.PowerShell.Create())
            {
                // Create a context
                NewAzureSqlDatabaseServerContextTests.CreateServerContextSqlAuth(powershell, "$context");

                var testSession = MockServerHelper.DefaultSessionCollection.GetSession(
                    "UnitTests.GetRestorableDroppedDatabaseWithSqlAuthNonExistentDb");
                DatabaseTestHelper.SetDefaultTestSessionSettings(testSession);
                testSession.RequestValidator =
                    new Action<HttpMessage, HttpMessage.Request>(
                        (expected, actual) =>
                        {
                            Assert.AreEqual(expected.RequestInfo.Method, actual.Method);
                            Assert.AreEqual(expected.RequestInfo.UserAgent, actual.UserAgent);
                            if (expected.Index < 1)
                            {
                                DatabaseTestHelper.ValidateHeadersForODataRequest(expected.RequestInfo, actual);
                            }
                            else
                            {
                                Assert.Fail("No more requests expected.");
                            }
                        });

                using (var exceptionManager = new AsyncExceptionManager())
                {
                    using (new MockHttpServer(
                        exceptionManager, MockHttpServer.DefaultServerPrefixUri, testSession))
                    {
                        powershell.InvokeBatchScript(
                            @"Get-AzureSqlDatabase -RestorableDropped " +
                            @"-Context $context " +
                            @"-DatabaseName testdbnonexistent " +
                            @"-DatabaseDeletionDate '10/01/2013 12:00:00 AM'");
                    }

                    Assert.AreEqual(
                        1, powershell.Streams.Error.Count,
                        "Expecting errors");
                    Assert.AreEqual(
                        2, powershell.Streams.Warning.Count,
                        "Expecting tracing IDs");
                    Assert.AreEqual(
                        string.Format(
                            CultureInfo.InvariantCulture,
                            "Database '{0}' with deletion date '{1}' not found.",
                            testSession.SessionProperties["Servername"] + ".testdbnonexistent",
                            new DateTime(2013, 10, 01, 0, 0, 0, DateTimeKind.Utc)),
                        powershell.Streams.Error.First().Exception.Message,
                        "Unexpected error message");
                    Assert.IsTrue(
                        powershell.Streams.Warning.Any(w => w.Message.StartsWith("Client Session Id")),
                        "Expecting Client Session Id");
                    Assert.IsTrue(
                        powershell.Streams.Warning.Any(w => w.Message.StartsWith("Client Request Id")),
                        "Expecting Client Request Id");
                }
            }
        }
        public void SetAzureSqlDatabaseNameWithSqlAuth()
        {
            using (System.Management.Automation.PowerShell powershell =
                System.Management.Automation.PowerShell.Create())
            {
                // Create a context
                NewAzureSqlDatabaseServerContextTests.CreateServerContextSqlAuth(
                    powershell,
                    "$context");
                // Create 2 test databases
                NewAzureSqlDatabaseTests.CreateTestDatabasesWithSqlAuth(
                    powershell,
                    "$context");

                HttpSession testSession = DatabaseTestHelper.DefaultSessionCollection.GetSession(
                    "UnitTests.SetAzureSqlDatabaseNameWithSqlAuth");
                DatabaseTestHelper.SetDefaultTestSessionSettings(testSession);
                testSession.RequestValidator =
                    new Action<HttpMessage, HttpMessage.Request>(
                    (expected, actual) =>
                    {
                        Assert.AreEqual(expected.RequestInfo.Method, actual.Method);
                        Assert.AreEqual(expected.RequestInfo.UserAgent, actual.UserAgent);
                        switch (expected.Index)
                        {
                            // Request 1-2: Set testdb1 with new name of testdb2
                            case 0:
                            case 1:
                            // Request 3: Get updated testdb2
                            case 2:
                                DatabaseTestHelper.ValidateHeadersForODataRequest(
                                    expected.RequestInfo,
                                    actual);
                                break;
                            default:
                                Assert.Fail("No more requests expected.");
                                break;
                        }
                    });

                using (AsyncExceptionManager exceptionManager = new AsyncExceptionManager())
                {
                    // Create context with both ManageUrl and ServerName overriden
                    Collection<PSObject> database;
                    using (new MockHttpServer(
                        exceptionManager,
                        MockHttpServer.DefaultServerPrefixUri,
                        testSession))
                    {
                        database = powershell.InvokeBatchScript(
                           @"Set-AzureSqlDatabase " +
                           @"-Context $context " +
                           @"-DatabaseName testdb1 " +
                           @"-NewName testdb3 " +
                           @"-Force " +
                           @"-PassThru");
                    }

                    Assert.AreEqual(0, powershell.Streams.Error.Count, "Errors during run!");
                    Assert.AreEqual(0, powershell.Streams.Warning.Count, "Warnings during run!");
                    powershell.Streams.ClearStreams();

                    Assert.IsTrue(
                        database.Single().BaseObject is Services.Server.Database,
                        "Expecting a Database object");
                    Services.Server.Database databaseObj =
                        (Services.Server.Database)database.Single().BaseObject;
                    Assert.AreEqual("testdb3", databaseObj.Name, "Expected db name to be testdb3");
                    Assert.AreEqual("Web", databaseObj.Edition, "Expected edition to be Web");
                    Assert.AreEqual(1, databaseObj.MaxSizeGB, "Expected max size to be 1 GB");
                }
            }
        }
        /// <summary>
        /// Helper function to create the test databases.
        /// </summary>
        public static void CreateTestDatabasesWithCertAuth(System.Management.Automation.PowerShell powershell)
        {
            HttpSession testSession = MockServerHelper.DefaultSessionCollection.GetSession(
                "UnitTest.Common.CreateTestDatabasesWithCertAuth");

            ServerTestHelper.SetDefaultTestSessionSettings(testSession);

            testSession.RequestValidator =
                new Action<HttpMessage, HttpMessage.Request>(
                    (expected, actual) =>
                    {
                        Assert.AreEqual(expected.RequestInfo.Method, actual.Method);
                        Assert.IsTrue(
                            actual.UserAgent.Contains(ApiConstants.UserAgentHeaderValue),
                            "Missing proper UserAgent string.");
                    });

            using (AsyncExceptionManager exceptionManager = new AsyncExceptionManager())
            {
                Collection<PSObject> database1, database2, database3;
                using (new MockHttpServer(
                    exceptionManager,
                    MockHttpServer.DefaultHttpsServerPrefixUri,
                    testSession))
                {
                    database1 = powershell.InvokeBatchScript(
                        @"$testdb1 = New-AzureSqlDatabase " +
                        @"-ServerName $serverName " +
                        @"-DatabaseName testdb1 " +
                        @"-Force",
                        @"$testdb1");
                    database2 = powershell.InvokeBatchScript(
                        @"$testdb2 = New-AzureSqlDatabase " +
                        @"-ServerName $serverName " +
                        @"-DatabaseName testdb2 " +
                        @"-Collation Japanese_CI_AS " +
                        @"-Edition Standard " +
                        @"-MaxSizeGB 5 " +
                        @"-Force",
                        @"$testdb2");
                    database3 = powershell.InvokeBatchScript(
                        @"$testdb3 = New-AzureSqlDatabase " +
                        @"-ServerName $serverName " +
                        @"-DatabaseName testdb3 " +
                        @"-MaxSizeBytes 104857600 " +
                        @"-Force",
                        @"$testdb3");
                }

                Assert.AreEqual(0, powershell.Streams.Error.Count, "Errors during run!");
                Assert.AreEqual(0, powershell.Streams.Warning.Count, "Warnings during run!");
                powershell.Streams.ClearStreams();

                Services.Server.Database database = database1.Single().BaseObject as Services.Server.Database;
                Assert.IsTrue(database != null, "Expecting a Database object");
                DatabaseTestHelper.ValidateDatabaseProperties(database, "testdb1", "Standard", 250, 268435456000L, "SQL_Latin1_General_CP1_CI_AS", "S0", false, DatabaseTestHelper.StandardS0SloGuid);

                database = database2.Single().BaseObject as Services.Server.Database;
                Assert.IsTrue(database != null, "Expecting a Database object");
                DatabaseTestHelper.ValidateDatabaseProperties(database, "testdb2", "Standard", 250, 268435456000L, "Japanese_CI_AS", "S0", false, DatabaseTestHelper.StandardS0SloGuid);

                database = database3.Single().BaseObject as Services.Server.Database;
                Assert.IsTrue(database != null, "Expecting a Database object");
                DatabaseTestHelper.ValidateDatabaseProperties(database, "testdb3", "Standard", 0, 104857600L, "SQL_Latin1_General_CP1_CI_AS", "S0", false, DatabaseTestHelper.StandardS0SloGuid);
            }
        }
        /// <summary>
        /// Removes $testdb1 and $testdb2 on the given context.
        /// </summary>
        /// <param name="powershell">The powershell instance containing the context.</param>
        /// <param name="contextVariable">The variable name that holds the server context.</param>
        public static void RemoveTestDatabasesWithSqlAuth(
            System.Management.Automation.PowerShell powershell,
            string contextVariable)
        {
            HttpSession testSession = MockServerHelper.DefaultSessionCollection.GetSession(
                "UnitTest.Common.RemoveTestDatabasesWithSqlAuth");
            DatabaseTestHelper.SetDefaultTestSessionSettings(testSession);
            testSession.RequestValidator =
                new Action<HttpMessage, HttpMessage.Request>(
                (expected, actual) =>
                {
                    Assert.AreEqual(expected.RequestInfo.Method, actual.Method);
                    Assert.AreEqual(expected.RequestInfo.UserAgent, actual.UserAgent);
                    switch (expected.Index)
                    {
                        // Request 0-5: Remove database requests
                        case 0:
                        case 1:
                        case 2:
                        case 3:
                        case 4:
                        case 5:
                        case 6:
                        case 7:
                        case 8:
                            DatabaseTestHelper.ValidateHeadersForODataRequest(
                                expected.RequestInfo,
                                actual);
                            break;
                        default:
                            Assert.Fail("No more requests expected.");
                            break;
                    }
                });

            using (AsyncExceptionManager exceptionManager = new AsyncExceptionManager())
            {
                using (new MockHttpServer(
                    exceptionManager,
                    MockHttpServer.DefaultServerPrefixUri,
                    testSession))
                {
                    powershell.InvokeBatchScript(
                        @"Remove-AzureSqlDatabase " +
                        @"-Context $context " +
                        @"-DatabaseName testdb1 " +
                        @"-Force");
                    powershell.InvokeBatchScript(
                        @"Remove-AzureSqlDatabase " +
                        @"-Context $context " +
                        @"-DatabaseName testdb2 " +
                        @"-Force");
                    powershell.InvokeBatchScript(
                        @"Remove-AzureSqlDatabase " +
                        @"-Context $context " +
                        @"-DatabaseName testdb3 " +
                        @"-Force");
                }

                Assert.AreEqual(0, powershell.Streams.Error.Count, "Errors during run!");
                Assert.AreEqual(0, powershell.Streams.Warning.Count, "Warnings during run!");
                powershell.Streams.ClearStreams();
            }
        }
        /// <summary>
        /// Create $testdb1 and $testdb2 on the given context.
        /// </summary>
        /// <param name="powershell">The powershell instance containing the context.</param>
        /// <param name="contextVariable">The variable name that holds the server context.</param>
        public static void CreateTestDatabasesWithSqlAuth(
            System.Management.Automation.PowerShell powershell,
            string contextVariable)
        {
            HttpSession testSession = MockServerHelper.DefaultSessionCollection.GetSession(
                "UnitTest.Common.CreateTestDatabasesWithSqlAuth");
            DatabaseTestHelper.SetDefaultTestSessionSettings(testSession);
            testSession.RequestValidator =
                new Action<HttpMessage, HttpMessage.Request>(
                (expected, actual) =>
                {
                    Assert.AreEqual(expected.RequestInfo.Method, actual.Method);
                    Assert.AreEqual(expected.RequestInfo.UserAgent, actual.UserAgent);
                    switch (expected.Index)
                    {
                        // Request 0-2: Create testdb1
                        // Request 3-5: Create testdb2
                        // Request 6-8: Create testdb3
                        case 0:
                        case 1:
                        case 2:
                        case 3:
                        case 4:
                        case 5:
                        case 6:
                        case 7:
                        case 8:
                            DatabaseTestHelper.ValidateHeadersForODataRequest(
                                expected.RequestInfo,
                                actual);
                            break;
                        default:
                            Assert.Fail("No more requests expected.");
                            break;
                    }
                });

            using (AsyncExceptionManager exceptionManager = new AsyncExceptionManager())
            {
                Collection<PSObject> database1, database2, database3;
                using (new MockHttpServer(
                    exceptionManager,
                    MockHttpServer.DefaultServerPrefixUri,
                    testSession))
                {
                    database1 = powershell.InvokeBatchScript(
                        @"$testdb1 = New-AzureSqlDatabase " +
                        @"-Context $context " +
                        @"-DatabaseName testdb1 " +
                        @"-Force",
                        @"$testdb1");
                    database2 = powershell.InvokeBatchScript(
                        @"$testdb2 = New-AzureSqlDatabase " +
                        @"-Context $context " +
                        @"-DatabaseName testdb2 " +
                        @"-Collation Japanese_CI_AS " +
                        @"-Edition Web " +
                        @"-MaxSizeGB 5 " +
                        @"-Force",
                        @"$testdb2");
                    database3 = powershell.InvokeBatchScript(
                        @"$testdb3 = New-AzureSqlDatabase " +
                        @"-Context $context " +
                        @"-DatabaseName testdb3 " +
                        @"-MaxSizeBytes 104857600 " +
                        @"-Force",
                        @"$testdb3");
                }

                Assert.AreEqual(0, powershell.Streams.Error.Count, "Errors during run!");
                Assert.AreEqual(0, powershell.Streams.Warning.Count, "Warnings during run!");
                powershell.Streams.ClearStreams();

                Services.Server.Database database = database1.Single().BaseObject as Services.Server.Database;
                Assert.IsTrue(database != null, "Expecting a Database object");
                DatabaseTestHelper.ValidateDatabaseProperties(database, "testdb1", "Web", 1, 1073741824L, "SQL_Latin1_General_CP1_CI_AS", "Shared", false, DatabaseTestHelper.SharedSloGuid);

                database = database2.Single().BaseObject as Services.Server.Database;
                Assert.IsTrue(database != null, "Expecting a Database object");
                DatabaseTestHelper.ValidateDatabaseProperties(database, "testdb2", "Web", 5, 5368709120L, "Japanese_CI_AS", "Shared", false, DatabaseTestHelper.SharedSloGuid);

                database = database3.Single().BaseObject as Services.Server.Database;
                Assert.IsTrue(database != null, "Expecting a Database object");
                DatabaseTestHelper.ValidateDatabaseProperties(database, "testdb3", "Web", 0, 104857600L, "SQL_Latin1_General_CP1_CI_AS", "Shared", false, DatabaseTestHelper.SharedSloGuid);

            }
        }
Exemple #14
0
        public void NewAzureSqlDatabaseServerContextWithSqlAuthNegativeCases()
        {
            HttpSession testSession = MockServerHelper.DefaultSessionCollection.GetSession(
                "UnitTests.NewAzureSqlDatabaseServerContextWithSqlAuthNegativeCases");

            using (System.Management.Automation.PowerShell powershell =
                       System.Management.Automation.PowerShell.Create())
            {
                UnitTestHelper.ImportAzureModule(powershell);
                UnitTestHelper.CreateTestCredential(powershell);

                powershell.Runspace.SessionStateProxy.SetVariable(
                    "serverName",
                    SqlDatabaseTestSettings.Instance.ServerName);

                using (AsyncExceptionManager exceptionManager = new AsyncExceptionManager())
                {
                    // Tell the sql auth factory to create a v2 context (skip checking sql version using select query).
                    //
                    SqlAuthContextFactory.sqlVersion = SqlAuthContextFactory.SqlVersion.v2;

                    // Test warning when different $metadata is received.
                    Collection <PSObject> serverContext;
                    using (new MockHttpServer(
                               exceptionManager,
                               MockHttpServer.DefaultServerPrefixUri,
                               testSession))
                    {
                        serverContext = powershell.InvokeBatchScript(
                            string.Format(
                                CultureInfo.InvariantCulture,
                                @"$context = New-AzureSqlDatabaseServerContext " +
                                @"-ServerName $servername " +
                                @"-ManageUrl {0} " +
                                @"-Credential $credential",
                                MockHttpServer.DefaultServerPrefixUri.AbsoluteUri),
                            @"$context");
                    }

                    Assert.AreEqual(1, powershell.Streams.Error.Count, "Errors during run!");
                    Assert.AreEqual(2, powershell.Streams.Warning.Count, "Should have warning!");
                    powershell.Streams.ClearStreams();

                    // Tell the sql auth factory to create a v2 context (skip checking sql version using select query).
                    //
                    SqlAuthContextFactory.sqlVersion = SqlAuthContextFactory.SqlVersion.v2;

                    // Test error case
                    using (new MockHttpServer(
                               exceptionManager,
                               MockHttpServer.DefaultServerPrefixUri,
                               testSession))
                    {
                        powershell.InvokeBatchScript(
                            string.Format(
                                CultureInfo.InvariantCulture,
                                @"$context = New-AzureSqlDatabaseServerContext " +
                                @"-ServerName $servername " +
                                @"-ManageUrl {0} " +
                                @"-Credential $credential",
                                MockHttpServer.DefaultServerPrefixUri.AbsoluteUri),
                            @"$context");
                    }

                    Assert.AreEqual(1, powershell.Streams.Error.Count, "Should have errors!");
                    Assert.AreEqual(2, powershell.Streams.Warning.Count, "Should have warning!");
                    Assert.AreEqual(
                        "Test error message",
                        powershell.Streams.Error.First().Exception.Message);
                    Assert.IsTrue(
                        powershell.Streams.Warning.Any(
                            (w) => w.Message.StartsWith("Client Session Id:")),
                        "Client session Id not written to warning");
                    Assert.IsTrue(
                        powershell.Streams.Warning.Any(
                            (w) => w.Message.StartsWith("Client Request Id:")),
                        "Client request Id not written to warning");
                    powershell.Streams.ClearStreams();
                }
            }
        }
Exemple #15
0
        /// <summary>
        /// Create $testdb1 and $testdb2 on the given context.
        /// </summary>
        /// <param name="powershell">The powershell instance containing the context.</param>
        /// <param name="contextVariable">The variable name that holds the server context.</param>
        public static void CreateTestDatabasesWithSqlAuth(
            System.Management.Automation.PowerShell powershell,
            string contextVariable)
        {
            HttpSession testSession = DatabaseTestHelper.DefaultSessionCollection.GetSession(
                "UnitTest.Common.CreateTestDatabasesWithSqlAuth");

            DatabaseTestHelper.SetDefaultTestSessionSettings(testSession);
            testSession.RequestValidator =
                new Action <HttpMessage, HttpMessage.Request>(
                    (expected, actual) =>
            {
                Assert.AreEqual(expected.RequestInfo.Method, actual.Method);
                Assert.AreEqual(expected.RequestInfo.UserAgent, actual.UserAgent);
                switch (expected.Index)
                {
                // Request 0-1: Create testdb1
                // Request 2-3: Create testdb2
                case 0:
                case 1:
                case 2:
                case 3:
                    DatabaseTestHelper.ValidateHeadersForODataRequest(
                        expected.RequestInfo,
                        actual);
                    break;

                default:
                    Assert.Fail("No more requests expected.");
                    break;
                }
            });

            using (AsyncExceptionManager exceptionManager = new AsyncExceptionManager())
            {
                Collection <PSObject> database1, database2;
                using (new MockHttpServer(
                           exceptionManager,
                           MockHttpServer.DefaultServerPrefixUri,
                           testSession))
                {
                    database1 = powershell.InvokeBatchScript(
                        @"$testdb1 = New-AzureSqlDatabase " +
                        @"-Context $context " +
                        @"-DatabaseName testdb1 " +
                        @"-Force",
                        @"$testdb1");
                    database2 = powershell.InvokeBatchScript(
                        @"$testdb2 = New-AzureSqlDatabase " +
                        @"-Context $context " +
                        @"-DatabaseName testdb2 " +
                        @"-Collation Japanese_CI_AS " +
                        @"-Edition Web " +
                        @"-MaxSizeGB 5 " +
                        @"-Force",
                        @"$testdb2");
                }

                Assert.AreEqual(0, powershell.Streams.Error.Count, "Errors during run!");
                Assert.AreEqual(0, powershell.Streams.Warning.Count, "Warnings during run!");
                powershell.Streams.ClearStreams();

                Assert.IsTrue(
                    database1.Single().BaseObject is Services.Server.Database,
                    "Expecting a Database object");
                Services.Server.Database database1Obj =
                    (Services.Server.Database)database1.Single().BaseObject;
                Assert.AreEqual("testdb1", database1Obj.Name, "Expected db name to be testdb1");

                Assert.IsTrue(
                    database2.Single().BaseObject is Services.Server.Database,
                    "Expecting a Database object");
                Services.Server.Database database2Obj =
                    (Services.Server.Database)database2.Single().BaseObject;
                Assert.AreEqual("testdb2", database2Obj.Name, "Expected db name to be testdb2");
                Assert.AreEqual(
                    "Japanese_CI_AS",
                    database2Obj.CollationName,
                    "Expected collation to be Japanese_CI_AS");
                Assert.AreEqual("Web", database2Obj.Edition, "Expected edition to be Web");
                Assert.AreEqual(5, database2Obj.MaxSizeGB, "Expected max size to be 5 GB");
            }
        }
 public AsyncExceptionManagerTest()
 {
     _exceptionMgr = new AsyncExceptionManager();
 }
        public void GetAzureSqlDatabaseWithSqlAuth()
        {
            using (System.Management.Automation.PowerShell powershell =
                       System.Management.Automation.PowerShell.Create())
            {
                // Create a context
                NewAzureSqlDatabaseServerContextTests.CreateServerContextSqlAuth(
                    powershell,
                    "$context");

                // Query the created test databases
                HttpSession testSession = MockServerHelper.DefaultSessionCollection.GetSession(
                    "UnitTests.GetAzureSqlDatabaseWithSqlAuth");
                DatabaseTestHelper.SetDefaultTestSessionSettings(testSession);
                testSession.RequestValidator =
                    new Action <HttpMessage, HttpMessage.Request>(
                        (expected, actual) =>
                {
                    Assert.AreEqual(expected.RequestInfo.Method, actual.Method);
                    Assert.IsNotNull(actual.UserAgent);
                    // 0 - 5
                    // Get all databases + ServiceObjective lookup
                    // 6 - 11
                    // get database requests, 2 requests per get.
                    if (expected.Index > 11)
                    {
                        Assert.Fail("No More Requests Expected");
                    }
                    else
                    {
                        DatabaseTestHelper.ValidateHeadersForODataRequest(
                            expected.RequestInfo,
                            actual);
                    }
                });

                using (AsyncExceptionManager exceptionManager = new AsyncExceptionManager())
                {
                    // Retrieve all databases then each individual ones
                    Collection <PSObject> databases, database1, database2, database3;
                    using (new MockHttpServer(
                               exceptionManager,
                               MockHttpServer.DefaultServerPrefixUri,
                               testSession))
                    {
                        databases = powershell.InvokeBatchScript(
                            @"Get-AzureSqlDatabase " +
                            @"-Context $context");
                        database1 = powershell.InvokeBatchScript(
                            @"Get-AzureSqlDatabase " +
                            @"-Context $context " +
                            @"-DatabaseName testdb1");
                        database2 = powershell.InvokeBatchScript(
                            @"Get-AzureSqlDatabase " +
                            @"-Context $context " +
                            @"-DatabaseName testdb2");
                        database3 = powershell.InvokeBatchScript(
                            @"Get-AzureSqlDatabase " +
                            @"-Context $context " +
                            @"-DatabaseName testdb3");
                    }

                    Assert.AreEqual(0, powershell.Streams.Error.Count, "Errors during run!");
                    Assert.AreEqual(0, powershell.Streams.Warning.Count, "Warnings during run!");
                    powershell.Streams.ClearStreams();

                    // Expecting master, testdb1, testdb2, testdb3
                    Assert.AreEqual(4, databases.Count, "Expecting four Database objects");

                    Services.Server.Database database = database1.Single().BaseObject as Services.Server.Database;
                    Assert.IsNotNull(database, "Expecting a Database object");
                    DatabaseTestHelper.ValidateDatabaseProperties(database, "testdb1", "Web", 1, 1073741824L, "SQL_Latin1_General_CP1_CI_AS", "Shared", false, DatabaseTestHelper.SharedSloGuid);

                    database = database2.Single().BaseObject as Services.Server.Database;
                    Assert.IsTrue(database != null, "Expecting a Database object");
                    DatabaseTestHelper.ValidateDatabaseProperties(database, "testdb2", "Web", 5, 5368709120L, "Japanese_CI_AS", "Shared", false, DatabaseTestHelper.SharedSloGuid);

                    database = database3.Single().BaseObject as Services.Server.Database;
                    Assert.IsTrue(database != null, "Expecting a Database object");
                    DatabaseTestHelper.ValidateDatabaseProperties(database, "testdb3", "Web", 0, 104857600L, "SQL_Latin1_General_CP1_CI_AS", "Shared", false, DatabaseTestHelper.SharedSloGuid);
                }
            }
        }
        public void GetAzureSqlDatabaseServerQuotaSqlAuthTest()
        {
            using (System.Management.Automation.PowerShell powershell =
                System.Management.Automation.PowerShell.Create())
            {
                // Create a context
                NewAzureSqlDatabaseServerContextTests.CreateServerContextSqlAuth(
                    powershell,
                    "$context");

                // Issue another create testdb1, causing a failure
                HttpSession testSession = MockServerHelper.DefaultSessionCollection.GetSession(
                    "UnitTest.GetAzureSqlDatabaseServerQuotaSqlAuthTest");

                DatabaseTestHelper.SetDefaultTestSessionSettings(testSession);

                testSession.RequestValidator =
                    new Action<HttpMessage, HttpMessage.Request>(
                    (expected, actual) =>
                    {
                        Assert.AreEqual(expected.RequestInfo.Method, actual.Method);
                        Assert.AreEqual(expected.RequestInfo.UserAgent, actual.UserAgent);
                        switch (expected.Index)
                        {
                            // Request 0-1: Create testdb1
                            case 0:
                            case 1:
                                DatabaseTestHelper.ValidateHeadersForODataRequest(
                                    expected.RequestInfo,
                                    actual);
                                break;
                            default:
                                Assert.Fail("No more requests expected.");
                                break;
                        }
                    });

                using (AsyncExceptionManager exceptionManager = new AsyncExceptionManager())
                {
                    Services.Server.ServerDataServiceSqlAuth context;
                    using (new MockHttpServer(
                        exceptionManager,
                        MockHttpServer.DefaultServerPrefixUri,
                        testSession))
                    {
                        Collection<PSObject> ctxPsObject = powershell.InvokeBatchScript("$context");

                        context =
                            (Services.Server.ServerDataServiceSqlAuth)ctxPsObject.First().BaseObject;

                        Collection<PSObject> q1, q2;
                        q1 = powershell.InvokeBatchScript(
                            @"$context | Get-AzureSqlDatabaseServerQuota");

                        q2 = powershell.InvokeBatchScript(
                            @"$context | Get-AzureSqlDatabaseServerQuota -QuotaName ""Premium_Databases""");

                        ServerQuota quota1 = q1.FirstOrDefault().BaseObject as ServerQuota;
                        ServerQuota quota2 = q2.FirstOrDefault().BaseObject as ServerQuota;

                        Assert.AreEqual(
                            "premium_databases",
                            quota1.Name,
                            "Unexpected quota name");
                        Assert.AreEqual(
                            "premium_databases",
                            quota2.Name,
                            "Unexpected quota name");
                    }
                }

                Assert.AreEqual(0, powershell.Streams.Error.Count, "There were errors while running the tests!");
                Assert.AreEqual(0, powershell.Streams.Warning.Count, "There were warnings while running the tests!");
            }
        }
        public void CreatePremiumDatabasesWithSqlAuth()
        {
            using (System.Management.Automation.PowerShell powershell =
                System.Management.Automation.PowerShell.Create())
            {
                NewAzureSqlDatabaseServerContextTests.CreateServerContextSqlAuth(
                    powershell,
                    "$context");
                HttpSession testSession = MockServerHelper.DefaultSessionCollection.GetSession(
                    "UnitTest.Common.CreatePremiumDatabasesWithSqlAuth");
                DatabaseTestHelper.SetDefaultTestSessionSettings(testSession);                
                testSession.RequestValidator =
                    new Action<HttpMessage, HttpMessage.Request>(
                    (expected, actual) =>
                    {
                        Assert.AreEqual(expected.RequestInfo.Method, actual.Method);
                        Assert.AreEqual(expected.RequestInfo.UserAgent, actual.UserAgent);
                        switch (expected.Index)
                        {
                            // Request 0-6: Query P1 and P2 Service Objective
                            case 0:
                            case 1:
                            case 2:
                            case 3:
                            case 4:
                            case 5:
                            case 6:
                            // Request 7-9: Create NewAzureSqlPremiumDatabaseTests_P1
                            case 7:
                            case 8:
                            case 9:
                            // Request 10-12: Create NewAzureSqlPremiumDatabaseTests_P2
                            case 10:
                            case 11:
                            case 12:
                                DatabaseTestHelper.ValidateHeadersForODataRequest(
                                    expected.RequestInfo,
                                    actual);
                                break;
                            default:
                                Assert.Fail("No more requests expected.");
                                break;
                        }
                    });

                using (AsyncExceptionManager exceptionManager = new AsyncExceptionManager())
                {
                    Collection<PSObject> premiumDB_P1, PremiumDB_P2;
                    using (new MockHttpServer(
                        exceptionManager,
                        MockHttpServer.DefaultServerPrefixUri,
                        testSession))
                    {
                        powershell.InvokeBatchScript(
                            @"$P1 = Get-AzureSqlDatabaseServiceObjective" +
                            @" -Context $context" +
                            @" -ServiceObjectiveName ""Reserved P1""");                        

                        powershell.InvokeBatchScript(
                            @"$P2 = Get-AzureSqlDatabaseServiceObjective " +
                            @"-Context $context" +
                            @" -ServiceObjectiveName ""Reserved P2"""); 

                        premiumDB_P1 = powershell.InvokeBatchScript(
                            @"$premiumDB_P1 = New-AzureSqlDatabase " +
                            @"-Context $context " +
                            @"-DatabaseName NewAzureSqlPremiumDatabaseTests_P1 " +
                            @"-Edition Premium " +
                            @"-ServiceObjective $P1 ");
                        premiumDB_P1 = powershell.InvokeBatchScript("$PremiumDB_P1");

                        powershell.InvokeBatchScript(
                            @"$PremiumDB_P2 = New-AzureSqlDatabase " +
                            @"-Context $context " +
                            @"-DatabaseName NewAzureSqlPremiumDatabaseTests_P2 " +
                            @"-Collation Japanese_CI_AS " +
                            @"-Edition Premium " +
                            @"-ServiceObjective $P2 " +
                            @"-MaxSizeGB 10 " +
                            @"-Force");
                        PremiumDB_P2 = powershell.InvokeBatchScript("$PremiumDB_P2");
                    }

                    Assert.AreEqual(0, powershell.Streams.Error.Count, "Errors during run!");
                    Assert.AreEqual(0, powershell.Streams.Warning.Count, "Warnings during run!");
                    powershell.Streams.ClearStreams();
                    
                    Assert.IsTrue(
                        premiumDB_P1.Single().BaseObject is Services.Server.Database,
                        "Expecting a Database object");
                    Services.Server.Database databaseP1 =
                        (Services.Server.Database)premiumDB_P1.Single().BaseObject;
                    Assert.AreEqual("NewAzureSqlPremiumDatabaseTests_P1", databaseP1.Name, "Expected db name to be NewAzureSqlPremiumDatabaseTests_P1");

                    Assert.IsTrue(
                        PremiumDB_P2.Single().BaseObject is Services.Server.Database,
                        "Expecting a Database object");
                    Services.Server.Database databaseP2 =
                        (Services.Server.Database)PremiumDB_P2.Single().BaseObject;
                    Assert.AreEqual("NewAzureSqlPremiumDatabaseTests_P2", databaseP2.Name, "Expected db name to be NewAzureSqlPremiumDatabaseTests_P2");

                    Assert.AreEqual(
                        "Japanese_CI_AS",
                        databaseP2.CollationName,
                        "Expected collation to be Japanese_CI_AS");
                    /* SQL Server: Defect 1655888: When creating a premium database, 
                     * the immediate returned value do not have valid Edition and Max Database Size info                 
                     * We should active the following asserts once the defect is fixed.
                    Assert.AreEqual("Premium", database2Obj.Edition, "Expected edition to be Premium");
                    Assert.AreEqual(10, database2Obj.MaxSizeGB, "Expected max size to be 10 GB");
                     */
                }
            }
        }
        public void NewAzureSqlDatabaseWithSqlAuthDuplicateName()
        {
            using (System.Management.Automation.PowerShell powershell =
                System.Management.Automation.PowerShell.Create())
            {
                // Create a context
                NewAzureSqlDatabaseServerContextTests.CreateServerContextSqlAuth(
                    powershell,
                    "$context");

                // Issue another create testdb1, causing a failure
                HttpSession testSession = MockServerHelper.DefaultSessionCollection.GetSession(
                    "UnitTest.NewAzureSqlDatabaseWithSqlAuthDuplicateName");
                DatabaseTestHelper.SetDefaultTestSessionSettings(testSession);
                testSession.RequestValidator =
                    new Action<HttpMessage, HttpMessage.Request>(
                    (expected, actual) =>
                    {
                        Assert.AreEqual(expected.RequestInfo.Method, actual.Method);
                        Assert.AreEqual(expected.RequestInfo.UserAgent, actual.UserAgent);
                        switch (expected.Index)
                        {
                            // Request 0-1: Create testdb1
                            case 0:
                            case 1:
                                DatabaseTestHelper.ValidateHeadersForODataRequest(
                                    expected.RequestInfo,
                                    actual);
                                break;
                            default:
                                Assert.Fail("No more requests expected.");
                                break;
                        }
                    });

                using (AsyncExceptionManager exceptionManager = new AsyncExceptionManager())
                {
                    Services.Server.ServerDataServiceSqlAuth context;
                    using (new MockHttpServer(
                        exceptionManager,
                        MockHttpServer.DefaultServerPrefixUri,
                        testSession))
                    {
                        Collection<PSObject> ctxPsObject = powershell.InvokeBatchScript("$context");
                        context = (Services.Server.ServerDataServiceSqlAuth)ctxPsObject.First().BaseObject;
                        powershell.InvokeBatchScript(
                            @"New-AzureSqlDatabase " +
                            @"-Context $context " +
                            @"-DatabaseName testdb1 " +
                            @"-Force");
                    }
                }

                Assert.AreEqual(1, powershell.Streams.Error.Count, "Expecting errors");
                Assert.AreEqual(2, powershell.Streams.Warning.Count, "Expecting tracing IDs");
                Assert.AreEqual(
                    "Database 'testdb1' already exists. Choose a different database name.",
                    powershell.Streams.Error.First().Exception.Message,
                    "Unexpected error message");
                Assert.IsTrue(
                    powershell.Streams.Warning.Any(w => w.Message.StartsWith("Client Session Id")),
                    "Expecting Client Session Id");
                Assert.IsTrue(
                    powershell.Streams.Warning.Any(w => w.Message.StartsWith("Client Request Id")),
                    "Expecting Client Request Id");
                powershell.Streams.ClearStreams();
            }
        }
        public void GetRestorableDroppedDatabaseWithCertAuthNonExistentDb()
        {
            var testSession = MockServerHelper.DefaultSessionCollection.GetSession(
                "UnitTest.GetRestorableDroppedDatabaseWithCertAuthNonExistentDb");
            ServerTestHelper.SetDefaultTestSessionSettings(testSession);

            testSession.RequestValidator =
                new Action<HttpMessage, HttpMessage.Request>(
                    (expected, actual) =>
                    {
                        Assert.AreEqual(expected.RequestInfo.Method, actual.Method);
                        Assert.IsTrue(
                            actual.UserAgent.Contains(ApiConstants.UserAgentHeaderValue),
                            "Missing proper UserAgent string.");
                    });

            using (var exceptionManager = new AsyncExceptionManager())
            {
                using (new MockHttpServer(
                    exceptionManager, MockHttpServer.DefaultHttpsServerPrefixUri, testSession))
                {
                    powershell.InvokeBatchScript(
                        @"Get-AzureSqlDatabase -RestorableDropped " +
                        @"-ServerName $serverName " +
                        @"-DatabaseName testdbnonexistent " +
                        @"-DatabaseDeletionDate '10/01/2013 12:00:00 AM'");
                }

                Assert.AreEqual(
                    1, powershell.Streams.Error.Count,
                    "Expecting errors");
                Assert.AreEqual(
                    1, powershell.Streams.Warning.Count,
                    "Expecting tracing IDs");
                Assert.AreEqual(
                    string.Format(
                        CultureInfo.InvariantCulture,
                        "Resource with the name '{0}' does not exist. To continue, specify a valid resource name.",
                        "testdbnonexistent,2013-10-01T00:00:00.000Z"),
                    powershell.Streams.Error.First().Exception.Message,
                    "Unexpected error message");
                Assert.IsTrue(
                    powershell.Streams.Warning[0].Message.StartsWith("Request Id"),
                    "Expecting Client Request Id");
            }
        }
        public void SetAzureSqlDatabaseNameWithSqlAuth()
        {
            using (System.Management.Automation.PowerShell powershell =
                       System.Management.Automation.PowerShell.Create())
            {
                // Create a context
                NewAzureSqlDatabaseServerContextTests.CreateServerContextSqlAuth(
                    powershell,
                    "$context");
                NewAzureSqlDatabaseServerContextTests.CreateServerContextSqlAuth(
                    powershell,
                    "$contextCleanup");

                HttpSession testSession = MockServerHelper.DefaultSessionCollection.GetSession(
                    "UnitTests.SetAzureSqlDatabaseNameWithSqlAuth");
                DatabaseTestHelper.SetDefaultTestSessionSettings(testSession);
                testSession.RequestValidator =
                    new Action <HttpMessage, HttpMessage.Request>(
                        (expected, actual) =>
                {
                    Assert.AreEqual(expected.RequestInfo.Method, actual.Method);
                    Assert.IsNotNull(actual.UserAgent);
                    if (expected.Index < 10)
                    {
                        // Request 0-4: Set testdb1 with new name of new_testdb1
                        // Request 5-9: Set new_testdb1 with new name of testdb1
                        DatabaseTestHelper.ValidateHeadersForODataRequest(
                            expected.RequestInfo,
                            actual);
                    }
                    else
                    {
                        Assert.Fail("No more requests expected.");
                    }
                });

                using (AsyncExceptionManager exceptionManager = new AsyncExceptionManager())
                {
                    // Create context with both ManageUrl and ServerName overriden
                    Collection <PSObject> database;
                    using (new MockHttpServer(
                               exceptionManager,
                               MockHttpServer.DefaultServerPrefixUri,
                               testSession))
                    {
                        database = powershell.InvokeBatchScript(
                            @"Set-AzureSqlDatabase " +
                            @"-Context $context " +
                            @"-DatabaseName testdb1 " +
                            @"-NewName new_testdb1 " +
                            @"-Force " +
                            @"-PassThru");
                        powershell.InvokeBatchScript(
                            @"Set-AzureSqlDatabase " +
                            @"-Context $contextCleanup " +
                            @"-DatabaseName new_testdb1 " +
                            @"-NewName testdb1 " +
                            @"-Force");
                    }

                    Assert.AreEqual(0, powershell.Streams.Error.Count, "Errors during run!");
                    Assert.AreEqual(0, powershell.Streams.Warning.Count, "Warnings during run!");
                    powershell.Streams.ClearStreams();

                    Services.Server.Database databaseObj = database.Single().BaseObject as Services.Server.Database;
                    Assert.IsNotNull(databaseObj, "Expecting a Database object");
                    DatabaseTestHelper.ValidateDatabaseProperties(databaseObj, "new_testdb1", "Web", 1, 1073741824L, "SQL_Latin1_General_CP1_CI_AS", "Shared", false, DatabaseTestHelper.SharedSloGuid);
                }
            }
        }
        public void GetAzureSqlDatabaseServiceObjectiveWithSqlAuth()
        {
            using (System.Management.Automation.PowerShell powershell =
                System.Management.Automation.PowerShell.Create())
            {
                // Create a context
                NewAzureSqlDatabaseServerContextTests.CreateServerContextSqlAuth(
                    powershell,
                    "$context");

                HttpSession testSession = MockServerHelper.DefaultSessionCollection.GetSession(
                    "UnitTests.GetAzureSqlServiceObjectiveWithSqlAuth");
                DatabaseTestHelper.SetDefaultTestSessionSettings(testSession);
                testSession.RequestValidator =
                    new Action<HttpMessage, HttpMessage.Request>(
                    (expected, actual) =>
                    {
                        Assert.AreEqual(expected.RequestInfo.Method, actual.Method);
                        Assert.AreEqual(expected.RequestInfo.UserAgent, actual.UserAgent);
                        switch (expected.Index)
                        {
                            // Request 0-6: Retrieving all (6) ServiceObjectives and DimensionSettings
                            case 0:
                            case 1:
                            case 2:
                            case 3:
                            case 4:
                            case 5:
                            case 6:
                            // Request 7-8: Retrieving Reserved P1 ServiceObjectives and DimensionSettings
                            case 7:
                            case 8:
                                DatabaseTestHelper.ValidateHeadersForODataRequest(
                                    expected.RequestInfo,
                                    actual);
                                break;
                            default:
                                Assert.Fail("No more requests expected.");
                                break;
                        }
                    });
                testSession.ResponseModifier =
                    new Action<HttpMessage>(
                        (message) =>
                        {
                            DatabaseTestHelper.FixODataResponseUri(
                                message.ResponseInfo,
                                testSession.ServiceBaseUri,
                                MockHttpServer.DefaultServerPrefixUri);
                        });

                using (AsyncExceptionManager exceptionManager = new AsyncExceptionManager())
                {
                    Collection<PSObject> objectives, objective1;
                    using (new MockHttpServer(
                        exceptionManager,
                        MockHttpServer.DefaultServerPrefixUri,
                        testSession))
                    {
                        objectives = powershell.InvokeBatchScript(
                            @"Get-AzureSqlDatabaseServiceObjective " +
                            @"-Context $context");

                        objective1 = powershell.InvokeBatchScript(
                            @"Get-AzureSqlDatabaseServiceObjective " +
                            @"-Context $context " +
                            @"-ServiceObjectiveName ""P1""");
                    }

                    Assert.AreEqual(0, powershell.Streams.Error.Count, "Errors during run!");
                    Assert.AreEqual(0, powershell.Streams.Warning.Count, "Warnings during run!");
                    powershell.Streams.ClearStreams();

                    Assert.AreEqual(6, objectives.Count, "Expecting 6 Objective objects");

                    Assert.IsTrue(
                        objective1.Single().BaseObject is Services.Server.ServiceObjective,
                        "Expecting a ServiceObjective object");
                    Services.Server.ServiceObjective objective1Obj =
                        (Services.Server.ServiceObjective)objective1.Single().BaseObject;
                    Assert.AreEqual("P1", objective1Obj.Name, "Expected objective name to be 'Reserved P1'");
                }
            }
        }
        public void SetAzureSqlPremiumDatabaseServiceObjectiveWithSqlAuth()
        {
            using (System.Management.Automation.PowerShell powershell =
                       System.Management.Automation.PowerShell.Create())
            {
                // Create a context
                NewAzureSqlDatabaseServerContextTests.CreateServerContextSqlAuth(
                    powershell,
                    "$context");
                HttpSession testSession = MockServerHelper.DefaultSessionCollection.GetSession(
                    "UnitTests.SetAzureSqlPremiumDatabaseServiceObjectiveWithSqlAuth");
                DatabaseTestHelper.SetDefaultTestSessionSettings(testSession);

                using (AsyncExceptionManager exceptionManager = new AsyncExceptionManager())
                {
                    // Create context with both ManageUrl and ServerName overriden
                    Collection <PSObject> premiumDB;
                    using (new MockHttpServer(
                               exceptionManager,
                               MockHttpServer.DefaultServerPrefixUri,
                               testSession))
                    {
                        powershell.InvokeBatchScript(
                            @"$P1 = Get-AzureSqlDatabaseServiceObjective" +
                            @" -Context $context" +
                            @" -ServiceObjectiveName ""P1""");

                        powershell.InvokeBatchScript(
                            @"$premiumDB_P1 = New-AzureSqlDatabase " +
                            @"-Context $context " +
                            @"-DatabaseName SetAzureSqlPremiumDatabaseTests_P1 " +
                            @"-Edition Premium " +
                            @"-ServiceObjective $P1 ");

                        premiumDB = powershell.InvokeBatchScript(
                            @"Set-AzureSqlDatabase " +
                            @"-Context $context " +
                            @"-DatabaseName SetAzureSqlPremiumDatabaseTests_P1 " +
                            @"-Edition Business " +
                            @"-Force " +
                            @"-PassThru");

                        powershell.InvokeBatchScript(
                            @"Remove-AzureSqlDatabase " +
                            @"-Context $context " +
                            @"-DatabaseName SetAzureSqlPremiumDatabaseTests_P1 " +
                            @"-Force ");
                    }

                    Assert.AreEqual(0, powershell.Streams.Error.Count, "Errors during run!");
                    Assert.AreEqual(0, powershell.Streams.Warning.Count, "Warnings during run!");
                    powershell.Streams.ClearStreams();


                    Services.Server.Database premiumDBObj = premiumDB.Single().BaseObject as Services.Server.Database;
                    Assert.IsNotNull(premiumDBObj, "Expecting a Database object");

                    DatabaseTestHelper.ValidateDatabaseProperties(premiumDBObj, "SetAzureSqlPremiumDatabaseTests_P1", "Premium", 10, 10737418240L, "SQL_Latin1_General_CP1_CI_AS", "P1", false, DatabaseTestHelper.PremiumP1SloGuid);
                }
            }
        }
        public void RemoveAzureSqlDatabaseWithSqlAuth()
        {
            using (System.Management.Automation.PowerShell powershell =
                System.Management.Automation.PowerShell.Create())
            {
                // Create a context
                NewAzureSqlDatabaseServerContextTests.CreateServerContextSqlAuth(
                    powershell,
                    "$context");
                // Create 2 test databases
                NewAzureSqlDatabaseTests.CreateTestDatabasesWithSqlAuth(
                    powershell,
                    "$context");

                HttpSession testSession = DatabaseTestHelper.DefaultSessionCollection.GetSession(
                    "UnitTests.RemoveAzureSqlDatabaseWithSqlAuth");
                DatabaseTestHelper.SetDefaultTestSessionSettings(testSession);
                testSession.RequestValidator =
                    new Action<HttpMessage, HttpMessage.Request>(
                        (expected, actual) =>
                        {
                            Assert.AreEqual(expected.RequestInfo.Method, actual.Method);
                            Assert.AreEqual(expected.RequestInfo.UserAgent, actual.UserAgent);
                            switch (expected.Index)
                            {
                                // Request 0-3: Remove database requests
                                case 0:
                                case 1:
                                case 2:
                                case 3:
                                // Request 4: Get all database request
                                case 4:
                                    DatabaseTestHelper.ValidateHeadersForODataRequest(
                                        expected.RequestInfo,
                                        actual);
                                    break;
                                default:
                                    Assert.Fail("No more requests expected.");
                                    break;
                            }
                        });

                using (AsyncExceptionManager exceptionManager = new AsyncExceptionManager())
                {
                    // Create context with both ManageUrl and ServerName overriden
                    Collection<PSObject> databases;
                    using (new MockHttpServer(
                        exceptionManager,
                        MockHttpServer.DefaultServerPrefixUri,
                        testSession))
                    {
                        powershell.InvokeBatchScript(
                            @"Remove-AzureSqlDatabase " +
                            @"-Context $context " +
                            @"-DatabaseName testdb1 " +
                            @"-Force");
                        powershell.InvokeBatchScript(
                            @"Remove-AzureSqlDatabase " +
                            @"-Context $context " +
                            @"-DatabaseName testdb2 " +
                            @"-Force");

                        databases = powershell.InvokeBatchScript(
                            @"Get-AzureSqlDatabase " +
                            @"-Context $context");
                    }

                    Assert.AreEqual(0, powershell.Streams.Error.Count, "Errors during run!");
                    Assert.AreEqual(0, powershell.Streams.Warning.Count, "Warnings during run!");
                    powershell.Streams.ClearStreams();

                    Assert.AreEqual(1, databases.Count, "Expecting only master database object");
                }
            }
        }
        public void SetAzureSqlDatabaseSizeWithSqlAuth()
        {
            using (System.Management.Automation.PowerShell powershell =
                       System.Management.Automation.PowerShell.Create())
            {
                // Create a context
                NewAzureSqlDatabaseServerContextTests.CreateServerContextSqlAuth(
                    powershell,
                    "$context");

                HttpSession testSession = MockServerHelper.DefaultSessionCollection.GetSession(
                    "UnitTests.SetAzureSqlDatabaseSizeWithSqlAuth");
                DatabaseTestHelper.SetDefaultTestSessionSettings(testSession);
                testSession.RequestValidator =
                    new Action <HttpMessage, HttpMessage.Request>(
                        (expected, actual) =>
                {
                    Assert.AreEqual(expected.RequestInfo.Method, actual.Method);
                    Assert.IsNotNull(actual.UserAgent);
                    if (expected.Index < 10)
                    {
                        // Request 0-2: Set testdb1 with new MaxSize
                        // Request 3-5: Set testdb2 with new MaxSize
                        // Request 6-7: Get updated testdb1
                        // Request 8-9: Get updated testdb2
                        DatabaseTestHelper.ValidateHeadersForODataRequest(
                            expected.RequestInfo,
                            actual);
                    }
                    else
                    {
                        Assert.Fail("No more requests expected.");
                    }
                });

                using (AsyncExceptionManager exceptionManager = new AsyncExceptionManager())
                {
                    // Create context with both ManageUrl and ServerName overriden
                    Collection <PSObject> database1, database2;
                    using (new MockHttpServer(
                               exceptionManager,
                               MockHttpServer.DefaultServerPrefixUri,
                               testSession))
                    {
                        database1 = powershell.InvokeBatchScript(
                            @"Set-AzureSqlDatabase " +
                            @"-Context $context " +
                            @"-DatabaseName testdb1 " +
                            @"-MaxSizeGB 5 " +
                            @"-Force " +
                            @"-PassThru");

                        // Set the database to 100MB
                        database2 = powershell.InvokeBatchScript(
                            @"Set-AzureSqlDatabase " +
                            @"-Context $context " +
                            @"-DatabaseName testdb2 " +
                            @"-MaxSizeBytes 104857600 " +
                            @"-Force " +
                            @"-PassThru");
                    }

                    Assert.AreEqual(0, powershell.Streams.Error.Count, "Errors during run!");
                    Assert.AreEqual(0, powershell.Streams.Warning.Count, "Warnings during run!");
                    powershell.Streams.ClearStreams();

                    Services.Server.Database database = database1.Single().BaseObject as Services.Server.Database;
                    Assert.IsTrue(database != null, "Expecting a Database object");
                    DatabaseTestHelper.ValidateDatabaseProperties(database, "testdb1", "Web", 5, 5368709120L, "SQL_Latin1_General_CP1_CI_AS", "Shared", false, DatabaseTestHelper.SharedSloGuid);

                    database = database2.Single().BaseObject as Services.Server.Database;
                    Assert.IsTrue(database != null, "Expecting a Database object");
                    DatabaseTestHelper.ValidateDatabaseProperties(database, "testdb2", "Web", 0, 104857600L, "Japanese_CI_AS", "Shared", false, DatabaseTestHelper.SharedSloGuid);
                }
            }
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="MockHttpServer" /> class with a specified
 /// server prefix.
 /// </summary>
 /// <param name="exceptionManager">
 /// The exception manager that captures all async exceptions.
 /// </param>
 /// <param name="baseUri">The server prefix to use.</param>
 private MockHttpServer(AsyncExceptionManager exceptionManager, Uri baseUri)
 {
     this.exceptionManager = exceptionManager;
     this.baseUri = baseUri;
 }
        public void SetAzureSqlDatabaseServiceObjectiveWithSqlAuth()
        {
            using (System.Management.Automation.PowerShell powershell =
                       System.Management.Automation.PowerShell.Create())
            {
                // Create a context
                NewAzureSqlDatabaseServerContextTests.CreateServerContextSqlAuth(
                    powershell,
                    "$context");

                HttpSession testSession = MockServerHelper.DefaultSessionCollection.GetSession(
                    "UnitTests.SetAzureSqlDatabaseServiceObjectiveWithSqlAuth");
                DatabaseTestHelper.SetDefaultTestSessionSettings(testSession);
                testSession.RequestValidator =
                    new Action <HttpMessage, HttpMessage.Request>(
                        (expected, actual) =>
                {
                    Assert.AreEqual(expected.RequestInfo.Method, actual.Method);
                    Assert.AreEqual(expected.RequestInfo.UserAgent, actual.UserAgent);
                    switch (expected.Index)
                    {
                    // Request 0-1: Get Service Objective
                    case 0:
                    case 1:
                    // Request 2-7: Get/Update/Re-Get testdb2
                    case 2:
                    case 3:
                    case 4:
                    case 5:
                    case 6:
                        DatabaseTestHelper.ValidateHeadersForODataRequest(
                            expected.RequestInfo,
                            actual);
                        break;

                    default:
                        Assert.Fail("No more requests expected.");
                        break;
                    }
                });

                using (AsyncExceptionManager exceptionManager = new AsyncExceptionManager())
                {
                    // Create context with both ManageUrl and ServerName overriden
                    Collection <PSObject> database;
                    using (new MockHttpServer(
                               exceptionManager,
                               MockHttpServer.DefaultServerPrefixUri,
                               testSession))
                    {
                        powershell.InvokeBatchScript(
                            @"$slo = Get-AzureSqlDatabaseServiceObjective " +
                            @"-Context $context " +
                            @"-ServiceObjectiveName ""Reserved P1""");

                        database = powershell.InvokeBatchScript(
                            @"Set-AzureSqlDatabase " +
                            @"-Context $context " +
                            @"-DatabaseName testdb2 " +
                            @"-ServiceObjective $slo " +
                            @"-Force " +
                            @"-PassThru");
                    }

                    Assert.AreEqual(0, powershell.Streams.Error.Count, "Errors during run!");
                    Assert.AreEqual(0, powershell.Streams.Warning.Count, "Warnings during run!");
                    powershell.Streams.ClearStreams();

                    Assert.IsTrue(
                        database.Single().BaseObject is Services.Server.Database,
                        "Expecting a Database object");
                    Services.Server.Database databaseObj =
                        (Services.Server.Database)database.Single().BaseObject;
                    databaseObj = (Services.Server.Database)database.Single().BaseObject;
                    Assert.AreEqual("testdb2", databaseObj.Name, "Expected db name to be testdb2");
                    Assert.AreEqual((byte)0, databaseObj.ServiceObjectiveAssignmentState, "Expected assignment state to be pending");
                    //Assert.AreEqual("Reserved P1", databaseObj.ServiceObjective.Name, "Expected Reserved P1");
                    //Assert.AreEqual("Reserved P1", databaseObj.ServiceObjectiveName, "Expected Reserved P1");
                }
            }
        }
        public void GetAzureSqlDatabaseWithSqlAuthNonExistentDb()
        {
            using (System.Management.Automation.PowerShell powershell =
                System.Management.Automation.PowerShell.Create())
            {
                // Create a context
                NewAzureSqlDatabaseServerContextTests.CreateServerContextSqlAuth(
                    powershell,
                    "$context");

                // Query a non-existent test database
                HttpSession testSession = DatabaseTestHelper.DefaultSessionCollection.GetSession(
                    "UnitTests.GetAzureSqlDatabaseWithSqlAuthNonExistentDb");
                DatabaseTestHelper.SetDefaultTestSessionSettings(testSession);
                testSession.RequestValidator =
                    new Action<HttpMessage, HttpMessage.Request>(
                    (expected, actual) =>
                    {
                        Assert.AreEqual(expected.RequestInfo.Method, actual.Method);
                        Assert.AreEqual(expected.RequestInfo.UserAgent, actual.UserAgent);
                        switch (expected.Index)
                        {
                            // Request 0-2: Get database requests
                            case 0:
                            case 1:
                            case 2:
                                DatabaseTestHelper.ValidateHeadersForODataRequest(
                                    expected.RequestInfo,
                                    actual);
                                break;
                            default:
                                Assert.Fail("No more requests expected.");
                                break;
                        }
                    });

                using (AsyncExceptionManager exceptionManager = new AsyncExceptionManager())
                {
                    using (new MockHttpServer(
                        exceptionManager,
                        MockHttpServer.DefaultServerPrefixUri,
                        testSession))
                    {
                        powershell.InvokeBatchScript(
                            @"Get-AzureSqlDatabase " +
                            @"-Context $context " +
                            @"-DatabaseName testdb3");
                    }
                }

                Assert.AreEqual(1, powershell.Streams.Error.Count, "Expecting errors");
                Assert.AreEqual(2, powershell.Streams.Warning.Count, "Expecting tracing IDs");
                Assert.AreEqual(
                    "Database 'testserver.testdb3' not found.",
                    powershell.Streams.Error.First().Exception.Message,
                    "Unexpected error message");
                Assert.IsTrue(
                    powershell.Streams.Warning.Any(w => w.Message.StartsWith("Client Session Id")),
                    "Expecting Client Session Id");
                Assert.IsTrue(
                    powershell.Streams.Warning.Any(w => w.Message.StartsWith("Client Request Id")),
                    "Expecting Client Request Id");
                powershell.Streams.ClearStreams();
            }
        }
        public void SetAzureSqlDatabaseSizeWithSqlAuth()
        {
            using (System.Management.Automation.PowerShell powershell =
                       System.Management.Automation.PowerShell.Create())
            {
                // Create a context
                NewAzureSqlDatabaseServerContextTests.CreateServerContextSqlAuth(
                    powershell,
                    "$context");

                HttpSession testSession = MockServerHelper.DefaultSessionCollection.GetSession(
                    "UnitTests.SetAzureSqlDatabaseSizeWithSqlAuth");
                DatabaseTestHelper.SetDefaultTestSessionSettings(testSession);
                testSession.RequestValidator =
                    new Action <HttpMessage, HttpMessage.Request>(
                        (expected, actual) =>
                {
                    Assert.AreEqual(expected.RequestInfo.Method, actual.Method);
                    Assert.AreEqual(expected.RequestInfo.UserAgent, actual.UserAgent);
                    if (expected.Index < 5)
                    {
                        // Request 0-2: Set testdb1 with new MaxSize
                        // Request 3-4: Get updated testdb1
                        DatabaseTestHelper.ValidateHeadersForODataRequest(
                            expected.RequestInfo,
                            actual);
                    }
                    else
                    {
                        Assert.Fail("No more requests expected.");
                    }
                });

                using (AsyncExceptionManager exceptionManager = new AsyncExceptionManager())
                {
                    // Create context with both ManageUrl and ServerName overriden
                    Collection <PSObject> database;
                    using (new MockHttpServer(
                               exceptionManager,
                               MockHttpServer.DefaultServerPrefixUri,
                               testSession))
                    {
                        database = powershell.InvokeBatchScript(
                            @"Set-AzureSqlDatabase " +
                            @"-Context $context " +
                            @"-DatabaseName testdb1 " +
                            @"-MaxSizeGB 5 " +
                            @"-Force " +
                            @"-PassThru");
                    }

                    Assert.AreEqual(0, powershell.Streams.Error.Count, "Errors during run!");
                    Assert.AreEqual(0, powershell.Streams.Warning.Count, "Warnings during run!");
                    powershell.Streams.ClearStreams();

                    Assert.IsTrue(
                        database.Single().BaseObject is Services.Server.Database,
                        "Expecting a Database object");
                    Services.Server.Database databaseObj =
                        (Services.Server.Database)database.Single().BaseObject;
                    Assert.AreEqual("testdb1", databaseObj.Name, "Expected db name to be testdb1");
                    Assert.AreEqual("Web", databaseObj.Edition, "Expected edition to be Web");
                    Assert.AreEqual(5, databaseObj.MaxSizeGB, "Expected max size to be 5 GB");
                }
            }
        }
        public void NewAzureSqlDatabaseServerContextWithSqlAuthNegativeCases()
        {
            HttpSession testSession = MockServerHelper.DefaultSessionCollection.GetSession(
                "UnitTests.NewAzureSqlDatabaseServerContextWithSqlAuthNegativeCases");

            using (System.Management.Automation.PowerShell powershell =
                System.Management.Automation.PowerShell.Create())
            {
                UnitTestHelper.ImportAzureModule(powershell);
                UnitTestHelper.CreateTestCredential(powershell);

                powershell.Runspace.SessionStateProxy.SetVariable(
                    "serverName",
                    SqlDatabaseTestSettings.Instance.ServerName);

                using (AsyncExceptionManager exceptionManager = new AsyncExceptionManager())
                {
                    // Tell the sql auth factory to create a v2 context (skip checking sql version using select query).
                    //
                    SqlAuthContextFactory.sqlVersion = SqlAuthContextFactory.SqlVersion.v2;

                    // Test warning when different $metadata is received.
                    Collection<PSObject> serverContext;
                    using (new MockHttpServer(
                        exceptionManager,
                        MockHttpServer.DefaultServerPrefixUri,
                        testSession))
                    {
                        serverContext = powershell.InvokeBatchScript(
                            string.Format(
                                CultureInfo.InvariantCulture,
                                @"$context = New-AzureSqlDatabaseServerContext " +
                                @"-ServerName $servername " +
                                @"-ManageUrl {0} " +
                                @"-Credential $credential",
                                MockHttpServer.DefaultServerPrefixUri.AbsoluteUri),
                            @"$context");
                    }

                    Assert.AreEqual(1, powershell.Streams.Error.Count, "Errors during run!");
                    Assert.AreEqual(2, powershell.Streams.Warning.Count, "Should have warning!");
                    powershell.Streams.ClearStreams();

                    // Tell the sql auth factory to create a v2 context (skip checking sql version using select query).
                    //
                    SqlAuthContextFactory.sqlVersion = SqlAuthContextFactory.SqlVersion.v2;

                    // Test error case
                    using (new MockHttpServer(
                        exceptionManager,
                        MockHttpServer.DefaultServerPrefixUri,
                        testSession))
                    {
                        powershell.InvokeBatchScript(
                            string.Format(
                                CultureInfo.InvariantCulture,
                                @"$context = New-AzureSqlDatabaseServerContext " +
                                @"-ServerName $servername " +
                                @"-ManageUrl {0} " +
                                @"-Credential $credential",
                                MockHttpServer.DefaultServerPrefixUri.AbsoluteUri),
                            @"$context");
                    }

                    Assert.AreEqual(1, powershell.Streams.Error.Count, "Should have errors!");
                    Assert.AreEqual(2, powershell.Streams.Warning.Count, "Should have warning!");
                    Assert.AreEqual(
                        "Test error message",
                        powershell.Streams.Error.First().Exception.Message);
                    Assert.IsTrue(
                        powershell.Streams.Warning.Any(
                            (w) => w.Message.StartsWith("Client Session Id:")),
                        "Client session Id not written to warning");
                    Assert.IsTrue(
                        powershell.Streams.Warning.Any(
                            (w) => w.Message.StartsWith("Client Request Id:")),
                        "Client request Id not written to warning");
                    powershell.Streams.ClearStreams();
                }
            }
        }
        public void RecoverAzureSqlDatabaseWithDatabaseName()
        {
            var testSession = MockServerHelper.DefaultSessionCollection.GetSession(
                "UnitTests.RecoverAzureSqlDatabaseWithDatabaseName");

            ServerTestHelper.SetDefaultTestSessionSettings(testSession);

            testSession.RequestValidator =
                new Action <HttpMessage, HttpMessage.Request>(
                    (expected, actual) =>
            {
                Assert.AreEqual(expected.RequestInfo.Method, actual.Method);
                Assert.IsTrue(
                    actual.UserAgent.Contains(ApiConstants.UserAgentHeaderValue),
                    "Missing proper UserAgent string.");
                Assert.IsTrue(
                    UnitTestHelper.GetUnitTestClientCertificate().Equals(actual.Certificate),
                    "Expected correct client certificate");
            });

            using (var exceptionManager = new AsyncExceptionManager())
            {
                Collection <PSObject> operation;
                using (new MockHttpServer(
                           exceptionManager, MockHttpServer.DefaultHttpsServerPrefixUri, testSession))
                {
                    operation = powershell.InvokeBatchScript(
                        @"Start-AzureSqlDatabaseRecovery " +
                        @"-SourceServerName $serverName " +
                        @"-SourceDatabaseName testdb1 " +
                        @"-TargetDatabaseName testdb1-restored");
                }

                Assert.AreEqual(0, powershell.Streams.Error.Count, "Errors during run!");
                Assert.AreEqual(0, powershell.Streams.Warning.Count, "Warnings during run!");
                powershell.Streams.ClearStreams();

                // Expecting one operation object
                Assert.AreEqual(1, operation.Count, "Expecting one operation object");

                Assert.IsInstanceOfType(
                    operation[0].BaseObject, typeof(RecoverDatabaseOperation),
                    "Expecting a RecoverDatabaseOperation object");

                var  operationObject = (RecoverDatabaseOperation)operation[0].BaseObject;
                Guid operationId;
                Assert.IsTrue(
                    Guid.TryParse(operationObject.Id, out operationId),
                    "Expecting a operation ID that's a GUID");
                Assert.AreNotEqual(
                    Guid.Empty, operationId,
                    "Expecting an operation ID that's not an empty GUID");
                Assert.AreEqual(
                    operationObject.SourceDatabaseName, "testdb1",
                    "Source database name mismatch");
                Assert.AreEqual(
                    operationObject.TargetServerName, serverName,
                    "Target server name mismatch");
                Assert.AreEqual(
                    operationObject.TargetDatabaseName, "testdb1-restored",
                    "Target database name mismatch");
            }
        }
        /// <summary>
        /// Create continuous copy of testdb1 to partnersrv.
        /// </summary>
        /// <param name="powershell">The powershell instance containing the context.</param>
        /// <param name="contextVariable">The variable name that holds the server context.</param>
        /// <param name="copyVariable">The variable name that holds the copy object.</param>
        /// <param name="databaseName">The name of the database to copy.</param>
        public static void StartDatabaseContinuousCopyWithSqlAuth(
            System.Management.Automation.PowerShell powershell,
            string contextVariable,
            string copyVariable,
            string databaseName)
        {
            HttpSession testSession = DatabaseTestHelper.DefaultSessionCollection.GetSession(
                "UnitTest.Common.StartAzureSqlDatabaseContinuousCopyWithSqlAuth." + databaseName);
            DatabaseTestHelper.SetDefaultTestSessionSettings(testSession);
            testSession.RequestValidator =
                new Action<HttpMessage, HttpMessage.Request>(
                (expected, actual) =>
                {
                    Assert.AreEqual(expected.RequestInfo.Method, actual.Method);
                    Assert.AreEqual(expected.RequestInfo.UserAgent, actual.UserAgent);
                    switch (expected.Index)
                    {
                        // Request 0-1: Start database copy request
                        case 0:
                        case 1:
                            DatabaseTestHelper.ValidateHeadersForODataRequest(
                                expected.RequestInfo,
                                actual);
                            break;
                        default:
                            Assert.Fail("No more requests expected.");
                            break;
                    }
                });

            using (AsyncExceptionManager exceptionManager = new AsyncExceptionManager())
            {
                Collection<PSObject> databaseCopy;
                using (new MockHttpServer(
                    exceptionManager,
                    MockHttpServer.DefaultServerPrefixUri,
                    testSession))
                {
                    databaseCopy = powershell.InvokeBatchScript(
                        string.Format(
                            CultureInfo.InvariantCulture,
                            @"{0} = Start-AzureSqlDatabaseCopy " +
                            @"-Context $context " +
                            @"-DatabaseName {1} " +
                            @"-PartnerServer partnersrv " +
                            @"-ContinuousCopy",
                            copyVariable,
                            databaseName),
                        copyVariable);
                }

                Assert.AreEqual(0, powershell.Streams.Error.Count, "Errors during run!");
                Assert.AreEqual(0, powershell.Streams.Warning.Count, "Warnings during run!");
                powershell.Streams.ClearStreams();

                Assert.IsTrue(
                    databaseCopy.Single().BaseObject is Services.Server.DatabaseCopy,
                    "Expecting a Database Copy object");
                Services.Server.DatabaseCopy databaseCopyObj =
                    (Services.Server.DatabaseCopy)databaseCopy.Single().BaseObject;
                Assert.AreEqual(
                    "testserver",
                    databaseCopyObj.SourceServerName,
                    "Unexpected source server name");
                Assert.AreEqual(
                    databaseName,
                    databaseCopyObj.SourceDatabaseName,
                    "Unexpected source database name");
                Assert.AreEqual(
                    "partnersrv",
                    databaseCopyObj.DestinationServerName,
                    "Unexpected destination server name");
                Assert.AreEqual(
                    databaseName,
                    databaseCopyObj.DestinationDatabaseName,
                    "Unexpected destination database name");
                Assert.IsTrue(
                    databaseCopyObj.IsContinuous,
                    "Expected copy to be continuous");
            }
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="MockHttpServer" /> class with a specified
 /// server prefix.
 /// </summary>
 /// <param name="exceptionManager">
 /// The exception manager that captures all async exceptions.
 /// </param>
 /// <param name="baseUri">The server prefix to use.</param>
 private MockHttpServer(AsyncExceptionManager exceptionManager, Uri baseUri)
 {
     this.exceptionManager = exceptionManager;
     this.baseUri          = baseUri;
 }
        /// <summary>
        /// Removes all existing db which name starting with PremiumTest on the given context.
        /// </summary>
        /// <param name="powershell">The powershell instance containing the context.</param>
        /// <param name="contextVariable">The variable name that holds the server context.</param>
        public static void RemoveTestDatabasesWithSqlAuth(
            System.Management.Automation.PowerShell powershell,
            string contextVariable)
        {
            HttpSession testSession = MockServerHelper.DefaultSessionCollection.GetSession(
                "UnitTest.Common.RemoveTestPremiumDatabasesWithSqlAuth");
            DatabaseTestHelper.SetDefaultTestSessionSettings(testSession);
            testSession.RequestValidator =
                new Action<HttpMessage, HttpMessage.Request>(
                (expected, actual) =>
                {
                    Assert.AreEqual(expected.RequestInfo.Method, actual.Method);
                    Assert.AreEqual(expected.RequestInfo.UserAgent, actual.UserAgent);
                    switch (expected.Index)
                    {
                        // Request 0-11: Remove database requests
                        case 0:
                        case 1:
                        case 2:
                        case 3:
                        case 4:
                        case 5:
                        case 6:
                        case 7:
                        case 8:
                        case 9:
                        case 10:
                        case 11:
                            DatabaseTestHelper.ValidateHeadersForODataRequest(
                                expected.RequestInfo,
                                actual);
                            break;
                        default:
                            Assert.Fail("No more requests expected.");
                            break;
                    }
                });

            using (AsyncExceptionManager exceptionManager = new AsyncExceptionManager())
            {
                using (new MockHttpServer(
                    exceptionManager,
                    MockHttpServer.DefaultServerPrefixUri,
                    testSession))
                {
                    powershell.InvokeBatchScript(
                        @"Get-AzureSqlDatabase $context | " +
                        @"? {$_.Name.contains(""NewAzureSqlPremiumDatabaseTests"")} " +
                        @"| Remove-AzureSqlDatabase -Context $context -Force");
                }

                Assert.AreEqual(0, powershell.Streams.Error.Count, "Errors during run!");
                Assert.AreEqual(0, powershell.Streams.Warning.Count, "Warnings during run!");
                powershell.Streams.ClearStreams();
            }
        }
        public void GetRecoverableDatabase()
        {
            var testSession = MockServerHelper.DefaultSessionCollection.GetSession(
                "UnitTest.GetRecoverableDatabase");

            ServerTestHelper.SetDefaultTestSessionSettings(testSession);

            testSession.RequestValidator =
                new Action <HttpMessage, HttpMessage.Request>(
                    (expected, actual) =>
            {
                Assert.AreEqual(expected.RequestInfo.Method, actual.Method);
                Assert.IsTrue(
                    actual.UserAgent.Contains(ApiConstants.UserAgentHeaderValue),
                    "Missing proper UserAgent string.");
                Assert.IsTrue(
                    UnitTestHelper.GetUnitTestClientCertificate().Equals(actual.Certificate),
                    "Expected correct client certificate");
            });

            using (var exceptionManager = new AsyncExceptionManager())
            {
                Collection <PSObject> databases, database1, database2;

                using (new MockHttpServer(exceptionManager, MockHttpServer.DefaultHttpsServerPrefixUri, testSession))
                {
                    databases = powershell.InvokeBatchScript(
                        @"Get-AzureSqlRecoverableDatabase -ServerName $serverName");
                }

                Assert.AreEqual(0, powershell.Streams.Error.Count, "Errors during run!");
                Assert.AreEqual(0, powershell.Streams.Warning.Count, "Warnings during run!");
                powershell.Streams.ClearStreams();

                // Expecting testdb1, testdb2, possibly dropped databases from previous runs
                Assert.IsTrue(
                    databases.Count >= 2,
                    "Expecting at-least two RecoverableDatabase objects");

                Assert.IsTrue(
                    databases[0].BaseObject is RecoverableDatabase,
                    "Expecting a RecoverableDatabase object");

                Assert.IsInstanceOfType(
                    databases[1].BaseObject, typeof(RecoverableDatabase),
                    "Expecting a RecoverableDatabase object");

                var database1Object = (RecoverableDatabase)databases[0].BaseObject;

                var database2Object = (RecoverableDatabase)databases[1].BaseObject;

                using (new MockHttpServer(
                           exceptionManager, MockHttpServer.DefaultHttpsServerPrefixUri, testSession))
                {
                    database1 = powershell.InvokeBatchScript(
                        @"Get-AzureSqlRecoverableDatabase " +
                        @"-ServerName $serverName " +
                        @"-DatabaseName " + database1Object.Name);
                    database2 = powershell.InvokeBatchScript(
                        @"Get-AzureSqlRecoverableDatabase " +
                        @"-ServerName $serverName " +
                        @"-DatabaseName " + database2Object.Name);
                }

                Assert.IsInstanceOfType(
                    database1.Single().BaseObject, typeof(RecoverableDatabase),
                    "Expecting a RecoverableDatabase object");
                var refreshedDatabase1Object = (RecoverableDatabase)database1.Single().BaseObject;
                Assert.AreEqual(
                    database1Object.Name, refreshedDatabase1Object.Name,
                    "Expected db name to be " + database1Object.Name);

                Assert.IsInstanceOfType(
                    database2.Single().BaseObject, typeof(RecoverableDatabase),
                    "Expecting a RecoverableDatabase object");
                var refreshedDatabase2Object = (RecoverableDatabase)database2.Single().BaseObject;
                Assert.AreEqual(
                    database2Object.Name, refreshedDatabase2Object.Name,
                    "Expected db name to be " + database2Object.Name);
                Assert.AreEqual(
                    database2Object.Edition, refreshedDatabase2Object.Edition,
                    "Expected edition to be " + database2Object.Edition);
            }
        }
        public void RestoreAzureSqlDatabaseWithRestorableDroppedDatabaseObjectWithCertAuth()
        {
            DropTestDatabases();

            var deletionDate = DateTime.UtcNow;
            var restorePoint = deletionDate - TimeSpan.FromMinutes(1);

            var testSession = MockServerHelper.DefaultSessionCollection.GetSession(
                "UnitTests.RestoreAzureSqlDatabaseWithRestorableDroppedDatabaseObjectWithCertAuth");
            ServerTestHelper.SetDefaultTestSessionSettings(testSession);
            testSession.RequestValidator =
                new Action<HttpMessage, HttpMessage.Request>(
                    (expected, actual) =>
                    {
                        Assert.AreEqual(expected.RequestInfo.Method, actual.Method);
                        Assert.IsTrue(
                            actual.UserAgent.Contains(ApiConstants.UserAgentHeaderValue),
                            "Missing proper UserAgent string.");
                    });

            using (var exceptionManager = new AsyncExceptionManager())
            {
                Collection<PSObject> droppedDatabase, operation;
                using (new MockHttpServer(
                    exceptionManager, MockHttpServer.DefaultHttpsServerPrefixUri, testSession))
                {
                    droppedDatabase = powershell.InvokeBatchScript(
                        @"$database = $(Get-AzureSqlDatabase -ServerName $serverName -RestorableDropped)[0];" +
                        @"$database");
                }

                Assert.AreEqual(0, powershell.Streams.Error.Count, "Errors during run!");
                Assert.AreEqual(0, powershell.Streams.Warning.Count, "Warnings during run!");
                powershell.Streams.ClearStreams();

                var droppedDatabaseObject = (RestorableDroppedDatabase)droppedDatabase[0].BaseObject;

                using (new MockHttpServer(
                    exceptionManager, MockHttpServer.DefaultHttpsServerPrefixUri, testSession))
                {
                    operation = powershell.InvokeBatchScript(
                        @"$database | Start-AzureSqlDatabaseRestore " +
                        @"-TargetDatabaseName testdb1-restored");
                }

                Assert.AreEqual(0, powershell.Streams.Error.Count, "Errors during run!");
                Assert.AreEqual(0, powershell.Streams.Warning.Count, "Warnings during run!");
                powershell.Streams.ClearStreams();

                // Expecting one operation object
                Assert.AreEqual(1, operation.Count, "Expecting one operation object");

                Assert.IsTrue(
                    operation[0].BaseObject is RestoreDatabaseOperation,
                    "Expecting a RestoreDatabaseOperation object");

                var operationObject = (RestoreDatabaseOperation)operation[0].BaseObject;
                Assert.IsTrue(
                    operationObject.RequestID != Guid.Empty,
                    "Expecting a non-empty operation ID");

                Assert.IsTrue(operationObject.SourceDatabaseName == droppedDatabaseObject.Name);
                Assert.IsTrue(operationObject.SourceDatabaseDeletionDate == droppedDatabaseObject.DeletionDate);
            }
        }
Exemple #38
0
        public void RemoveAzureSqlDatabaseWithSqlAuth()
        {
            using (System.Management.Automation.PowerShell powershell =
                       System.Management.Automation.PowerShell.Create())
            {
                // Create a context
                NewAzureSqlDatabaseServerContextTests.CreateServerContextSqlAuth(
                    powershell,
                    "$context");
                // Create 2 test databases
                NewAzureSqlDatabaseTests.CreateTestDatabasesWithSqlAuth(
                    powershell,
                    "$context");

                HttpSession testSession = DatabaseTestHelper.DefaultSessionCollection.GetSession(
                    "UnitTests.RemoveAzureSqlDatabaseWithSqlAuth");
                DatabaseTestHelper.SetDefaultTestSessionSettings(testSession);
                testSession.RequestValidator =
                    new Action <HttpMessage, HttpMessage.Request>(
                        (expected, actual) =>
                {
                    Assert.AreEqual(expected.RequestInfo.Method, actual.Method);
                    Assert.AreEqual(expected.RequestInfo.UserAgent, actual.UserAgent);
                    switch (expected.Index)
                    {
                    // Request 0-3: Remove database requests
                    case 0:
                    case 1:
                    case 2:
                    case 3:
                    // Request 4: Get all database request
                    case 4:
                        DatabaseTestHelper.ValidateHeadersForODataRequest(
                            expected.RequestInfo,
                            actual);
                        break;

                    default:
                        Assert.Fail("No more requests expected.");
                        break;
                    }
                });

                using (AsyncExceptionManager exceptionManager = new AsyncExceptionManager())
                {
                    // Create context with both ManageUrl and ServerName overriden
                    Collection <PSObject> databases;
                    using (new MockHttpServer(
                               exceptionManager,
                               MockHttpServer.DefaultServerPrefixUri,
                               testSession))
                    {
                        powershell.InvokeBatchScript(
                            @"Remove-AzureSqlDatabase " +
                            @"-Context $context " +
                            @"-DatabaseName testdb1 " +
                            @"-Force");
                        powershell.InvokeBatchScript(
                            @"Remove-AzureSqlDatabase " +
                            @"-Context $context " +
                            @"-DatabaseName testdb2 " +
                            @"-Force");

                        databases = powershell.InvokeBatchScript(
                            @"Get-AzureSqlDatabase " +
                            @"-Context $context");
                    }

                    Assert.AreEqual(0, powershell.Streams.Error.Count, "Errors during run!");
                    Assert.AreEqual(0, powershell.Streams.Warning.Count, "Warnings during run!");
                    powershell.Streams.ClearStreams();

                    Assert.AreEqual(1, databases.Count, "Expecting only master database object");
                }
            }
        }
        public void GetAzureSqlDatabaseOperationWithSqlAuth()
        {
            using (System.Management.Automation.PowerShell powershell =
                System.Management.Automation.PowerShell.Create())
            {
                NewAzureSqlDatabaseServerContextTests.CreateServerContextSqlAuth(
                    powershell,
                    "$context");
                HttpSession testSession = MockServerHelper.DefaultSessionCollection.GetSession(
                    "UnitTest.Common.GetAzureSqlDatabaseOperationWithSqlAuth");
                DatabaseTestHelper.SetDefaultTestSessionSettings(testSession);
                testSession.RequestValidator =
                    new Action<HttpMessage, HttpMessage.Request>(
                        (expected, actual) =>
                        {
                            Assert.AreEqual(expected.RequestInfo.Method, actual.Method);
                            Assert.AreEqual(expected.RequestInfo.UserAgent, actual.UserAgent);
                            switch (expected.Index)
                            {
                                // Request 0-7: Create and Query $testdb                                                                
                                case 0:
                                case 1:
                                case 2:
                                case 3:
                                case 4:
                                case 5:
                                case 6:
                                case 7:
                                // Request 8: Delete $testdb
                                case 8:
                                // Request 9-11: Query Database Operations                                
                                case 9:
                                case 10:
                                case 11:                                
                                    DatabaseTestHelper.ValidateHeadersForODataRequest(
                                    expected.RequestInfo,
                                    actual);
                                    break;
                                default:
                                    Assert.Fail("No more requests expected.");
                                    break;
                            }
                        });

                using (AsyncExceptionManager exceptionManager = new AsyncExceptionManager())
                {
                    // There is a known issue about the Get-AzureSqlDatabaseOperation that it returns all
                    // operations which has the required database name no matter it's been deleted and recreated.
                    // So when run it against the mock session, please use the hard coded testsDBName.
                    // Run against onebox, please use the one with NewGuid(). 
                    // This unit test should be updated once that behavior get changed which was already been 
                    // created as a task.

                    // string testsDBName = string.Format("getAzureSqlDatabaseOperationTestsDB_{0}",
                    //     Guid.NewGuid().ToString());
                    string testsDBName = "getAzureSqlDatabaseOperationTestsDB_08ebd7c9-bfb7-426a-9e2f-9921999567e1";
                    Collection<PSObject> database, operationsByName, operationsByDatabase, operationsById;
                    using (new MockHttpServer(
                            exceptionManager,
                            MockHttpServer.DefaultServerPrefixUri,
                            testSession))
                    {
                        database = powershell.InvokeBatchScript(
                            string.Format(
                                @"$testdb = New-AzureSqlDatabase " +
                                @"-Context $context " +
                                @"-DatabaseName {0} " +
                                @"-Force", testsDBName),
                            @"$testdb");

                        powershell.InvokeBatchScript(
                            string.Format(
                                @"Remove-AzureSqlDatabase " +
                                @"-Context $context " +
                                @"-DatabaseName {0} " +
                                @"-Force", testsDBName));

                        operationsByName = powershell.InvokeBatchScript(
                            string.Format(
                                @"$operations = Get-AzureSqlDatabaseOperation " +
                                @"-ConnectionContext $context " +
                                @"-DatabaseName {0}",
                                testsDBName),
                            @"$operations");

                        operationsByDatabase = powershell.InvokeBatchScript(
                            @"Get-AzureSqlDatabaseOperation " +
                            @"-ConnectionContext $context " +
                            @"-Database $testdb");

                        operationsById = powershell.InvokeBatchScript(
                            @"Get-AzureSqlDatabaseOperation " +
                            @"-ConnectionContext $context " +
                            @"-OperationGuid $operations[0].Id"
                            );
                    }

                    Assert.AreEqual(0, powershell.Streams.Error.Count, "Errors during run!");
                    Assert.AreEqual(0, powershell.Streams.Warning.Count, "Warnings during run!");
                    powershell.Streams.ClearStreams();

                    VerifyGetOperationsResult(testsDBName, operationsByName);
                    VerifyGetOperationsResult(testsDBName, operationsByDatabase);
                    // Update this verification once Task 1615375:Adding Drop record in dm_operation_status resolved
                    VerifyGetOperationsResult(testsDBName, operationsById);
                }
            }
        }
        public void GetAzureSqlDatabaseServerQuotaSqlAuthTest()
        {
            using (System.Management.Automation.PowerShell powershell =
                       System.Management.Automation.PowerShell.Create())
            {
                // Create a context
                NewAzureSqlDatabaseServerContextTests.CreateServerContextSqlAuth(
                    powershell,
                    "$context");

                // Issue another create testdb1, causing a failure
                HttpSession testSession = MockServerHelper.DefaultSessionCollection.GetSession(
                    "UnitTest.GetAzureSqlDatabaseServerQuotaSqlAuthTest");

                DatabaseTestHelper.SetDefaultTestSessionSettings(testSession);

                testSession.RequestValidator =
                    new Action <HttpMessage, HttpMessage.Request>(
                        (expected, actual) =>
                {
                    Assert.AreEqual(expected.RequestInfo.Method, actual.Method);
                    Assert.AreEqual(expected.RequestInfo.UserAgent, actual.UserAgent);
                    switch (expected.Index)
                    {
                    // Request 0-1: Create testdb1
                    case 0:
                    case 1:
                        DatabaseTestHelper.ValidateHeadersForODataRequest(
                            expected.RequestInfo,
                            actual);
                        break;

                    default:
                        Assert.Fail("No more requests expected.");
                        break;
                    }
                });

                using (AsyncExceptionManager exceptionManager = new AsyncExceptionManager())
                {
                    Services.Server.ServerDataServiceSqlAuth context;
                    using (new MockHttpServer(
                               exceptionManager,
                               MockHttpServer.DefaultServerPrefixUri,
                               testSession))
                    {
                        Collection <PSObject> ctxPsObject = powershell.InvokeBatchScript("$context");

                        context =
                            (Services.Server.ServerDataServiceSqlAuth)ctxPsObject.First().BaseObject;

                        Collection <PSObject> q1, q2;
                        q1 = powershell.InvokeBatchScript(
                            @"$context | Get-AzureSqlDatabaseServerQuota");

                        q2 = powershell.InvokeBatchScript(
                            @"$context | Get-AzureSqlDatabaseServerQuota -QuotaName ""Premium_Databases""");

                        ServerQuota quota1 = q1.FirstOrDefault().BaseObject as ServerQuota;
                        ServerQuota quota2 = q2.FirstOrDefault().BaseObject as ServerQuota;

                        Assert.AreEqual(
                            "premium_databases",
                            quota1.Name,
                            "Unexpected quota name");
                        Assert.AreEqual(
                            "premium_databases",
                            quota2.Name,
                            "Unexpected quota name");
                    }
                }

                Assert.AreEqual(0, powershell.Streams.Error.Count, "There were errors while running the tests!");
                Assert.AreEqual(0, powershell.Streams.Warning.Count, "There were warnings while running the tests!");
            }
        }
        public void GetRestorableDroppedDatabaseWithCertAuth()
        {
            var testSession = MockServerHelper.DefaultSessionCollection.GetSession(
                "UnitTest.GetRestorableDroppedDatabaseWithCertAuth");
            ServerTestHelper.SetDefaultTestSessionSettings(testSession);

            testSession.RequestValidator =
                new Action<HttpMessage, HttpMessage.Request>(
                    (expected, actual) =>
                    {
                        Assert.AreEqual(expected.RequestInfo.Method, actual.Method);
                        Assert.IsTrue(
                            actual.UserAgent.Contains(ApiConstants.UserAgentHeaderValue),
                            "Missing proper UserAgent string.");
                    });

            using (var exceptionManager = new AsyncExceptionManager())
            {
                Collection<PSObject> databases, database1, database2;

                using(new MockHttpServer(exceptionManager, MockHttpServer.DefaultHttpsServerPrefixUri, testSession))
                {
                    databases = powershell.InvokeBatchScript(
                        @"Get-AzureSqlDatabase -RestorableDropped -ServerName $serverName");
                }

                Assert.AreEqual(0, powershell.Streams.Error.Count, "Errors during run!");
                Assert.AreEqual(0, powershell.Streams.Warning.Count, "Warnings during run!");
                powershell.Streams.ClearStreams();

                // Expecting testdb1, testdb2, possibly dropped databases from previous runs
                Assert.IsTrue(
                    databases.Count >= 2,
                    "Expecting at-least two RestorableDroppedDatabase objects");

                Assert.IsTrue(
                    databases[0].BaseObject is RestorableDroppedDatabase,
                    "Expecting a RestorableDroppedDatabase object");

                Assert.IsTrue(
                    databases[1].BaseObject is RestorableDroppedDatabase,
                    "Expecting a RestorableDroppedDatabase object");

                var database1Object = (RestorableDroppedDatabase)databases[0].BaseObject;
                var database1DeletionDate = database1Object.DeletionDate.ToUniversalTime().ToString(deletionDateStringFormat);

                var database2Object = (RestorableDroppedDatabase)databases[1].BaseObject;
                var database2DeletionDate = database2Object.DeletionDate.ToUniversalTime().ToString(deletionDateStringFormat);

                using (new MockHttpServer(
                    exceptionManager, MockHttpServer.DefaultHttpsServerPrefixUri, testSession))
                {
                    database1 = powershell.InvokeBatchScript(
                        @"Get-AzureSqlDatabase -RestorableDropped " +
                        @"-ServerName $serverName " +
                        @"-DatabaseName " + database1Object.Name + @" " +
                        @"-DatabaseDeletionDate " + database1DeletionDate);
                    database2 = powershell.InvokeBatchScript(
                        @"Get-AzureSqlDatabase -RestorableDropped " +
                        @"-ServerName $serverName " +
                        @"-DatabaseName " + database2Object.Name + @" " +
                        @"-DatabaseDeletionDate " + database2DeletionDate);
                }

                Assert.IsTrue(
                    database1.Single().BaseObject is RestorableDroppedDatabase,
                    "Expecting a RestorableDroppedDatabase object");
                var refreshedDatabase1Object = (RestorableDroppedDatabase)database1.Single().BaseObject;
                Assert.AreEqual(
                    database1Object.Name, refreshedDatabase1Object.Name,
                    "Expected db name to be " + database1Object.Name);

                Assert.IsTrue(
                    database2.Single().BaseObject is RestorableDroppedDatabase,
                    "Expecting a RestorableDroppedDatabase object");
                var refreshedDatabase2Object = (RestorableDroppedDatabase)database2.Single().BaseObject;
                Assert.AreEqual(
                    database2Object.Name, refreshedDatabase2Object.Name,
                    "Expected db name to be " + database2Object.Name);
                Assert.AreEqual(
                    database2Object.Edition, refreshedDatabase2Object.Edition,
                    "Expected edition to be " + database2Object.Edition);
                Assert.AreEqual(
                    database2Object.MaxSizeBytes, refreshedDatabase2Object.MaxSizeBytes,
                    "Expected max size to be " + database2Object.MaxSizeBytes);
            }
        }
Exemple #42
0
        public void GetAzureSqlDatabaseServiceObjectiveWithSqlAuth()
        {
            using (System.Management.Automation.PowerShell powershell =
                       System.Management.Automation.PowerShell.Create())
            {
                // Create a context
                NewAzureSqlDatabaseServerContextTests.CreateServerContextSqlAuth(
                    powershell,
                    "$context");

                HttpSession testSession = MockServerHelper.DefaultSessionCollection.GetSession(
                    "UnitTests.GetAzureSqlServiceObjectiveWithSqlAuth");
                DatabaseTestHelper.SetDefaultTestSessionSettings(testSession);
                testSession.RequestValidator =
                    new Action <HttpMessage, HttpMessage.Request>(
                        (expected, actual) =>
                {
                    Assert.AreEqual(expected.RequestInfo.Method, actual.Method);
                    Assert.IsNotNull(actual.UserAgent);
                    switch (expected.Index)
                    {
                    // Request 0-6: Retrieving all (6) ServiceObjectives and DimensionSettings
                    case 0:
                    case 1:
                    case 2:
                    case 3:
                    case 4:
                    case 5:
                    case 6:
                    // Request 7-8: Retrieving Reserved P1 ServiceObjectives and DimensionSettings
                    case 7:
                    case 8:
                        DatabaseTestHelper.ValidateHeadersForODataRequest(
                            expected.RequestInfo,
                            actual);
                        break;

                    default:
                        Assert.Fail("No more requests expected.");
                        break;
                    }
                });
                testSession.ResponseModifier =
                    new Action <HttpMessage>(
                        (message) =>
                {
                    DatabaseTestHelper.FixODataResponseUri(
                        message.ResponseInfo,
                        testSession.ServiceBaseUri,
                        MockHttpServer.DefaultServerPrefixUri);
                });

                using (AsyncExceptionManager exceptionManager = new AsyncExceptionManager())
                {
                    Collection <PSObject> objectives, objective1;
                    using (new MockHttpServer(
                               exceptionManager,
                               MockHttpServer.DefaultServerPrefixUri,
                               testSession))
                    {
                        objectives = powershell.InvokeBatchScript(
                            @"Get-AzureSqlDatabaseServiceObjective " +
                            @"-Context $context");

                        objective1 = powershell.InvokeBatchScript(
                            @"Get-AzureSqlDatabaseServiceObjective " +
                            @"-Context $context " +
                            @"-ServiceObjectiveName ""P1""");
                    }

                    Assert.AreEqual(0, powershell.Streams.Error.Count, "Errors during run!");
                    Assert.AreEqual(0, powershell.Streams.Warning.Count, "Warnings during run!");
                    powershell.Streams.ClearStreams();

                    Assert.AreEqual(6, objectives.Count, "Expecting 6 Objective objects");

                    Assert.IsTrue(
                        objective1.Single().BaseObject is Services.Server.ServiceObjective,
                        "Expecting a ServiceObjective object");
                    Services.Server.ServiceObjective objective1Obj =
                        (Services.Server.ServiceObjective)objective1.Single().BaseObject;
                    Assert.AreEqual("P1", objective1Obj.Name, "Expected objective name to be 'Reserved P1'");
                }
            }
        }
        public void GetRestorableDroppedDatabaseWithSqlAuth()
        {
            using (var powershell = System.Management.Automation.PowerShell.Create())
            {
                // Create a context
                NewAzureSqlDatabaseServerContextTests.CreateServerContextSqlAuth(powershell, "$context");

                var testSession = MockServerHelper.DefaultSessionCollection.GetSession(
                    "UnitTests.GetRestorableDroppedDatabaseWithSqlAuth");
                DatabaseTestHelper.SetDefaultTestSessionSettings(testSession);
                testSession.RequestValidator =
                    new Action<HttpMessage, HttpMessage.Request>(
                        (expected, actual) =>
                        {
                            Assert.AreEqual(expected.RequestInfo.Method, actual.Method);
                            Assert.AreEqual(expected.RequestInfo.UserAgent, actual.UserAgent);
                            if (expected.Index < 3)
                            {
                                DatabaseTestHelper.ValidateHeadersForODataRequest(expected.RequestInfo, actual);
                            }
                            else
                            {
                                Assert.Fail("No more requests expected.");
                            }
                        });

                using (var exceptionManager = new AsyncExceptionManager())
                {
                    Collection<PSObject> databases, database1, database2;
                    using (new MockHttpServer(exceptionManager, MockHttpServer.DefaultServerPrefixUri, testSession))
                    {
                        databases = powershell.InvokeBatchScript(
                            @"Get-AzureSqlDatabase -RestorableDropped " +
                            @"-Context $context");
                    }

                    Assert.AreEqual(0, powershell.Streams.Error.Count, "Errors during run!");
                    Assert.AreEqual(0, powershell.Streams.Warning.Count, "Warnings during run!");
                    powershell.Streams.ClearStreams();

                    // Expecting testdb1, testdb2, possibly dropped databases from previous runs
                    Assert.IsTrue(
                        databases.Count >= 2,
                        "Expecting at-least two RestorableDroppedDatabase objects");

                    Assert.IsTrue(
                        databases[0].BaseObject is RestorableDroppedDatabase,
                        "Expecting a RestorableDroppedDatabase object");

                    Assert.IsTrue(
                        databases[1].BaseObject is RestorableDroppedDatabase,
                        "Expecting a RestorableDroppedDatabase object");

                    var database1Object = (RestorableDroppedDatabase)databases[0].BaseObject;
                    var database1DeletionDate = database1Object.DeletionDate.ToUniversalTime().ToString(deletionDateStringFormat);

                    var database2Object = (RestorableDroppedDatabase)databases[1].BaseObject;
                    var database2DeletionDate = database2Object.DeletionDate.ToUniversalTime().ToString(deletionDateStringFormat);

                    using (new MockHttpServer(
                        exceptionManager, MockHttpServer.DefaultServerPrefixUri, testSession))
                    {
                        database1 = powershell.InvokeBatchScript(
                            @"Get-AzureSqlDatabase -RestorableDropped " +
                            @"-Context $context " +
                            @"-DatabaseName " + database1Object.Name + @" " +
                            @"-DatabaseDeletionDate " + database1DeletionDate);
                        database2 = powershell.InvokeBatchScript(
                            @"Get-AzureSqlDatabase -RestorableDropped " +
                            @"-Context $context " +
                            @"-DatabaseName " + database2Object.Name + @" " +
                            @"-DatabaseDeletionDate " + database2DeletionDate);
                    }

                    Assert.IsTrue(
                        database1.Single().BaseObject is RestorableDroppedDatabase,
                        "Expecting a RestorableDroppedDatabase object");
                    var refreshedDatabase1Object = (RestorableDroppedDatabase)database1.Single().BaseObject;
                    Assert.AreEqual(
                        database1Object.Name, refreshedDatabase1Object.Name,
                        "Expected db name to be " + database1Object.Name);

                    Assert.IsTrue(
                        database2.Single().BaseObject is RestorableDroppedDatabase,
                        "Expecting a RestorableDroppedDatabase object");
                    var refreshedDatabase2Object = (RestorableDroppedDatabase)database2.Single().BaseObject;
                    Assert.AreEqual(
                        database2Object.Name, refreshedDatabase2Object.Name,
                        "Expected db name to be " + database2Object.Name);
                    Assert.AreEqual(
                        database2Object.Edition, refreshedDatabase2Object.Edition,
                        "Expected edition to be " + database2Object.Edition);
                    Assert.AreEqual(
                        database2Object.MaxSizeBytes, refreshedDatabase2Object.MaxSizeBytes,
                        "Expected max size to be " + database2Object.MaxSizeBytes);
                }
            }
        }
Exemple #44
0
        /// <summary>
        /// Helper function to create premium database in the powershell environment provided.
        /// </summary>
        /// <param name="powershell">The powershell environment</param>
        /// <param name="testSession">The test session</param>
        private static void TestCreatePremiumDatabase(System.Management.Automation.PowerShell powershell, HttpSession testSession)
        {
            using (AsyncExceptionManager exceptionManager = new AsyncExceptionManager())
            {
                Collection <PSObject> premiumDB_P1, PremiumDB_P2;
                using (new MockHttpServer(
                           exceptionManager,
                           MockHttpServer.DefaultServerPrefixUri,
                           testSession))
                {
                    powershell.InvokeBatchScript(
                        @"$P1 = Get-AzureSqlDatabaseServiceObjective" +
                        @" -Context $context" +
                        @" -ServiceObjectiveName ""P1""");

                    powershell.InvokeBatchScript(
                        @"$P2 = Get-AzureSqlDatabaseServiceObjective " +
                        @"-Context $context" +
                        @" -ServiceObjectiveName ""P2""");

                    premiumDB_P1 = powershell.InvokeBatchScript(
                        @"$premiumDB_P1 = New-AzureSqlDatabase " +
                        @"-Context $context " +
                        @"-DatabaseName NewAzureSqlPremiumDatabaseTests_P1 " +
                        @"-Edition Premium " +
                        @"-ServiceObjective $P1 ");
                    premiumDB_P1 = powershell.InvokeBatchScript("$PremiumDB_P1");

                    powershell.InvokeBatchScript(
                        @"$PremiumDB_P2 = New-AzureSqlDatabase " +
                        @"-Context $context " +
                        @"-DatabaseName NewAzureSqlPremiumDatabaseTests_P2 " +
                        @"-Collation Japanese_CI_AS " +
                        @"-Edition Premium " +
                        @"-ServiceObjective $P2 " +
                        @"-MaxSizeGB 10 " +
                        @"-Force");
                    PremiumDB_P2 = powershell.InvokeBatchScript("$PremiumDB_P2");
                }

                Assert.AreEqual(0, powershell.Streams.Error.Count, "Errors during run!");
                Assert.AreEqual(0, powershell.Streams.Warning.Count, "Warnings during run!");
                powershell.Streams.ClearStreams();

                Assert.IsTrue(
                    premiumDB_P1.Single().BaseObject is Services.Server.Database,
                    "Expecting a Database object");
                Services.Server.Database databaseP1 =
                    (Services.Server.Database)premiumDB_P1.Single().BaseObject;
                Assert.AreEqual("NewAzureSqlPremiumDatabaseTests_P1", databaseP1.Name, "Expected db name to be NewAzureSqlPremiumDatabaseTests_P1");

                Assert.IsTrue(
                    PremiumDB_P2.Single().BaseObject is Services.Server.Database,
                    "Expecting a Database object");
                Services.Server.Database databaseP2 =
                    (Services.Server.Database)PremiumDB_P2.Single().BaseObject;
                Assert.AreEqual("NewAzureSqlPremiumDatabaseTests_P2", databaseP2.Name, "Expected db name to be NewAzureSqlPremiumDatabaseTests_P2");

                Assert.AreEqual(
                    "Japanese_CI_AS",
                    databaseP2.CollationName,
                    "Expected collation to be Japanese_CI_AS");
                Assert.AreEqual("Premium", databaseP2.Edition, "Expected edition to be Premium");
                Assert.AreEqual(10, databaseP2.MaxSizeGB, "Expected max size to be 10 GB");
            }
        }
        public void NewAzureSqlDatabaseServerContextWithSqlAuth()
        {
            // Create standard context with both ManageUrl and ServerName overridden
            using (System.Management.Automation.PowerShell powershell =
                System.Management.Automation.PowerShell.Create())
            {
                NewAzureSqlDatabaseServerContextTests.CreateServerContextSqlAuth(
                    powershell,
                    "$context");
            }

            // Create context with just ManageUrl and a derived servername
            HttpSession testSession = DatabaseTestHelper.DefaultSessionCollection.GetSession(
                "UnitTests.NewAzureSqlDatabaseServerContextWithSqlAuthDerivedName");
            using (System.Management.Automation.PowerShell powershell =
                System.Management.Automation.PowerShell.Create())
            {
                UnitTestHelper.ImportSqlDatabaseModule(powershell);
                UnitTestHelper.CreateTestCredential(powershell);

                using (AsyncExceptionManager exceptionManager = new AsyncExceptionManager())
                {
                    Collection<PSObject> serverContext;
                    using (new MockHttpServer(
                        exceptionManager,
                        MockHttpServer.DefaultServerPrefixUri,
                        testSession))
                    {
                        serverContext = powershell.InvokeBatchScript(
                            string.Format(
                                CultureInfo.InvariantCulture,
                                @"$context = New-AzureSqlDatabaseServerContext " +
                                @"-ManageUrl {0} " +
                                @"-Credential $credential",
                                MockHttpServer.DefaultServerPrefixUri.AbsoluteUri),
                            @"$context");
                    }

                    Assert.AreEqual(0, powershell.Streams.Error.Count, "Errors during run!");
                    powershell.Streams.ClearStreams();

                    PSObject contextPsObject = serverContext.Single();
                    Assert.IsTrue(
                        contextPsObject.BaseObject is ServerDataServiceSqlAuth,
                        "Expecting a ServerDataServiceSqlAuth object");
                }
            }
        }
Exemple #46
0
        public void GetAzureSqlDatabaseWithSqlAuth()
        {
            using (System.Management.Automation.PowerShell powershell =
                       System.Management.Automation.PowerShell.Create())
            {
                // Create a context
                NewAzureSqlDatabaseServerContextTests.CreateServerContextSqlAuth(
                    powershell,
                    "$context");

                // Query the created test databases
                HttpSession testSession = DatabaseTestHelper.DefaultSessionCollection.GetSession(
                    "UnitTests.GetAzureSqlDatabaseWithSqlAuth");
                DatabaseTestHelper.SetDefaultTestSessionSettings(testSession);
                testSession.RequestValidator =
                    new Action <HttpMessage, HttpMessage.Request>(
                        (expected, actual) =>
                {
                    Assert.AreEqual(expected.RequestInfo.Method, actual.Method);
                    Assert.AreEqual(expected.RequestInfo.UserAgent, actual.UserAgent);
                    switch (expected.Index)
                    {
                    // Request 0-3: Get all databases + ServiceObjective lookup for each database
                    case 0:
                    case 1:
                    case 2:
                    case 3:
                    // Request 4-7: Get database requests, 2 requests per get
                    case 4:
                    case 5:
                    case 6:
                    case 7:
                        DatabaseTestHelper.ValidateHeadersForODataRequest(
                            expected.RequestInfo,
                            actual);
                        break;

                    default:
                        Assert.Fail("No more requests expected.");
                        break;
                    }
                });

                using (AsyncExceptionManager exceptionManager = new AsyncExceptionManager())
                {
                    Collection <PSObject> databases, database1, database2;
                    using (new MockHttpServer(
                               exceptionManager,
                               MockHttpServer.DefaultServerPrefixUri,
                               testSession))
                    {
                        databases = powershell.InvokeBatchScript(
                            @"Get-AzureSqlDatabase " +
                            @"-Context $context");
                        database1 = powershell.InvokeBatchScript(
                            @"Get-AzureSqlDatabase " +
                            @"-Context $context " +
                            @"-DatabaseName testdb1");
                        database2 = powershell.InvokeBatchScript(
                            @"Get-AzureSqlDatabase " +
                            @"-Context $context " +
                            @"-DatabaseName testdb2");
                    }

                    Assert.AreEqual(0, powershell.Streams.Error.Count, "Errors during run!");
                    Assert.AreEqual(0, powershell.Streams.Warning.Count, "Warnings during run!");
                    powershell.Streams.ClearStreams();

                    // Expecting master, testdb1, testdb2
                    Assert.AreEqual(
                        3,
                        databases.Count,
                        "Expecting three Database objects");

                    Assert.IsTrue(
                        database1.Single().BaseObject is Services.Server.Database,
                        "Expecting a Database object");
                    Services.Server.Database database1Obj =
                        (Services.Server.Database)database1.Single().BaseObject;
                    Assert.AreEqual(
                        "testdb1",
                        database1Obj.Name,
                        "Expected db name to be testdb1");

                    Assert.IsTrue(
                        database2.Single().BaseObject is Services.Server.Database,
                        "Expecting a Database object");
                    Services.Server.Database database2Obj =
                        (Services.Server.Database)database2.Single().BaseObject;
                    Assert.AreEqual(
                        "testdb2",
                        database2Obj.Name,
                        "Expected db name to be testdb2");
                    Assert.AreEqual(
                        "Japanese_CI_AS",
                        database2Obj.CollationName,
                        "Expected collation to be Japanese_CI_AS");
                    Assert.AreEqual("Web", database2Obj.Edition, "Expected edition to be Web");
                    Assert.AreEqual(5, database2Obj.MaxSizeGB, "Expected max size to be 5 GB");
                }
            }
        }
        /// <summary>
        /// Common helper method for other tests to create a context.
        /// </summary>
        /// <param name="contextVariable">The variable name that will hold the new context.</param>
        public static void CreateServerContextSqlAuth(
            System.Management.Automation.PowerShell powershell,
            string contextVariable)
        {
            HttpSession testSession = DatabaseTestHelper.DefaultSessionCollection.GetSession(
                "UnitTest.Common.NewAzureSqlDatabaseServerContextWithSqlAuth");
            DatabaseTestHelper.SetDefaultTestSessionSettings(testSession);
            testSession.RequestValidator =
                new Action<HttpMessage, HttpMessage.Request>(
                (expected, actual) =>
                {
                    Assert.AreEqual(expected.RequestInfo.Method, actual.Method);
                    Assert.AreEqual(expected.RequestInfo.UserAgent, actual.UserAgent);
                    switch (expected.Index)
                    {
                        // Request 0-2: Create context with both ManageUrl and ServerName overriden
                        case 0:
                            // GetAccessToken call
                            DatabaseTestHelper.ValidateGetAccessTokenRequest(
                                expected.RequestInfo,
                                actual);
                            break;
                        case 1:
                            // Get server call
                            DatabaseTestHelper.ValidateHeadersForODataRequest(
                                expected.RequestInfo,
                                actual);
                            break;
                        case 2:
                            // $metadata call
                            Assert.IsTrue(
                                actual.RequestUri.AbsoluteUri.EndsWith("$metadata"),
                                "Incorrect Uri specified for $metadata");
                            DatabaseTestHelper.ValidateHeadersForServiceRequest(
                                expected.RequestInfo,
                                actual);
                            Assert.AreEqual(
                                expected.RequestInfo.Headers[DataServiceConstants.AccessTokenHeader],
                                actual.Headers[DataServiceConstants.AccessTokenHeader],
                                "AccessToken header does not match");
                            Assert.AreEqual(
                                expected.RequestInfo.Cookies[DataServiceConstants.AccessCookie],
                                actual.Cookies[DataServiceConstants.AccessCookie],
                                "AccessCookie does not match");
                            break;
                        default:
                            Assert.Fail("No more requests expected.");
                            break;
                    }
                });

            UnitTestHelper.ImportSqlDatabaseModule(powershell);
            UnitTestHelper.CreateTestCredential(powershell);

            Collection<PSObject> serverContext;
            using (AsyncExceptionManager exceptionManager = new AsyncExceptionManager())
            {
                using (new MockHttpServer(
                    exceptionManager,
                    MockHttpServer.DefaultServerPrefixUri,
                    testSession))
                {
                    serverContext = powershell.InvokeBatchScript(
                        string.Format(
                            CultureInfo.InvariantCulture,
                            @"{1} = New-AzureSqlDatabaseServerContext " +
                            @"-ServerName testserver " +
                            @"-ManageUrl {0} " +
                            @"-Credential $credential",
                            MockHttpServer.DefaultServerPrefixUri.AbsoluteUri,
                            contextVariable),
                        contextVariable);
                }
            }

            Assert.AreEqual(0, powershell.Streams.Error.Count, "Errors during run!");
            Assert.AreEqual(0, powershell.Streams.Warning.Count, "Warnings during run!");
            powershell.Streams.ClearStreams();

            PSObject contextPsObject = serverContext.Single();
            Assert.IsTrue(
                contextPsObject.BaseObject is ServerDataServiceSqlAuth,
                "Expecting a ServerDataServiceSqlAuth object");
        }
Exemple #48
0
        public void NewAzureSqlDatabaseServerContextWithSqlAuthNegativeCases()
        {
            HttpSession testSession = DatabaseTestHelper.DefaultSessionCollection.GetSession(
                "UnitTests.NewAzureSqlDatabaseServerContextWithSqlAuthNegativeCases");

            using (System.Management.Automation.PowerShell powershell =
                       System.Management.Automation.PowerShell.Create())
            {
                UnitTestHelper.ImportSqlDatabaseModule(powershell);
                UnitTestHelper.CreateTestCredential(powershell);

                using (AsyncExceptionManager exceptionManager = new AsyncExceptionManager())
                {
                    // Test warning when different $metadata is received.
                    Collection <PSObject> serverContext;
                    using (new MockHttpServer(
                               exceptionManager,
                               MockHttpServer.DefaultServerPrefixUri,
                               testSession))
                    {
                        serverContext = powershell.InvokeBatchScript(
                            string.Format(
                                CultureInfo.InvariantCulture,
                                @"$context = New-AzureSqlDatabaseServerContext " +
                                @"-ServerName testserver " +
                                @"-ManageUrl {0} " +
                                @"-Credential $credential",
                                MockHttpServer.DefaultServerPrefixUri.AbsoluteUri),
                            @"$context");
                    }

                    Assert.AreEqual(0, powershell.Streams.Error.Count, "Errors during run!");
                    Assert.AreEqual(1, powershell.Streams.Warning.Count, "Should have warning!");
                    Assert.AreEqual(
                        Resources.WarningModelOutOfDate,
                        powershell.Streams.Warning.First().Message);
                    powershell.Streams.ClearStreams();

                    PSObject contextPsObject = serverContext.Single();
                    Assert.IsTrue(
                        contextPsObject.BaseObject is ServerDataServiceSqlAuth,
                        "Expecting a ServerDataServiceSqlAuth object");

                    // Test error case
                    using (new MockHttpServer(
                               exceptionManager,
                               MockHttpServer.DefaultServerPrefixUri,
                               testSession))
                    {
                        powershell.InvokeBatchScript(
                            string.Format(
                                CultureInfo.InvariantCulture,
                                @"$context = New-AzureSqlDatabaseServerContext " +
                                @"-ServerName testserver " +
                                @"-ManageUrl {0} " +
                                @"-Credential $credential",
                                MockHttpServer.DefaultServerPrefixUri.AbsoluteUri),
                            @"$context");
                    }

                    Assert.AreEqual(1, powershell.Streams.Error.Count, "Should have errors!");
                    Assert.AreEqual(2, powershell.Streams.Warning.Count, "Should have warning!");
                    Assert.AreEqual(
                        "Test error message",
                        powershell.Streams.Error.First().Exception.Message);
                    Assert.IsTrue(
                        powershell.Streams.Warning.Any(
                            (w) => w.Message.StartsWith("Client Session Id:")),
                        "Client session Id not written to warning");
                    Assert.IsTrue(
                        powershell.Streams.Warning.Any(
                            (w) => w.Message.StartsWith("Client Request Id:")),
                        "Client request Id not written to warning");
                    powershell.Streams.ClearStreams();
                }
            }
        }
        public void InitializeTest()
        {
            TestStartTime = DateTime.Now;

            // This test uses the https endpoint, setup the certificates.
            MockHttpServer.SetupCertificates();
            PowerShell = PowerShell.Create();
            Subscription = UnitTestHelper.SetupUnitTestSubscription(PowerShell);

            // Set names for the servers we'll use in PowerShell.
            PowerShell.Runspace.SessionStateProxy.SetVariable(
                "homeServerName", HomeServer);

            PowerShell.Runspace.SessionStateProxy.SetVariable(
                "partnerServerName", PartnerServer);

            // Create a new server
            HttpSession testSession = MockServerHelper.DefaultSessionCollection.GetSession(
                string.Format("UnitTest.{0}.{1}", TestContext.FullyQualifiedTestClassName, TestContext.TestName));

            ServerTestHelper.SetDefaultTestSessionSettings(testSession);

            // When testing production use RDFE
            // testSession.ServiceBaseUri = new Uri("https://management.core.windows.net");
            // When testing OneBox use Mock RDFE:
            if (IsRunningAgainstOneBox)
            {
                testSession.ServiceBaseUri = new Uri("https://management.dev.mscds.com:12346/");
            }

            testSession.RequestValidator =
                new Action<HttpMessage, HttpMessage.Request>(
                (expected, actual) =>
                {
                    Assert.AreEqual(expected.RequestInfo.Method, actual.Method);
                    Assert.IsTrue(
                        actual.UserAgent.Contains(ApiConstants.UserAgentHeaderValue),
                        "Missing proper UserAgent string.");
                    Assert.IsTrue(
                        UnitTestHelper.GetUnitTestClientCertificate().Equals(actual.Certificate),
                        "Expected correct client certificate");
                });

            ExceptionManager = new AsyncExceptionManager();
            MockHttpServer = new MockHttpServer(ExceptionManager, MockHttpServer.DefaultHttpsServerPrefixUri,
                                                testSession);
        }
Exemple #50
0
        /// <summary>
        /// Common helper method for other tests to create a context.
        /// </summary>
        /// <param name="contextVariable">The variable name that will hold the new context.</param>
        public static void CreateServerContextSqlAuth(
            System.Management.Automation.PowerShell powershell,
            string contextVariable)
        {
            HttpSession testSession = DatabaseTestHelper.DefaultSessionCollection.GetSession(
                "UnitTest.Common.NewAzureSqlDatabaseServerContextWithSqlAuth");

            DatabaseTestHelper.SetDefaultTestSessionSettings(testSession);
            testSession.RequestValidator =
                new Action <HttpMessage, HttpMessage.Request>(
                    (expected, actual) =>
            {
                Assert.AreEqual(expected.RequestInfo.Method, actual.Method);
                Assert.AreEqual(expected.RequestInfo.UserAgent, actual.UserAgent);
                switch (expected.Index)
                {
                // Request 0-2: Create context with both ManageUrl and ServerName overriden
                case 0:
                    // GetAccessToken call
                    DatabaseTestHelper.ValidateGetAccessTokenRequest(
                        expected.RequestInfo,
                        actual);
                    break;

                case 1:
                    // Get server call
                    DatabaseTestHelper.ValidateHeadersForODataRequest(
                        expected.RequestInfo,
                        actual);
                    break;

                case 2:
                    // $metadata call
                    Assert.IsTrue(
                        actual.RequestUri.AbsoluteUri.EndsWith("$metadata"),
                        "Incorrect Uri specified for $metadata");
                    DatabaseTestHelper.ValidateHeadersForServiceRequest(
                        expected.RequestInfo,
                        actual);
                    Assert.AreEqual(
                        expected.RequestInfo.Headers[DataServiceConstants.AccessTokenHeader],
                        actual.Headers[DataServiceConstants.AccessTokenHeader],
                        "AccessToken header does not match");
                    Assert.AreEqual(
                        expected.RequestInfo.Cookies[DataServiceConstants.AccessCookie],
                        actual.Cookies[DataServiceConstants.AccessCookie],
                        "AccessCookie does not match");
                    break;

                default:
                    Assert.Fail("No more requests expected.");
                    break;
                }
            });

            UnitTestHelper.ImportSqlDatabaseModule(powershell);
            UnitTestHelper.CreateTestCredential(
                powershell,
                testSession.SessionProperties["Username"],
                testSession.SessionProperties["Password"]);

            Collection <PSObject> serverContext;

            using (AsyncExceptionManager exceptionManager = new AsyncExceptionManager())
            {
                using (new MockHttpServer(
                           exceptionManager,
                           MockHttpServer.DefaultServerPrefixUri,
                           testSession))
                {
                    serverContext = powershell.InvokeBatchScript(
                        string.Format(
                            CultureInfo.InvariantCulture,
                            @"{1} = New-AzureSqlDatabaseServerContext " +
                            @"-ServerName {2} " +
                            @"-ManageUrl {0} " +
                            @"-Credential $credential",
                            MockHttpServer.DefaultServerPrefixUri.AbsoluteUri,
                            contextVariable,
                            testSession.SessionProperties["Servername"]),
                        contextVariable);
                }
            }

            Assert.AreEqual(0, powershell.Streams.Error.Count, "Errors during run!");
            Assert.AreEqual(0, powershell.Streams.Warning.Count, "Warnings during run!");
            powershell.Streams.ClearStreams();

            PSObject contextPsObject = serverContext.Single();

            Assert.IsTrue(
                contextPsObject.BaseObject is ServerDataServiceSqlAuth,
                "Expecting a ServerDataServiceSqlAuth object");
        }
        public void SetAzureSqlDatabaseNameWithSqlAuth()
        {
            using (System.Management.Automation.PowerShell powershell =
                System.Management.Automation.PowerShell.Create())
            {
                // Create a context
                NewAzureSqlDatabaseServerContextTests.CreateServerContextSqlAuth(
                    powershell,
                    "$context");
                NewAzureSqlDatabaseServerContextTests.CreateServerContextSqlAuth(
                    powershell,
                    "$contextCleanup");

                HttpSession testSession = MockServerHelper.DefaultSessionCollection.GetSession(
                    "UnitTests.SetAzureSqlDatabaseNameWithSqlAuth");
                DatabaseTestHelper.SetDefaultTestSessionSettings(testSession);
                testSession.RequestValidator =
                    new Action<HttpMessage, HttpMessage.Request>(
                    (expected, actual) =>
                    {
                        Assert.AreEqual(expected.RequestInfo.Method, actual.Method);
                        Assert.AreEqual(expected.RequestInfo.UserAgent, actual.UserAgent);
                        if (expected.Index < 10)
                        {
                            // Request 0-4: Set testdb1 with new name of new_testdb1
                            // Request 5-9: Set new_testdb1 with new name of testdb1
                            DatabaseTestHelper.ValidateHeadersForODataRequest(
                                expected.RequestInfo,
                                actual);
                        }
                        else
                        {
                            Assert.Fail("No more requests expected.");
                        }
                    });

                using (AsyncExceptionManager exceptionManager = new AsyncExceptionManager())
                {
                    // Create context with both ManageUrl and ServerName overriden
                    Collection<PSObject> database;
                    using (new MockHttpServer(
                        exceptionManager,
                        MockHttpServer.DefaultServerPrefixUri,
                        testSession))
                    {
                        database = powershell.InvokeBatchScript(
                           @"Set-AzureSqlDatabase " +
                           @"-Context $context " +
                           @"-DatabaseName testdb1 " +
                           @"-NewName new_testdb1 " +
                           @"-Force " +
                           @"-PassThru");
                        powershell.InvokeBatchScript(
                           @"Set-AzureSqlDatabase " +
                           @"-Context $contextCleanup " +
                           @"-DatabaseName new_testdb1 " +
                           @"-NewName testdb1 " +
                           @"-Force");
                    }

                    Assert.AreEqual(0, powershell.Streams.Error.Count, "Errors during run!");
                    Assert.AreEqual(0, powershell.Streams.Warning.Count, "Warnings during run!");
                    powershell.Streams.ClearStreams();

                    Services.Server.Database databaseObj = database.Single().BaseObject as Services.Server.Database;
                    Assert.IsNotNull(databaseObj, "Expecting a Database object");
                    DatabaseTestHelper.ValidateDatabaseProperties(databaseObj, "new_testdb1", "Web", 1, 1073741824L, "SQL_Latin1_General_CP1_CI_AS", "Shared", false, DatabaseTestHelper.SharedSloGuid);
                }
            }
        }
        public void SetAzureSqlPremiumDatabaseServiceObjectiveWithSqlAuth()
        {
            using (System.Management.Automation.PowerShell powershell =
                System.Management.Automation.PowerShell.Create())
            {
                // Create a context
                NewAzureSqlDatabaseServerContextTests.CreateServerContextSqlAuth(
                    powershell,
                    "$context");
                HttpSession testSession = MockServerHelper.DefaultSessionCollection.GetSession(
                    "UnitTests.SetAzureSqlPremiumDatabaseServiceObjectiveWithSqlAuth");
                DatabaseTestHelper.SetDefaultTestSessionSettings(testSession);                

                using (AsyncExceptionManager exceptionManager = new AsyncExceptionManager())
                {
                    // Create context with both ManageUrl and ServerName overriden
                    Collection<PSObject> premiumDB;
                    using (new MockHttpServer(
                        exceptionManager,
                        MockHttpServer.DefaultServerPrefixUri,
                        testSession))
                    {
                        powershell.InvokeBatchScript(
                            @"$P1 = Get-AzureSqlDatabaseServiceObjective" +
                            @" -Context $context" +
                            @" -ServiceObjectiveName ""P1""");

                        powershell.InvokeBatchScript(
                            @"$premiumDB_P1 = New-AzureSqlDatabase " +
                            @"-Context $context " +
                            @"-DatabaseName SetAzureSqlPremiumDatabaseTests_P1 " +
                            @"-Edition Premium " +
                            @"-ServiceObjective $P1 ");

                        premiumDB = powershell.InvokeBatchScript(
                            @"Set-AzureSqlDatabase " +
                            @"-Context $context " +
                            @"-DatabaseName SetAzureSqlPremiumDatabaseTests_P1 " +
                            @"-Edition Business " +
                            @"-Force " +
                            @"-PassThru");

                        powershell.InvokeBatchScript(
                            @"Remove-AzureSqlDatabase " +
                            @"-Context $context " +
                            @"-DatabaseName SetAzureSqlPremiumDatabaseTests_P1 " +
                            @"-Force ");
                    }

                    Assert.AreEqual(0, powershell.Streams.Error.Count, "Errors during run!");
                    Assert.AreEqual(0, powershell.Streams.Warning.Count, "Warnings during run!");
                    powershell.Streams.ClearStreams();


                    Services.Server.Database premiumDBObj = premiumDB.Single().BaseObject as Services.Server.Database;
                    Assert.IsNotNull(premiumDBObj, "Expecting a Database object");

                    DatabaseTestHelper.ValidateDatabaseProperties(premiumDBObj, "SetAzureSqlPremiumDatabaseTests_P1", "Premium", 10, 10737418240L, "SQL_Latin1_General_CP1_CI_AS", "P1", false, DatabaseTestHelper.PremiumP1SloGuid);
                }
            }
        }
Exemple #53
0
        public void GetAzureSqlDatabaseOperationWithSqlAuth()
        {
            using (System.Management.Automation.PowerShell powershell =
                       System.Management.Automation.PowerShell.Create())
            {
                NewAzureSqlDatabaseServerContextTests.CreateServerContextSqlAuth(
                    powershell,
                    "$context");
                HttpSession testSession = MockServerHelper.DefaultSessionCollection.GetSession(
                    "UnitTest.Common.GetAzureSqlDatabaseOperationWithSqlAuth");
                DatabaseTestHelper.SetDefaultTestSessionSettings(testSession);
                testSession.RequestValidator =
                    new Action <HttpMessage, HttpMessage.Request>(
                        (expected, actual) =>
                {
                    Assert.AreEqual(expected.RequestInfo.Method, actual.Method);
                    Assert.AreEqual(expected.RequestInfo.UserAgent, actual.UserAgent);
                    switch (expected.Index)
                    {
                    // Request 0-7: Create and Query $testdb
                    case 0:
                    case 1:
                    case 2:
                    case 3:
                    case 4:
                    case 5:
                    case 6:
                    case 7:
                    // Request 8: Delete $testdb
                    case 8:
                    // Request 9-11: Query Database Operations
                    case 9:
                    case 10:
                    case 11:
                        DatabaseTestHelper.ValidateHeadersForODataRequest(
                            expected.RequestInfo,
                            actual);
                        break;

                    default:
                        Assert.Fail("No more requests expected.");
                        break;
                    }
                });

                using (AsyncExceptionManager exceptionManager = new AsyncExceptionManager())
                {
                    // There is a known issue about the Get-AzureSqlDatabaseOperation that it returns all
                    // operations which has the required database name no matter it's been deleted and recreated.
                    // So when run it against the mock session, please use the hard coded testsDBName.
                    // Run against onebox, please use the one with NewGuid().
                    // This unit test should be updated once that behavior get changed which was already been
                    // created as a task.

                    // string testsDBName = string.Format("getAzureSqlDatabaseOperationTestsDB_{0}",
                    //     Guid.NewGuid().ToString());
                    string testsDBName = "getAzureSqlDatabaseOperationTestsDB_08ebd7c9-bfb7-426a-9e2f-9921999567e1";
                    Collection <PSObject> database, operationsByName, operationsByDatabase, operationsById;
                    using (new MockHttpServer(
                               exceptionManager,
                               MockHttpServer.DefaultServerPrefixUri,
                               testSession))
                    {
                        database = powershell.InvokeBatchScript(
                            string.Format(
                                @"$testdb = New-AzureSqlDatabase " +
                                @"-Context $context " +
                                @"-DatabaseName {0} " +
                                @"-Force", testsDBName),
                            @"$testdb");

                        powershell.InvokeBatchScript(
                            string.Format(
                                @"Remove-AzureSqlDatabase " +
                                @"-Context $context " +
                                @"-DatabaseName {0} " +
                                @"-Force", testsDBName));

                        operationsByName = powershell.InvokeBatchScript(
                            string.Format(
                                @"$operations = Get-AzureSqlDatabaseOperation " +
                                @"-ConnectionContext $context " +
                                @"-DatabaseName {0}",
                                testsDBName),
                            @"$operations");

                        operationsByDatabase = powershell.InvokeBatchScript(
                            @"Get-AzureSqlDatabaseOperation " +
                            @"-ConnectionContext $context " +
                            @"-Database $testdb");

                        operationsById = powershell.InvokeBatchScript(
                            @"Get-AzureSqlDatabaseOperation " +
                            @"-ConnectionContext $context " +
                            @"-OperationGuid $operations[0].Id"
                            );
                    }

                    Assert.AreEqual(0, powershell.Streams.Error.Count, "Errors during run!");
                    Assert.AreEqual(0, powershell.Streams.Warning.Count, "Warnings during run!");
                    powershell.Streams.ClearStreams();

                    VerifyGetOperationsResult(testsDBName, operationsByName);
                    VerifyGetOperationsResult(testsDBName, operationsByDatabase);
                    // Update this verification once Task 1615375:Adding Drop record in dm_operation_status resolved
                    VerifyGetOperationsResult(testsDBName, operationsById);
                }
            }
        }
Exemple #54
0
        public void GetRestorableDroppedDatabaseWithSqlAuthNonExistentDb()
        {
            using (var powershell = System.Management.Automation.PowerShell.Create())
            {
                // Create a context
                NewAzureSqlDatabaseServerContextTests.CreateServerContextSqlAuth(powershell, "$context");

                var testSession = MockServerHelper.DefaultSessionCollection.GetSession(
                    "UnitTests.GetRestorableDroppedDatabaseWithSqlAuthNonExistentDb");
                DatabaseTestHelper.SetDefaultTestSessionSettings(testSession);
                testSession.RequestValidator =
                    new Action <HttpMessage, HttpMessage.Request>(
                        (expected, actual) =>
                {
                    Assert.AreEqual(expected.RequestInfo.Method, actual.Method);
                    Assert.AreEqual(expected.RequestInfo.UserAgent, actual.UserAgent);
                    if (expected.Index < 1)
                    {
                        DatabaseTestHelper.ValidateHeadersForODataRequest(expected.RequestInfo, actual);
                    }
                    else
                    {
                        Assert.Fail("No more requests expected.");
                    }
                });

                using (var exceptionManager = new AsyncExceptionManager())
                {
                    using (new MockHttpServer(
                               exceptionManager, MockHttpServer.DefaultServerPrefixUri, testSession))
                    {
                        powershell.InvokeBatchScript(
                            @"Get-AzureSqlDatabase -RestorableDropped " +
                            @"-Context $context " +
                            @"-DatabaseName testdbnonexistent " +
                            @"-DatabaseDeletionDate '10/01/2013 12:00:00 AM'");
                    }

                    Assert.AreEqual(
                        1, powershell.Streams.Error.Count,
                        "Expecting errors");
                    Assert.AreEqual(
                        2, powershell.Streams.Warning.Count,
                        "Expecting tracing IDs");
                    Assert.AreEqual(
                        string.Format(
                            CultureInfo.InvariantCulture,
                            "Database '{0}' with deletion date '{1}' not found.",
                            testSession.SessionProperties["Servername"] + ".testdbnonexistent",
                            new DateTime(2013, 10, 01, 0, 0, 0, DateTimeKind.Utc)),
                        powershell.Streams.Error.First().Exception.Message,
                        "Unexpected error message");
                    Assert.IsTrue(
                        powershell.Streams.Warning.Any(w => w.Message.StartsWith("Client Session Id")),
                        "Expecting Client Session Id");
                    Assert.IsTrue(
                        powershell.Streams.Warning.Any(w => w.Message.StartsWith("Client Request Id")),
                        "Expecting Client Request Id");
                }
            }
        }
        public void SetAzureSqlDatabaseServiceObjectiveWithSqlAuth()
        {
            using (System.Management.Automation.PowerShell powershell =
                System.Management.Automation.PowerShell.Create())
            {
                // Create a context
                NewAzureSqlDatabaseServerContextTests.CreateServerContextSqlAuth(
                    powershell,
                    "$context");

                HttpSession testSession = MockServerHelper.DefaultSessionCollection.GetSession(
                    "UnitTests.SetAzureSqlDatabaseServiceObjectiveWithSqlAuth");
                DatabaseTestHelper.SetDefaultTestSessionSettings(testSession);
                testSession.RequestValidator =
                    new Action<HttpMessage, HttpMessage.Request>(
                    (expected, actual) =>
                    {
                        Assert.AreEqual(expected.RequestInfo.Method, actual.Method);
                        Assert.AreEqual(expected.RequestInfo.UserAgent, actual.UserAgent);
                        switch (expected.Index)
                        {
                            // Request 0-1: Get Service Objective
                            case 0:
                            case 1:
                            // Request 2-7: Get/Update/Re-Get testdb2
                            case 2:
                            case 3:
                            case 4:
                            case 5:
                            case 6:
                                DatabaseTestHelper.ValidateHeadersForODataRequest(
                                    expected.RequestInfo,
                                    actual);
                                break;
                            default:
                                Assert.Fail("No more requests expected.");
                                break;
                        }
                    });

                using (AsyncExceptionManager exceptionManager = new AsyncExceptionManager())
                {
                    // Create context with both ManageUrl and ServerName overriden
                    Collection<PSObject> database;
                    using (new MockHttpServer(
                        exceptionManager,
                        MockHttpServer.DefaultServerPrefixUri,
                        testSession))
                    {
                        powershell.InvokeBatchScript(
                            @"$slo = Get-AzureSqlDatabaseServiceObjective " +
                            @"-Context $context " +
                            @"-ServiceObjectiveName ""P1""");

                        database = powershell.InvokeBatchScript(
                            @"Set-AzureSqlDatabase " +
                            @"-Context $context " +
                            @"-DatabaseName testdb2 " +
                            @"-ServiceObjective $slo " +
                            @"-Force " +
                            @"-PassThru");
                    }

                    Assert.AreEqual(0, powershell.Streams.Error.Count, "Errors during run!");
                    Assert.AreEqual(0, powershell.Streams.Warning.Count, "Warnings during run!");
                    powershell.Streams.ClearStreams();

                    Services.Server.Database databaseObj = database.Single().BaseObject as Services.Server.Database;
                    Assert.IsNotNull(databaseObj, "Expecting a Database object");
                    Assert.AreEqual("testdb2", databaseObj.Name, "Expected db name to be testdb2");
                    Assert.AreEqual((byte)0, databaseObj.ServiceObjectiveAssignmentState, "Expected assignment state to be complete");
                    DatabaseTestHelper.ValidateDatabaseProperties(databaseObj, "testdb2", "Web", 5, 5368709120L, "Japanese_CI_AS", "Shared", false, DatabaseTestHelper.PremiumP1SloGuid);
                }
            }
        }
        public void GetAzureSqlDatabaseWithSqlAuthByPipe()
        {
            using (System.Management.Automation.PowerShell powershell =
                       System.Management.Automation.PowerShell.Create())
            {
                // Create a context
                NewAzureSqlDatabaseServerContextTests.CreateServerContextSqlAuth(
                    powershell,
                    "$context");

                // Query the created test databases
                HttpSession testSession = MockServerHelper.DefaultSessionCollection.GetSession(
                    "UnitTests.GetAzureSqlDatabaseWithSqlAuthByPipe");
                DatabaseTestHelper.SetDefaultTestSessionSettings(testSession);
                testSession.RequestValidator =
                    new Action <HttpMessage, HttpMessage.Request>(
                        (expected, actual) =>
                {
                    Assert.AreEqual(expected.RequestInfo.Method, actual.Method);
                    Assert.IsNotNull(actual.UserAgent);
                    if (expected.Index < 12)
                    {
                        // Request 0-3: Get all databases + ServiceObjectives requests
                        // Request 4-11: 4 Get databases, 2 requests per get call
                        DatabaseTestHelper.ValidateHeadersForODataRequest(
                            expected.RequestInfo,
                            actual);
                    }
                    else
                    {
                        Assert.Fail("No more requests expected.");
                    }
                });

                using (AsyncExceptionManager exceptionManager = new AsyncExceptionManager())
                {
                    Collection <PSObject> databases, database1, database2;
                    using (new MockHttpServer(
                               exceptionManager,
                               MockHttpServer.DefaultServerPrefixUri,
                               testSession))
                    {
                        databases = powershell.InvokeBatchScript(
                            @"Get-AzureSqlDatabase " +
                            @"-Context $context");
                        powershell.InvokeBatchScript(
                            @"$testdb1 = Get-AzureSqlDatabase $context -DatabaseName testdb1");
                        powershell.InvokeBatchScript(
                            @"$testdb2 = Get-AzureSqlDatabase $context -DatabaseName testdb2");
                        database1 = powershell.InvokeBatchScript(
                            @"$testdb1 | Get-AzureSqlDatabase");
                        database2 = powershell.InvokeBatchScript(
                            @"$testdb2 | Get-AzureSqlDatabase");
                    }

                    Assert.AreEqual(0, powershell.Streams.Error.Count, "Errors during run!");
                    Assert.AreEqual(0, powershell.Streams.Warning.Count, "Warnings during run!");
                    powershell.Streams.ClearStreams();

                    // Expecting master, testdb1, testdb2
                    Assert.AreEqual(
                        3,
                        databases.Count,
                        "Expecting three Database objects");

                    Services.Server.Database database1Obj = database1.Single().BaseObject as Services.Server.Database;
                    Assert.IsNotNull(database1Obj, "Expecting a Database object");
                    DatabaseTestHelper.ValidateDatabaseProperties(database1Obj, "testdb1", "Web", 1, 1073741824L, "SQL_Latin1_General_CP1_CI_AS", "Shared", false, DatabaseTestHelper.SharedSloGuid);

                    Services.Server.Database database2Obj = database2.Single().BaseObject as Services.Server.Database;
                    Assert.IsNotNull(database2Obj, "Expecting a Database object");
                    DatabaseTestHelper.ValidateDatabaseProperties(database2Obj, "testdb2", "Web", 5, 5368709120L, "Japanese_CI_AS", "Shared", false, DatabaseTestHelper.SharedSloGuid);
                }
            }
        }
        public void SetAzureSqlDatabaseSizeWithSqlAuth()
        {
            using (System.Management.Automation.PowerShell powershell =
                System.Management.Automation.PowerShell.Create())
            {
                // Create a context
                NewAzureSqlDatabaseServerContextTests.CreateServerContextSqlAuth(
                    powershell,
                    "$context");

                HttpSession testSession = MockServerHelper.DefaultSessionCollection.GetSession(
                    "UnitTests.SetAzureSqlDatabaseSizeWithSqlAuth");
                DatabaseTestHelper.SetDefaultTestSessionSettings(testSession);
                testSession.RequestValidator =
                    new Action<HttpMessage, HttpMessage.Request>(
                    (expected, actual) =>
                    {
                        Assert.AreEqual(expected.RequestInfo.Method, actual.Method);
                        Assert.AreEqual(expected.RequestInfo.UserAgent, actual.UserAgent);
                        if (expected.Index < 10)
                        {
                            // Request 0-2: Set testdb1 with new MaxSize
                            // Request 3-5: Set testdb2 with new MaxSize
                            // Request 6-7: Get updated testdb1
                            // Request 8-9: Get updated testdb2
                            DatabaseTestHelper.ValidateHeadersForODataRequest(
                                expected.RequestInfo,
                                actual);
                        }
                        else
                        {
                            Assert.Fail("No more requests expected.");
                        }
                    });

                using (AsyncExceptionManager exceptionManager = new AsyncExceptionManager())
                {
                    // Create context with both ManageUrl and ServerName overriden
                    Collection<PSObject> database1,database2;
                    using (new MockHttpServer(
                        exceptionManager,
                        MockHttpServer.DefaultServerPrefixUri,
                        testSession))
                    {
                        database1 = powershell.InvokeBatchScript(
                            @"Set-AzureSqlDatabase " +
                            @"-Context $context " +
                            @"-DatabaseName testdb1 " +
                            @"-MaxSizeGB 5 " +
                            @"-Force " +
                            @"-PassThru");

                        // Set the database to 100MB
                        database2 = powershell.InvokeBatchScript(
                            @"Set-AzureSqlDatabase " +
                            @"-Context $context " +
                            @"-DatabaseName testdb2 " +
                            @"-MaxSizeBytes 104857600 " +
                            @"-Force " +
                            @"-PassThru");
                    }

                    Assert.AreEqual(0, powershell.Streams.Error.Count, "Errors during run!");
                    Assert.AreEqual(0, powershell.Streams.Warning.Count, "Warnings during run!");
                    powershell.Streams.ClearStreams();

                    Services.Server.Database database = database1.Single().BaseObject as Services.Server.Database;
                    Assert.IsTrue(database != null, "Expecting a Database object");
                    DatabaseTestHelper.ValidateDatabaseProperties(database, "testdb1", "Web", 5, 5368709120L, "SQL_Latin1_General_CP1_CI_AS", "Shared", false, DatabaseTestHelper.SharedSloGuid);

                    database = database2.Single().BaseObject as Services.Server.Database;
                    Assert.IsTrue(database != null, "Expecting a Database object");
                    DatabaseTestHelper.ValidateDatabaseProperties(database, "testdb2", "Web", 0, 104857600L, "Japanese_CI_AS", "Shared", false, DatabaseTestHelper.SharedSloGuid);
                }
            }
        }
        public void GetAzureSqlDatabaseWithSqlAuthNonExistentDb()
        {
            using (System.Management.Automation.PowerShell powershell =
                       System.Management.Automation.PowerShell.Create())
            {
                // Create a context
                NewAzureSqlDatabaseServerContextTests.CreateServerContextSqlAuth(
                    powershell,
                    "$context");

                // Query a non-existent test database
                HttpSession testSession = MockServerHelper.DefaultSessionCollection.GetSession(
                    "UnitTests.GetAzureSqlDatabaseWithSqlAuthNonExistentDb");
                DatabaseTestHelper.SetDefaultTestSessionSettings(testSession);
                testSession.RequestValidator =
                    new Action <HttpMessage, HttpMessage.Request>(
                        (expected, actual) =>
                {
                    Assert.AreEqual(expected.RequestInfo.Method, actual.Method);
                    Assert.IsNotNull(actual.UserAgent);
                    switch (expected.Index)
                    {
                    // Request 0-2: Get database requests
                    case 0:
                        DatabaseTestHelper.ValidateHeadersForODataRequest(
                            expected.RequestInfo,
                            actual);
                        break;

                    default:
                        Assert.Fail("No more requests expected.");
                        break;
                    }
                });

                using (AsyncExceptionManager exceptionManager = new AsyncExceptionManager())
                {
                    using (new MockHttpServer(
                               exceptionManager,
                               MockHttpServer.DefaultServerPrefixUri,
                               testSession))
                    {
                        powershell.InvokeBatchScript(
                            @"Get-AzureSqlDatabase " +
                            @"-Context $context " +
                            @"-DatabaseName testdb3");
                    }
                }

                Assert.AreEqual(1, powershell.Streams.Error.Count, "Expecting errors");
                Assert.AreEqual(2, powershell.Streams.Warning.Count, "Expecting tracing IDs");
                Assert.AreEqual(
                    "Database 'myserver01.testdb3' not found.",
                    powershell.Streams.Error.First().Exception.Message,
                    "Unexpected error message");
                Assert.IsTrue(
                    powershell.Streams.Warning.Any(w => w.Message.StartsWith("Client Session Id")),
                    "Expecting Client Session Id");
                Assert.IsTrue(
                    powershell.Streams.Warning.Any(w => w.Message.StartsWith("Client Request Id")),
                    "Expecting Client Request Id");
                powershell.Streams.ClearStreams();
            }
        }
        public void GetAzureSqlDatabaseWithSqlAuth()
        {
            using (System.Management.Automation.PowerShell powershell =
                System.Management.Automation.PowerShell.Create())
            {
                // Create a context
                NewAzureSqlDatabaseServerContextTests.CreateServerContextSqlAuth(
                    powershell,
                    "$context");

                // Create 2 test databases
                NewAzureSqlDatabaseTests.CreateTestDatabasesWithSqlAuth(
                    powershell,
                    "$context");

                // Query the created test databases
                HttpSession testSession = DatabaseTestHelper.DefaultSessionCollection.GetSession(
                    "UnitTests.GetAzureSqlDatabaseWithSqlAuth");
                DatabaseTestHelper.SetDefaultTestSessionSettings(testSession);
                testSession.RequestValidator =
                    new Action<HttpMessage, HttpMessage.Request>(
                    (expected, actual) =>
                    {
                        Assert.AreEqual(expected.RequestInfo.Method, actual.Method);
                        Assert.AreEqual(expected.RequestInfo.UserAgent, actual.UserAgent);
                        switch (expected.Index)
                        {
                            // Request 0-2: Get database requests
                            case 0:
                            case 1:
                            case 2:
                                DatabaseTestHelper.ValidateHeadersForODataRequest(
                                    expected.RequestInfo,
                                    actual);
                                break;
                            default:
                                Assert.Fail("No more requests expected.");
                                break;
                        }
                    });

                using (AsyncExceptionManager exceptionManager = new AsyncExceptionManager())
                {
                    Collection<PSObject> databases, database1, database2;
                    using (new MockHttpServer(
                        exceptionManager,
                        MockHttpServer.DefaultServerPrefixUri,
                        testSession))
                    {
                        databases = powershell.InvokeBatchScript(
                            @"Get-AzureSqlDatabase " +
                            @"-Context $context");
                        database1 = powershell.InvokeBatchScript(
                            @"Get-AzureSqlDatabase " +
                            @"-Context $context " +
                            @"-DatabaseName testdb1");
                        database2 = powershell.InvokeBatchScript(
                            @"Get-AzureSqlDatabase " +
                            @"-Context $context " +
                            @"-DatabaseName testdb2");
                    }

                    Assert.AreEqual(0, powershell.Streams.Error.Count, "Errors during run!");
                    Assert.AreEqual(0, powershell.Streams.Warning.Count, "Warnings during run!");
                    powershell.Streams.ClearStreams();

                    // Expecting master, testdb1, testdb2
                    Assert.AreEqual(3, databases.Count, "Expecting three Database objects");

                    Assert.IsTrue(
                        database1.Single().BaseObject is Services.Server.Database,
                        "Expecting a Database object");
                    Services.Server.Database database1Obj =
                        (Services.Server.Database)database1.Single().BaseObject;
                    Assert.AreEqual("testdb1", database1Obj.Name, "Expected db name to be testdb1");

                    Assert.IsTrue(
                        database2.Single().BaseObject is Services.Server.Database,
                        "Expecting a Database object");
                    Services.Server.Database database2Obj =
                        (Services.Server.Database)database2.Single().BaseObject;
                    Assert.AreEqual("testdb2", database2Obj.Name, "Expected db name to be testdb2");
                    Assert.AreEqual(
                        "Japanese_CI_AS",
                        database2Obj.CollationName,
                        "Expected collation to be Japanese_CI_AS");
                    Assert.AreEqual("Web", database2Obj.Edition, "Expected edition to be Web");
                    Assert.AreEqual(5, database2Obj.MaxSizeGB, "Expected max size to be 5 GB");
                }
            }
        }
        public void GetAzureSqlDatabaseContinuousCopyWithSqlAuth()
        {
            using (System.Management.Automation.PowerShell powershell =
                       System.Management.Automation.PowerShell.Create())
            {
                // Create a context
                NewAzureSqlDatabaseServerContextTests.CreateServerContextSqlAuth(
                    powershell,
                    "$context");
                // Create 2 test databases
                NewAzureSqlDatabaseTests.CreateTestDatabasesWithSqlAuth(
                    powershell,
                    "$context");
                // Start two continuous database copy operation
                StartAzureSqlDatabaseCopyTests.StartDatabaseContinuousCopyWithSqlAuth(
                    powershell,
                    "$context",
                    "$copy1",
                    "testdb1");
                StartAzureSqlDatabaseCopyTests.StartDatabaseContinuousCopyWithSqlAuth(
                    powershell,
                    "$context",
                    "$copy2",
                    "testdb2");

                HttpSession testSession = DatabaseTestHelper.DefaultSessionCollection.GetSession(
                    "UnitTest.GetAzureSqlDatabaseContinuousCopyWithSqlAuth");
                DatabaseTestHelper.SetDefaultTestSessionSettings(testSession);
                testSession.RequestValidator =
                    new Action <HttpMessage, HttpMessage.Request>(
                        (expected, actual) =>
                {
                    Assert.AreEqual(expected.RequestInfo.Method, actual.Method);
                    Assert.AreEqual(expected.RequestInfo.UserAgent, actual.UserAgent);
                    switch (expected.Index)
                    {
                    // Request 0-1: Get all database copies request
                    case 0:
                    case 1:
                    // Request 2-3: Get database copies for testdb1
                    case 2:
                    case 3:
                    // Request 4-5: Get database copies for testdb2
                    case 4:
                    case 5:
                        DatabaseTestHelper.ValidateHeadersForODataRequest(
                            expected.RequestInfo,
                            actual);
                        break;

                    default:
                        Assert.Fail("No more requests expected.");
                        break;
                    }
                });

                using (AsyncExceptionManager exceptionManager = new AsyncExceptionManager())
                {
                    Collection <PSObject> databaseCopies, databaseCopy1, databaseCopy2;
                    using (new MockHttpServer(
                               exceptionManager,
                               MockHttpServer.DefaultServerPrefixUri,
                               testSession))
                    {
                        databaseCopies = powershell.InvokeBatchScript(
                            @"Get-AzureSqlDatabaseCopy " +
                            @"-Context $context");
                        databaseCopy1 = powershell.InvokeBatchScript(
                            @"Get-AzureSqlDatabaseCopy " +
                            @"-Context $context " +
                            @"-DatabaseName testdb1");
                        databaseCopy2 = powershell.InvokeBatchScript(
                            @"Get-AzureSqlDatabaseCopy " +
                            @"-Context $context " +
                            @"-DatabaseName testdb2");
                    }

                    Assert.AreEqual(0, powershell.Streams.Error.Count, "Errors during run!");
                    Assert.AreEqual(0, powershell.Streams.Warning.Count, "Warnings during run!");
                    powershell.Streams.ClearStreams();

                    Assert.AreEqual(2, databaseCopies.Count, "Expecting 2 Database Copy objects");
                    Assert.IsTrue(
                        databaseCopy1.First().BaseObject is Services.Server.DatabaseCopy,
                        "Expecting a Database Copy object");
                    Services.Server.DatabaseCopy databaseCopyObj =
                        (Services.Server.DatabaseCopy)databaseCopy1.Single().BaseObject;
                    Assert.AreEqual(
                        "testserver",
                        databaseCopyObj.SourceServerName,
                        "Expected source server name to be testserver");
                    Assert.AreEqual(
                        "testdb1",
                        databaseCopyObj.SourceDatabaseName,
                        "Expected source database name to be testdb1");
                    Assert.AreEqual(
                        "partnersrv",
                        databaseCopyObj.DestinationServerName,
                        "Expected destination server name to be partnersrv");
                    Assert.AreEqual(
                        "testdb1",
                        databaseCopyObj.DestinationDatabaseName,
                        "Expected destination database name to be testdb1");
                    Assert.IsTrue(
                        databaseCopyObj.IsContinuous,
                        "Expected copy to be continuous");

                    Assert.IsTrue(
                        databaseCopy2.First().BaseObject is Services.Server.DatabaseCopy,
                        "Expecting a Database Copy object");
                    databaseCopyObj =
                        (Services.Server.DatabaseCopy)databaseCopy2.Single().BaseObject;
                    Assert.AreEqual(
                        "testserver",
                        databaseCopyObj.SourceServerName,
                        "Expected source server name to be testserver");
                    Assert.AreEqual(
                        "testdb2",
                        databaseCopyObj.SourceDatabaseName,
                        "Expected source database name to be testdb2");
                    Assert.AreEqual(
                        "partnersrv",
                        databaseCopyObj.DestinationServerName,
                        "Expected destination server name to be partnersrv");
                    Assert.AreEqual(
                        "testdb2",
                        databaseCopyObj.DestinationDatabaseName,
                        "Expected destination database name to be testdb2");
                    Assert.IsTrue(
                        databaseCopyObj.IsContinuous,
                        "Expected copy to be continuous");
                }
            }
        }