Esempio n. 1
0
 def setUp(self):
     """Set up a class ready for testing"""
     super(ReviewUgQnViewTest, self).setUp()
     self.loghandlers = dict(
         sqlalchemy=InstalledHandler('sqlalchemy.engine'),
         sync=InstalledHandler('tutorweb.quizdb.browser.sync')
     )
    def setUp(self):
        """Set up a class ready for testing"""
        super(SyncClassSubscriptionsTest, self).setUp()
        portal = self.layer['portal']

        self.loghandlers = dict(
            sqlalchemy=InstalledHandler('sqlalchemy.engine'),
            sync=InstalledHandler('tutorweb.quizdb.browser.sync'))
Esempio n. 3
0
    def setUp(self):
        super(FunctionalTestCase, self).setUp()
        self.loghandlers = dict(
            sqlalchemy=InstalledHandler('sqlalchemy.engine'),
            sync=InstalledHandler('tutorweb.quizdb.browser.sync'),
            syncm=InstalledHandler('tutorweb.quizdb.sync'),
        )

        self.objectPublish(self.layer['portal']['dept1']['tut1']['lec1'])
        self.objectPublish(self.layer['portal']['dept1']['tut1']['lec2'])
Esempio n. 4
0
def setUp(test):
    test.globs['root'] = ZopeTestCase.base.app()
    # As task will be run in different threads, we cannot rely on print
    # results. We need to log calls to prove correctness.
    log_info = InstalledHandler('z3c.taskqueue')
    test.globs['log_info'] = log_info
    # We pass the ZPublisher conflict logger to prove that no conflict
    # happened.
    conflict_logger = InstalledHandler('ZPublisher.Conflict')
    test.globs['conflict_logger'] = conflict_logger
    # Make sure ZPublisher conflict error log level is setup.
    _configure_conflict_error_log_level()
    test.origArgs = service.TaskService.processorArguments
    service.TaskService.processorArguments = {'waitTime': 0.0}
    # Make tests predictable
    random.seed(27)
Esempio n. 5
0
    def setUp(self):
        """Set up a class ready for testing"""
        portal = self.layer['portal']
        login(portal, MANAGER_ID)

        self.loghandlers = dict(
            sqlalchemy=InstalledHandler('sqlalchemy.engine'),
            sync=InstalledHandler('tutorweb.quizdb.browser.sync'))

        # Create an extra test tutorial
        portal['dept1'].invokeFactory(
            type_name="tw_tutorial",
            id="tut_extra",
            title="Unittest D1 tutExtra",
        )
        self.extra_lec = self.createTestLecture(qnCount=1)
    def test_ActionExecutor(self):

        self.createIFTTTAction()

        # configure easyform actions
        self.assertTrue('ifttt' in get_actions(self.ff1))
        ifttt_trigger = get_actions(self.ff1)['ifttt']
        ifttt_trigger.ifttt_event_name = u'ifttt applet'
        ifttt_trigger.payload_fields = ['replyto', 'topic', 'comments']

        request = FakeRequest(
            add_auth=True,
            method='POST',
            topic='test subject',
            replyto='*****@*****.**',
            comments='test comments'
        )

        self.assertFalse(ifttt_trigger.onSuccess(request.form, request))

        # set secret key
        api.portal.set_registry_record(
            name='ifttt.ifttt_secret_key',
            value=u'secret',
        )

        # inspect logs
        handler = InstalledHandler('collective.ifttt.requests')

        # execute action
        self.assertTrue(ifttt_trigger.onSuccess(request.form, request))

        messages = [record.getMessage() for record in handler.records]
        self.assertGreater(len(messages), 0)
        self.assertTrue(messages[0].startswith('Dispatched requests.post'))
Esempio n. 7
0
    def test_detect_delete_trigger(self):
        # Cause the delete trigger to be deleted by opening a newt.db
        # connection:
        import newt.db
        self.ex("drop table object_state")
        newt.db.storage(self.dsn).close()

        # Verify the trigger is there:
        from newt.db._util import trigger_exists
        from newt.db._adapter import DELETE_TRIGGER
        self.assertTrue(trigger_exists(self.cursor, DELETE_TRIGGER))

        from zope.testing.loggingsupport import InstalledHandler
        handler = InstalledHandler('newt.db.updater')

        self.assertEqual(1, updater.main([self.dsn]))
        self.assertEqual(
            "newt.db.updater ERROR\n"
            "  The Newt DB delete trigger exists.\n"
            "It is incompatible with the updater.\n"
            "Use -T to remove it.", str(handler))
        handler.clear()

        # Now run the updater with the -T option, which causes the
        # trigger to be deleted.  (We also use -g, which causes it to
        # to GC and nothing else, which makes it stop, so we don't
        # have to run in a thread.)
        self.assertEqual(0, updater.main([self.dsn, '-Tg']))
        self.assertEqual("", str(handler))

        # And the trigger is gone.
        self.assertFalse(trigger_exists(self.cursor, DELETE_TRIGGER))
    def testCookieErrorToLog(self):
        from zope.testing.loggingsupport import InstalledHandler
        cookies = {
            'HTTP_COOKIE':
                'foo=bar; path=/; spam="eggs"; ldap/OU="Williams"'
        }
        handler = InstalledHandler('eventlog')
        try:
            req = self._createRequest(extra_env=cookies)
        finally:
            handler.uninstall()

        self.assertEqual(len(handler.records), 1)

        message = handler.records[0].getMessage()
        self.assertTrue(message.startswith('Illegal key'))
        self.assertIn('ldap/OU', message)

        self.assertNotIn('foo', req.cookies)
        self.assertNotIn('foo', req)

        self.assertNotIn('spam', req.cookies)
        self.assertNotIn('spam', req)

        self.assertNotIn('ldap/OU', req.cookies)
        self.assertNotIn('ldap/OU', req)

        # Reserved key
        self.assertNotIn('path', req.cookies)
Esempio n. 9
0
 def setUp(self):
     from Products.LongRequestLogger.patch import do_patch
     from Products.LongRequestLogger.dumper import logger_name
     from zope.testing.loggingsupport import InstalledHandler
     self.setTestEnvironment()
     do_patch()
     self.loghandler = InstalledHandler(logger_name)
     self.requests = []
 def setUp(self):
     from Products.LongRequestLogger import do_patch, monitor, dumper
     from zope.testing.loggingsupport import InstalledHandler
     dumper.config = dict(logfile=os.devnull)
     log = dumper.getLogger()
     self.monitor = monitor.Monitor(log, **dumper.get_configuration())
     do_patch(self.monitor)
     self.loghandler = InstalledHandler(log.name)
     self.requests = []
Esempio n. 11
0
def setUp(test):
    root = placefulSetUp(site=True)
    test.globs['root'] = root
    log_info = InstalledHandler('z3c.taskqueue')
    test.globs['log_info'] = log_info
    test.origArgs = service.TaskService.processorArguments
    service.TaskService.processorArguments = {'waitTime': 0.0}
    # Make tests predictable
    random.seed(27)
Esempio n. 12
0
    def test_search_for_factory_updates_search_set(self):
        from zope.testing.loggingsupport import InstalledHandler

        with warnings.catch_warnings(record=True):
            INT.register_legacy_search_module(__name__)
            # The cache is initialized lazily
            assert_that(__name__, is_in(INT.LEGACY_FACTORY_SEARCH_MODULES))

            assert_that(INT.find_factory_for_class_name('testfunctions'),
                        is_(none()))

            # And we have been examined and removed
            assert_that(__name__,
                        is_not(is_in(INT.LEGACY_FACTORY_SEARCH_MODULES)))
            assert_that(INT.LEGACY_FACTORY_SEARCH_MODULES, is_(set()))

            # Now we're going to fiddle with our public classes and try again.
            # This will force re-registration to occur. Note we do this before
            # we make ourself public, so that we can assert it's lazy
            INT.register_legacy_search_module(__name__)

            TestFunctions.__external_can_create__ = True
            handler = InstalledHandler(INT.__name__)
            try:
                assert_that(INT.find_factory_for_class_name('testfunctions'),
                            equal_to(TestFunctions))

                # Now lets register ourself again, to trigger the logged warnings.
                assert_that(__name__,
                            is_not(is_in(INT.LEGACY_FACTORY_SEARCH_MODULES)))
                assert_that(INT.LEGACY_FACTORY_SEARCH_MODULES, is_(set()))

                # Now we're going to fiddle with our public classes and try again.
                # This will force re-registration to occur. Note we do this before
                # we make ourself public, so that we can assert it's lazy
                INT.register_legacy_search_module(__name__)

                assert_that(INT.find_factory_for_class_name('testfunctions'),
                            equal_to(TestFunctions))
                # case doesn't matter
                assert_that(INT.find_factory_for_class_name('TeStfUnctIons'),
                            equal_to(TestFunctions))

                assert_that(
                    str(handler),
                    contains_string(
                        "Found duplicate registration for legacy search path.")
                )

                assert_that(INT.legacy_factories.count_legacy_classes_found(),
                            greater_than_or_equal_to)

            finally:
                del TestFunctions.__external_can_create__
                handler.uninstall()
Esempio n. 13
0
    def test_database_events(self):
        from Zope2.App.startup import startup
        from zope.component import provideHandler
        from zope.processlifetime import IDatabaseOpened
        from zope.processlifetime import IDatabaseOpenedWithRoot

        handler = InstalledHandler('Zope2.App.test_startup')
        provideHandler(logevent, [IDatabaseOpenedWithRoot])
        provideHandler(logevent, [IDatabaseOpened])
        startup()
        self.assertEqual(str(handler), logged)
Esempio n. 14
0
    def test_remove_words_in_already_corrupted_index(self):
        from zope.testing.loggingsupport import InstalledHandler
        handler = InstalledHandler('nti.zope_catalog.index')
        self.addCleanup(handler.uninstall)

        index = self.index
        index.index_doc(1, ('aizen', ))
        index.index_doc(2, ['ichigo'])
        index.index_doc(3, ['Kuchiki', 'rukia'])
        del index._rev_index[3]
        index.remove_words(('Kuchiki', ))
        assert_that(handler.records[0].msg, is_("Your index is corrupted: %s"))
    def testConsumeFromQueue(self):
        self.assertEqual(len(self.task_queue), 0)
        taskqueue.add("/", queue=self.queue)
        taskqueue.add("/Plone", queue=self.queue)
        transaction.commit()
        self.assertEqual(len(self.task_queue), 2)

        handler = InstalledHandler("collective.taskqueue")
        runAsyncTest(self._testConsumeFromQueue)
        messages = [record.getMessage() for record in handler.records]
        self.assertEqual(messages[-2:],
                         ["http://nohost:/", "http://nohost:/Plone"])
Esempio n. 16
0
    def test_log_info(self):
        from zope.server import zlogintegration
        from zope.testing.loggingsupport import InstalledHandler

        handler = InstalledHandler('zope.server')
        try:
            zlogintegration.log_info(None, "Some Info")
        finally:
            handler.uninstall()

        self.assertEqual(1, len(handler.records))
        self.assertEqual("Some Info", str(handler.records[0].getMessage()))
Esempio n. 17
0
    def setUp(self):
        """Set up a class ready for testing"""
        portal = self.layer['portal']
        login(portal, MANAGER_ID)

        if 'classa' not in portal:
            portal.invokeFactory(
                type_name="tw_class",
                id="classa",
                title="Unittest ClassA",
                students=[USER_A_ID, USER_C_ID, USER_B_ID],
                lectures=[],
            )
        else:
            portal['classa'].lectures = []

        self.loghandlers = dict(
            sqlalchemy=InstalledHandler('sqlalchemy.engine'),
            sync=InstalledHandler('tutorweb.quizdb.browser.sync'))

        self.objectPublish(portal['dept1']['tut1']['lec1'])
        self.objectPublish(portal['dept1']['tut1']['lec2'])
Esempio n. 18
0
    def test_update_index_with_error(self):
        from zope.testing.loggingsupport import InstalledHandler
        handler = InstalledHandler('nti.zope_catalog.catalog')
        self.addCleanup(handler.uninstall)

        cat = self._makeOne()
        cat._PERSISTENCE_EXCEPTIONS = AttributeError

        cat.updateIndex(42, ignore_persistence_exceptions=True)

        assert_that(handler.records, has_length(1))
        assert_that(handler.records[0].msg,
                    is_("Error indexing object %s(%s); %s"))
    def testConsume100FromQueue(self):
        self.assertEqual(len(self.task_queue), 0)
        expected_result = []
        for i in range(100):
            taskqueue.add("/{0:02d}".format(i), queue=self.queue)
            expected_result.append("http://nohost:/{0:02d}".format(i))
        transaction.commit()
        self.assertEqual(len(self.task_queue), 100)

        handler = InstalledHandler("collective.taskqueue")
        runAsyncTest(self._testConsumeFromQueue)
        messages = [record.getMessage() for record in handler.records]

        self.assertEqual(sorted(messages[-100:]), expected_result)
Esempio n. 20
0
    def test_warnings_are_shown(self):
        import warnings
        import logging
        from zope.testing.loggingsupport import InstalledHandler

        handler = InstalledHandler("py.warnings", level=logging.WARNING)
        self.addCleanup(handler.uninstall)

        logging.captureWarnings(True)
        self.addCleanup(logging.captureWarnings, False)

        msg = "This should be visible by default"
        warnings.warn(msg, DeprecationWarning)

        self.assertEqual(1, len(handler.records))
        self.assertIn('DeprecationWarning', handler.records[0].getMessage())
        self.assertIn(msg, handler.records[0].getMessage())
Esempio n. 21
0
def test_suite():
    suite = unittest.TestSuite()
    my_dir = os.path.dirname(__file__)
    docs = os.path.join('..', '..', '..', 'docs')
    registerConfiguration = PLONEBLUEPRINTS_FUNCTIONAL_TESTING \
        .baseResolutionOrder[1].registerConfiguration
    for filename in os.listdir(os.path.join(my_dir, docs)):
        path = os.path.join(docs, filename)
        globs = {
            'registerConfiguration': registerConfiguration,
            'ITransmogrifier': ITransmogrifier,
            'api': api,
            'logger': InstalledHandler('logger', level=logging.INFO)
        }
        flags = doctest.NORMALIZE_WHITESPACE | doctest.ELLIPSIS
        suite.addTests([
            layered(doctest.DocFileSuite(path, globs=globs, optionflags=flags),
                    layer=PLONEBLUEPRINTS_FUNCTIONAL_TESTING)
        ])
    return suite
    def test_ActionExecutor(self):

        element = IftttTriggerAction()
        context = self.portal.restrictedTraverse('')

        api.portal.set_registry_record(
            name='ifttt.ifttt_secret_key',
            value=u'secret',
        )
        element.ifttt_event_name = 'ifttt_applet'

        for option in payload_options:
            # inspect logs
            handler = InstalledHandler('collective.ifttt.requests')

            element.payload_option = option.value
            ex = getMultiAdapter((context, element, DummyEvent(self.folder)),
                                 IExecutable)
            self.assertTrue(ex())
            messages = [record.getMessage() for record in handler.records]
            self.assertGreater(len(messages), 0)
            self.assertTrue(messages[0].startswith('Dispatched requests.post'))
Esempio n. 23
0
    def test_jsonifier(self):
        from zope.testing.loggingsupport import InstalledHandler
        handler = InstalledHandler('newt.db.jsonpickle')
        from ..jsonpickle import Jsonifier

        jsonifier = Jsonifier()

        p, tid = self.conn._storage.load(z64)
        class_name, ghost_pickle, state = jsonifier('0', p)
        self.assertEqual('persistent.mapping.PersistentMapping', class_name)
        self.assertEqual('{"data": {}}', state)
        self.assertTrue(
            p.startswith(ghost_pickle) and ghost_pickle[-1:] == b'.'
            and b'persistent.mapping' in ghost_pickle)

        # custon skip_class
        jsonifier2 = Jsonifier(skip_class=lambda c: 1)
        self.assertEqual((None, None, None), jsonifier2('0', p))

        # empty records are skipped:
        self.assertEqual((None, None, None), jsonifier('0', ''))

        # BTrees are skipped by default
        from BTrees.OOBTree import BTree
        self.root.x = BTree()
        self.conn.transaction_manager.commit()
        p, tid = self.conn._storage.load(self.root.x._p_oid)
        self.assertEqual((None, None, None), jsonifier('0', p))

        # errors are logged, and return Nones:
        self.assertEqual(handler.records, [])
        self.assertEqual((None, None, None), jsonifier('foo', b'badness'))
        self.assertEqual(
            [r.getMessage().replace("b'", "'") for r in handler.records],
            ["Failed pickle load, oid: 'foo', pickle starts: 'badness'"])

        handler.uninstall()
Esempio n. 24
0
 def setUp(self):
     super(TestLogActivityMonitor, self).setUp()
     self.handler = InstalledHandler('nti.zodb.activitylog')
     self.addCleanup(self.handler.uninstall)
Esempio n. 25
0
# -*- coding: utf-8 -*-
"""Tests for pyramid_bimt events."""

from pyramid import testing
from pyramid_bimt.security import SymmetricEncryption

import mock
import unittest

from zope.testing.loggingsupport import InstalledHandler  # noqa
handler = InstalledHandler('pyramid_bimt.security')


class TestVerify(unittest.TestCase):
    def setUp(self):
        testing.setUp()

    def tearDown(self):
        testing.tearDown()

    def test_invalid_cyphertext(self):
        """Test handling of an invalid cyphertext stored in DB."""
        from pyramid_bimt.security import verify
        self.assertFalse(verify('foo', 'invalid'))

        # error is not raised, but it is written to log so we get notified
        self.assertEqual(len(handler.records), 1)
        self.assertEqual(handler.records[0].message,
                         'hash could not be identified')

    def test_verify(self):
Esempio n. 26
0
 def setUp(self):
     self.handler = InstalledHandler('zope.i18n')
     self.addCleanup(self.handler.uninstall)
Esempio n. 27
0
from sqlalchemy import Column
from sqlalchemy import Enum
from sqlalchemy import ForeignKey
from sqlalchemy import Integer
from sqlalchemy import String
from sqlalchemy import Unicode
from sqlalchemy.orm import backref
from sqlalchemy.orm import relationship
from zope.testing.loggingsupport import InstalledHandler

import json
import mock
import transaction
import unittest

handler = InstalledHandler('pyramid_bimt.task')


class FooTaskModel(Base, BaseMixin):
    """A dummy celery task backend."""

    __tablename__ = 'foo_tasks'

    user_id = Column(Integer, ForeignKey('users.id'))
    user = relationship(
        User,
        backref=backref('tasks'),
    )

    task_id = Column(
        String,
Esempio n. 28
0
 def setUp(self):
     Test_ro.setUp(self)
     from zope.testing.loggingsupport import InstalledHandler
     self.log_handler = handler = InstalledHandler('zope.interface.ro')
     self.addCleanup(handler.uninstall)
"""Tests for HerokuappAccess tween."""

from pyramid import testing
from zope.testing.loggingsupport import InstalledHandler

import mock
import unittest

tweens_handler = InstalledHandler('pyramid_heroku.herokuapp_access')


class TestHerokuappAccessTween(unittest.TestCase):
    def setUp(self):
        tweens_handler.clear()
        self.config = testing.setUp()
        self.handler = mock.Mock()
        self.request = testing.DummyRequest()
        self.request.registry.settings = {
            'pyramid_heroku.herokuapp_whitelist': [
                '1.2.3.4',
            ]
        }

    def tearDown(self):
        tweens_handler.clear()
        testing.tearDown()

    def test_whitelisted_ip(self):
        from pyramid_heroku.herokuapp_access import HerokuappAccess
        self.request.client_addr = '1.2.3.4'
        self.request.headers = {
Esempio n. 30
0
 def setUp(self):
     """Set up a class ready for testing"""
     self.loghandlers = dict(
         errorlog=InstalledHandler('tutorweb.quizdb.browser')
     )