Python twisted.trial.unittest.SkipTest() Examples

The following are 30 code examples of twisted.trial.unittest.SkipTest(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module twisted.trial.unittest , or try the search function .
Example #1
Source File: test_scripts.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def test_twistdPathInsert(self):
        """
        The twistd script adds the current working directory to sys.path so
        that it's able to import modules from it.
        """
        script = self.bin.child("twistd")
        if not script.exists():
            raise SkipTest(
                "Script tests do not apply to installed configuration.")
        cwd = getcwd()
        self.addCleanup(chdir, cwd)
        testDir = FilePath(self.mktemp())
        testDir.makedirs()
        chdir(testDir.path)
        testDir.child("bar.tac").setContent(
            "import sys\n"
            "print sys.path\n")
        output = outputFromPythonScript(script, '-ny', 'bar.tac')
        self.assertIn(repr(testDir.path), output) 
Example #2
Source File: test_wsgi.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def test_wsgiErrorsAcceptsOnlyNativeStringsInPython3(self):
        """
        The C{'wsgi.errors'} file-like object from the C{environ} C{dict}
        permits writes of only native strings in Python 3, and raises
        C{TypeError} for writes of non-native strings.
        """
        if not _PY3:
            raise SkipTest("Relevant only in Python 3")

        request, result = self.prepareRequest()
        request.requestReceived()
        environ, _ = self.successResultOf(result)
        errors = environ["wsgi.errors"]

        error = self.assertRaises(TypeError, errors.write, b"fred")
        self.assertEqual(
            "write() argument must be str, not b'fred' (bytes)",
            str(error)) 
Example #3
Source File: test_pidfile.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def test_isRunningInit(self):
        """
        L{PIDFile.isRunning} returns true for a process that we are not allowed
        to kill (errno=EPERM).

        @note: This differs from L{PIDFileTests.test_isRunningNotAllowed} in
        that it actually invokes the C{kill} system call, which is useful for
        testing of our chosen method for probing the existence of a process
        that we are not allowed to kill.

        @note: In this case, we try killing C{init}, which is process #1 on
        POSIX systems, so this test is not portable.  C{init} should always be
        running and should not be killable by non-root users.
        """
        if SYSTEM_NAME != "posix":
            raise SkipTest("This test assumes POSIX")

        pidFile = PIDFile(DummyFilePath())
        pidFile._write(1)  # PID 1 is init on POSIX systems

        self.assertTrue(pidFile.isRunning()) 
Example #4
Source File: test_wsgi.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def test_wsgiErrorsExpectsOnlyNativeStringsInPython2(self):
        """
        The C{'wsgi.errors'} file-like object from the C{environ} C{dict}
        expects writes of only native strings in Python 2. Some existing WSGI
        applications may write non-native (i.e. C{unicode}) strings so, for
        compatibility, these elicit only a warning in Python 2.
        """
        if _PY3:
            raise SkipTest("Not relevant in Python 3")

        request, result = self.prepareRequest()
        request.requestReceived()
        environ, _ = self.successResultOf(result)
        errors = environ["wsgi.errors"]

        with warnings.catch_warnings(record=True) as caught:
            errors.write(u"fred")
        self.assertEqual(1, len(caught))
        self.assertEqual(UnicodeWarning, caught[0].category)
        self.assertEqual(
            "write() argument should be str, not u'fred' (unicode)",
            str(caught[0].message)) 
Example #5
Source File: test_wsgi.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def test_wsgiErrorsAcceptsOnlyNativeStringsInPython3(self):
        """
        The C{'wsgi.errors'} file-like object from the C{environ} C{dict}
        permits writes of only native strings in Python 3, and raises
        C{TypeError} for writes of non-native strings.
        """
        if not _PY3:
            raise SkipTest("Relevant only in Python 3")

        request, result = self.prepareRequest()
        request.requestReceived()
        environ, _ = self.successResultOf(result)
        errors = environ["wsgi.errors"]

        error = self.assertRaises(TypeError, errors.write, b"fred")
        self.assertEqual(
            "write() argument must be str, not b'fred' (bytes)",
            str(error)) 
Example #6
Source File: test_pidfile.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def test_isRunningInit(self):
        """
        L{PIDFile.isRunning} returns true for a process that we are not allowed
        to kill (errno=EPERM).

        @note: This differs from L{PIDFileTests.test_isRunningNotAllowed} in
        that it actually invokes the C{kill} system call, which is useful for
        testing of our chosen method for probing the existence of a process
        that we are not allowed to kill.

        @note: In this case, we try killing C{init}, which is process #1 on
        POSIX systems, so this test is not portable.  C{init} should always be
        running and should not be killable by non-root users.
        """
        if SYSTEM_NAME != "posix":
            raise SkipTest("This test assumes POSIX")

        pidFile = PIDFile(DummyFilePath())
        pidFile._write(1)  # PID 1 is init on POSIX systems

        self.assertTrue(pidFile.isRunning()) 
Example #7
Source File: test_wsgi.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def test_wsgiErrorsExpectsOnlyNativeStringsInPython2(self):
        """
        The C{'wsgi.errors'} file-like object from the C{environ} C{dict}
        expects writes of only native strings in Python 2. Some existing WSGI
        applications may write non-native (i.e. C{unicode}) strings so, for
        compatibility, these elicit only a warning in Python 2.
        """
        if _PY3:
            raise SkipTest("Not relevant in Python 3")

        request, result = self.prepareRequest()
        request.requestReceived()
        environ, _ = self.successResultOf(result)
        errors = environ["wsgi.errors"]

        with warnings.catch_warnings(record=True) as caught:
            errors.write(u"fred")
        self.assertEqual(1, len(caught))
        self.assertEqual(UnicodeWarning, caught[0].category)
        self.assertEqual(
            "write() argument should be str, not u'fred' (unicode)",
            str(caught[0].message)) 
Example #8
Source File: test_tests.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def test_decorateTestSuiteReferences(self):
        """
        When decorating a test suite in-place, the number of references to the
        test objects in that test suite should stay the same.

        Previously, L{unittest.decorate} recreated a test suite, so the
        original suite kept references to the test objects. This test is here
        to ensure the problem doesn't reappear again.
        """
        getrefcount = getattr(sys, 'getrefcount', None)
        if getrefcount is None:
            raise unittest.SkipTest(
                "getrefcount not supported on this platform")
        test = self.TestCase()
        suite = unittest.TestSuite([test])
        count1 = getrefcount(test)
        unittest.decorate(suite, unittest.TestDecorator)
        count2 = getrefcount(test)
        self.assertEqual(count1, count2) 
Example #9
Source File: test_tzhelper.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def mktime(t9):
    """
    Call L{mktime_real}, and if it raises L{OverflowError}, catch it and raise
    SkipTest instead.

    @param t9: A time as a 9-item tuple.
    @type t9: L{tuple}

    @return: A timestamp.
    @rtype: L{float}
    """
    try:
        return mktime_real(t9)
    except OverflowError:
        raise SkipTest(
            "Platform cannot construct time zone for {0!r}"
            .format(t9)
        ) 
Example #10
Source File: test_unittest.py    From pytest with MIT License 6 votes vote down vote up
def test_unittest_raise_skip_issue748(testdir):
    testdir.makepyfile(
        test_foo="""
        import unittest

        class MyTestCase(unittest.TestCase):
            def test_one(self):
                raise unittest.SkipTest('skipping due to reasons')
    """
    )
    result = testdir.runpytest("-v", "-rs")
    result.stdout.fnmatch_lines(
        """
        *SKIP*[1]*test_foo.py*skipping due to reasons*
        *1 skipped*
    """
    ) 
Example #11
Source File: test_format.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def test_formatTimeDefault(self):
        """
        Time is first field.  Default time stamp format is RFC 3339 and offset
        respects the timezone as set by the standard C{TZ} environment variable
        and L{tzset} API.
        """
        if tzset is None:
            raise SkipTest(
                "Platform cannot change timezone; unable to verify offsets."
            )

        addTZCleanup(self)
        setTZ("UTC+00")

        t = mktime((2013, 9, 24, 11, 40, 47, 1, 267, 1))
        event = dict(log_format=u"XYZZY", log_time=t)
        self.assertEqual(
            formatEventAsClassicLogText(event),
            u"2013-09-24T11:40:47+0000 [-#-] XYZZY\n",
        ) 
Example #12
Source File: test_application.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def test_UDP(self):
        """
        Test L{internet.UDPServer} with a random port: starting the service
        should give it valid port, and stopService should free it so that we
        can start a server on the same port again.
        """
        if not interfaces.IReactorUDP(reactor, None):
            raise unittest.SkipTest("This reactor does not support UDP sockets")
        p = protocol.DatagramProtocol()
        t = internet.UDPServer(0, p)
        t.startService()
        num = t._port.getHost().port
        self.assertNotEqual(num, 0)
        def onStop(ignored):
            t = internet.UDPServer(num, p)
            t.startService()
            return t.stopService()
        return defer.maybeDeferred(t.stopService).addCallback(onStop) 
Example #13
Source File: __init__.py    From flocker with Apache License 2.0 6 votes vote down vote up
def assertNoFDsLeaked(test_case):
    """Context manager that asserts no file descriptors are leaked.

    :param test_case: The ``TestCase`` running this unit test.
    :raise SkipTest: when /dev/fd virtual filesystem is not available.
    """
    # Make sure there's no file descriptors that will be cleared by GC
    # later on:
    gc.collect()

    def process_fds():
        path = FilePath(b"/dev/fd")
        if not path.exists():
            raise SkipTest("/dev/fd is not available.")

        return set([child.basename() for child in path.children()])

    fds = process_fds()
    try:
        yield
    finally:
        test_case.assertEqual(process_fds(), fds) 
Example #14
Source File: test_sslverify.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def test_ecSuccessWithRealBindings(self):
        """
        Integration test that checks the positive code path to ensure that we
        use the API properly.
        """
        try:
            defaultCurve = sslverify._OpenSSLECCurve(
                sslverify._defaultCurveName
            )
        except NotImplementedError:
            raise unittest.SkipTest(
                "Underlying pyOpenSSL is not based on cryptography."
            )
        opts = sslverify.OpenSSLCertificateOptions(
            privateKey=self.sKey,
            certificate=self.sCert,
        )
        self.assertEqual(defaultCurve, opts._ecCurve)
        # Exercise positive code path.  getContext swallows errors so we do it
        # explicitly by hand.
        opts._ecCurve.addECKeyToContext(opts.getContext()) 
Example #15
Source File: test_scripts.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def test_trialPathInsert(self):
        """
        The trial script adds the current working directory to sys.path so that
        it's able to import modules from it.
        """
        script = self.bin.child("trial")
        if not script.exists():
            raise SkipTest(
                "Script tests do not apply to installed configuration.")
        cwd = getcwd()
        self.addCleanup(chdir, cwd)
        testDir = FilePath(self.mktemp())
        testDir.makedirs()
        chdir(testDir.path)
        testDir.child("foo.py").setContent("")
        output = outputFromPythonScript(script, 'foo')
        self.assertIn("PASSED", output) 
Example #16
Source File: test_gireactor.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def runReactor(self, app, reactor):
        """
        Register the app, run the reactor, make sure app was activated, and
        that reactor was running, and that reactor can be stopped.
        """
        if not hasattr(app, "quit"):
            raise SkipTest("Version of PyGObject is too old.")

        result = []
        def stop():
            result.append("stopped")
            reactor.stop()
        def activate(widget):
            result.append("activated")
            reactor.callLater(0, stop)
        app.connect('activate', activate)

        # We want reactor.stop() to *always* stop the event loop, even if
        # someone has called hold() on the application and never done the
        # corresponding release() -- for more details see
        # http://developer.gnome.org/gio/unstable/GApplication.html.
        app.hold()

        reactor.registerGApplication(app)
        ReactorBuilder.runReactor(self, reactor)
        self.assertEqual(result, ["activated", "stopped"]) 
Example #17
Source File: test_jobs.py    From ccs-twistedextensions with Apache License 2.0 5 votes vote down vote up
def buildStore(*args, **kwargs):
        raise SkipTest(
            "buildStore is not available, because it's in txdav; duh."
        ) 
Example #18
Source File: test_endpoints.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def test_parseStreamServerUNIX(self):
        """
        A UNIX domain socket can be specified using the string C{"UNIX"}.
        """
        try:
            from socket import AF_UNIX
        except ImportError:
            raise unittest.SkipTest("Platform lacks AF_UNIX support")
        else:
            self._parseStreamServerTest(AF_UNIX, "UNIX") 
Example #19
Source File: test_sqlsyntax.py    From ccs-twistedextensions with Apache License 2.0 5 votes vote down vote up
def addSQLToSchema(*args, **kwargs):
        raise SkipTest("addSQLToSchema is not available: {0}".format(e)) 
Example #20
Source File: test_parseschema.py    From ccs-twistedextensions with Apache License 2.0 5 votes vote down vote up
def addSQLToSchema(*args, **kwargs):
        raise SkipTest("addSQLToSchema is not available: {0}".format(e)) 
Example #21
Source File: test_reporter.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def test_addSkip(self):
        """
        C{addSkip} wraps its test with the provided adapter.
        """
        self.wrappedResult.addSkip(
            self, self.getFailure(SkipTest('no reason')))
        self.assertWrapped(self.wrappedResult, self) 
Example #22
Source File: test_tests.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def test_setUp(self):
        """
        Running a suite in which all methods are skipped by C{setUp} raising
        L{SkipTest} produces a successful result with no recorded errors or
        failures, all skipped methods recorded as skips, and no methods recorded
        as successes.
        """
        self.loadSuite(self.SkippingSetUp)
        self.suite(self.reporter)
        self.assertTrue(self.reporter.wasSuccessful())
        self.assertEqual(self.reporter.errors, [])
        self.assertEqual(self.reporter.failures, [])
        self.assertEqual(len(self.reporter.skips), 2)
        self.assertEqual(self.reporter.successes, 0) 
Example #23
Source File: test_tests.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def test_deprecatedSkipWithoutReason(self):
        """
        If a test method raises L{SkipTest} with no reason, a deprecation
        warning is emitted.
        """
        self.loadSuite(self.DeprecatedReasonlessSkip)
        self.suite(self.reporter)
        warnings = self.flushWarnings([
                self.DeprecatedReasonlessSkip.test_1])
        self.assertEqual(1, len(warnings))
        self.assertEqual(DeprecationWarning, warnings[0]['category'])
        self.assertEqual(
            "Do not raise unittest.SkipTest with no arguments! Give a reason "
            "for skipping tests!",
            warnings[0]['message']) 
Example #24
Source File: test_ceph_rbd.py    From ceph-flocker-driver with Apache License 2.0 5 votes vote down vote up
def api_factory(test_case):
    """
    :param test: A twisted.trial.unittest.TestCase instance
    """
    flocker_functional_test = environ.get('FLOCKER_FUNCTIONAL_TEST')
    if flocker_functional_test is None:
        raise SkipTest(
            'Please set FLOCKER_FUNCTIONAL_TEST environment variable to '
            'run storage backend functional tests.'
        )
    api = rbd_from_configuration(
        "flocker", "client.admin", "/etc/ceph/ceph.conf", "rbd")
    test_case.addCleanup(api.destroy_all_flocker_volumes)
    return api 
Example #25
Source File: __init__.py    From flocker with Apache License 2.0 5 votes vote down vote up
def skip_on_broken_permissions(test_method):
    """
    Skips the wrapped test when the temporary directory is on a
    filesystem with broken permissions.

    Virtualbox's shared folder (as used for :file:`/vagrant`) doesn't entirely
    respect changing permissions. For example, this test detects running on a
    shared folder by the fact that all permissions can't be removed from a
    file.

    :param callable test_method: Test method to wrap.
    :return: The wrapped method.
    :raise SkipTest: when the temporary directory is on a filesystem with
        broken permissions.
    """
    @wraps(test_method)
    def wrapper(case, *args, **kwargs):
        test_file = FilePath(case.mktemp())
        test_file.touch()
        test_file.chmod(0o000)
        permissions = test_file.getPermissions()
        test_file.chmod(0o777)
        if permissions != Permissions(0o000):
            raise SkipTest(
                "Can't run test on filesystem with broken permissions.")
        return test_method(case, *args, **kwargs)
    return wrapper 
Example #26
Source File: test_tests.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def test_reasons(self):
        """
        Test methods which raise L{unittest.SkipTest} or have their C{skip}
        attribute set to something are skipped.
        """
        self.suite(self.reporter)
        expectedReasons = ['class', 'skip2', 'class', 'class']
        # whitebox reporter
        reasonsGiven = [reason for test, reason in self.reporter.skips]
        self.assertEqual(expectedReasons, reasonsGiven) 
Example #27
Source File: test_tuntap.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def ioctl(self, *args, **kwargs):
        """
        Attempt an ioctl, but translate permission denied errors into
        L{SkipTest} so that tests that require elevated system privileges and
        do not have them are skipped instead of failed.
        """
        try:
            return super(TestRealSystem, self).ioctl(*args, **kwargs)
        except IOError as e:
            if EPERM == e.errno:
                raise SkipTest("Permission to configure device denied")
            raise 
Example #28
Source File: test_tuntap.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def open(self, filename, *args, **kwargs):
        """
        Attempt an open, but if the file is /dev/net/tun and it does not exist,
        translate the error into L{SkipTest} so that tests that require
        platform support for tuntap devices are skipped instead of failed.
        """
        try:
            return super(TestRealSystem, self).open(filename, *args, **kwargs)
        except OSError as e:
            # The device file may simply be missing.  The device file may also
            # exist but be unsupported by the kernel.
            if e.errno in (ENOENT, ENODEV) and filename == b"/dev/net/tun":
                raise SkipTest("Platform lacks /dev/net/tun")
            raise 
Example #29
Source File: test_tests.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def test_addCleanupCalledIfSetUpSkips(self):
        """
        Callables added with C{addCleanup} are run even if setUp raises
        L{SkipTest}. This allows test authors to reliably provide clean up
        code using C{addCleanup}.
        """
        self.test.setUp = self.test.skippingSetUp
        self.test.addCleanup(self.test.append, 'foo')
        self.test.run(self.result)
        self.assertEqual(['setUp', 'foo'], self.test.log) 
Example #30
Source File: test_queue.py    From ccs-twistedextensions with Apache License 2.0 5 votes vote down vote up
def buildStore(*args, **kwargs):
        raise SkipTest(
            "buildStore is not available, because it's in txdav; duh."
        )