示例#1
0
        public void TestNormalUserAccessOtherAccount()
        {
            Account account = SingletonProvider <TestSetup> .Instance.AddAccount(_domain, "*****@*****.**", "test");

            account.AdminLevel = eAdminLevel.hAdminLevelNormal;
            account.Save();

            Account secondAccount = SingletonProvider <TestSetup> .Instance.AddAccount(_domain, "*****@*****.**", "test");

            secondAccount.AdminLevel = eAdminLevel.hAdminLevelNormal;
            secondAccount.Save();

            var newApplication = new Application();

            newApplication.Authenticate("*****@*****.**", "test");
            CustomAssert.AreEqual(1, newApplication.Domains.Count);
            CustomAssert.AreEqual(1, newApplication.Domains[0].Accounts.Count);

            Account myAccount = newApplication.Domains[0].Accounts.get_ItemByAddress("*****@*****.**");

            try
            {
                Account otherAccount = newApplication.Domains[0].Accounts.get_ItemByAddress("*****@*****.**");

                CustomAssert.Fail();
            }
            catch (COMException ex)
            {
                CustomAssert.IsTrue(ex.Message.Contains("Invalid index."));
            }

            Domains domains = SingletonProvider <TestSetup> .Instance.GetApp().Domains;

            CustomAssert.AreEqual(2, domains[0].Accounts.Count);
        }
示例#2
0
        public void TestDeliverToServerNotSupportingEHLO()
        {
            CustomAssert.AreEqual(0, _status.UndeliveredMessages.Length);

            var deliveryResults = new Dictionary <string, int>()
            {
                { "*****@*****.**", 250 }
            };

            int smtpServerPort = TestSetup.GetNextFreePort();

            using (var server = new SMTPServerSimulator(1, smtpServerPort))
            {
                server.ServerSupportsEhlo = false;
                server.AddRecipientResult(deliveryResults);
                server.StartListen();

                // Add a route so we can conenct to localhost.
                SMTPClientTests.AddRoutePointingAtLocalhost(1, smtpServerPort, false, eConnectionSecurity.eCSNone);

                // Send message to this route.

                if (!SMTPClientSimulator.StaticSend("*****@*****.**", "*****@*****.**", "Test", "Test message"))
                {
                    CustomAssert.Fail("Delivery failed");
                }

                // Wait for the client to disconnect.
                server.WaitForCompletion();

                TestSetup.AssertRecipientsInDeliveryQueue(0, false);

                CustomAssert.IsTrue(server.MessageData.Contains("Test message"));
            }
        }
示例#3
0
        public void WaitForCompletion()
        {
            if (_workerThreadException != null)
            {
                throw new Exception("An error occurred when calling AcceptSocket.", _workerThreadException);
            }

            for (int i = 0; i < SecondsToWaitBeforeTerminate; i++)
            {
                if (_workerThreadFinished.WaitOne(1000, true))
                {
                    return;
                }
            }

            string log = TestSetup.ReadCurrentDefaultLog();

            if (_numberOfConnectedClients < _maxNumberOfConnections)
            {
                CustomAssert.Fail(
                    string.Format(
                        "At {0} - Client did not connect to simulated server. Expected connection count: {1}, Actual: {2}\r\nLog:\r\n{3}",
                        DateTime.Now, _maxNumberOfConnections, _numberOfConnectedClients, log));
            }
            else
            {
                CustomAssert.Fail(
                    string.Format(
                        "At {0} - Client did not disconnect from simulated server. Expected connection count: {1}, Actual: {2}\r\nLog:\r\n{3}",
                        DateTime.Now, _maxNumberOfConnections, _numberOfConnectedClients, log));
            }
        }
示例#4
0
        public void DoNotUseStartTlsIfNotEnabledButAvailable()
        {
            // No valid recipients...
            var deliveryResults = new Dictionary <string, int>();

            deliveryResults["*****@*****.**"] = 250;

            int smtpServerPort = TestSetup.GetNextFreePort();

            using (var server = new SMTPServerSimulator(1, smtpServerPort, eConnectionSecurity.eCSSTARTTLSOptional))
            {
                server.AddRecipientResult(deliveryResults);
                server.StartListen();

                Route route = SMTPClientTests.AddRoutePointingAtLocalhost(1, smtpServerPort, false, eConnectionSecurity.eCSNone);

                // Send message to this route.
                var smtp = new SMTPClientSimulator();
                if (!smtp.Send("*****@*****.**", "*****@*****.**", "Test", "Test message"))
                {
                    CustomAssert.Fail("Delivery failed");
                }

                // Wait for the client to disconnect.
                server.WaitForCompletion();

                TestSetup.AssertRecipientsInDeliveryQueue(0, false);

                Assert.IsNotNullOrEmpty(server.MessageData);

                CustomAssert.IsFalse(TestSetup.DefaultLogContains("220 Ready to start TLS"));
            }
        }
示例#5
0
        public void TestSpamMessage()
        {
            // Send a messages to this account.
            var oSMTP = new SMTPClientSimulator();

            oSMTP.Send(account.Address, account.Address, "SA test",
                       "This is a test message with spam.\r\n XJS*C4JDBQADN1.NSBN3*2IDNEN*GTUBE-STANDARD-ANTI-UBE-TEST-EMAIL*C.34X.");

            string sMessageContents = POP3ClientSimulator.AssertGetFirstMessageText(account.Address, "test");

            if (!sMessageContents.Contains("X-Spam-Status: Yes"))
            {
                CustomAssert.Fail("Spam message not treated as spam (no X-Spam-Status-header).");
            }

            if (!sMessageContents.Contains("X-hMailServer-Spam"))
            {
                CustomAssert.Fail("Spam message not treated as spam (no X-hMailServer-Spam header).");
            }

            if (!sMessageContents.Contains("X-hMailServer-Reason"))
            {
                CustomAssert.Fail("Spam message not treated as spam (no X-hMailServer-Reason header).");
            }

            if (!sMessageContents.Contains("X-hMailServer-Reason-Score"))
            {
                CustomAssert.Fail("Spam message not treated as spam (no X-hMailServer-Reason-Score header).");
            }
        }
示例#6
0
        private static SSLCertificate SetupSSLCertificate(hMailServer.Application application)
        {
            var sslPath = GetSslCertPath();

            var exampleCert = Path.Combine(sslPath, "example.crt");
            var exampleKey  = Path.Combine(sslPath, "example.key");

            if (!File.Exists(exampleCert))
            {
                CustomAssert.Fail("Certificate " + exampleCert + " was not found");
            }
            if (!File.Exists(exampleKey))
            {
                CustomAssert.Fail("Private key " + exampleKey + " was not found");
            }


            SSLCertificate sslCertificate = application.Settings.SSLCertificates.Add();

            sslCertificate.Name            = "Example";
            sslCertificate.CertificateFile = exampleCert;
            sslCertificate.PrivateKeyFile  = exampleKey;
            sslCertificate.Save();

            return(sslCertificate);
        }
        public static string AssertGetFirstMessageText(string accountName, string accountPassword)
        {
            // Wait for the message to appear.
            var pop3 = new POP3ClientSimulator();

            for (int i = 0; i < 5000; i++)
            {
                if (pop3.GetMessageCount(accountName, accountPassword) > 0)
                {
                    break;
                }

                Thread.Sleep(20);
            }

            // Download it.
            string text = pop3.GetFirstMessageText(accountName, accountPassword);

            if (text.Length == 0)
            {
                CustomAssert.Fail("Message was found but contents could not be received");
            }

            return(text);
        }
示例#8
0
        public static void AssertFolderMessageCount(IMAPFolder folder, int expectedCount)
        {
            if (expectedCount == 0)
            {
                // just in case.
                AssertRecipientsInDeliveryQueue(0);
            }

            int currentCount = 0;
            int timeout      = 100;

            while (timeout > 0)
            {
                currentCount = folder.Messages.Count;

                if (currentCount == expectedCount)
                {
                    return;
                }

                timeout--;
                Thread.Sleep(100);
            }

            string error = "Wrong number of messages in mailbox " + folder.Name;

            CustomAssert.Fail(error);
        }
示例#9
0
        public static void AssertFileExists(string file, bool delete)
        {
            int timeout = 100;

            while (timeout > 0)
            {
                try
                {
                    if (File.Exists(file))
                    {
                        if (delete)
                        {
                            TestTracer.WriteTraceInfo("Deleting file {0}...", file);
                            File.Delete(file);
                        }

                        return;
                    }
                }
                catch (Exception)
                {
                }

                timeout--;
                Thread.Sleep(100);
            }

            CustomAssert.Fail("Expected file does not exist:" + file);
        }
示例#10
0
        public void SetupSSLPort()
        {
            _application.Settings.Logging.Enabled  = true;
            _application.Settings.Logging.LogTCPIP = true;
            _application.Settings.Logging.EnableLiveLogging(true);

            var cs = new TcpConnection();

            if (!cs.Connect(25001))
            {
                CustomAssert.Fail("Could not connect to SSL server.");
            }

            cs.Disconnect();

            for (int i = 0; i <= 40; i++)
            {
                CustomAssert.IsTrue(i != 40);

                string liveLog = _application.Settings.Logging.LiveLog;
                if (liveLog.Contains("TCPConnection - TLS/SSL handshake failed."))
                {
                    break;
                }

                Thread.Sleep(250);
            }

            _application.Settings.Logging.EnableLiveLogging(false);
        }
示例#11
0
        public void TestDomainLimitNumberOfAliases()
        {
            _domain.MaxNumberOfAliasesEnabled = true;
            _domain.MaxNumberOfAliases        = 4;
            _domain.Save();

            SingletonProvider <TestSetup> .Instance.AddAlias(_domain, "*****@*****.**", "*****@*****.**");

            SingletonProvider <TestSetup> .Instance.AddAlias(_domain, "*****@*****.**", "*****@*****.**");

            SingletonProvider <TestSetup> .Instance.AddAlias(_domain, "*****@*****.**", "*****@*****.**");

            SingletonProvider <TestSetup> .Instance.AddAlias(_domain, "*****@*****.**", "*****@*****.**");

            try
            {
                SingletonProvider <TestSetup> .Instance.AddAlias(_domain, "*****@*****.**", "*****@*****.**");
            }
            catch (Exception)
            {
                return;
            }

            CustomAssert.Fail("Number of aliases exceeded max no of accounts");
        }
示例#12
0
        public void TestDomainAdminAccessOtherDomain()
        {
            Account account = SingletonProvider <TestSetup> .Instance.AddAccount(_domain, "*****@*****.**", "test");

            account.AdminLevel = eAdminLevel.hAdminLevelDomainAdmin;
            account.Save();

            SingletonProvider <TestSetup> .Instance.AddDomain("example.com");

            var newApplication = new Application();

            newApplication.Authenticate("*****@*****.**", "test");
            CustomAssert.AreEqual(1, newApplication.Domains.Count);

            Domains domains = SingletonProvider <TestSetup> .Instance.GetApp().Domains;

            CustomAssert.AreEqual(2, domains.Count);

            try
            {
                Domain secondDomain = newApplication.Domains.get_ItemByName("example.com");
                CustomAssert.Fail("Was able to access other domain.");
            }
            catch (COMException ex)
            {
                CustomAssert.IsTrue(ex.Message.Contains("Invalid index."));
            }
        }
示例#13
0
 private static void ExpectNoErrors(ICollection <Diagnostic> diagnostics)
 {
     if (diagnostics.Count != 0)
     {
         string message = $"Expected no errors but got {diagnostics.Count}.\r\n{DiagnosticMessages(diagnostics)}";
         CustomAssert.Fail(message);
     }
 }
示例#14
0
 public static void AssertNoReportedError()
 {
     if (File.Exists(GetErrorLogFileName()))
     {
         string contents = File.ReadAllText(GetErrorLogFileName());
         CustomAssert.Fail(contents);
     }
 }
        private static void ExpectNoErrors(string code)
        {
            var diagnostics = GetSemanticDiagnostics(code);

            if (diagnostics.Count != 0)
            {
                string message = $"Expected no errors but got {diagnostics.Count}.\r\n{DiagnosticMessages(diagnostics)}";
                CustomAssert.Fail(message);
            }
        }
示例#16
0
        /// <summary>
        /// Validates a given <paramref name="tsFileName"/>.
        /// </summary>
        private static void CheckTypeScriptTestCases(string tsFileName)
        {
            tsFileName = TypeScript.Net.Core.Path.NormalizePath(tsFileName);
            var tsFileContent = File.ReadAllText(tsFileName);
            var tsInputFile   = new TestFile(tsFileName, tsFileContent);
            List <Diagnostic> diagnostics;

            // Getting diagnostic for the file.
            diagnostics = TypeCheckingHelper.ParseAndCheck(tsInputFile, ParsingOptions.TypeScriptParsingOptions);

            // Check that number of errors is correct
            var expectedErrorCount = GetExpectedErrorCount(tsFileName);

            if (expectedErrorCount == 0 && diagnostics.Count != 0)
            {
                // Special case: expecting no errors but got some
                string message =
                    $"Expecting 0 errors but got {diagnostics.Count}. All diagnostics: {DiagnosticMessages(diagnostics)}";

                CustomAssert.Fail(message);
            }

            if (expectedErrorCount != 0)
            {
                // Now, trying to compare actual content with an expected one.

                // To simplify future diagnostic, we're going to do following trick:

                // First, we'll compare content scrumbling file names in the error file (this will simplify migration
                // of the existing cases from TypeScript code base).
                // Second, if they're different we'll dump both expected and actual content.

                // So we're expecting errors, let's check that they're the same.
                var expectedErrorContent = ReadExpectedNormalizedErrorContent(tsFileName);

                // Dumping the file content for further diagnostic
                var actualErrorContent = GetActualNormalizedErrorContent(tsInputFile, diagnostics);

                try
                {
                    Assert.Equal(expectedErrorContent, actualErrorContent);
                }
                catch (Exception e)
                {
                    CustomAssert.Fail(
                        "Expected and actual files are different.\r\n" +
                        "Expected: \r\n" +
                        expectedErrorContent + "\r\n" +
                        "Actual: \r\n" +
                        actualErrorContent + "\r\n" +
                        "Original error:\r\n" + e.ToString());
                }
            }
        }
示例#17
0
 public void TestAccountContainingForwardSlash()
 {
     try
     {
         SingletonProvider <TestSetup> .Instance.AddAccount(_domain, "\\@test.com", "secret2");
     }
     catch (Exception)
     {
         return;
     }
     CustomAssert.Fail("Account containing forward slash was permitted");
 }
示例#18
0
        public void TestBasic()
        {
            // Send a messages to this account.
            var oSMTP = new SMTPClientSimulator();

            CustomAssert.IsTrue(oSMTP.Send(account.Address, account.Address, "SA test", "This is a test message."));
            string sMessageContents = POP3ClientSimulator.AssertGetFirstMessageText(account.Address, "test");

            if (!sMessageContents.Contains("X-Spam-Status"))
            {
                CustomAssert.Fail("SpamAssassin did not run");
            }
        }
示例#19
0
        public void TestMultipleHostsTemporaryFailureDeliveryOnSecondServer()
        {
            CustomAssert.AreEqual(0, _status.UndeliveredMessages.Length);

            // No valid recipients...
            var deliveryResults = new Dictionary <string, int>();

            deliveryResults["*****@*****.**"] = 250;
            deliveryResults["*****@*****.**"] = 250;
            deliveryResults["*****@*****.**"] = 450;

            var deliveryResultsSecond = new Dictionary <string, int>();

            deliveryResultsSecond["*****@*****.**"] = 250;
            deliveryResultsSecond["*****@*****.**"] = 250;
            deliveryResultsSecond["*****@*****.**"] = 250;

            int smtpServerPort = TestSetup.GetNextFreePort();

            using (var server = new SMTPServerSimulator(2, smtpServerPort))
            {
                server.AddRecipientResult(deliveryResults);
                server.AddRecipientResult(deliveryResultsSecond);
                server.StartListen();


                // Add a route so we can connect to localhost.
                AddRoutePointingAtLocalhostMultipleHosts(2, smtpServerPort);

                // Send message to this route.
                var smtp       = new SMTPClientSimulator();
                var recipients = new List <string>();

                recipients.Add("*****@*****.**");
                recipients.Add("*****@*****.**");
                recipients.Add("*****@*****.**");

                if (!smtp.Send("*****@*****.**", recipients, "Test", "Accepted message"))
                {
                    CustomAssert.Fail("Delivery failed");
                }

                // Wait for the client to disconnect.
                server.WaitForCompletion();

                // Trigger a sending of the bounce message.
                TestSetup.AssertRecipientsInDeliveryQueue(0);

                CustomAssert.IsTrue(server.MessageData.Contains("Accepted message"));
            }
        }
示例#20
0
        public void TestNameDuplicateGroup()
        {
            SingletonProvider <TestSetup> .Instance.AddGroup("*****@*****.**");

            try
            {
                SingletonProvider <TestSetup> .Instance.AddGroup("*****@*****.**");
            }
            catch (Exception)
            {
                return;
            }
            CustomAssert.Fail("Two groups with same name was permitted.");
        }
示例#21
0
        public void TestNameDuplicateAlias()
        {
            SingletonProvider <TestSetup> .Instance.AddAccount(_domain, "*****@*****.**", "secret1");

            try
            {
                SingletonProvider <TestSetup> .Instance.AddAlias(_domain, "*****@*****.**", "secret2");
            }
            catch (Exception)
            {
                return;
            }
            CustomAssert.Fail("Alias with same name as account was permitted.");
        }
示例#22
0
        private void DumpFailedAssertions(List <TestCaseResult> assertions)
        {
            string content = assertions.Aggregate(
                new StringBuilder(value: "Failed assertions:\r\n"),
                (sb, tc) =>
            {
                sb.AppendLine($"Test case: {tc.TestCase}")
                .AppendLine($"Duration: {tc.Duration}")
                .AppendLine($"Failure: {tc.Failure}\r\n");
                return(sb);
            }).ToString();

            CustomAssert.Fail(content);
        }
示例#23
0
        public void TestIpAddressAsHostName()
        {
            var smtpClientSimulator = new SMTPClientSimulator();

            _settings.AntiSpam.SpamAssassinEnabled = true;
            _settings.AntiSpam.SpamAssassinHost    = "127.0.0.1";
            smtpClientSimulator.Send(account.Address, account.Address, "SA test", "This is a test message.");
            string messageContents = POP3ClientSimulator.AssertGetFirstMessageText(account.Address, "test");

            if (!messageContents.Contains("X-Spam-Status"))
            {
                CustomAssert.Fail("SpamAssassin did not run");
            }
        }
示例#24
0
        public void TestTooManyInvalidCommandsAUTH()
        {
            Application application = SingletonProvider <TestSetup> .Instance.GetApp();

            Settings settings = _settings;

            settings.DisconnectInvalidClients   = true;
            settings.MaxNumberOfInvalidCommands = 3;

            var sim = new TcpConnection();

            sim.Connect(25);
            sim.Send("EHLO test.com\r\n");

            for (int i = 1; i <= 6; i++)
            {
                try
                {
                    sim.Send("AUTH LOGIN\r\n");

                    string result = sim.Receive();

                    if (result.Contains("Too many invalid commands"))
                    {
                        return;
                    }

                    if (i > 5)
                    {
                        break;
                    }

                    sim.Send("YWNhZGVtaWE=\r\n");
                    sim.Receive();
                    sim.Send("abc\r\n");
                    sim.Receive();
                }
                catch (Exception)
                {
                    if (i < 5)
                    {
                        CustomAssert.Fail("Was disconnected prematurely.");
                    }

                    return;
                }
            }

            CustomAssert.Fail("Wasn't disconnected");
        }
示例#25
0
        private void AssertFolderExists(string folderName)
        {
            // wait for the folder to appear.
            for (int i = 1; i <= 1000; i++)
            {
                if (SelectFolder(folderName))
                {
                    return;
                }

                Thread.Sleep(25);
            }

            CustomAssert.Fail("Folder not found: " + folderName);
        }
示例#26
0
        public void TestAlgorithmSHA256()
        {
            _domain.DKIMPrivateKeyFile   = GetPrivateKeyFile();
            _domain.DKIMSelector         = "TestSelector";
            _domain.DKIMSigningAlgorithm = eDKIMAlgorithm.eSHA256;
            _domain.DKIMSignEnabled      = true;
            _domain.Save();

            string result = SendMessage();

            if (result.ToLower().Contains("a=rsa-sha256") == false)
            {
                CustomAssert.Fail(result);
            }
        }
示例#27
0
        public void AssertBounceMessageExistsInQueue(string bounceTo)
        {
            Status status = application.Status;

            for (int i = 0; i < 100; i++)
            {
                if (status.UndeliveredMessages.Length == 0 || status.UndeliveredMessages.Contains("\t" + bounceTo))
                {
                    return;
                }

                Thread.Sleep(100);
            }

            CustomAssert.Fail("Delivery queue not empty");
        }
示例#28
0
        public void TestNameDuplicateDistributionList()
        {
            SingletonProvider <TestSetup> .Instance.AddAlias(_domain, "*****@*****.**", "*****@*****.**");

            var recipients = new List <string>();

            try
            {
                SingletonProvider <TestSetup> .Instance.AddDistributionList(_domain, "*****@*****.**", recipients);
            }
            catch (Exception)
            {
                return;
            }
            CustomAssert.Fail("Distribution list with same name as alias was permitted.");
        }
示例#29
0
        public void TestDomainLimitAccountMaxSizeTest2()
        {
            _domain.MaxAccountSize = 25;
            _domain.Save();

            try
            {
                SingletonProvider <TestSetup> .Instance.AddAccount(_domain, "*****@*****.**", "secret1", 32);
            }
            catch (Exception)
            {
                return;
            }

            CustomAssert.Fail("Max account size limit exceeded.");
        }
示例#30
0
        public void Authenticate()
        {
            Account account = application.Authenticate("Administrator", "testar");

            if (account == null)
            {
                account = application.Authenticate("Administrator", "");
            }

            if (account == null)
            {
                CustomAssert.Fail("hMailServer API authentication failed");
            }

            _settings = application.Settings;
        }