Exemple #1
0
class SSHCheckerTests(unittest.TestCase):
    """
    Tests for the C{--auth=sshkey:...} checker.  The majority of the tests for the
    ssh public key database checker are in
    L{twisted.conch.test.test_checkers.SSHPublicKeyCheckerTestCase}.
    """

    skip = None

    if requireModule('cryptography') is None:
        skip = 'cryptography is not available'

    if requireModule('pyasn1') is None:
        skip = 'pyasn1 is not available'


    def test_isChecker(self):
        """
        Verifies that strcred.makeChecker('sshkey') returns an object
        that implements the L{ICredentialsChecker} interface.
        """
        sshChecker = strcred.makeChecker('sshkey')
        self.assertTrue(checkers.ICredentialsChecker.providedBy(sshChecker))
        self.assertIn(
            credentials.ISSHPrivateKey, sshChecker.credentialInterfaces)
Exemple #2
0
 def test_deprecation(self):
     """
     Accessing L{twisted.words.protocols.msn} emits a deprecation warning
     """
     requireModule('twisted.words.protocols').msn
     warningsShown = self.flushWarnings([self.test_deprecation])
     self.assertEqual(len(warningsShown), 1)
     self.assertIdentical(warningsShown[0]['category'], DeprecationWarning)
     self.assertEqual(
         warningsShown[0]['message'],
         'twisted.words.protocols.msn was deprecated in Twisted 15.1.0: ' +
         'MSN has shutdown.')
 def test_deprecation(self):
     """
     Accessing L{twisted.words.protocols.msn} emits a deprecation warning
     """
     requireModule('twisted.words.protocols').msn
     warningsShown = self.flushWarnings([self.test_deprecation])
     self.assertEqual(len(warningsShown), 1)
     self.assertIdentical(warningsShown[0]['category'], DeprecationWarning)
     self.assertEqual(
         warningsShown[0]['message'],
         'twisted.words.protocols.msn was deprecated in Twisted 15.1.0: ' +
         'MSN has shutdown.')
    def getHandleErrorCode(self):
        """
        Return the argument L{OpenSSL.SSL.Error} will be constructed with for
        this case. This is basically just a random OpenSSL implementation
        detail. It would be better if this test worked in a way which did not
        require this.
        """
        # Windows 2000 SP 4 and Windows XP SP 2 give back WSAENOTSOCK for
        # SSL.Connection.write for some reason.  The twisted.protocols.tls
        # implementation of IReactorSSL doesn't suffer from this imprecation,
        # though, since it is isolated from the Windows I/O layer (I suppose?).

        # If test_properlyCloseFiles waited for the SSL handshake to complete
        # and performed an orderly shutdown, then this would probably be a
        # little less weird: writing to a shutdown SSL connection has a more
        # well-defined failure mode (or at least it should).

        # So figure out if twisted.protocols.tls is in use.  If it can be
        # imported, it should be.
        if requireModule('twisted.protocols.tls') is None:
            # It isn't available, so we expect WSAENOTSOCK if we're on Windows.
            if platform.getType() == 'win32':
                return errno.WSAENOTSOCK

        # Otherwise, we expect an error about how we tried to write to a
        # shutdown connection.  This is terribly implementation-specific.
        return [('SSL routines', 'SSL_write', 'protocol is shutdown')]
Exemple #5
0
    def getHandleErrorCode(self):
        """
        Return the argument L{OpenSSL.SSL.Error} will be constructed with for
        this case. This is basically just a random OpenSSL implementation
        detail. It would be better if this test worked in a way which did not
        require this.
        """
        # Windows 2000 SP 4 and Windows XP SP 2 give back WSAENOTSOCK for
        # SSL.Connection.write for some reason.  The twisted.protocols.tls
        # implementation of IReactorSSL doesn't suffer from this imprecation,
        # though, since it is isolated from the Windows I/O layer (I suppose?).

        # If test_properlyCloseFiles waited for the SSL handshake to complete
        # and performed an orderly shutdown, then this would probably be a
        # little less weird: writing to a shutdown SSL connection has a more
        # well-defined failure mode (or at least it should).

        # So figure out if twisted.protocols.tls is in use.  If it can be
        # imported, it should be.
        if requireModule('twisted.protocols.tls') is None:
            # It isn't available, so we expect WSAENOTSOCK if we're on Windows.
            if platform.getType() == 'win32':
                return errno.WSAENOTSOCK

        # Otherwise, we expect an error about how we tried to write to a
        # shutdown connection.  This is terribly implementation-specific.
        return [('SSL routines', 'SSL_write', 'protocol is shutdown')]
    def test_requireModuleDefaultNone(self):
        """
        When module import fails it returns L{None} by default.
        """
        result = reflect.requireModule('no.such.module')

        self.assertIsNone(result)
Exemple #7
0
    def test_requireModuleDefaultNone(self):
        """
        When module import fails it returns C{None} by default.
        """
        result = reflect.requireModule('no.such.module')

        self.assertIs(None, result)
Exemple #8
0
class DomishExpatStreamTests(DomishStreamTestsMixin, unittest.TestCase):
    """
    Tests for L{domish.ExpatElementStream}, the expat-based element stream
    implementation.
    """
    streamClass = domish.ExpatElementStream

    if requireModule('pyexpat', default=None) is None:
        skip = "pyexpat is required for ExpatElementStream tests."
Exemple #9
0
 def can_connect(self):
     if requireModule('kinterbasdb') is None:
         return False
     try:
         self.startDB()
         self.stopDB()
         return True
     except:
         return False
Exemple #10
0
 def can_connect(self):
     if requireModule('kinterbasdb') is None:
         return False
     try:
         self.startDB()
         self.stopDB()
         return True
     except:
         return False
Exemple #11
0
 def can_connect(self):
     if requireModule("kinterbasdb") is None:
         return False
     try:
         self.startDB()
         self.stopDB()
         return True
     except BaseException:
         return False
Exemple #12
0
    def test_requireModuleRequestedImport(self):
        """
        When module import succeed it returns the module and not the default
        value.
        """
        from twisted.python import monkey

        default = object()

        self.assertIs(reflect.requireModule("twisted.python.monkey", default=default), monkey)
    def test_requireModuleImportError(self):
        """
        When module import fails with ImportError it returns the specified
        default value.
        """
        for name in ['nosuchmtopodule', 'no.such.module']:
            default = object()

            result = reflect.requireModule(name, default=default)

            self.assertIs(result, default)
 def test_linux(self):
     """
     L{_getInstallFunction} chooses the epoll reactor on Linux, or poll if
     epoll is unavailable.
     """
     install = _getInstallFunction(linux)
     if requireModule('twisted.internet.epollreactor') is None:
         self.assertIsPoll(install)
     else:
         self.assertEqual(
             install.__module__, 'twisted.internet.epollreactor')
Exemple #15
0
 def test_linux(self):
     """
     L{_getInstallFunction} chooses the epoll reactor on Linux, or poll if
     epoll is unavailable.
     """
     install = _getInstallFunction(linux)
     if requireModule('twisted.internet.epollreactor') is None:
         self.assertIsPoll(install)
     else:
         self.assertEqual(install.__module__,
                          'twisted.internet.epollreactor')
Exemple #16
0
    def test_requireModuleImportError(self):
        """
        When module import fails with ImportError it returns the specified
        default value.
        """
        for name in ['nosuchmtopodule', 'no.such.module']:
            default = object()

            result = reflect.requireModule(name, default=default)

            self.assertIs(result, default)
Exemple #17
0
    def test_requireModuleRequestedImport(self):
        """
        When module import succeed it returns the module and not the default
        value.
        """
        from twisted.python import monkey
        default = object()

        self.assertIs(
            reflect.requireModule('twisted.python.monkey', default=default),
            monkey,
        )
Exemple #18
0
    def test_defaultAuths(self):
        """
        Make sure that if the C{--auth} command-line option is not passed,
        the default checkers are (for backwards compatibility): SSH, UNIX, and
        PAM if available
        """
        numCheckers = 2

        if requireModule('twisted.cred.pamauth'):
            self.assertIn(IPluggableAuthenticationModules,
                self.options['credInterfaces'],
                "PAM should be one of the modules")
            numCheckers += 1

        self.assertIn(ISSHPrivateKey, self.options['credInterfaces'],
            "SSH should be one of the default checkers")
        self.assertIn(IUsernamePassword, self.options['credInterfaces'],
            "UNIX should be one of the default checkers")
        self.assertEqual(numCheckers, len(self.options['credCheckers']),
            "There should be %d checkers by default" % (numCheckers,))
Exemple #19
0
    async def go(reactor):

        mod = requireModule(f"sybench.methods.{method}")

        if not mod:
            raise Exception("Not a valid method!")

        work, results = await mod.create(url, username, password, {})

        workers = []

        for i in range(count):

            l = LoopingCall(work)
            workers.append(l.start(0, now=False))

        try:
            await DeferredList(workers, consumeErrors=True)
        finally:
            results()
Exemple #20
0
    def test_defaultAuths(self):
        """
        Make sure that if the C{--auth} command-line option is not passed,
        the default checkers are (for backwards compatibility): SSH, UNIX, and
        PAM if available
        """
        numCheckers = 2

        if requireModule('twisted.cred.pamauth'):
            self.assertIn(IPluggableAuthenticationModules,
                          self.options['credInterfaces'],
                          "PAM should be one of the modules")
            numCheckers += 1

        self.assertIn(ISSHPrivateKey, self.options['credInterfaces'],
                      "SSH should be one of the default checkers")
        self.assertIn(IUsernamePassword, self.options['credInterfaces'],
                      "UNIX should be one of the default checkers")
        self.assertEqual(
            numCheckers, len(self.options['credCheckers']),
            "There should be %d checkers by default" % (numCheckers, ))
Exemple #21
0
 def can_connect(self):
     if requireModule("sqlite3") is None:
         return False
     else:
         return True
from zope.interface.verify import verifyObject

from twisted.python import util
from twisted.python.failure import Failure
from twisted.python.reflect import requireModule
from twisted.trial.unittest import TestCase
from twisted.python.filepath import FilePath
from twisted.cred.checkers import InMemoryUsernamePasswordDatabaseDontUse
from twisted.cred.credentials import UsernamePassword, IUsernamePassword, \
    SSHPrivateKey, ISSHPrivateKey
from twisted.cred.error import UnhandledCredentials, UnauthorizedLogin
from twisted.python.fakepwd import UserDatabase, ShadowDatabase
from twisted.test.test_process import MockOS

if requireModule('Crypto.Cipher.DES3') and requireModule('pyasn1'):
    dependencySkip = None
    from twisted.conch.ssh import keys
    from twisted.conch import checkers
    from twisted.conch.error import NotEnoughAuthentication, ValidPublicKey
    from twisted.conch.test import keydata
else:
    dependencySkip = "can't run without Crypto and PyASN1"

if getattr(os, 'geteuid', None) is None:
    euidSkip = "Cannot run without effective UIDs (questionable)"
else:
    euidSkip = None


class HelperTests(TestCase):
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.

"""
Tests for the command-line interfaces to conch.
"""
from twisted.python.reflect import requireModule

if requireModule('pyasn1'):
    pyasn1Skip = None
else:
    pyasn1Skip =  "Cannot run without PyASN1"

if requireModule('Crypto'):
    cryptoSkip = None
else:
    cryptoSkip = "can't run w/o PyCrypto"

if requireModule('tty'):
    ttySkip = None
else:
    ttySkip = "can't run w/o tty"

try:
    import Tkinter
except ImportError:
    tkskip = "can't run w/o Tkinter"
else:
    try:
        Tkinter.Tk().destroy()
    except Tkinter.TclError, e:
Exemple #24
0
 def can_connect(self):
     if requireModule('sqlite3') is None:
         return False
     else:
         return True
Exemple #25
0
from foolscap.api import Tub, Referenceable, fireEventually, flushEventualQueue
from twisted.application import service
from allmydata.interfaces import InsufficientVersionError
from allmydata.introducer.client import IntroducerClient
from allmydata.introducer.server import IntroducerService, FurlFileConflictError
from allmydata.introducer.common import get_tubid_string_from_ann, \
     get_tubid_string, sign_to_foolscap, unsign_from_foolscap, \
     UnknownKeyError
# the "new way" to create introducer node instance
from allmydata.introducer.server import create_introducer
from allmydata.web import introweb
from allmydata.client import create_client
from allmydata.util import pollmixin, keyutil, idlib, fileutil, iputil, yamlutil
import allmydata.test.common_util as testutil

fcntl = requireModule("fcntl")


class LoggingMultiService(service.MultiService):
    def log(self, msg, **kw):
        log.msg(msg, **kw)


class Node(testutil.SignalMixin, testutil.ReallyEqualMixin, unittest.TestCase):
    def test_backwards_compat_import(self):
        # for old introducer .tac files
        from allmydata.introducer import IntroducerNode
        IntroducerNode  # pyflakes

    def test_furl(self):
        basedir = "introducer.IntroducerNode.test_furl"
Exemple #26
0
import StringIO
from hashlib import md5

from twisted.internet.defer import Deferred
from twisted.protocols import loopback
from twisted.python.reflect import requireModule
from twisted.test.proto_helpers import StringTransport, StringIOWithoutClosing
from twisted.trial import unittest

# t.w.p.msn requires an HTTP client
try:
    # So try to get one - do it directly instead of catching an ImportError
    # from t.w.p.msn so that other problems which cause that module to fail
    # to import don't cause the tests to be skipped.
    requireModule('twisted.web.client')
except ImportError:
    # If there isn't one, we're going to skip all the tests.
    msn = None
else:
    # Otherwise importing it should work, so do it.
    from twisted.words.protocols import msn



def printError(f):
    print f


class PassportTests(unittest.TestCase):
Exemple #27
0
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""
Tests for L{twisted.mail.tap}.
"""

from twisted.trial.unittest import TestCase

from twisted.python.usage import UsageError
from twisted.mail import protocols
from twisted.mail.tap import Options, makeService
from twisted.python.filepath import FilePath
from twisted.python.reflect import requireModule
from twisted.internet import endpoints, defer

if requireModule('OpenSSL') is None:
    sslSkip = 'Missing OpenSSL package.'
else:
    sslSkip = None


class OptionsTestCase(TestCase):
    """
    Tests for the command line option parser used for I{twistd mail}.
    """
    def setUp(self):
        self.aliasFilename = self.mktemp()
        aliasFile = file(self.aliasFilename, 'w')
        aliasFile.write('someuser:\tdifferentuser\n')
        aliasFile.close()
Exemple #28
0
from twisted.python.runtime import platform
from twisted.python.compat import xrange, intToBytes, bytesEnviron
from twisted.internet import error, defer, protocol, stdio, reactor
from twisted.test.test_tcp import ConnectionLostNotifyingProtocol


# A short string which is intended to appear here and nowhere else,
# particularly not in any random garbage output CPython unavoidable
# generates (such as in warning text and so forth).  This is searched
# for in the output from stdio_test_lastwrite and if it is found at
# the end, the functionality works.
UNIQUE_LAST_WRITE_STRING = b'xyz123abc Twisted is great!'

skipWindowsNopywin32 = None
if platform.isWindows():
    if requireModule('win32process') is None:
        skipWindowsNopywin32 = ("On windows, spawnProcess is not available "
                                "in the absence of win32process.")
    properEnv = dict(os.environ)
    properEnv["PYTHONPATH"] = os.pathsep.join(sys.path)
else:
    properEnv = bytesEnviron()
    properEnv[b"PYTHONPATH"] = os.pathsep.join(sys.path).encode(
        sys.getfilesystemencoding())


class StandardIOTestProcessProtocol(protocol.ProcessProtocol):
    """
    Test helper for collecting output from a child process and notifying
    something when it exits.
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.

"""
Tests for the inotify wrapper in L{twisted.internet.inotify}.
"""

from twisted.internet import defer, reactor
from twisted.python import filepath, runtime
from twisted.python.reflect import requireModule
from twisted.trial import unittest

if requireModule('twisted.python._inotify') is not None:
    from twisted.internet import inotify
else:
    inotify = None



class INotifyTests(unittest.TestCase):
    """
    Define all the tests for the basic functionality exposed by
    L{inotify.INotify}.
    """
    if not runtime.platform.supportsINotify():
        skip = "This platform doesn't support INotify."

    def setUp(self):
        self.dirname = filepath.FilePath(self.mktemp())
        self.dirname.createDirectory()
        self.inotify = inotify.INotify()
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE file for details.

"""
Tests for L{twisted.conch.scripts.cftp}.
"""

import locale
import time, sys, os, operator, getpass, struct
from io import BytesIO

from twisted.python.filepath import FilePath
from twisted.python.reflect import requireModule
from zope.interface import implementer

pyasn1 = requireModule('pyasn1')
cryptography = requireModule('cryptography')
unix = requireModule('twisted.conch.unix')

_reason = None
if cryptography and pyasn1:
    try:
        from twisted.conch.scripts import cftp
        from twisted.conch.scripts.cftp import SSHSession
        from twisted.conch.ssh import filetransfer
        from twisted.conch.test.test_filetransfer import FileTransferForTestAvatar
        from twisted.conch.test import test_ssh, test_conch
        from twisted.conch.test.test_conch import FakeStdio
    except ImportError:
        pass
Exemple #31
0
 def can_connect(self):
     if requireModule('pysqlite2.dbapi2') is None:
         return False
     else:
         return True
Exemple #32
0
 def can_connect(self):
     if requireModule("pysqlite2.dbapi2") is None:
         return False
     else:
         return True
Exemple #33
0
# from the Python Standard Library
import os, re, socket, subprocess, errno
from sys import platform

# from Twisted
from twisted.python.reflect import requireModule
from twisted.internet import defer, threads, reactor
from twisted.internet.protocol import DatagramProtocol
from twisted.internet.error import CannotListenError
from twisted.python.procutils import which
from twisted.python import log
from twisted.internet.endpoints import AdoptedStreamServerEndpoint
from twisted.internet.interfaces import IReactorSocket

fcntl = requireModule("fcntl")

from foolscap.util import allocate_tcp_port # re-exported

try:
    import resource
    def increase_rlimits():
        # We'd like to raise our soft resource.RLIMIT_NOFILE, since certain
        # systems (OS-X, probably solaris) start with a relatively low limit
        # (256), and some unit tests want to open up more sockets than this.
        # Most linux systems start with both hard and soft limits at 1024,
        # which is plenty.

        # unfortunately the values to pass to setrlimit() vary widely from
        # one system to another. OS-X reports (256, HUGE), but the real hard
        # limit is 10240, and accepts (-1,-1) to mean raise it to the
        # maximum. Cygwin reports (256, -1), then ignores a request of
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.

"""
Tests for L{twisted.conch.scripts.ckeygen}.
"""

import __builtin__
import getpass
import sys
from StringIO import StringIO

from twisted.python.reflect import requireModule

if requireModule("cryptography") and requireModule("pyasn1"):
    from twisted.conch.ssh.keys import Key, BadKeyError
    from twisted.conch.scripts.ckeygen import changePassPhrase, displayPublicKey, printFingerprint, _saveKey
else:
    skip = "cryptography and pyasn1 required for twisted.conch.scripts.ckeygen"

from twisted.python.filepath import FilePath
from twisted.trial.unittest import TestCase
from twisted.conch.test.keydata import publicRSA_openssh, privateRSA_openssh, privateRSA_openssh_encrypted


def makeGetpass(*passphrases):
    """
    Return a callable to patch C{getpass.getpass}.  Yields a passphrase each
    time called. Use case is to provide an old, then new passphrase(s) as if
    requested interactively.
Exemple #35
0
import os
from binascii import Error as BinasciiError, b2a_base64, a2b_base64
from unittest import skipIf

from zope.interface.verify import verifyObject

from twisted.python.compat import networkString
from twisted.python.reflect import requireModule
from twisted.python.filepath import FilePath
from twisted.trial.unittest import TestCase
from twisted.internet.defer import Deferred
from twisted.conch.interfaces import IKnownHostEntry
from twisted.conch.error import HostKeyChanged, UserRejectedKey, InvalidEntry
from twisted.test.testutils import ComparisonTestsMixin

if requireModule("cryptography") and requireModule("pyasn1"):
    from twisted.conch.ssh.keys import Key, BadKeyError
    from twisted.conch.client.knownhosts import (
        PlainEntry,
        HashedEntry,
        KnownHostsFile,
        UnparsedEntry,
        ConsoleUI,
    )
    from twisted.conch.client import default
    from twisted.conch.test import keydata
else:
    skip = "cryptography and PyASN1 required for twisted.conch.knownhosts."

sampleEncodedKey = (
    b"AAAAB3NzaC1yc2EAAAABIwAAAQEAsV0VMRbGmzhqxxayLRHmvnFvtyNqgbNKV46dU1bVFB+3y"
Exemple #36
0
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.

"""
Tests for implementations of L{inetdtap}.
"""

from twisted.python.reflect import requireModule
from twisted.trial import unittest

inetdtap = requireModule('twisted.runner.inetdtap')
inetdtapSkip = None
if inetdtap is None:
    inetdtapSkip = 'inetdtap not available'



class RPCServerTests(unittest.TestCase):
    """
    Tests for L{inetdtap.RPCServer}
    """
    if inetdtapSkip:
        skip = inetdtapSkip


    def test_deprecation(self):
        """
        It is deprecated.
        """
        inetdtap.RPCServer(
            'some-versions', '/tmp/rpc.conf', 'tcp', 'some-service')
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.

"""
Tests for L{twisted.conch.openssh_compat}.
"""

import os

from twisted.trial.unittest import TestCase
from twisted.python.filepath import FilePath
from twisted.python.reflect import requireModule

if requireModule('cryptography') and requireModule('pyasn1'):
    from twisted.conch.openssh_compat.factory import OpenSSHFactory
else:
    OpenSSHFactory = None

from twisted.conch.ssh._kex import getDHGeneratorAndPrime
from twisted.conch.test import keydata
from twisted.test.test_process import MockOS


class OpenSSHFactoryTests(TestCase):
    """
    Tests for L{OpenSSHFactory}.
    """
    if getattr(os, "geteuid", None) is None:
        skip = "geteuid/seteuid not available"
    elif OpenSSHFactory is None:
        skip = "Cannot run without cryptography or PyASN1"
Exemple #38
0
# -*- test-case-name: twisted.conch.test.test_unix -*-
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.

from __future__ import absolute_import

from zope.interface import implementer

from twisted.internet.interfaces import IReactorProcess
from twisted.python.reflect import requireModule
from twisted.trial import unittest

cryptography = requireModule("cryptography")
unix = requireModule('twisted.conch.unix')


@implementer(IReactorProcess)
class MockProcessSpawner(object):
    """
    An L{IReactorProcess} that logs calls to C{spawnProcess}.
    """
    def __init__(self):
        self._spawnProcessCalls = []

    def spawnProcess(self,
                     processProtocol,
                     executable,
                     args=(),
                     env={},
                     path=None,
                     uid=None,
Exemple #39
0
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.

"""
Tests for L{twisted.python._pydoctor}.
"""
from twisted.python.compat import _PY3
from twisted.python.reflect import requireModule

from twisted.trial.unittest import TestCase

model = requireModule('pydoctor.model')
pydoctorSkip = None
TwistedSphinxInventory = object
TwistedSystem = object
if model is None:
    pydoctorSkip = 'Pydoctor is not present.'
elif _PY3:
    pydoctorSkip = 'Pydoctor not supported on Python3.'
else:
    # We have a valid pydoctor.
    from twisted.python._pydoctor import TwistedSphinxInventory, TwistedSystem


class TwistedSystemTests(TestCase):
    """
    Tests for L{TwistedSystem}.
    """
    skip = pydoctorSkip

    def test_initCustomSphinxInventory(self):
# -*- test-case-name: twisted.conch.test.test_unix -*-
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.

from __future__ import absolute_import

from zope.interface import implementer

from twisted.internet.interfaces import IReactorProcess
from twisted.python.reflect import requireModule
from twisted.trial import unittest

cryptography = requireModule("cryptography")
unix = requireModule('twisted.conch.unix')



@implementer(IReactorProcess)
class MockProcessSpawner(object):
    """
    An L{IReactorProcess} that logs calls to C{spawnProcess}.
    """

    def __init__(self):
        self._spawnProcessCalls = []


    def spawnProcess(self, processProtocol, executable, args=(), env={},
                     path=None, uid=None, gid=None, usePTY=0, childFDs=None):
        """
        Log a call to C{spawnProcess}. Do not actually spawn a process.
Exemple #41
0
# See LICENSE for details.

"""
Tests for L{twisted.python.lockfile}.
"""

import os, errno

from twisted.trial import unittest
from twisted.python import lockfile
from twisted.python.reflect import requireModule
from twisted.python.runtime import platform

skipKill = None
if platform.isWindows():
    if(requireModule('win32api.OpenProcess') is None and
        requireModule('pywintypes') is None
            ):
        skipKill = ("On windows, lockfile.kill is not implemented in the "
                    "absence of win32api and/or pywintypes.")

class UtilTests(unittest.TestCase):
    """
    Tests for the helper functions used to implement L{FilesystemLock}.
    """
    def test_symlinkEEXIST(self):
        """
        L{lockfile.symlink} raises L{OSError} with C{errno} set to L{EEXIST}
        when an attempt is made to create a symlink which already exists.
        """
        name = self.mktemp()
Exemple #42
0
from zope.interface.verify import verifyObject

from twisted.python import util
from twisted.python.failure import Failure
from twisted.python.reflect import requireModule
from twisted.trial.unittest import TestCase
from twisted.python.filepath import FilePath
from twisted.cred.checkers import InMemoryUsernamePasswordDatabaseDontUse
from twisted.cred.credentials import UsernamePassword, IUsernamePassword, \
    SSHPrivateKey, ISSHPrivateKey
from twisted.cred.error import UnhandledCredentials, UnauthorizedLogin
from twisted.python.fakepwd import UserDatabase, ShadowDatabase
from twisted.test.test_process import MockOS

if requireModule('Crypto.Cipher.DES3') and requireModule('pyasn1'):
    dependencySkip = None
    from twisted.conch.ssh import keys
    from twisted.conch import checkers
    from twisted.conch.error import NotEnoughAuthentication, ValidPublicKey
    from twisted.conch.test import keydata
else:
    dependencySkip = "can't run without Crypto and PyASN1"

if getattr(os, 'geteuid', None) is None:
    euidSkip = "Cannot run without effective UIDs (questionable)"
else:
    euidSkip = None


class HelperTests(TestCase):
Exemple #43
0
# -*- test-case-name: twisted.conch.test.test_unix -*-
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.

from __future__ import absolute_import

from zope.interface import implementer

from twisted.internet.interfaces import IReactorProcess
from twisted.python.reflect import requireModule
from twisted.trial import unittest

from .test_session import StubConnection, StubClient

unix = requireModule('twisted.conch.unix')



@implementer(IReactorProcess)
class MockProcessSpawner(object):
    """
    An L{IReactorProcess} that logs calls to C{spawnProcess}.
    """

    def __init__(self):
        self._spawnProcessCalls = []


    def spawnProcess(self, processProtocol, executable, args=(), env={},
                     path=None, uid=None, gid=None, usePTY=0, childFDs=None):
        """
Exemple #44
0
from twisted.conch.test.test_ssh import ConchTestRealm
from twisted.python.procutils import which

from twisted.conch.test.keydata import publicRSA_openssh, privateRSA_openssh
from twisted.conch.test.keydata import publicDSA_openssh, privateDSA_openssh
from twisted.python.filepath import FilePath

try:
    from twisted.conch.test.test_ssh import (
        ConchTestServerFactory,
        conchTestPublicKeyChecker,
    )
except ImportError:
    pass

pyasn1 = requireModule("pyasn1")
cryptography = requireModule("cryptography")

if cryptography:
    from twisted.conch.avatar import ConchUser
    from twisted.conch.ssh.session import ISession, SSHSession, wrapProtocol
else:
    from twisted.conch.interfaces import ISession

    class ConchUser:  # type: ignore[no-redef]
        pass


try:
    from twisted.conch.scripts.conch import SSHSession as _StdioInteractingSession
except ImportError as e:
Exemple #45
0
from twisted.internet.error import ConnectionClosed, FileDescriptorOverrun
from twisted.internet.address import UNIXAddress
from twisted.internet.endpoints import UNIXServerEndpoint, UNIXClientEndpoint
from twisted.internet.defer import Deferred, fail
from twisted.internet.task import LoopingCall
from twisted.internet import interfaces
from twisted.internet.protocol import (
    ServerFactory, ClientFactory, DatagramProtocol)
from twisted.internet.test.test_core import ObjectModelIntegrationMixin
from twisted.internet.test.test_tcp import StreamTransportTestsMixin
from twisted.internet.test.connectionmixins import (
    EndpointCreator, ConnectableProtocol, runProtocolsWithReactor,
    ConnectionTestsMixin, StreamClientTestsMixin)
from twisted.internet.test.reactormixins import ReactorBuilder

if requireModule('twisted.python.sendmsg') is None:
    sendmsgSkip = (
        "sendmsg extension unavailable, extended UNIX features disabled")
else:
    sendmsgSkip = None



class UNIXFamilyMixin:
    """
    Test-helper defining mixin for things related to AF_UNIX sockets.
    """
    def _modeTest(self, methodName, path, factory):
        """
        Assert that the mode of the created unix socket is set to the mode
        specified to the reactor method.
Exemple #46
0
import struct
import sys
from unittest import skipIf

from zope.interface import implementer

from twisted.internet import defer, error, protocol
from twisted.internet.address import IPv4Address
from twisted.internet.error import ProcessDone, ProcessTerminated
from twisted.python import components, failure
from twisted.python.failure import Failure
from twisted.python.reflect import requireModule
from twisted.python.test.test_components import RegistryUsingMixin
from twisted.trial.unittest import TestCase

cryptography = requireModule("cryptography")

if cryptography:
    from twisted.conch.ssh import common, connection, session
else:

    class session:  # type: ignore[no-redef]
        from twisted.conch.interfaces import (
            EnvironmentVariableNotPermitted,
            ISession,
            ISessionSetEnv,
        )


class SubsystemOnlyAvatar:
    """
"""
Tests for the 'session' channel implementation in twisted.conch.ssh.session.

See also RFC 4254.
"""

from __future__ import division, absolute_import

import os, signal, sys, struct

from zope.interface import implementer

from twisted.python.reflect import requireModule

cryptography = requireModule("cryptography")
if cryptography:
    from twisted.conch.ssh import common, session, connection
else:
    class session:
        from twisted.conch.interfaces import ISession

from twisted.internet.address import IPv4Address
from twisted.internet.error import ProcessTerminated, ProcessDone
from twisted.python.failure import Failure
from twisted.internet import defer, protocol, error
from twisted.python import components, failure
from twisted.trial import unittest


Exemple #48
0
from twisted.conch import ls
from twisted.conch.interfaces import ISFTPFile
from twisted.conch.test.test_filetransfer import SFTPTestBase
from twisted.conch.test.test_filetransfer import FileTransferTestAvatar
from twisted.cred import portal
from twisted.internet import reactor, protocol, interfaces, defer, error
from twisted.internet.utils import getProcessOutputAndValue, getProcessValue
from twisted.python import log
from twisted.python.compat import unicode
from twisted.python.fakepwd import UserDatabase
from twisted.test.proto_helpers import StringTransport
from twisted.internet.task import Clock
from twisted.trial.unittest import TestCase

pyasn1 = requireModule('pyasn1')
cryptography = requireModule('cryptography')
unix = requireModule('twisted.conch.unix')

if cryptography and pyasn1:
    try:
        from twisted.conch.scripts import cftp
        from twisted.conch.scripts.cftp import SSHSession
        from twisted.conch.ssh import filetransfer
        from twisted.conch.test.test_filetransfer import (
            FileTransferForTestAvatar)
        from twisted.conch.test import test_ssh, test_conch
        from twisted.conch.test.test_conch import FakeStdio
    except ImportError:
        pass
Exemple #49
0
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""
Tests for L{twisted.python.lockfile}.
"""

import os, errno

from twisted.trial import unittest
from twisted.python import lockfile
from twisted.python.reflect import requireModule
from twisted.python.runtime import platform

skipKill = None
if platform.isWindows():
    if (requireModule('win32api.OpenProcess') is None
            and requireModule('pywintypes') is None):
        skipKill = ("On windows, lockfile.kill is not implemented in the "
                    "absence of win32api and/or pywintypes.")


class UtilTests(unittest.TestCase):
    """
    Tests for the helper functions used to implement L{FilesystemLock}.
    """
    def test_symlinkEEXIST(self):
        """
        L{lockfile.symlink} raises L{OSError} with C{errno} set to L{EEXIST}
        when an attempt is made to create a symlink which already exists.
        """
        name = self.mktemp()
# See LICENSE for details.

"""
Tests for L{twisted.mail.tap}.
"""

from twisted.trial.unittest import TestCase

from twisted.python.usage import UsageError
from twisted.mail import protocols
from twisted.mail.tap import Options, makeService
from twisted.python.filepath import FilePath
from twisted.python.reflect import requireModule
from twisted.internet import endpoints, defer

if requireModule('OpenSSL') is None:
    sslSkip = 'Missing OpenSSL package.'
else:
    sslSkip = None


class OptionsTests(TestCase):
    """
    Tests for the command line option parser used for I{twistd mail}.
    """
    def setUp(self):
        self.aliasFilename = self.mktemp()
        aliasFile = file(self.aliasFilename, 'w')
        aliasFile.write('someuser:\tdifferentuser\n')
        aliasFile.close()
Exemple #51
0
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.

"""
Tests for L{twisted.conch.openssh_compat}.
"""

import os

from twisted.trial.unittest import TestCase
from twisted.python.filepath import FilePath
from twisted.python.reflect import requireModule

if requireModule("Crypto.Cipher.DES3") and requireModule("pyasn1"):
    from twisted.conch.openssh_compat.factory import OpenSSHFactory
else:
    OpenSSHFactory = None

from twisted.conch.test import keydata
from twisted.test.test_process import MockOS


class OpenSSHFactoryTests(TestCase):
    """
    Tests for L{OpenSSHFactory}.
    """

    if getattr(os, "geteuid", None) is None:
        skip = "geteuid/seteuid not available"
    elif OpenSSHFactory is None:
        skip = "Cannot run without PyCrypto or PyASN1"
Exemple #52
0
class ServiceTests(TestCase):
    """
    Tests for the service creation APIs in L{twisted.web.tap}.
    """
    def _pathOption(self):
        """
        Helper for the I{--path} tests which creates a directory and creates
        an L{Options} object which uses that directory as its static
        filesystem root.

        @return: A two-tuple of a L{FilePath} referring to the directory and
            the value associated with the C{'root'} key in the L{Options}
            instance after parsing a I{--path} option.
        """
        path = FilePath(self.mktemp())
        path.makedirs()
        options = Options()
        options.parseOptions(['--path', path.path])
        root = options['root']
        return path, root

    def test_path(self):
        """
        The I{--path} option causes L{Options} to create a root resource
        which serves responses from the specified path.
        """
        path, root = self._pathOption()
        self.assertIsInstance(root, File)
        self.assertEqual(root.path, path.path)

    def test_pathServer(self):
        """
        The I{--path} option to L{makeService} causes it to return a service
        which will listen on the server address given by the I{--port} option.
        """
        path = FilePath(self.mktemp())
        path.makedirs()
        port = self.mktemp()
        options = Options()
        options.parseOptions(['--port', 'unix:' + port, '--path', path.path])
        service = makeService(options)
        service.startService()
        self.addCleanup(service.stopService)
        self.assertIsInstance(service.services[0].factory.resource, File)
        self.assertEqual(service.services[0].factory.resource.path, path.path)
        self.assertTrue(os.path.exists(port))
        self.assertTrue(stat.S_ISSOCK(os.stat(port).st_mode))

    if not IReactorUNIX.providedBy(reactor):
        test_pathServer.skip = (
            "The reactor does not support UNIX domain sockets")

    def test_cgiProcessor(self):
        """
        The I{--path} option creates a root resource which serves a
        L{CGIScript} instance for any child with the C{".cgi"} extension.
        """
        path, root = self._pathOption()
        path.child("foo.cgi").setContent(b"")
        self.assertIsInstance(root.getChild("foo.cgi", None), CGIScript)

    if _PY3:
        test_cgiProcessor.skip = (
            "Will be ported in https://twistedmatrix.com/trac/ticket/8009")

    def test_epyProcessor(self):
        """
        The I{--path} option creates a root resource which serves a
        L{PythonScript} instance for any child with the C{".epy"} extension.
        """
        path, root = self._pathOption()
        path.child("foo.epy").setContent(b"")
        self.assertIsInstance(root.getChild("foo.epy", None), PythonScript)

    def test_rpyProcessor(self):
        """
        The I{--path} option creates a root resource which serves the
        C{resource} global defined by the Python source in any child with
        the C{".rpy"} extension.
        """
        path, root = self._pathOption()
        path.child("foo.rpy").setContent(
            b"from twisted.web.static import Data\n"
            b"resource = Data('content', 'major/minor')\n")
        child = root.getChild("foo.rpy", None)
        self.assertIsInstance(child, Data)
        self.assertEqual(child.data, 'content')
        self.assertEqual(child.type, 'major/minor')

    def test_makePersonalServerFactory(self):
        """
        L{makePersonalServerFactory} returns a PB server factory which has
        as its root object a L{ResourcePublisher}.
        """
        # The fact that this pile of objects can actually be used somehow is
        # verified by twisted.web.test.test_distrib.
        site = Site(Data(b"foo bar", "text/plain"))
        serverFactory = makePersonalServerFactory(site)
        self.assertIsInstance(serverFactory, PBServerFactory)
        self.assertIsInstance(serverFactory.root, ResourcePublisher)
        self.assertIdentical(serverFactory.root.site, site)

    def test_personalServer(self):
        """
        The I{--personal} option to L{makeService} causes it to return a
        service which will listen on the server address given by the I{--port}
        option.
        """
        port = self.mktemp()
        options = Options()
        options.parseOptions(['--port', 'unix:' + port, '--personal'])
        service = makeService(options)
        service.startService()
        self.addCleanup(service.stopService)
        self.assertTrue(os.path.exists(port))
        self.assertTrue(stat.S_ISSOCK(os.stat(port).st_mode))

    if not IReactorUNIX.providedBy(reactor):
        test_personalServer.skip = (
            "The reactor does not support UNIX domain sockets")

    def test_defaultPersonalPath(self):
        """
        If the I{--port} option not specified but the I{--personal} option is,
        L{Options} defaults the port to C{UserDirectory.userSocketName} in the
        user's home directory.
        """
        options = Options()
        options.parseOptions(['--personal'])
        path = os.path.expanduser(
            os.path.join('~', UserDirectory.userSocketName))
        self.assertEqual(
            strports.parse(options['port'], None)[:2], ('UNIX', (path, None)))

    if not IReactorUNIX.providedBy(reactor):
        test_defaultPersonalPath.skip = (
            "The reactor does not support UNIX domain sockets")

    if _PY3:
        for i in [
                test_makePersonalServerFactory, test_personalServer,
                test_defaultPersonalPath
        ]:
            i.skip = (
                "Will be ported in https://twistedmatrix.com/trac/ticket/8010")
        del i

    def test_defaultPort(self):
        """
        If the I{--port} option is not specified, L{Options} defaults the port
        to C{8080}.
        """
        options = Options()
        options.parseOptions([])
        self.assertEqual(
            endpoints._parseServer(options['port'], None)[:2],
            ('TCP', (8080, None)))

    def test_wsgi(self):
        """
        The I{--wsgi} option takes the fully-qualifed Python name of a WSGI
        application object and creates a L{WSGIResource} at the root which
        serves that application.
        """
        options = Options()
        options.parseOptions(['--wsgi', __name__ + '.application'])
        root = options['root']
        self.assertTrue(root, WSGIResource)
        self.assertIdentical(root._reactor, reactor)
        self.assertTrue(isinstance(root._threadpool, ThreadPool))
        self.assertIdentical(root._application, application)

        # The threadpool should start and stop with the reactor.
        self.assertFalse(root._threadpool.started)
        reactor.fireSystemEvent('startup')
        self.assertTrue(root._threadpool.started)
        self.assertFalse(root._threadpool.joined)
        reactor.fireSystemEvent('shutdown')
        self.assertTrue(root._threadpool.joined)

    if _PY3:
        test_wsgi.skip = (
            "Will be ported in https://twistedmatrix.com/trac/ticket/7993")

    def test_invalidApplication(self):
        """
        If I{--wsgi} is given an invalid name, L{Options.parseOptions}
        raises L{UsageError}.
        """
        options = Options()
        for name in [__name__ + '.nosuchthing', 'foo.']:
            exc = self.assertRaises(UsageError, options.parseOptions,
                                    ['--wsgi', name])
            self.assertEqual(str(exc),
                             "No such WSGI application: %r" % (name, ))

    def test_HTTPSFailureOnMissingSSL(self):
        """
        An L{UsageError} is raised when C{https} is requested but there is no
        support for SSL.
        """
        options = Options()

        exception = self.assertRaises(UsageError, options.parseOptions,
                                      ['--https=443'])

        self.assertEqual('SSL support not installed', exception.args[0])

    if requireModule('OpenSSL.SSL') is not None:
        test_HTTPSFailureOnMissingSSL.skip = 'SSL module is available.'

    def test_HTTPSAcceptedOnAvailableSSL(self):
        """
        When SSL support is present, it accepts the --https option.
        """
        options = Options()

        options.parseOptions(['--https=443'])

        self.assertEqual('443', options['https'])

    if requireModule('OpenSSL.SSL') is None:
        test_HTTPSAcceptedOnAvailableSSL.skip = 'SSL module is not available.'
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.

"""
Tests for L{twisted.conch.client.knownhosts}.
"""

import os
from binascii import Error as BinasciiError, b2a_base64, a2b_base64

from twisted.python.reflect import requireModule

if requireModule('Crypto') and requireModule('pyasn1'):
    from twisted.conch.ssh.keys import Key, BadKeyError
    from twisted.conch.client.knownhosts import \
        PlainEntry, HashedEntry, KnownHostsFile, UnparsedEntry, ConsoleUI
    from twisted.conch.client import default
else:
    skip = "PyCrypto and PyASN1 required for twisted.conch.knownhosts."

from zope.interface.verify import verifyObject

from twisted.python.filepath import FilePath
from twisted.trial.unittest import TestCase
from twisted.internet.defer import Deferred
from twisted.conch.interfaces import IKnownHostEntry
from twisted.conch.error import HostKeyChanged, UserRejectedKey, InvalidEntry
from twisted.test.testutils import ComparisonTestsMixin


sampleEncodedKey = (
Exemple #54
0
    WriteSequenceTestsMixin,
    MyClientFactory,
    MyServerFactory,
)
from twisted.internet.test.connectionmixins import ConnectableProtocol
from twisted.internet.test.connectionmixins import ConnectionTestsMixin
from twisted.internet.test.connectionmixins import StreamClientTestsMixin
from twisted.internet.test.connectionmixins import runProtocolsWithReactor
from twisted.python.compat import nativeString, _PY3, iteritems
from twisted.python.failure import Failure
from twisted.python.log import addObserver, removeObserver, err
from twisted.python.runtime import platform
from twisted.python.reflect import requireModule
from twisted.python.filepath import _coerceToFilesystemEncoding

if requireModule("twisted.python.sendmsg") is not None:
    sendmsgSkip = None
else:
    sendmsgSkip = (
        "sendmsg extension unavailable, extended UNIX features disabled")


class UNIXFamilyMixin(object):
    """
    Test-helper defining mixin for things related to AF_UNIX sockets.
    """
    def _modeTest(self, methodName, path, factory):
        """
        Assert that the mode of the created unix socket is set to the mode
        specified to the reactor method.
        """
from twisted.internet.test.reactormixins import ReactorBuilder
from twisted.internet.test.test_core import ObjectModelIntegrationMixin
from twisted.internet.test.test_tcp import (StreamTransportTestsMixin,
    WriteSequenceTestsMixin, MyClientFactory, MyServerFactory,)
from twisted.internet.test.connectionmixins import ConnectableProtocol
from twisted.internet.test.connectionmixins import ConnectionTestsMixin
from twisted.internet.test.connectionmixins import StreamClientTestsMixin
from twisted.internet.test.connectionmixins import runProtocolsWithReactor
from twisted.python.compat import nativeString, _PY3, iteritems
from twisted.python.failure import Failure
from twisted.python.log import addObserver, removeObserver, err
from twisted.python.runtime import platform
from twisted.python.reflect import requireModule
from twisted.python.filepath import _coerceToFilesystemEncoding

if requireModule("twisted.python.sendmsg") is not None:
    sendmsgSkip = None
else:
    sendmsgSkip = (
        "sendmsg extension unavailable, extended UNIX features disabled")



class UNIXFamilyMixin(object):
    """
    Test-helper defining mixin for things related to AF_UNIX sockets.
    """
    def _modeTest(self, methodName, path, factory):
        """
        Assert that the mode of the created unix socket is set to the mode
        specified to the reactor method.
Exemple #56
0
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""
Tests for the inotify wrapper in L{twisted.internet.inotify}.
"""

from twisted.internet import defer, reactor
from twisted.python import filepath, runtime
from twisted.python.reflect import requireModule
from twisted.trial import unittest

if requireModule('twisted.python._inotify') is not None:
    from twisted.internet import inotify
else:
    inotify = None


class INotifyTests(unittest.TestCase):
    """
    Define all the tests for the basic functionality exposed by
    L{inotify.INotify}.
    """
    if not runtime.platform.supportsINotify():
        skip = "This platform doesn't support INotify."

    def setUp(self):
        self.dirname = filepath.FilePath(self.mktemp())
        self.dirname.createDirectory()
        self.inotify = inotify.INotify()
        self.inotify.startReading()
        self.addCleanup(self.inotify.loseConnection)
Exemple #57
0
class ServiceTests(TestCase):
    """
    Tests for the service creation APIs in L{twisted.web.tap}.
    """
    def _pathOption(self):
        """
        Helper for the I{--path} tests which creates a directory and creates
        an L{Options} object which uses that directory as its static
        filesystem root.

        @return: A two-tuple of a L{FilePath} referring to the directory and
            the value associated with the C{'root'} key in the L{Options}
            instance after parsing a I{--path} option.
        """
        path = FilePath(self.mktemp())
        path.makedirs()
        options = Options()
        options.parseOptions(["--path", path.path])
        root = options["root"]
        return path, root

    def test_path(self):
        """
        The I{--path} option causes L{Options} to create a root resource
        which serves responses from the specified path.
        """
        path, root = self._pathOption()
        self.assertIsInstance(root, File)
        self.assertEqual(root.path, path.path)

    @skipIf(
        not IReactorUNIX.providedBy(reactor),
        "The reactor does not support UNIX domain sockets",
    )
    def test_pathServer(self):
        """
        The I{--path} option to L{makeService} causes it to return a service
        which will listen on the server address given by the I{--port} option.
        """
        path = FilePath(self.mktemp())
        path.makedirs()
        port = self.mktemp()
        options = Options()
        options.parseOptions(["--port", "unix:" + port, "--path", path.path])
        service = makeService(options)
        service.startService()
        self.addCleanup(service.stopService)
        self.assertIsInstance(service.services[0].factory.resource, File)
        self.assertEqual(service.services[0].factory.resource.path, path.path)
        self.assertTrue(os.path.exists(port))
        self.assertTrue(stat.S_ISSOCK(os.stat(port).st_mode))

    def test_cgiProcessor(self):
        """
        The I{--path} option creates a root resource which serves a
        L{CGIScript} instance for any child with the C{".cgi"} extension.
        """
        path, root = self._pathOption()
        path.child("foo.cgi").setContent(b"")
        self.assertIsInstance(root.getChild("foo.cgi", None), CGIScript)

    def test_epyProcessor(self):
        """
        The I{--path} option creates a root resource which serves a
        L{PythonScript} instance for any child with the C{".epy"} extension.
        """
        path, root = self._pathOption()
        path.child("foo.epy").setContent(b"")
        self.assertIsInstance(root.getChild("foo.epy", None), PythonScript)

    def test_rpyProcessor(self):
        """
        The I{--path} option creates a root resource which serves the
        C{resource} global defined by the Python source in any child with
        the C{".rpy"} extension.
        """
        path, root = self._pathOption()
        path.child("foo.rpy").setContent(
            b"from twisted.web.static import Data\n"
            b"resource = Data('content', 'major/minor')\n")
        child = root.getChild("foo.rpy", None)
        self.assertIsInstance(child, Data)
        self.assertEqual(child.data, "content")
        self.assertEqual(child.type, "major/minor")

    def test_makePersonalServerFactory(self):
        """
        L{makePersonalServerFactory} returns a PB server factory which has
        as its root object a L{ResourcePublisher}.
        """
        # The fact that this pile of objects can actually be used somehow is
        # verified by twisted.web.test.test_distrib.
        site = Site(Data(b"foo bar", "text/plain"))
        serverFactory = makePersonalServerFactory(site)
        self.assertIsInstance(serverFactory, PBServerFactory)
        self.assertIsInstance(serverFactory.root, ResourcePublisher)
        self.assertIdentical(serverFactory.root.site, site)

    @skipIf(
        not IReactorUNIX.providedBy(reactor),
        "The reactor does not support UNIX domain sockets",
    )
    def test_personalServer(self):
        """
        The I{--personal} option to L{makeService} causes it to return a
        service which will listen on the server address given by the I{--port}
        option.
        """
        port = self.mktemp()
        options = Options()
        options.parseOptions(["--port", "unix:" + port, "--personal"])
        service = makeService(options)
        service.startService()
        self.addCleanup(service.stopService)
        self.assertTrue(os.path.exists(port))
        self.assertTrue(stat.S_ISSOCK(os.stat(port).st_mode))

    @skipIf(
        not IReactorUNIX.providedBy(reactor),
        "The reactor does not support UNIX domain sockets",
    )
    def test_defaultPersonalPath(self):
        """
        If the I{--port} option not specified but the I{--personal} option is,
        L{Options} defaults the port to C{UserDirectory.userSocketName} in the
        user's home directory.
        """
        options = Options()
        options.parseOptions(["--personal"])
        path = os.path.expanduser(
            os.path.join("~", UserDirectory.userSocketName))
        self.assertEqual(options["ports"][0], f"unix:{path}")

    def test_defaultPort(self):
        """
        If the I{--port} option is not specified, L{Options} defaults the port
        to C{8080}.
        """
        options = Options()
        options.parseOptions([])
        self.assertEqual(
            endpoints._parseServer(options["ports"][0], None)[:2],
            ("TCP", (8080, None)))

    def test_twoPorts(self):
        """
        If the I{--http} option is given twice, there are two listeners
        """
        options = Options()
        options.parseOptions(["--listen", "tcp:8001", "--listen", "tcp:8002"])
        self.assertIn("8001", options["ports"][0])
        self.assertIn("8002", options["ports"][1])

    def test_wsgi(self):
        """
        The I{--wsgi} option takes the fully-qualifed Python name of a WSGI
        application object and creates a L{WSGIResource} at the root which
        serves that application.
        """
        options = Options()
        options.parseOptions(["--wsgi", __name__ + ".application"])
        root = options["root"]
        self.assertTrue(root, WSGIResource)
        self.assertIdentical(root._reactor, reactor)
        self.assertTrue(isinstance(root._threadpool, ThreadPool))
        self.assertIdentical(root._application, application)

        # The threadpool should start and stop with the reactor.
        self.assertFalse(root._threadpool.started)
        reactor.fireSystemEvent("startup")
        self.assertTrue(root._threadpool.started)
        self.assertFalse(root._threadpool.joined)
        reactor.fireSystemEvent("shutdown")
        self.assertTrue(root._threadpool.joined)

    def test_invalidApplication(self):
        """
        If I{--wsgi} is given an invalid name, L{Options.parseOptions}
        raises L{UsageError}.
        """
        options = Options()
        for name in [__name__ + ".nosuchthing", "foo."]:
            exc = self.assertRaises(UsageError, options.parseOptions,
                                    ["--wsgi", name])
            self.assertEqual(str(exc), f"No such WSGI application: {name!r}")

    @skipIf(
        requireModule("OpenSSL.SSL") is not None, "SSL module is available.")
    def test_HTTPSFailureOnMissingSSL(self):
        """
        An L{UsageError} is raised when C{https} is requested but there is no
        support for SSL.
        """
        options = Options()

        exception = self.assertRaises(UsageError, options.parseOptions,
                                      ["--https=443"])

        self.assertEqual("SSL support not installed", exception.args[0])

    @skipIf(
        requireModule("OpenSSL.SSL") is None, "SSL module is not available.")
    def test_HTTPSAcceptedOnAvailableSSL(self):
        """
        When SSL support is present, it accepts the --https option.
        """
        options = Options()

        options.parseOptions(["--https=443"])

        self.assertIn("ssl", options["ports"][0])
        self.assertIn("443", options["ports"][0])

    def test_add_header_parsing(self):
        """
        When --add-header is specific, the value is parsed.
        """
        options = Options()
        options.parseOptions(
            ["--add-header", "K1: V1", "--add-header", "K2: V2"])
        self.assertEqual(options["extraHeaders"], [("K1", "V1"), ("K2", "V2")])

    def test_add_header_resource(self):
        """
        When --add-header is specified, the resource is a composition that adds
        headers.
        """
        options = Options()
        options.parseOptions(
            ["--add-header", "K1: V1", "--add-header", "K2: V2"])
        service = makeService(options)
        resource = service.services[0].factory.resource
        self.assertIsInstance(resource, _AddHeadersResource)
        self.assertEqual(resource._headers, [("K1", "V1"), ("K2", "V2")])
        self.assertIsInstance(resource._originalResource, demo.Test)

    def test_noTracebacksDeprecation(self):
        """
        Passing --notracebacks is deprecated.
        """
        options = Options()
        options.parseOptions(["--notracebacks"])
        makeService(options)

        warnings = self.flushWarnings([self.test_noTracebacksDeprecation])
        self.assertEqual(warnings[0]["category"], DeprecationWarning)
        self.assertEqual(warnings[0]["message"],
                         "--notracebacks was deprecated in Twisted 19.7.0")
        self.assertEqual(len(warnings), 1)

    def test_displayTracebacks(self):
        """
        Passing --display-tracebacks will enable traceback rendering on the
        generated Site.
        """
        options = Options()
        options.parseOptions(["--display-tracebacks"])
        service = makeService(options)
        self.assertTrue(service.services[0].factory.displayTracebacks)

    def test_displayTracebacksNotGiven(self):
        """
        Not passing --display-tracebacks will leave traceback rendering on the
        generated Site off.
        """
        options = Options()
        options.parseOptions([])
        service = makeService(options)
        self.assertFalse(service.services[0].factory.displayTracebacks)
Exemple #58
0
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""
Tests for the command-line interfaces to conch.
"""
from twisted.python.reflect import requireModule

if requireModule('pyasn1'):
    pyasn1Skip = None
else:
    pyasn1Skip = "Cannot run without PyASN1"

if requireModule('cryptography'):
    cryptoSkip = None
else:
    cryptoSkip = "can't run w/o cryptography"

if requireModule('tty'):
    ttySkip = None
else:
    ttySkip = "can't run w/o tty"

try:
    import Tkinter
except ImportError:
    tkskip = "can't run w/o Tkinter"
else:
    try:
        Tkinter.Tk().destroy()
    except Tkinter.TclError as e:
        tkskip = "Can't test Tkinter: " + str(e)
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.

"""
Tests for L{twisted.python._pydoctor}.
"""
from collections import namedtuple

from twisted.python.compat import _PY3
from twisted.python.reflect import requireModule

from twisted.trial.unittest import TestCase

model = requireModule('pydoctor.model')
pydoctorSkip = None
TwistedSphinxInventory = object
TwistedSystem = object
if model is None:
    pydoctorSkip = 'Pydoctor is not present.'
elif _PY3:
    pydoctorSkip = 'Pydoctor not supported on Python3.'
else:
    # We have a valid pydoctor.
    from twisted.python._pydoctor import TwistedSphinxInventory, TwistedSystem


class TwistedSystemTests(TestCase):
    """
    Tests for L{TwistedSystem}.
    """
    skip = pydoctorSkip