Beispiel #1
0
def ObjectManager_importObjectFromFile(self, filepath, verify=1, set_owner=1, id=None, suppress_events=False):
    #LOG('_importObjectFromFile, filepath',0,filepath)
    # locate a valid connection
    connection=self._p_jar
    obj=self

    while connection is None:
        obj=obj.aq_parent
        connection=obj._p_jar
    ob=connection.importFile(
        filepath, customImporters=customImporters)
    if verify: self._verifyObjectPaste(ob, validate_src=0)
    if id is None:
      id=ob.id
    if hasattr(id, 'im_func'): id=id()

    if getZopeVersion()[1] >= 10:
      # only in Zope > 2.10
      self._setObject(id, ob, set_owner=set_owner, suppress_events=suppress_events)
    else:
      self._setObject(id, ob, set_owner=set_owner)

    # try to make ownership implicit if possible in the context
    # that the object was imported into.
    ob=self._getOb(id)
    if set_owner:
      ob.manage_changeOwnershipType(explicit=0)
    return ob
Beispiel #2
0
    def test_ZopeVersion(self):
        import pkg_resources
        from App.version_txt import getZopeVersion

        app = self._makeOne()
        pkg_version = pkg_resources.get_distribution('Zope').version
        zversion = getZopeVersion()

        self.assertEqual(app.ZopeVersion(major=True), zversion.major)
        self.assertEqual(app.ZopeVersion(major=True),
                         int(pkg_version.split('.')[0]))
Beispiel #3
0
    def cook(cls, source_file, text, engine, content_type):
        if getattr(engine, "untrusted", False):

            def sanitize(m):
                match = m.group(1)
                logger.info(
                    'skipped "<?python%s?>" code block in '
                    'Zope 2 page template object "%s".', match, source_file)
                return ''

            text, count = re_match_pi.subn(sanitize, text)
            if count:
                logger.warning("skipped %d code block%s (not allowed in "
                               "restricted evaluation scope)." %
                               (count, 's' if count > 1 else ''))

        if isinstance(engine, ZopeBaseEngine):
            # use ``zope.tales`` expressions
            expr_types = {
                ty: MappedExprType(engine, ty)
                for ty in engine.types
            }
        else:
            # use ``chameleon.tales`` expressions
            expr_types = engine.types

        # BBB: Support CMFCore's FSPagetemplateFile formatting
        if source_file is not None and source_file.startswith('file:'):
            source_file = source_file[5:]

        if source_file is None:
            # Default to '<string>'
            source_file = ChameleonPageTemplate.filename

        zope_version = getZopeVersion()
        template = ZtPageTemplate(
            text,
            filename=source_file,
            keep_body=True,
            expression_types=expr_types,
            encoding='utf-8',
            extra_builtins={
                "modules":
                SecureModuleImporter,
                # effectively invalidate the template file cache for
                #   every new ``Zope`` version
                "zope_version_" + "_".join(
                    str(c) for c in zope_version if not (isinstance(c, int) and c < 0)):
                getZopeVersion
            })

        return cls(template, engine), template.macros
Beispiel #4
0
    def getZopeVersion(self):
        """
        This function returns a Version-ready tuple. For use with the Version
        object, use extended call syntax:

            v = Version(*getZopeVersion())
            v.full()
        """
        from App import version_txt as version

        name = 'Zope'
        major, minor, micro, status, release = version.getZopeVersion()
        return Version(name, major, minor, micro)
Beispiel #5
0
def get_conflictInfo():
    """from version 2.11 on conflict_errors are not global anymore
    http://svn.zope.org/Zope/tags/2.10.9/lib/python/Zope2/App/startup.py?view=markup
    http://svn.zope.org/Zope/tags/2.11.1/lib/python/Zope2/App/startup.py?view=markup
    """
    major, minor, micro = getZopeVersion()[:3]
    assert major == 2, "ZNagios has been built for Zope2, " \
        "your version seems to be %d" % major

    if minor < 11:
        return Zope2.App.startup
    else:
        #Zope >= 2.11 does not store conflict_errors globally
        return Zope2.App.startup.zpublisher_exception_hook
Beispiel #6
0
def MessageFactory(projectname):
    "Get a i18n message factory"
    vmajor, vminor, vmicro, vstatus, vrelease = getZopeVersion()
    MessageFactory = lambda : "no message factory found"
    if (vmajor > 2) or ((vmajor, vminor) == (2,9)):
        from zope.i18nmessageid import MessageFactory
    elif (vmajor, vminor) == (2,8):
        from zope.i18nmessageid import MessageIDFactory as MessageFactory
    else:
        try:
           from Products.PlacelessTranslationService.MessageID import MessageIDFactory as MessageFactory
        except:
           logging.info("[qPloneCaptchas] No i18n Message Factory found -> cannot provide translations!")
    return MessageFactory(projectname.lower())
Beispiel #7
0
    def ZopeVersion(self, major=False):
        """Utility method to return the Zope version

        Restricted to ZMI to prevent information disclosure
        """
        zversion = getZopeVersion()
        if major:
            return zversion.major
        else:
            version = f'{zversion.major}.{zversion.minor}.{zversion.micro}'
            if zversion.status:
                version += f'.{zversion.status}{zversion.release}'

            return version
Beispiel #8
0
    def ZopeVersion(self, major=False):
        """Utility method to return the Zope version

        Restricted to ZMI to prevent information disclosure
        """
        zversion = getZopeVersion()
        if major:
            return zversion.major
        else:
            version = '%s.%s.%s' % (zversion.major, zversion.minor,
                                    zversion.micro)
            if zversion.status:
                version += '.%s%s' % (zversion.status, zversion.release)

            return version
    def test_ZopeVersion(self):
        import pkg_resources
        from App.version_txt import getZopeVersion

        app = self._makeOne()
        pkg_version = pkg_resources.get_distribution('Zope').version
        zversion = getZopeVersion()

        self.assertEqual(app.ZopeVersion(major=True), zversion.major)
        # ZopeVersion will always return a normalized version with
        # MAJOR.MINOR.FIX but pkg_version takes whatever the package claims,
        # so we need to "normalize" pkg_version because we are not strict
        # in our package version numbering.
        self.assertEqual(app.ZopeVersion(),
                         (pkg_version + ((2 - pkg_version.count('.')) * '.0')))
Beispiel #10
0
def get_conflictInfo():
    """from version 2.11 on conflict_errors are not global anymore
    http://svn.zope.org/Zope/tags/2.10.9/lib/python/Zope2/App/startup.py?view=markup
    http://svn.zope.org/Zope/tags/2.11.1/lib/python/Zope2/App/startup.py?view=markup
    """
    major, minor, micro = getZopeVersion()[:3]

    # handle zope2.10.11 (shipped with plone3.3.5 that misses the version number
    # see https://bugs.launchpad.net/zope2/+bug/510477
    if major == -1:
        major = 2
        minor = 10

    assert major == 2, "ZNagios has been built for Zope2, " \
        "your version seems to be %d" % major

    if minor < 11:
        return Zope2.App.startup
    else:
        #Zope >= 2.11 does not store conflict_errors globally
        return Zope2.App.startup.zpublisher_exception_hook
Beispiel #11
0
    def test_complete(self):
        positions = {
            0: 'major',
            1: 'minor',
            2: 'micro',
            3: 'status',
            4: 'release',
        }
        distversion = get_distribution('Zope').version
        zversion = getZopeVersion()

        for (pos, value) in enumerate(distversion.split('.')):
            if pos < 2:
                self.assertEqual(int(value), getattr(zversion, positions[pos]))
            elif pos == 2:
                # Could be int or string
                self.assertEqual(value, str(getattr(zversion, positions[pos])))
            elif pos == 3:
                zstatus = getattr(zversion, positions[pos])
                zrelease = getattr(zversion, positions[pos + 1])
                self.assertEqual(value, '%s%s' % (zstatus, zrelease))
Beispiel #12
0
def get_conflictInfo():
    """from version 2.11 on conflict_errors are not global anymore
    http://svn.zope.org/Zope/tags/2.10.9/lib/python/Zope2/App/startup.py?view=markup
    http://svn.zope.org/Zope/tags/2.11.1/lib/python/Zope2/App/startup.py?view=markup
    """
    major, minor, micro = getZopeVersion()[:3]
    
    # handle zope2.10.11 (shipped with plone3.3.5 that misses the version number
    # see https://bugs.launchpad.net/zope2/+bug/510477
    if major == -1:
        major = 2
        minor = 10
        
    assert major == 2, "ZNagios has been built for Zope2, " \
        "your version seems to be %d" % major

    if minor < 11:
        return Zope2.App.startup
    else:
        #Zope >= 2.11 does not store conflict_errors globally
        return Zope2.App.startup.zpublisher_exception_hook
Beispiel #13
0
 def test_major(self):
     self.assertEqual(getZopeVersion().major,
                      int(get_distribution("Zope").version.split(".")[0]))
 def test_major(self):
     self.assertEqual(
         getZopeVersion().major,
         int(get_distribution("Zope").version.split(".")[0]))
 def test_types(self):
     zv = getZopeVersion()
     for i in (0, 1, 2, 4):
         self.assertIsInstance(zv[i], int, str(i))
     self.assertIsInstance(zv[3], str, '3')
Beispiel #16
0
# CMF imports
try:
    from Products.CMFCore import permissions as CMFCorePermissions
except ImportError:
    from Products.CMFCore import CMFCorePermissions

PROJECTNAME = "FileSystemStorage"
GLOBALS = globals()
SKINS_DIR = "skins"
DEBUG = False
INSTALL_EXAMPLE_TYPES_ENVIRONMENT_VARIABLE = "FSS_INSTALL_EXAMPLE_TYPES"

from App.version_txt import getZopeVersion

ZOPE_VERSION = getZopeVersion()  # = (2, 9, 5, ...)
del getZopeVersion

try:
    from Products.CMFPlone.utils import getFSVersionTuple

    PLONE_VERSION = getFSVersionTuple()[:2]  # as (2, 1)
    del getFSVersionTuple
except ImportError, e:
    PLONE_VERSION = (2, 0)

ZCONFIG, dummy_handler, CONFIG_FILE = None, None, None


def loadConfig():
    """Loads configuration from a ZConfig file"""
Beispiel #17
0
 def test_types(self):
     zv = getZopeVersion()
     for i in (0, 1, 4):
         self.assertIsInstance(zv[i], int, str(i))
     self.assertIsInstance(zv[3], str, '3')
Beispiel #18
0
PYTHON_VER = sys.version_info[:3]
if PYTHON_VER < MINIMUM_PYTHON_VER:
    log(("Python version %s found but Plone needs at least "
         "Python %s. Please download and install Python %s "
     "from http://python.org/" % (PYTHON_VER,
     MINIMUM_PYTHON_VER, PREFERRED_PYTHON_VER) ))

# test zope version
ZOPE_VER = "unknown"
try:
    from App.version_txt import getZopeVersion
except ImportError:
    pass
else:
    try:
        ZOPE_VER = getZopeVersion()[:3]
    except (ValueError, TypeError, KeyError):
        pass

if ZOPE_VER in ('unknown', (-1, -1, -1)): # -1, -1, 1 is developer release
    log(("Unable to detect Zope version. Please make sure you have Zope "
         "%s installed." % PREFERRED_ZOPE_VER), severity=logging.INFO)
elif ZOPE_VER < MINIMUM_ZOPE_VER:
    log(("Zope version %s found but Plone needs at least "
         "Zope %s Please download and install Zope %s "
     "from http://zope.org/" %
     ('.'.join([str(x) for x in ZOPE_VER]),
       '.'.join([str(x) for x in MINIMUM_ZOPE_VER]), PREFERRED_ZOPE_VER) ))

# make sure CMF is installed
cmfcore = 0
class TransactionalEmailTests(EmailTestBase):

    def _getTargetClass(self):
        from Products.MaildropHost.MaildropHost import TransactionalEmail
        return TransactionalEmail


    def test_send_notransaction(self):
        # First of all, make sure we are in a clean transaction
        transaction.begin()

        # Transactional emails need a successful commit
        self.assertEqual(len(self._listSpools()), 0)
        email1 = self._makeOne()
        email1.send()
        email1_turd = email1._tempfile

        # Now that the email has been sent, there should be two files: The
        # lock file and the actual email. The lockfile stays until the
        # transaction commits.
        self.assertEqual(len(self._listSpools()), 2)

        # Make sure we clean up after ourselves...
        os.unlink(email1_turd)
        os.unlink('%s.lck' % email1_turd)
        self.assertEqual(len(self._listSpools()), 0)


    def test_send_transaction(self):
        # First of all, make sure we are in a clean transaction
        transaction.begin()

        self.assertEqual(len(self._listSpools()), 0)
        email1 = self._makeOne()
        email1.send()
        email1_turd = email1._tempfile

        # Now that the email has been sent, there should be two files: The
        # lock file and the actual email. The lockfile stays until the
        # transaction commits.
        self.assertEqual(len(self._listSpools()), 2)

        # Committing the transaction will remove the lock file so that the
        # maildrop daemon will process the mail file. That means only the
        # mail file itself remains in the spool after the commit.
        transaction.commit()
        self.assertEqual(len(self._listSpools()), 1)

        # Make sure we clean up after ourselves...
        os.unlink(email1_turd)
        self.assertEqual(len(self._listSpools()), 0)

        # abort the current transaction
        transaction.abort()
        self.assertEqual(len(self._listSpools()), 0)


    def test_send_subtransaction(self):
        from Products.MaildropHost.TransactionalMixin import transactions

        # First of all, make sure we are in a clean transaction
        transaction.begin()

        self.assertEqual(len(list(transactions.keys())), 0)
        self.assertEqual(len(self._listSpools()), 0)
        email1 = self._makeOne()
        email1.send()

        # Now that the email has been sent, there should be two files: The
        # lock file and the actual email. The lockfile stays until the
        # transaction commits.
        self.assertEqual(len(self._listSpools()), 2)

        # Checking the transaction queue. A single transaction with a single
        # savepoint exists, which does not point to any other savepoints.
        self.assertEqual(len(list(transactions.keys())), 1)
        trans = list(transactions.values())[0]
        first_savepoint = trans._savepoint
        next = getattr(first_savepoint, 'next', None)
        previous = getattr(first_savepoint, 'previous', None)
        self.assertTrue(next is None)
        self.assertTrue(previous is None)

        # Committing a subtransaction should not do anything. Both email file
        # and lockfile should remain!
        transaction.savepoint(optimistic=True)
        self.assertEqual(len(self._listSpools()), 2)

        # The transaction queue still contains a single transaction, but we 
        # now have two savepoints pointing to each other.
        self.assertEqual(len(list(transactions.keys())), 1)
        trans = list(transactions.values())[0]
        second_savepoint = trans._savepoint
        next = getattr(second_savepoint, 'next', None)
        previous = getattr(second_savepoint, 'previous', None)
        self.assertTrue(next is None)
        self.assertTrue(previous is first_savepoint)
        self.assertTrue(previous.__next__ is second_savepoint)

        # Send another email and commit the subtransaction. Only the spool
        # file count changes.
        email2 = self._makeOne()
        email2.send()
        self.assertEqual(len(self._listSpools()), 4)
        self.assertEqual(len(list(transactions.keys())), 1)
        transaction.savepoint(optimistic=True)
        self.assertEqual(len(self._listSpools()), 4)

        # The transaction queue still contains a single transaction, but we 
        # now have three savepoints pointing to each other.
        self.assertEqual(len(list(transactions.keys())), 1)
        trans = list(transactions.values())[0]
        third_savepoint = trans._savepoint
        next = getattr(third_savepoint, 'next', None)
        previous = getattr(third_savepoint, 'previous', None)
        self.assertTrue(next is None)
        self.assertTrue(previous is second_savepoint)
        self.assertTrue(previous.__next__ is third_savepoint)

        # abort the current transaction, which will clean the spool as well
        # as the transactions mapping
        transaction.abort()
        self.assertEqual(len(self._listSpools()), 0)
        self.assertEqual(len(list(transactions.keys())), 0)


    if getZopeVersion()[1] < 11 and getZopeVersion()[0] != -1:
        def test_send_subtransaction_oldstyle(self):
            from Products.MaildropHost.TransactionalMixin import transactions

            # Don't emit the DeprecationWarning we get
            warnings.filterwarnings('ignore', category=DeprecationWarning)

            # First of all, make sure we are in a clean transaction
            transaction.begin()

            self.assertEqual(len(list(transactions.keys())), 0)
            self.assertEqual(len(self._listSpools()), 0)
            email1 = self._makeOne()
            email1.send()

            # Now that the email has been sent, there should be two files: The
            # lock file and the actual email. The lockfile stays until the
            # transaction commits.
            self.assertEqual(len(self._listSpools()), 2)

            # Checking the transaction queue. A single transaction with a single
            # savepoint exists, which does not point to any other savepoints.
            self.assertEqual(len(list(transactions.keys())), 1)
            trans = list(transactions.values())[0]
            first_savepoint = trans._savepoint
            next = getattr(first_savepoint, 'next', None)
            previous = getattr(first_savepoint, 'previous', None)
            self.assertTrue(next is None)
            self.assertTrue(previous is None)

            # Committing a subtransaction should not do anything. Both email file
            # and lockfile should remain!
            transaction.commit(1)
            self.assertEqual(len(self._listSpools()), 2)

            # The transaction queue still contains a single transaction, but we 
            # now have two savepoints pointing to each other.
            self.assertEqual(len(list(transactions.keys())), 1)
            trans = list(transactions.values())[0]
            second_savepoint = trans._savepoint
            next = getattr(second_savepoint, 'next', None)
            previous = getattr(second_savepoint, 'previous', None)
            self.assertTrue(next is None)
            self.assertTrue(previous is first_savepoint)
            self.assertTrue(previous.__next__ is second_savepoint)

            # Send another email and commit the subtransaction. Only the spool
            # file count changes.
            email2 = self._makeOne()
            email2.send()
            self.assertEqual(len(self._listSpools()), 4)
            self.assertEqual(len(list(transactions.keys())), 1)
            transaction.commit(1)
            self.assertEqual(len(self._listSpools()), 4)

            # The transaction queue still contains a single transaction, but we 
            # now have three savepoints pointing to each other.
            self.assertEqual(len(list(transactions.keys())), 1)
            trans = list(transactions.values())[0]
            third_savepoint = trans._savepoint
            next = getattr(third_savepoint, 'next', None)
            previous = getattr(third_savepoint, 'previous', None)
            self.assertTrue(next is None)
            self.assertTrue(previous is second_savepoint)
            self.assertTrue(previous.__next__ is third_savepoint)

            # abort the current transaction, which will clean the spool as well
            transaction.abort()
            self.assertEqual(len(self._listSpools()), 0)
            self.assertEqual(len(list(transactions.keys())), 0)

            # Clean up warnfilter
            warnings.resetwarnings()


    def test_send_transaction_abort(self):
        # First of all, make sure we are in a clean transaction
        transaction.begin()

        self.assertEqual(len(self._listSpools()), 0)
        email1 = self._makeOne()
        email1.send()

        # Now that the email has been sent, there should be two files: The
        # lock file and the actual email. The lockfile stays until the
        # transaction commits.
        self.assertEqual(len(self._listSpools()), 2)

        # Aborting a transaction should remove the email file and the
        # lockfile.
        transaction.abort()
        self.assertEqual(len(self._listSpools()), 0)


    def test_savepoints(self):
        # First of all, make sure we are in a clean transaction
        transaction.begin()

        self.assertEqual(len(self._listSpools()), 0)
        
        email1 = self._makeOne()
        email1.send()
        
        # Now that the email has been sent, there should be two files: The
        # lock file and the actual email. The lockfile stays until the
        # transaction commits.        
        self.assertEqual(len(self._listSpools()), 2)

        # create a savepoint
        savepoint1 = transaction.savepoint()

        # send a second mail
        email2 = self._makeOne()
        email2.send()
        self.assertEqual(len(self._listSpools()), 4)

        # create another savepoint
        savepoint2 = transaction.savepoint()
        
        # send a third mail
        email3 = self._makeOne()
        email3.send()
        self.assertEqual(len(self._listSpools()), 6)

        # rollback, this should remove email3
        savepoint2.rollback()        
        self.assertEqual(len(self._listSpools()), 4)

        # rollback again, this should remove email2
        savepoint1.rollback()        
        self.assertEqual(len(self._listSpools()), 2)
        
        # Aborting a transaction should remove the email file and the
        # lockfile.
        transaction.abort()
        self.assertEqual(len(self._listSpools()), 0)


    def test_savepoints_earlier_rollback(self):
        from transaction.interfaces import InvalidSavepointRollbackError

        # First of all, make sure we are in a clean transaction
        transaction.begin()

        self.assertEqual(len(self._listSpools()), 0)

        email1 = self._makeOne()
        email1.send()
        
        # Now that the email has been sent, there should be two files: The
        # lock file and the actual email. The lockfile stays until the
        # transaction commits.
        self.assertEqual(len(self._listSpools()), 2)

        # create a savepoint
        savepoint1 = transaction.savepoint()
        
        # send a second mail
        email2 = self._makeOne()
        email2.send()
        self.assertEqual(len(self._listSpools()), 4)

        # create another savepoint
        savepoint2 = transaction.savepoint()
        
        # send a third mail
        email3 = self._makeOne()
        email3.send()
        self.assertEqual(len(self._listSpools()), 6)

        # rollback should remove email2 and email3
        savepoint1.rollback()        
        self.assertEqual(len(self._listSpools()), 2)

        # out of order rollback, should raise an exception
        self.assertRaises(InvalidSavepointRollbackError,
                          savepoint2.rollback)
        
        # Aborting a transaction should remove the email file and the
        # lockfile.
        transaction.abort()
        self.assertEqual(len(self._listSpools()), 0)


    def test_savepoints_change_after_rollback(self):
        from transaction.interfaces import InvalidSavepointRollbackError

        # First of all, make sure we are in a clean transaction
        transaction.begin()

        self.assertEqual(len(self._listSpools()), 0)

        email1 = self._makeOne()
        email1.send()
        
        # Now that the email has been sent, there should be two files: The
        # lock file and the actual email. The lockfile stays until the
        # transaction commits.
        self.assertEqual(len(self._listSpools()), 2)

        # create a savepoint
        savepoint1 = transaction.savepoint()
        
        # send a second mail
        email2 = self._makeOne()
        email2.send()
        self.assertEqual(len(self._listSpools()), 4)

        # rollback should remove email2
        savepoint1.rollback()        
        self.assertEqual(len(self._listSpools()), 2)

        # send a third mail
        email3 = self._makeOne()
        email3.send()
        self.assertEqual(len(self._listSpools()), 4)

        # create another savepoint
        savepoint2 = transaction.savepoint()

        # rollback should remove email3
        savepoint1.rollback()        
        self.assertEqual(len(self._listSpools()), 2)

        # out of order rollback, should raise an exception
        self.assertRaises(InvalidSavepointRollbackError,
                          savepoint2.rollback)
        
        # Aborting a transaction should remove the email file and the lockfile.
        transaction.abort()
        self.assertEqual(len(self._listSpools()), 0)
from StringIO import StringIO
from copy import deepcopy

try: import twill
except: twill = None

try: import wsgiref.validate
except: wsgiref = None

from App.version_txt import getZopeVersion
from ZPublisher.Response import Response
from ZPublisher.Test import publish_module

import NaayaTestCase

if getZopeVersion() < (2, 10, 9):
    newline = '\n'
else:
    newline = '\r\n'

if getattr(sys, 'winver', None):
    newline = '\r\n'

class NaayaFunctionalTestCase(NaayaTestCase.NaayaTestCase):
    """
    Functional test case for Naaya - use Twill (http://twill.idyll.org/) for client-side tests
    """

    wsgi_debug = False

    def divert_twill_output(self):