def setup():
    debug_enabled = os.environ.get('DEBUG', False)
    reactor_manager.start_reactor(logging=debug_enabled)
    app.config.from_pyfile(os.path.join(os.environ['HOME'], '.pixelated'))
    leap_session = open_leap_session(app.config['LEAP_USERNAME'], app.config['LEAP_PASSWORD'], app.config['LEAP_SERVER_NAME'])
    mail_service = MailService(leap_session)
    global mail_service
    mail_service.start()
    app.run(host=app.config['HOST'], debug=debug_enabled, port=app.config['PORT'])
    def setUp(self):
        self.querier = mock()
        self.mailboxes = mock()
        self.tag_service = mock()
        self.mailboxes.drafts = lambda: mock()
        self.mailboxes.trash = lambda: mock()
        self.mailboxes.sent = lambda: mock()

        self.mail_sender = mock()
        self.mail_service = MailService(self.mailboxes, self.mail_sender, self.tag_service, self.querier)
    def test_search_without_query_returns_unfiltered_mailbox(self):
        # given
        mailbox = test_helper.leap_mailbox(leap_flags=['\\Recent'], extra_flags=['tag_custom_tag'])
        account = MagicMock()
        account.getMailbox.return_value = mailbox
        leap_session = MagicMock(account=account)

        # when
        mailservice = MailService(leap_session)
        mails = mailservice.mails({})

        # then
        self.assertEqual(1, len(mails))
    def test_send_mail(self):
        leap_session = Mock(account_email=lambda: "username@leap_server")
        mail_service = MailService(leap_session)
        mail_service._create_smtp_server = lambda: None
        mail_service._create_smtp_server = lambda: None

        mail_service.smtp_client = Mock()
        mail = Mock(
            to_smtp_format=lambda _from=None: "mail as string",
            get_to=lambda: '*****@*****.**'
        )

        mail_service.send(mail)

        mail_service.smtp_client.sendmail.assert_called_with('username@leap_server', '*****@*****.**', "mail as string")
    def test_custom_tags_get_created_if_not_exists(self, mockRemoveFlags, mockAppendFlags):
        mailbox = test_helper.leap_mailbox(leap_flags=['\\Recent'])
        account = MagicMock()
        leap_session = MagicMock()
        leap_session.account = account
        leap_session.account.getMailbox.return_value = mailbox

        mailservice = MailService(leap_session)

        new_tags = ['test', 'inbox']
        updated_tags = mailservice.update_tags(6, new_tags)

        self.assertEquals(set([Tag('test'), Tag('inbox')]), set(updated_tags))
        # make sure that special tags are skipped when setting leap flags (eg.: tag_inbox)
        mockAppendFlags.assert_called_with(6, ['tag_test'])
        mockRemoveFlags.assert_called_with(6, [])
    def setup_soledad(self):
        self.soledad = initialize_soledad(tempdir=soledad_test_folder)
        self.mail_address = "*****@*****.**"

        # setup app
        PixelatedMail.from_email_address = self.mail_address

        SearchEngine.INDEX_FOLDER = soledad_test_folder + '/search_index'

        self.client = pixelated.runserver.app.test_client()

        self._reset_routes(self.client.application)
        self.soledad_querier = SoledadQuerier(self.soledad)
        self.account = FakeAccount()
        self.mailboxes = Mailboxes(self.account, self.soledad_querier)
        self.mail_sender = mock()
        self.tag_service = TagService()
        self.draft_service = DraftService(self.mailboxes)
        self.mail_service = MailService(self.mailboxes, self.mail_sender, self.tag_service,
                                        self.soledad_querier)
        self.search_engine = SearchEngine()
        self.search_engine.index_mails(self.mail_service.all_mails())

        features_controller = FeaturesController()
        features_controller.DISABLED_FEATURES.append('autoReload')
        home_controller = HomeController()
        mails_controller = MailsController(mail_service=self.mail_service,
                                           draft_service=self.draft_service,
                                           search_engine=self.search_engine)
        tags_controller = TagsController(search_engine=self.search_engine)
        sync_info_controller = SyncInfoController()

        app_factory._setup_routes(self.client.application, home_controller, mails_controller, tags_controller,
                                  features_controller, sync_info_controller)
    def setup_soledad(self):
        unstub()  # making sure all mocks from other tests are reset

        # making sure soledad test folder is not there
        if (os.path.isdir(soledad_test_folder)):
            shutil.rmtree(soledad_test_folder)

        self.soledad = initialize_soledad(tempdir=soledad_test_folder)
        self.mail_address = "*****@*****.**"

        # resetting soledad querier
        SoledadQuerier.reset()
        SoledadQuerier.get_instance(soledad=self.soledad)

        # setup app
        PixelatedMail.from_email_address = self.mail_address
        self.app = pixelated.user_agent.app.test_client()
        self.account = FakeAccount()
        self.pixelated_mailboxes = PixelatedMailBoxes(self.account)
        self.mail_sender = mock()
        self.tag_index = TagIndex(os.path.join(soledad_test_folder, 'tag_index'))
        self.tag_service = TagService(self.tag_index)
        self.draft_service = DraftService(self.pixelated_mailboxes)
        self.mail_service = MailService(self.pixelated_mailboxes, self.mail_sender, self.tag_service)

        SearchEngine.INDEX_FOLDER = soledad_test_folder + '/search_index'
        self.search_engine = SearchEngine()

        self.search_engine.index_mails(self.mail_service.all_mails())

        pixelated.user_agent.mail_service = self.mail_service
        pixelated.user_agent.draft_service = self.draft_service
        pixelated.user_agent.tag_service = self.tag_service
        pixelated.user_agent.search_engine = self.search_engine
    def setUp(self):
        self.querier = mock()
        self.mailboxes = mock()
        self.tag_service = mock()
        self.mailboxes.drafts = lambda: mock()
        self.mailboxes.trash = lambda: mock()
        self.mailboxes.sent = lambda: mock()

        self.mail_sender = mock()
        self.mail_service = MailService(self.mailboxes, self.mail_sender, self.tag_service, self.querier)
    def test_search_for_tags(self):
        # given
        mailbox = test_helper.leap_mailbox(leap_flags=['\\Recent'], extra_flags=['tag_custom_tag'])
        matching_mail = test_helper.leap_mail(uid=6, leap_flags=[], extra_flags=['tag_custom_tag'])
        not_matching_mail = test_helper.leap_mail(uid=6, leap_flags=[], extra_flags=['tag_other'])
        mailbox.messages = [matching_mail, not_matching_mail]
        mailbox.all_tags.return_value = set()
        account = MagicMock()
        account.mailboxes = ['inbox']
        account.getMailbox.return_value = mailbox

        leap_session = MagicMock(account=account)

        # when
        mailservice = MailService(leap_session)
        mails = mailservice.mails({'tags': ['inbox', 'custom_tag']})

        # then
        self.assertEqual(1, len(mails))
        self.assertEqual(set([Tag('custom_tag')]), mails[0].tags)
    def setUp(self):
        self.querier = mock()
        pixelated.adapter.soledad_querier.get_soledad_querier_instance = lambda x, y: self.querier

        self.mailboxes = mock()
        self.mailboxes.drafts = lambda: mock()
        self.mailboxes.trash = lambda: mock()
        self.mailboxes.sent = lambda: mock()

        self.mail_sender = mock()
        self.mail_service = MailService(self.mailboxes, self.mail_sender)
Beispiel #11
0
    def __init__(self, soledad_test_folder='soledad-test'):

        self.soledad = initialize_soledad(tempdir=soledad_test_folder)
        self.mail_address = "*****@*****.**"

        # setup app
        PixelatedMail.from_email_address = self.mail_address

        SearchEngine.INDEX_FOLDER = soledad_test_folder + '/search_index'

        self.app = pixelated.runserver.app

        self.soledad_querier = SoledadQuerier(self.soledad)
        self.soledad_querier.get_index_masterkey = lambda: '_yg2oG_5ELM8_-sQYcsxI37WesI0dOtZQXpwAqjvhR4='

        self.account = SoledadBackedAccount('test', self.soledad, MagicMock())
        self.mailboxes = Mailboxes(self.account, self.soledad_querier)
        self.mail_sender = Mock()
        self.tag_service = TagService()
        self.draft_service = DraftService(self.mailboxes)
        self.mail_service = MailService(self.mailboxes, self.mail_sender,
                                        self.tag_service, self.soledad_querier)
        self.search_engine = SearchEngine(self.soledad_querier)
        self.search_engine.index_mails(self.mail_service.all_mails())

        features_controller = FeaturesController()
        features_controller.DISABLED_FEATURES.append('autoReload')
        home_controller = HomeController()
        mails_controller = MailsController(mail_service=self.mail_service,
                                           draft_service=self.draft_service,
                                           search_engine=self.search_engine)
        tags_controller = TagsController(search_engine=self.search_engine)
        contacts_controller = ContactsController(
            search_engine=self.search_engine)
        sync_info_controller = SyncInfoController()
        attachments_controller = AttachmentsController(self.soledad_querier)

        setup_routes(self.app, home_controller, mails_controller,
                     tags_controller, features_controller,
                     sync_info_controller, attachments_controller,
                     contacts_controller)
class TestMailService(unittest.TestCase):
    def setUp(self):
        self.querier = mock()
        self.mailboxes = mock()
        self.tag_service = mock()
        self.mailboxes.drafts = lambda: mock()
        self.mailboxes.trash = lambda: mock()
        self.mailboxes.sent = lambda: mock()

        self.mail_sender = mock()
        self.mail_service = MailService(self.mailboxes, self.mail_sender, self.tag_service, self.querier)

    def test_send_mail(self):
        mail = "mail"

        self.mail_service.send(1, mail)

        verify(self.mail_sender).sendmail(mail)

    def test_mark_as_read(self):
        mail = mock()
        when(self.mail_service).mail(any()).thenReturn(mail)
        self.mail_service.mark_as_read(1)

        verify(mail).mark_as_read()

    def test_delete_mail(self):
        self.mail_service.delete_mail(1)

        verify(self.mailboxes).move_to_trash(1)
class TestMailService(unittest.TestCase):
    def setUp(self):
        self.querier = mock()
        pixelated.adapter.soledad_querier.get_soledad_querier_instance = lambda x, y: self.querier

        self.mailboxes = mock()
        self.mailboxes.drafts = lambda: mock()
        self.mailboxes.trash = lambda: mock()
        self.mailboxes.sent = lambda: mock()

        self.mail_sender = mock()
        self.mail_service = MailService(self.mailboxes, self.mail_sender)

    def test_send_mail(self):
        mail = "mail"

        self.mail_service.send(1, mail)

        verify(self.mail_sender).sendmail(mail)

    def test_mark_as_read(self):
        mail = mock()
        when(self.mail_service).mail(any()).thenReturn(mail)
        self.mail_service.mark_as_read(1)

        verify(mail).mark_as_read()

    def test_delete_mail(self):
        self.mail_service.delete_mail(1)

        verify(self.mailboxes).move_to_trash(1)
def init_app(app):
    leap_session = init_leap_session(app)
    soledad_querier = SoledadQuerier(soledad=leap_session.account._soledad)

    tag_service = TagService()
    search_engine = SearchEngine(soledad_querier)
    pixelated_mail_sender = MailSender(leap_session.account_email())

    pixelated_mailboxes = Mailboxes(leap_session.account, soledad_querier)
    draft_service = DraftService(pixelated_mailboxes)
    mail_service = MailService(pixelated_mailboxes, pixelated_mail_sender,
                               tag_service, soledad_querier)

    MailboxIndexerListener.SEARCH_ENGINE = search_engine
    InputMail.FROM_EMAIL_ADDRESS = leap_session.account_email()

    home_controller = HomeController()
    features_controller = FeaturesController()
    mails_controller = MailsController(mail_service=mail_service,
                                       draft_service=draft_service,
                                       search_engine=search_engine)
    tags_controller = TagsController(search_engine=search_engine)
    contacts_controller = ContactsController(search_engine=search_engine)
    sync_info_controller = SyncInfoController()
    attachments_controller = AttachmentsController(soledad_querier)

    register(signal=proto.SOLEDAD_SYNC_RECEIVE_STATUS,
             callback=update_info_sync_and_index_partial(
                 sync_info_controller=sync_info_controller,
                 search_engine=search_engine,
                 mail_service=mail_service))
    register(signal=proto.SOLEDAD_DONE_DATA_SYNC,
             callback=init_index_and_remove_dupes(querier=soledad_querier,
                                                  search_engine=search_engine,
                                                  mail_service=mail_service))

    register(signal=proto.SOLEDAD_DONE_DATA_SYNC,
             uid=CREATE_KEYS_IF_KEYS_DONT_EXISTS_CALLBACK,
             callback=look_for_user_key_and_create_if_cant_find(leap_session))

    setup_routes(app, home_controller, mails_controller, tags_controller,
                 features_controller, sync_info_controller,
                 attachments_controller, contacts_controller)
class TestMailService(unittest.TestCase):
    def setUp(self):
        self.querier = mock()
        self.mailboxes = mock()
        self.tag_service = mock()
        self.mailboxes.drafts = lambda: mock()
        self.mailboxes.trash = lambda: mock()
        self.mailboxes.sent = lambda: mock()

        self.mail_sender = mock()
        self.mail_service = MailService(self.mailboxes, self.mail_sender, self.tag_service, self.querier)

    def test_send_mail(self):
        mail = "mail"

        self.mail_service.send(1, mail)

        verify(self.mail_sender).sendmail(mail)

    def test_mark_as_read(self):
        mail = mock()
        when(self.mail_service).mail(any()).thenReturn(mail)
        self.mail_service.mark_as_read(1)

        verify(mail).mark_as_read()

    def test_delete_mail(self):
        self.mail_service.delete_mail(1)

        verify(self.mailboxes).move_to_trash(1)

    def test_reply_all_template(self):
        mail = mock()
        when(self.mail_service).mail(1).thenReturn(mail)

        self.mail_service.reply_all_template(1)

        verify(mail).to_reply_template()
    def __init__(self, soledad_test_folder='soledad-test'):

        self.soledad = initialize_soledad(tempdir=soledad_test_folder)
        self.mail_address = "*****@*****.**"

        # setup app
        PixelatedMail.from_email_address = self.mail_address

        SearchEngine.INDEX_FOLDER = soledad_test_folder + '/search_index'

        self.app = pixelated.runserver.app

        self.soledad_querier = SoledadQuerier(self.soledad)
        self.soledad_querier.get_index_masterkey = lambda: '_yg2oG_5ELM8_-sQYcsxI37WesI0dOtZQXpwAqjvhR4='

        self.account = SoledadBackedAccount('test', self.soledad, MagicMock())
        self.mailboxes = Mailboxes(self.account, self.soledad_querier)
        self.mail_sender = Mock()
        self.tag_service = TagService()
        self.draft_service = DraftService(self.mailboxes)
        self.mail_service = MailService(self.mailboxes, self.mail_sender, self.tag_service,
                                        self.soledad_querier)
        self.search_engine = SearchEngine(self.soledad_querier)
        self.search_engine.index_mails(self.mail_service.all_mails())

        features_controller = FeaturesController()
        features_controller.DISABLED_FEATURES.append('autoReload')
        home_controller = HomeController()
        mails_controller = MailsController(mail_service=self.mail_service,
                                           draft_service=self.draft_service,
                                           search_engine=self.search_engine)
        tags_controller = TagsController(search_engine=self.search_engine)
        contacts_controller = ContactsController(search_engine=self.search_engine)
        sync_info_controller = SyncInfoController()
        attachments_controller = AttachmentsController(self.soledad_querier)

        setup_routes(self.app, home_controller, mails_controller, tags_controller,
                     features_controller, sync_info_controller, attachments_controller, contacts_controller)
class AppTestClient:
    def __init__(self, soledad_test_folder='soledad-test'):

        self.soledad = initialize_soledad(tempdir=soledad_test_folder)
        self.mail_address = "*****@*****.**"

        # setup app
        PixelatedMail.from_email_address = self.mail_address

        SearchEngine.INDEX_FOLDER = soledad_test_folder + '/search_index'

        self.app = pixelated.runserver.app

        self.soledad_querier = SoledadQuerier(self.soledad)
        self.soledad_querier.get_index_masterkey = lambda: '_yg2oG_5ELM8_-sQYcsxI37WesI0dOtZQXpwAqjvhR4='

        self.account = SoledadBackedAccount('test', self.soledad, MagicMock())
        self.mailboxes = Mailboxes(self.account, self.soledad_querier)
        self.mail_sender = Mock()
        self.tag_service = TagService()
        self.draft_service = DraftService(self.mailboxes)
        self.mail_service = MailService(self.mailboxes, self.mail_sender, self.tag_service,
                                        self.soledad_querier)
        self.search_engine = SearchEngine(self.soledad_querier)
        self.search_engine.index_mails(self.mail_service.all_mails())

        features_controller = FeaturesController()
        features_controller.DISABLED_FEATURES.append('autoReload')
        home_controller = HomeController()
        mails_controller = MailsController(mail_service=self.mail_service,
                                           draft_service=self.draft_service,
                                           search_engine=self.search_engine)
        tags_controller = TagsController(search_engine=self.search_engine)
        contacts_controller = ContactsController(search_engine=self.search_engine)
        sync_info_controller = SyncInfoController()
        attachments_controller = AttachmentsController(self.soledad_querier)

        setup_routes(self.app, home_controller, mails_controller, tags_controller,
                     features_controller, sync_info_controller, attachments_controller, contacts_controller)

    def _render(self, request, as_json=True):
        def get_request_written_data(_=None):
            written_data = request.getWrittenData()
            if written_data:
                return json.loads(written_data) if as_json else written_data

        d = _render(self.app.resource(), request)
        if request.finished:
            return get_request_written_data(), request
        else:
            d.addCallback(get_request_written_data)
            return d, request

    def run_on_a_thread(self, logfile='/tmp/app_test_client.log', port=4567, host='localhost'):
        worker = lambda: self.app.run(host=host, port=port, logFile=open(logfile, 'w'))
        process = multiprocessing.Process(target=worker)
        process.start()
        time.sleep(1)  # just let it start
        return lambda: process.terminate()

    def get(self, path, get_args, as_json=True):
        request = requestMock(path)
        request.args = get_args
        return self._render(request, as_json)

    def post(self, path, body=''):
        request = requestMock(path=path, method="POST", body=body, headers={'Content-Type': ['application/json']})
        return self._render(request)

    def put(self, path, body):
        request = requestMock(path=path, method="PUT", body=body, headers={'Content-Type': ['application/json']})
        return self._render(request)

    def delete(self, path):
        request = requestMock(path=path, method="DELETE")
        return self._render(request)

    def add_document_to_soledad(self, _dict):
        self.soledad_querier.soledad.create_doc(_dict)

    def add_mail_to_inbox(self, input_mail):
        mail = self.mailboxes.inbox().add(input_mail)
        mail.update_tags(input_mail.tags)
        self.search_engine.index_mail(mail)

    def add_multiple_to_mailbox(self, num, mailbox='', flags=[], tags=[]):
        mails = []
        for _ in range(num):
            input_mail = MailBuilder().with_status(flags).with_tags(tags).build_input_mail()
            mail = self.mailboxes._create_or_get(mailbox).add(input_mail)
            mails.append(mail)
            mail.update_tags(input_mail.tags)
            self.search_engine.index_mail(mail)
        return mails
class SoledadTestBase:
    def teardown_soledad(self):
        self.soledad.close()
        shutil.rmtree(soledad_test_folder)

    def setup_soledad(self):
        unstub()  # making sure all mocks from other tests are reset

        # making sure soledad test folder is not there
        if (os.path.isdir(soledad_test_folder)):
            shutil.rmtree(soledad_test_folder)

        self.soledad = initialize_soledad(tempdir=soledad_test_folder)
        self.mail_address = "*****@*****.**"

        # resetting soledad querier
        SoledadQuerier.reset()
        SoledadQuerier.get_instance(soledad=self.soledad)

        # setup app
        PixelatedMail.from_email_address = self.mail_address
        self.app = pixelated.user_agent.app.test_client()
        self.account = FakeAccount()
        self.pixelated_mailboxes = PixelatedMailBoxes(self.account)
        self.mail_sender = mock()
        self.tag_index = TagIndex(os.path.join(soledad_test_folder, 'tag_index'))
        self.tag_service = TagService(self.tag_index)
        self.draft_service = DraftService(self.pixelated_mailboxes)
        self.mail_service = MailService(self.pixelated_mailboxes, self.mail_sender, self.tag_service)

        SearchEngine.INDEX_FOLDER = soledad_test_folder + '/search_index'
        self.search_engine = SearchEngine()

        self.search_engine.index_mails(self.mail_service.all_mails())

        pixelated.user_agent.mail_service = self.mail_service
        pixelated.user_agent.draft_service = self.draft_service
        pixelated.user_agent.tag_service = self.tag_service
        pixelated.user_agent.search_engine = self.search_engine

    def get_mails_by_tag(self, tag):
        response = json.loads(self.app.get("/mails?q=tag:" + tag).data)
        return [ResponseMail(m) for m in response['mails']]

    def post_mail(self, data):
        response = json.loads(self.app.post('/mails', data=data, content_type="application/json").data)
        return ResponseMail(response)

    def put_mail(self, data):
        response = json.loads(self.app.put('/mails', data=data, content_type="application/json").data)
        return response['ident']

    def post_tags(self, mail_ident, tags_json):
        return json.loads(
            self.app.post('/mail/' + mail_ident + '/tags', data=tags_json, content_type="application/json").data)

    def delete_mail(self, mail_ident):
        self.app.delete('/mail/' + mail_ident)

    def mark_as_read(self, mail_ident):
        self.app.post('/mail/' + mail_ident + '/read', content_type="application/json")

    def add_mail_to_inbox(self, input_mail):
        mail = self.pixelated_mailboxes.inbox().add(input_mail)
        self.search_engine.index_mail(mail)
Beispiel #19
0
class AppTestClient:
    def __init__(self, soledad_test_folder='soledad-test'):

        self.soledad = initialize_soledad(tempdir=soledad_test_folder)
        self.mail_address = "*****@*****.**"

        # setup app
        PixelatedMail.from_email_address = self.mail_address

        SearchEngine.INDEX_FOLDER = soledad_test_folder + '/search_index'

        self.app = pixelated.runserver.app

        self.soledad_querier = SoledadQuerier(self.soledad)
        self.soledad_querier.get_index_masterkey = lambda: '_yg2oG_5ELM8_-sQYcsxI37WesI0dOtZQXpwAqjvhR4='

        self.account = SoledadBackedAccount('test', self.soledad, MagicMock())
        self.mailboxes = Mailboxes(self.account, self.soledad_querier)
        self.mail_sender = Mock()
        self.tag_service = TagService()
        self.draft_service = DraftService(self.mailboxes)
        self.mail_service = MailService(self.mailboxes, self.mail_sender,
                                        self.tag_service, self.soledad_querier)
        self.search_engine = SearchEngine(self.soledad_querier)
        self.search_engine.index_mails(self.mail_service.all_mails())

        features_controller = FeaturesController()
        features_controller.DISABLED_FEATURES.append('autoReload')
        home_controller = HomeController()
        mails_controller = MailsController(mail_service=self.mail_service,
                                           draft_service=self.draft_service,
                                           search_engine=self.search_engine)
        tags_controller = TagsController(search_engine=self.search_engine)
        contacts_controller = ContactsController(
            search_engine=self.search_engine)
        sync_info_controller = SyncInfoController()
        attachments_controller = AttachmentsController(self.soledad_querier)

        setup_routes(self.app, home_controller, mails_controller,
                     tags_controller, features_controller,
                     sync_info_controller, attachments_controller,
                     contacts_controller)

    def _render(self, request, as_json=True):
        def get_request_written_data(_=None):
            written_data = request.getWrittenData()
            if written_data:
                return json.loads(written_data) if as_json else written_data

        d = _render(self.app.resource(), request)
        if request.finished:
            return get_request_written_data(), request
        else:
            d.addCallback(get_request_written_data)
            return d, request

    def run_on_a_thread(self,
                        logfile='/tmp/app_test_client.log',
                        port=4567,
                        host='localhost'):
        worker = lambda: self.app.run(
            host=host, port=port, logFile=open(logfile, 'w'))
        process = multiprocessing.Process(target=worker)
        process.start()
        time.sleep(1)  # just let it start
        return lambda: process.terminate()

    def get(self, path, get_args, as_json=True):
        request = requestMock(path)
        request.args = get_args
        return self._render(request, as_json)

    def post(self, path, body=''):
        request = requestMock(path=path,
                              method="POST",
                              body=body,
                              headers={'Content-Type': ['application/json']})
        return self._render(request)

    def put(self, path, body):
        request = requestMock(path=path,
                              method="PUT",
                              body=body,
                              headers={'Content-Type': ['application/json']})
        return self._render(request)

    def delete(self, path):
        request = requestMock(path=path, method="DELETE")
        return self._render(request)

    def add_document_to_soledad(self, _dict):
        self.soledad_querier.soledad.create_doc(_dict)

    def add_mail_to_inbox(self, input_mail):
        mail = self.mailboxes.inbox().add(input_mail)
        mail.update_tags(input_mail.tags)
        self.search_engine.index_mail(mail)

    def add_multiple_to_mailbox(self, num, mailbox='', flags=[], tags=[]):
        mails = []
        for _ in range(num):
            input_mail = MailBuilder().with_status(flags).with_tags(
                tags).build_input_mail()
            mail = self.mailboxes._create_or_get(mailbox).add(input_mail)
            mails.append(mail)
            mail.update_tags(input_mail.tags)
            self.search_engine.index_mail(mail)
        return mails
class SoledadTestBase:
    def __init__(self):
        pass

    def teardown_soledad(self):
        pass

    def setup_soledad(self):
        self.soledad = initialize_soledad(tempdir=soledad_test_folder)
        self.mail_address = "*****@*****.**"

        # setup app
        PixelatedMail.from_email_address = self.mail_address

        SearchEngine.INDEX_FOLDER = soledad_test_folder + '/search_index'

        self.app = pixelated.runserver.app

        self.soledad_querier = SoledadQuerier(self.soledad)

        self.account = SoledadBackedAccount('test', self.soledad, MagicMock())
        self.mailboxes = Mailboxes(self.account, self.soledad_querier)
        self.mail_sender = mock()
        self.tag_service = TagService()
        self.draft_service = DraftService(self.mailboxes)
        self.mail_service = MailService(self.mailboxes, self.mail_sender, self.tag_service,
                                        self.soledad_querier)
        self.search_engine = SearchEngine(self.soledad_querier)
        self.search_engine.index_mails(self.mail_service.all_mails())

        features_controller = FeaturesController()
        features_controller.DISABLED_FEATURES.append('autoReload')
        home_controller = HomeController()
        mails_controller = MailsController(mail_service=self.mail_service,
                                           draft_service=self.draft_service,
                                           search_engine=self.search_engine)
        tags_controller = TagsController(search_engine=self.search_engine)
        sync_info_controller = SyncInfoController()
        attachments_controller = AttachmentsController(self.soledad_querier)

        app_factory._setup_routes(self.app, home_controller, mails_controller, tags_controller,
                                  features_controller, sync_info_controller, attachments_controller)
        self.resource = KleinResource(self.app)

    def get_mails_by_tag(self, tag, page=1, window=100):
        request = requestMock(path="/mails")
        request.args = {
            'q': ['tag:%s' % tag],
            'w': [str(window)],
            'p': [str(page)]
        }
        _render(self.resource, request)
        response = json.loads(request.getWrittenData())
        return [ResponseMail(m) for m in response['mails']]

    def post_mail(self, data):
        request = requestMock(path='/mails', method="POST", body=data, headers={'Content-Type': ['application/json']})
        _render(self.resource, request)
        response = json.loads(request.getWrittenData())
        return ResponseMail(response)

    def get_attachment(self, ident, encoding):
        request = requestMock(path='/attachment/' + ident)
        request.args = {
            'encoding': [encoding]
        }
        _render(self.resource, request)
        return request.getWrittenData()

    def put_mail(self, data):
        request = requestMock('/mails', method="PUT", body=data, headers={'Content-Type': ['application/json']})
        _render(self.resource, request)
        response = json.loads(request.getWrittenData())
        return response['ident']

    def post_tags(self, mail_ident, tags_json):
        request = requestMock('/mail/' + mail_ident + '/tags', method="POST", body=tags_json,
                              headers={'Content-Type': ['application/json']})
        _render(self.resource, request)
        return json.loads(request.getWrittenData())

    def get_tags(self, **kwargs):
        request = requestMock('/tags')
        request.args = kwargs
        _render(self.resource, request)
        return json.loads(request.getWrittenData())

    def delete_mail(self, mail_ident):
        request = requestMock(path='/mail/' + mail_ident, method="DELETE")
        _render(self.resource, request)
        return request

    def mark_as_read(self, mail_ident):
        request = requestMock('/mail/' + mail_ident + '/read', method="POST", headers={'Content-Type': ['application/json']})
        _render(self.resource, request)
        return request

    def mark_as_unread(self, mail_ident):
        request = requestMock('/mail/' + mail_ident + '/unread', method="POST", headers={'Content-Type': ['application/json']})
        _render(self.resource, request)
        return request

    def mark_many_as_unread(self, idents):
        request = requestMock('/mails/unread', method="POST", body=json.dumps({'idents': idents}), headers={'Content-Type': ['application/json']})
        _render(self.resource, request)
        return request

    def mark_many_as_read(self, idents):
        request = requestMock('/mails/read', method="POST", body=json.dumps({'idents': idents}), headers={'Content-Type': ['application/json']})
        _render(self.resource, request)
        return request

    def add_document_to_soledad(self, _dict):
        self.soledad_querier.soledad.create_doc(_dict)

    def add_mail_to_inbox(self, input_mail):
        mail = self.mailboxes.inbox().add(input_mail)
        mail.update_tags(input_mail.tags)
        self.search_engine.index_mail(mail)

    def add_multiple_to_mailbox(self, num, mailbox='', flags=[], tags=[]):
        mails = []
        for _ in range(num):
            input_mail = MailBuilder().with_status(flags).with_tags(tags).build_input_mail()
            mail = self.mailboxes._create_or_get(mailbox).add(input_mail)
            mails.append(mail)
            mail.update_tags(input_mail.tags)
            self.search_engine.index_mail(mail)
        return mails
class SoledadTestBase:
    def __init__(self):
        pass

    def teardown_soledad(self):
        pass

    def _reset_routes(self, app):
        static_files_route = app.view_functions['static']
        app.view_functions = {'static': static_files_route}

    def setup_soledad(self):
        self.soledad = initialize_soledad(tempdir=soledad_test_folder)
        self.mail_address = "*****@*****.**"

        # setup app
        PixelatedMail.from_email_address = self.mail_address

        SearchEngine.INDEX_FOLDER = soledad_test_folder + '/search_index'

        self.client = pixelated.runserver.app.test_client()

        self._reset_routes(self.client.application)
        self.soledad_querier = SoledadQuerier(self.soledad)
        self.account = FakeAccount()
        self.mailboxes = Mailboxes(self.account, self.soledad_querier)
        self.mail_sender = mock()
        self.tag_service = TagService()
        self.draft_service = DraftService(self.mailboxes)
        self.mail_service = MailService(self.mailboxes, self.mail_sender, self.tag_service,
                                        self.soledad_querier)
        self.search_engine = SearchEngine()
        self.search_engine.index_mails(self.mail_service.all_mails())

        features_controller = FeaturesController()
        features_controller.DISABLED_FEATURES.append('autoReload')
        home_controller = HomeController()
        mails_controller = MailsController(mail_service=self.mail_service,
                                           draft_service=self.draft_service,
                                           search_engine=self.search_engine)
        tags_controller = TagsController(search_engine=self.search_engine)
        sync_info_controller = SyncInfoController()

        app_factory._setup_routes(self.client.application, home_controller, mails_controller, tags_controller,
                                  features_controller, sync_info_controller)

    def get_mails_by_tag(self, tag, page=1, window=100):
        response = json.loads(self.client.get("/mails?q=tag:%s&w=%s&p=%s" % (tag, window, page)).data)
        return [ResponseMail(m) for m in response['mails']]

    def post_mail(self, data):
        response = json.loads(self.client.post('/mails', data=data, content_type="application/json").data)
        return ResponseMail(response)

    def put_mail(self, data):
        response = json.loads(self.client.put('/mails', data=data, content_type="application/json").data)
        return response['ident']

    def post_tags(self, mail_ident, tags_json):
        return json.loads(
            self.client.post('/mail/' + mail_ident + '/tags', data=tags_json, content_type="application/json").data)

    def get_tags(self, query_string=""):
        return json.loads(
            self.client.get('/tags' + query_string, content_type="application/json").data)

    def delete_mail(self, mail_ident):
        self.client.delete('/mail/' + mail_ident)

    def mark_as_read(self, mail_ident):
        self.client.post('/mail/' + mail_ident + '/read', content_type="application/json")

    def mark_as_unread(self, mail_ident):
        self.client.post('/mail/' + mail_ident + '/unread', content_type="application/json")

    def mark_many_as_unread(self, idents):
        self.client.post('/mails/unread', data={'idents': json.dumps(idents)})

    def mark_many_as_read(self, idents):
        return self.client.post('/mails/read', data={'idents': json.dumps(idents)})

    def add_mail_to_inbox(self, input_mail):
        mail = self.mailboxes.inbox().add(input_mail)
        mail.update_tags(input_mail.tags)
        self.search_engine.index_mail(mail)

    def add_multiple_to_mailbox(self, num, mailbox='', flags=[], tags=[]):
        mails = []
        for _ in range(num):
            input_mail = MailBuilder().with_status(flags).with_tags(tags).build_input_mail()
            mail = self.mailboxes._create_or_get(mailbox).add(input_mail)
            mails.append(mail)
            mail.update_tags(input_mail.tags)
            self.search_engine.index_mail(mail)
        return mails