public void SendWithExclusion()
        {
            var client = TestClient.CreateNaked(session);
            var user   = client.Users[0];

            var inforoomRegion = TestRegion.Find(TestRegion.Inforoom);

            SetUp(
                new List <TestUser> {
                user
            },
                inforoomRegion,
                "Это письмо пользователю",
                "Это текст письма пользователю",
                null);

            var handler = new DocSourceHandlerForTesting(Settings.Default.TestIMAPUser, Settings.Default.TestIMAPPass);

            handler.TestProcessMime(_info.Mime);
            var existsMessages = ImapHelper.CheckImapFolder(Settings.Default.TestIMAPUser, Settings.Default.TestIMAPPass, ImapHelper.INBOXFolder);

            Assert.That(existsMessages.Count, Is.GreaterThanOrEqualTo(1), "Не найдены письма в IMAP-папке");
            var responseCount = existsMessages
                                .Count(m => m.Envelope?.Subject?.Equals(_responseSubject, StringComparison.CurrentCultureIgnoreCase) == true);

            Assert.That(responseCount, Is.EqualTo(1), "Не найдено письмо с загловком '{0}'", _responseSubject);

            var mails = TestMailSendLog.Queryable.Where(l => l.User.Id == user.Id).ToList();

            Assert.That(mails.Count, Is.EqualTo(1));

            var mailLog = mails[0];

            Assert.That(mailLog.Mail.Supplier.Id, Is.EqualTo(_info.Supplier.Id));
        }
        public void ErrorOnEmptyLetter()
        {
            var client = TestClient.CreateNaked(session);
            var user   = client.Users[0];

            var supplier = TestSupplier.CreateNaked(session);
            var from     = $"{supplier.Id}@supplier.test";

            PrepareSupplier(supplier, from);

            var message = ImapHelper.BuildMessageWithAttachments(
                "  ",
                "   ",
                new string[] { "{0}@docs.analit.net".Format(user.AvaliableAddresses[0].Id) },
                new[] { from },
                null);

            var handler = new DocSourceHandlerForTesting(Settings.Default.TestIMAPUser, Settings.Default.TestIMAPPass);

            try {
                handler.CheckMime(message);
                Assert.Fail("Должно было возникнуть исключение MiniMailOnEmptyLetterException");
            }
            catch (MiniMailOnEmptyLetterException exception) {
                Assert.That(exception.Template, Is.EqualTo(ResponseTemplate.MiniMailOnEmptyLetter));
                SendErrorToProvider(handler, exception, message);
            }
        }
        public void ErrorOnAllowedExtensions()
        {
            var client = TestClient.CreateNaked(session);
            var user   = client.Users[0];

            var supplier = TestSupplier.CreateNaked(session);
            var from     = String.Format("{0}@supplier.test", supplier.Id);

            PrepareSupplier(supplier, from);

            var message = ImapHelper.BuildMessageWithAttachments(
                "test AllowedExtensions",
                "body AllowedExtensions",
                new string[] { "{0}@docs.analit.net".Format(user.AvaliableAddresses[0].Id) },
                new[] { from },
                new string[] { @"..\..\Data\Waybills\70983_906384.zip" });

            var handler = new DocSourceHandlerForTesting(Settings.Default.TestIMAPUser, Settings.Default.TestIMAPPass);

            try {
                handler.CheckMime(message);
                Assert.Fail("Должно было возникнуть исключение MiniMailOnAllowedExtensionsException");
            }
            catch (MiniMailOnAllowedExtensionsException exception) {
                Assert.That(exception.Template, Is.EqualTo(ResponseTemplate.MiniMailOnAllowedExtensions));
                Assert.That(exception.ErrorExtention, Is.EqualTo(".zip").IgnoreCase);
                Assert.That(exception.AllowedExtensions, Is.EqualTo("doc, xls, gif, tiff, tif, jpg, pdf, txt").IgnoreCase);
                SendErrorToProvider(handler, exception, message);
            }
        }
        public void PrepareDublicateMessage()
        {
            string subject = "Тест на дубликаты";
            string body    = "Дублирующее сообщение";
            var    client  = TestClient.CreateNaked(session);
            var    user    = client.Users[0];

            SetUp(
                new List <TestUser> {
                user
            },
                null,
                subject,
                body,
                null);
            var filter  = new EventFilter <DocSourceHandlerForTesting>(log4net.Core.Level.All);
            var handler = new DocSourceHandlerForTesting(Settings.Default.TestIMAPUser, Settings.Default.TestIMAPPass, true);

            handler.CreateDirectoryPath();
            //вызываем обработку первый раз
            handler.ProcessMime(this._info.Mime);
            //вызываем обработку второй раз
            handler.ProcessMime(this._info.Mime);
            //проверяем, был ли вызван перекрытый метод отправки письма
            Assert.That(handler.MessageSended, Is.EqualTo(false));
            //смотрим, пришло ли сообщение в лог
            Assert.That(filter.Events.Count, Is.EqualTo(1));
            //смотрим, содержит ли строка сообщения заголовок письма
            Assert.That(filter.Events[0].GetLoggingEventData().Message.Contains(subject), Is.EqualTo(true));
        }
        public void NotFoundError()
        {
            var supplier = TestSupplier.CreateNaked(session);
            var from     = String.Format("{0}@supplier.test", supplier.Id);

            PrepareSupplier(supplier, from);

            var message = ImapHelper.BuildMessageWithAttachments(
                "test NotFound",
                "body NotFound",
                new string[] { "*****@*****.**" },
                new[] { from },
                null);

            var handler = new DocSourceHandlerForTesting(Settings.Default.TestIMAPUser, Settings.Default.TestIMAPPass);

            try {
                handler.CheckMime(message);
                Assert.Fail("Должно было возникнуть исключение MiniMailOnEmptyRecipientsException");
            }
            catch (MiniMailOnEmptyRecipientsException exception) {
                Assert.That(exception.Template, Is.EqualTo(ResponseTemplate.MiniMailOnEmptyRecipients));
                Assert.That(exception.CauseList, Is.EqualTo("[email protected] : " + RecipientStatus.NotFound.GetDescription()));
                SendErrorToProvider(handler, exception, message);
            }
        }
        private void SendErrorToProvider(DocSourceHandlerForTesting handler, MiniMailException exception, Mime sourceLetter)
        {
            try {
                var memoryAppender = new MemoryAppender();
                memoryAppender.AddFilter(new LoggerMatchFilter {
                    AcceptOnMatch = true, LoggerToMatch = "PriceProcessor", Next = new DenyAllFilter()
                });
                BasicConfigurator.Configure(memoryAppender);

                handler.SendErrorLetterToSupplier(exception, sourceLetter);

                var events = memoryAppender.GetEvents();
                Assert.That(
                    events.Length,
                    Is.EqualTo(0),
                    "Ошибки при обработки задач сертификатов:\r\n{0}",
                    events.Select(item => {
                    if (string.IsNullOrEmpty(item.GetExceptionString()))
                    {
                        return(item.RenderedMessage);
                    }
                    else
                    {
                        return(item.RenderedMessage + Environment.NewLine + item.GetExceptionString());
                    }
                }).Implode("\r\n"));
            }
            finally {
                LogManager.ResetConfiguration();
            }
        }
        public void SendVIPMail()
        {
            var client = TestClient.CreateNaked(session);
            var user   = client.Users[0];

            SetUp(
                new List <TestUser> {
                user
            },
                null,
                "Это письмо пользователю",
                "Это текст письма пользователю",
                null);

            var handler = new DocSourceHandlerForTesting(Settings.Default.TestIMAPUser, Settings.Default.TestIMAPPass);

            TemplateHolder.Values.VIPMailPayerId = _info.Supplier.Payer.Id;
            handler.TestProcessMime(_info.Mime);

            var mails = TestMailSendLog.Queryable.Where(l => l.User.Id == user.Id).ToList();

            Assert.That(mails.Count, Is.EqualTo(1));

            var mailLog = mails[0];

            Assert.That(mailLog.UpdateLogEntry, Is.Null);
            Assert.That(mailLog.Committed, Is.False);
            Assert.That(mailLog.Mail.Supplier.Id, Is.EqualTo(_info.Supplier.Id));
            Assert.That(mailLog.Mail.IsVIPMail, Is.True);
        }
        private void Process()
        {
            Assert.That(_info, Is.Not.Null, "Перед обработкой должен быть вызван метод SetUp");
            Assert.That(_info.Mime, Is.Not.Null, "Перед обработкой должен быть вызван метод SetUp");
            var handler = new DocSourceHandlerForTesting(Settings.Default.TestIMAPUser, Settings.Default.TestIMAPPass);

            handler.TestProcessMime(_info.Mime);
            var existsMessages = ImapHelper.CheckImapFolder(Settings.Default.TestIMAPUser, Settings.Default.TestIMAPPass, Settings.Default.IMAPSourceFolder);

            Assert.That(existsMessages.Count, Is.EqualTo(0), "Существуют письма в IMAP-папками с темами: {0}", existsMessages.Select(m => m.Envelope.Subject).Implode());
        }
        public void NotFoundSupplierError()
        {
            var supplier = TestSupplier.CreateNaked(session);
            var from     = String.Format("{0}@supplier.test", supplier.Id);

            var message = ImapHelper.BuildMessageWithAttachments(
                "test NotFoundSupplier",
                "body NotFoundSupplier",
                new string[] { "*****@*****.**" },
                new[] { from },
                null);

            var handler = new DocSourceHandlerForTesting(Settings.Default.TestIMAPUser, Settings.Default.TestIMAPPass);

            try {
                handler.CheckMime(message);
                Assert.Fail("Должно было возникнуть исключение MiniMailOnUnknownProviderException");
            }
            catch (MiniMailOnUnknownProviderException exception) {
                Assert.That(exception.Template, Is.EqualTo(ResponseTemplate.MiniMailOnUnknownProvider));
                Assert.That(exception.SuppliersEmails, Is.StringContaining(from));
                SendErrorToProvider(handler, exception, message);
            }
        }