def test_handle_partly_imported_name(self):
     # try_import('thing.other') when thing.other is mid-import
     # used to fail because thing.other is not assigned until thing.other
     # finishes its import - but thing.other is accessible via sys.modules.
     outer = types.ModuleType("extras.outer")
     inner = types.ModuleType("extras.outer.inner")
     inner.attribute = object()
     self.addCleanup(sys.modules.pop, "extras.outer", None)
     self.addCleanup(sys.modules.pop, "extras.outer.inner", None)
     sys.modules["extras.outer"] = outer
     sys.modules["extras.outer.inner"] = inner
     result = try_import("extras.outer.inner.attribute")
     self.expectThat(result, Is(inner.attribute))
     result = try_import("extras.outer.inner")
     self.expectThat(result, Is(inner))
Example #2
0
 def test_handle_partly_imported_name(self):
     # try_import('thing.other') when thing.other is mid-import
     # used to fail because thing.other is not assigned until thing.other
     # finishes its import - but thing.other is accessible via sys.modules.
     outer = types.ModuleType("extras.outer")
     inner = types.ModuleType("extras.outer.inner")
     inner.attribute = object()
     self.addCleanup(sys.modules.pop, "extras.outer", None)
     self.addCleanup(sys.modules.pop, "extras.outer.inner", None)
     sys.modules["extras.outer"] = outer
     sys.modules["extras.outer.inner"] = inner
     result = try_import("extras.outer.inner.attribute")
     self.expectThat(result, Is(inner.attribute))
     result = try_import("extras.outer.inner")
     self.expectThat(result, Is(inner))
Example #3
0
import traceback

from extras import try_import

from testtools.compat import (
    _b,
    _format_exception_only,
    _format_stack_list,
    _isbytes,
    _TB_HEADER,
    _u,
    str_is_unicode,
)
from testtools.content_type import ContentType, JSON, UTF8_TEXT

functools = try_import('functools')

_join_b = _b("").join

DEFAULT_CHUNK_SIZE = 4096

STDOUT_LINE = '\nStdout:\n%s'
STDERR_LINE = '\nStderr:\n%s'


def _iter_chunks(stream, chunk_size, seek_offset=None, seek_whence=0):
    """Read 'stream' in chunks of 'chunk_size'.

    :param stream: A file-like object to read from.
    :param chunk_size: The size of each read from 'stream'.
    :param seek_offset: If non-None, seek before iterating.
import unittest

from extras import try_import

from testtools import (
    TestCase,
    content,
    content_type,
    )
from testtools.compat import _b, _u
from testtools.matchers import Contains
from testtools.testresult.doubles import (
    ExtendedTestResult,
    )

fixtures = try_import('fixtures')
LoggingFixture = try_import('fixtures.tests.helpers.LoggingFixture')


class TestFixtureSupport(TestCase):

    def setUp(self):
        super(TestFixtureSupport, self).setUp()
        if fixtures is None or LoggingFixture is None:
            self.skipTest("Need fixtures")

    def test_useFixture(self):
        fixture = LoggingFixture()
        class SimpleTest(TestCase):
            def test_foo(self):
                self.useFixture(fixture)
# Copyright (c) 2010-2011 Testtools authors. See LICENSE for details.

"""Tests for the distutils test command logic."""

from distutils.dist import Distribution

from extras import try_import

from testtools.compat import (
    _b,
    _u,
    BytesIO,
    )
fixtures = try_import('fixtures')

import testtools
from testtools import TestCase
from testtools.distutilscmd import TestCommand
from testtools.matchers import MatchesRegex


if fixtures:
    class SampleTestFixture(fixtures.Fixture):
        """Creates testtools.runexample temporarily."""

        def __init__(self):
            self.package = fixtures.PythonPackage(
            'runexample', [('__init__.py', _b("""
from testtools import TestCase

class TestFoo(TestCase):
Example #6
0
import signal

from extras import try_import

from testtools import (
    skipIf,
    TestCase,
    )
from testtools.matchers import (
    Equals,
    Is,
    MatchesException,
    Raises,
    )

_spinner = try_import('testtools._spinner')

defer = try_import('twisted.internet.defer')
Failure = try_import('twisted.python.failure.Failure')


class NeedsTwistedTestCase(TestCase):

    def setUp(self):
        super(NeedsTwistedTestCase, self).setUp()
        if defer is None or Failure is None:
            self.skipTest("Need Twisted to run")


class TestNotReentrant(NeedsTwistedTestCase):
Example #7
0
# Unless required by applicable law or agreed to in writing, software
# distributed under these licenses is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
# license you chose for the specific language governing permissions and
# limitations under that license.
"""Run a projects tests and load them into testrepository."""

from io import BytesIO
from math import ceil
import optparse
import re

from extras import try_import
import subunit

v2_avail = try_import('subunit.ByteStreamToStreamResult')
import testtools
from testtools import (
    TestByTestResult, )
from testtools.compat import _b

from testrepository.arguments.doubledash import DoubledashArgument
from testrepository.arguments.string import StringArgument
from testrepository.commands import Command
from testrepository.commands.load import load
from testrepository.repository import RepositoryNotFound
from testrepository.ui import decorator
from testrepository.testcommand import TestCommand, testrconf_help
from testrepository.testlist import parse_list

LINEFEED = _b('\n')[0]
Example #8
0
# Copyright (c) 2010, 2016 testtools developers. See LICENSE for details.

__all__ = [
    'NeedsTwistedTestCase',
]

from extras import try_import
from testtools import TestCase

defer = try_import('twisted.internet.defer')


class NeedsTwistedTestCase(TestCase):
    def setUp(self):
        super().setUp()
        if defer is None:
            self.skipTest("Need Twisted to run")
Example #9
0
import abc
import argparse
import configparser
import daemon
import extras
import io
import logging
import logging.config
import os
import signal
import socket
import sys
import traceback
import threading

yappi = extras.try_import('yappi')
objgraph = extras.try_import('objgraph')

# as of python-daemon 1.6 it doesn't bundle pidlockfile anymore
# instead it depends on lockfile-0.9.1 which uses pidfile.
pid_file_module = extras.try_imports(['daemon.pidlockfile', 'daemon.pidfile'])

from zuul.ansible import logconfig
import zuul.lib.connections
from zuul.lib.config import get_default


def stack_dump_handler(signum, frame):
    signal.signal(signal.SIGUSR2, signal.SIG_IGN)
    log = logging.getLogger("zuul.stack_dump")
    log.debug("Beginning debug handler")
 def test_existing_module(self):
     # try_import('thing', foo) imports 'thing' and returns it if it's a
     # module that exists.
     result = try_import('os', object())
     import os
     self.assertThat(result, Is(os))
 def test_None_is_default_alternative(self):
     # try_import('thing') returns None if 'thing' doesn't exist.
     result = try_import('doesntexist')
     self.assertThat(result, Is(None))
 def test_doesnt_exist(self):
     # try_import('thing', foo) returns foo if 'thing' doesn't exist.
     marker = object()
     result = try_import('doesntexist', marker)
     self.assertThat(result, Is(marker))
 def test_object_from_module(self):
     # try_import('thing.object') imports 'thing' and returns
     # 'thing.object' if 'thing' is a module and 'object' is not.
     result = try_import('os.path.join')
     import os
     self.assertThat(result, Is(os.path.join))
 def test_nonexistent_submodule(self):
     # try_import('thing.another', foo) imports 'thing' and returns foo if
     # 'another' doesn't exist.
     marker = object()
     result = try_import('os.doesntexist', marker)
     self.assertThat(result, Is(marker))
Example #15
0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under these licenses is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
# license you chose for the specific language governing permissions and
# limitations under that license.

"""Load data into a repository."""

from functools import partial
from operator import methodcaller
import optparse
import threading

from extras import try_import
v2_avail = try_import('subunit.ByteStreamToStreamResult')

import subunit.test_results
import testtools

from testrepository.arguments.path import ExistingPathArgument
from testrepository.commands import Command
from testrepository.repository import RepositoryNotFound
from testrepository.testcommand import TestCommand

class InputToStreamResult(object):
    """Generate Stream events from stdin.

    Really a UI responsibility?
    """
Example #16
0
    'TestCase',
    'unique_text_generator',
]

import copy
import functools
import itertools
import sys
import warnings

from extras import (
    safe_hasattr,
    try_import,
    try_imports,
)
fixtures = try_import('fixtures')
# To let setup.py work, make this a conditional import.
unittest = try_imports(['unittest2', 'unittest'])
import six

from testtools import (
    content, )
from testtools.compat import (
    advance_iterator,
    reraise,
)
from testtools.matchers import (
    Annotate,
    Contains,
    MatchesAll,
    MatchesException,
Example #17
0
# Copyright (c) testtools developers. See LICENSE for details.
"""Tests for Deferred matchers."""

from extras import try_import

from testtools.content import TracebackContent
from testtools.matchers import (
    AfterPreprocessing,
    Equals,
    Is,
    MatchesDict,
)
from ._helpers import NeedsTwistedTestCase

has_no_result = try_import('testtools.twistedsupport.has_no_result')
failed = try_import('testtools.twistedsupport.failed')
succeeded = try_import('testtools.twistedsupport.succeeded')

defer = try_import('twisted.internet.defer')
Failure = try_import('twisted.python.failure.Failure')


def mismatches(description, details=None):
    """Match a ``Mismatch`` object."""
    if details is None:
        details = Equals({})

    matcher = MatchesDict({
        'description': description,
        'details': details,
    })
Example #18
0
from collections import defaultdict
ConfigParser = try_imports(['ConfigParser', 'configparser'])
import io
import itertools
import operator
import os.path
import re
import subprocess
import sys
import tempfile
import multiprocessing
from textwrap import dedent

from fixtures import Fixture
v2 = try_import('subunit.v2')

from testrepository import results
from testrepository.testlist import (
    parse_enumeration,
    write_list,
    )

testrconf_help = dedent("""
    Configuring via .testr.conf:
    ---
    [DEFAULT]
    test_command=foo $IDOPTION
    test_id_option=--bar $IDFILE
    ---
    will cause 'testr run' to run 'foo' to execute tests, and
Example #19
0
import codecs
import io
import locale
import os
import re
import sys
import traceback
import unicodedata

from extras import try_import, try_imports

BytesIO = try_imports(['StringIO.StringIO', 'io.BytesIO'])
StringIO = try_imports(['StringIO.StringIO', 'io.StringIO'])
# To let setup.py work, make this a conditional import.
linecache = try_import('linecache2')

try:
    from testtools import _compat2x as _compat
except SyntaxError:
    from testtools import _compat3x as _compat

reraise = _compat.reraise

__u_doc = """A function version of the 'u' prefix.

This is needed becayse the u prefix is not usable in Python 3 but is required
in Python 2 to get a unicode object.

To migrate code that was written as u'\u1234' in Python 2 to 2+3 change
it to be _u('\u1234'). The Python 3 interpreter will decode it
Example #20
0
    TestResult,
    )
from testtools.content import (
    text_content,
    )
from testtools.matchers import (
    Equals,
    KeysEqual,
    MatchesException,
    Raises,
    )
from testtools.runtest import RunTest
from testtools.testresult.doubles import ExtendedTestResult
from testtools.tests.test_spinner import NeedsTwistedTestCase

assert_fails_with = try_import('testtools.deferredruntest.assert_fails_with')
AsynchronousDeferredRunTest = try_import(
    'testtools.deferredruntest.AsynchronousDeferredRunTest')
flush_logged_errors = try_import(
    'testtools.deferredruntest.flush_logged_errors')
SynchronousDeferredRunTest = try_import(
    'testtools.deferredruntest.SynchronousDeferredRunTest')

defer = try_import('twisted.internet.defer')
failure = try_import('twisted.python.failure')
log = try_import('twisted.python.log')
DelayedCall = try_import('twisted.internet.base.DelayedCall')


class X(object):
    """Tests that we run as part of our tests, nested to avoid discovery."""
Example #21
0
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.

from six.moves import configparser as ConfigParser
import cStringIO
import extras
import logging
import logging.config
import os
import signal
import sys
import traceback

yappi = extras.try_import('yappi')

import zuul.lib.connections

# Do not import modules that will pull in paramiko which must not be
# imported until after the daemonization.
# https://github.com/paramiko/paramiko/issues/59
# Similar situation with gear and statsd.


def stack_dump_handler(signum, frame):
    signal.signal(signal.SIGUSR2, signal.SIG_IGN)
    log_str = ""
    for thread_id, stack_frame in sys._current_frames().items():
        log_str += "Thread: %s\n" % thread_id
        log_str += "".join(traceback.format_stack(stack_frame))
Example #22
0
#!/usr/bin/env python
"""Distutils installer for extras."""

from setuptools import setup
import os.path

import extras
testtools_cmd = extras.try_import('testtools.TestCommand')


def get_version():
    """Return the version of extras that we are building."""
    version = '.'.join(
        str(component) for component in extras.__version__[0:3])
    return version


def get_long_description():
    readme_path = os.path.join(
        os.path.dirname(__file__), 'README.rst')
    return open(readme_path).read()


cmdclass = {}

if testtools_cmd is not None:
    cmdclass['test'] = testtools_cmd


setup(name='extras',
      author='Testing cabal',
# Copyright (c) testtools developers. See LICENSE for details.

"""Tests for testtools._deferred."""

from extras import try_import

from testtools.matchers import (
    Equals,
    MatchesException,
    Raises,
    )
from testtools.tests.test_spinner import NeedsTwistedTestCase

from testtools._deferred import DeferredNotFired, extract_result

defer = try_import('twisted.internet.defer')
Failure = try_import('twisted.python.failure.Failure')


class TestExtractResult(NeedsTwistedTestCase):
    """Tests for ``extract_result``."""

    def test_not_fired(self):
        # _spinner.extract_result raises _spinner.DeferredNotFired if it's
        # given a Deferred that has not fired.
        self.assertThat(
            lambda: extract_result(defer.Deferred()),
            Raises(MatchesException(DeferredNotFired)))

    def test_success(self):
        # _spinner.extract_result returns the value of the Deferred if it has
    ContainsAll,
    EndsWith,
    Equals,
    Is,
    KeysEqual,
    MatchesDict,
    MatchesException,
    MatchesListwise,
    Not,
    Raises,
)
from testtools.runtest import RunTest
from testtools.testresult.doubles import ExtendedTestResult
from testtools.tests.test_spinner import NeedsTwistedTestCase

assert_fails_with = try_import('testtools.deferredruntest.assert_fails_with')
AsynchronousDeferredRunTest = try_import(
    'testtools.deferredruntest.AsynchronousDeferredRunTest')
flush_logged_errors = try_import(
    'testtools.deferredruntest.flush_logged_errors')
SynchronousDeferredRunTest = try_import(
    'testtools.deferredruntest.SynchronousDeferredRunTest')

defer = try_import('twisted.internet.defer')
failure = try_import('twisted.python.failure')
log = try_import('twisted.python.log')
DelayedCall = try_import('twisted.internet.base.DelayedCall')


class MatchesEvents(object):
    """Match a list of test result events.
Example #25
0
# Copyright (c) testtools developers. See LICENSE for details.

"""Tests for testtools._deferred."""

from extras import try_import

from testtools.matchers import (
    Equals,
    MatchesException,
    Raises,
    )
from ._helpers import NeedsTwistedTestCase


DeferredNotFired = try_import(
    'testtools.twistedsupport._deferred.DeferredNotFired')
extract_result = try_import(
    'testtools.twistedsupport._deferred.extract_result')

defer = try_import('twisted.internet.defer')
Failure = try_import('twisted.python.failure.Failure')


class TestExtractResult(NeedsTwistedTestCase):
    """Tests for ``extract_result``."""

    def test_not_fired(self):
        # _spinner.extract_result raises _spinner.DeferredNotFired if it's
        # given a Deferred that has not fired.
        self.assertThat(
            lambda: extract_result(defer.Deferred()),
Example #26
0
    MatchesException,
    MismatchError,
    Is,
    IsInstance,
    Not,
    Raises,
    )
from testtools.matchers._basic import _FlippedEquals
from testtools.monkey import patch
from testtools.runtest import RunTest
from testtools.testresult import (
    ExtendedToOriginalDecorator,
    TestResult,
    )

wraps = try_import('functools.wraps')
import six

class TestSkipped(Exception):
    """Raised within TestCase.run() when a test is skipped."""
TestSkipped = try_import('unittest.case.SkipTest', TestSkipped)
TestSkipped = try_import('unittest2.case.SkipTest', TestSkipped)


class _UnexpectedSuccess(Exception):
    """An unexpected success was raised.

    Note that this exception is private plumbing in testtools' testcase
    module.
    """
_UnexpectedSuccess = try_import(
    'content_from_file',
    'content_from_stream',
    'json_content',
    'text_content',
    'TracebackContent',
    ]

import codecs
import inspect
import json
import os
import sys

from extras import try_import
# To let setup.py work, make this a conditional import.
traceback = try_import('traceback2')

from testtools.compat import (
    _b,
    _u,
    istext,
    str_is_unicode,
)
from testtools.content_type import ContentType, JSON, UTF8_TEXT


functools = try_import('functools')

_join_b = _b("").join

 def test_existing_submodule(self):
     # try_import('thing.another', foo) imports 'thing' and returns it if
     # it's a module that exists.
     result = try_import('os.path', object())
     import os
     self.assertThat(result, Is(os.path))
Example #29
0
from collections import defaultdict
ConfigParser = try_imports(['ConfigParser', 'configparser'])
import io
import itertools
import operator
import os.path
import re
import subprocess
import sys
import tempfile
import multiprocessing
from textwrap import dedent

from fixtures import Fixture
v2 = try_import('subunit.v2')

from testrepository import results
from testrepository.testlist import (
    parse_enumeration,
    write_list,
)

testrconf_help = dedent("""
    Configuring via .testr.conf:
    ---
    [DEFAULT]
    test_command=foo $IDOPTION
    test_id_option=--bar $IDFILE
    ---
    will cause 'testr run' to run 'foo' to execute tests, and
Example #30
0
from extras import try_import

from testtools import (
    ConcurrentTestSuite,
    ConcurrentStreamTestSuite,
    iterate_tests,
    PlaceHolder,
    TestByTestResult,
    TestCase,
)
from testtools.matchers import DocTestMatches, Equals
from testtools.testsuite import FixtureSuite, sorted_tests
from testtools.tests.helpers import LoggingResult
from testtools.testresult.doubles import StreamResult as LoggingStream

FunctionFixture = try_import('fixtures.FunctionFixture')


class Sample(TestCase):
    def __hash__(self):
        return id(self)

    def test_method1(self):
        pass

    def test_method2(self):
        pass


class TestConcurrentTestSuiteRun(TestCase):
    def test_broken_test(self):
Example #31
0
# Copyright (c) 2010-2011 Testtools authors. See LICENSE for details.
"""Tests for the distutils test command logic."""

from distutils.dist import Distribution

from extras import try_import

from testtools.compat import (
    _b, )
fixtures = try_import('fixtures')

import testtools
from testtools import TestCase
from testtools.distutilscmd import TestCommand
from testtools.matchers import MatchesRegex

if fixtures:

    class SampleTestFixture(fixtures.Fixture):
        """Creates testtools.runexample temporarily."""
        def __init__(self):
            self.package = fixtures.PythonPackage('runexample',
                                                  [('__init__.py',
                                                    _b("""
from testtools import TestCase

class TestFoo(TestCase):
    def test_bar(self):
        pass
    def test_quux(self):
        pass
Example #32
0
import signal
import sys
import time

import eventlet
import extras
import logging as std_logging

from reddwarf.openstack.common import cfg
from reddwarf.openstack.common import eventlet_backdoor
from reddwarf.openstack.common.gettextutils import _
from reddwarf.openstack.common import log as logging
from reddwarf.openstack.common import threadgroup


rpc = extras.try_import('reddwarf.openstack.common.rpc')
CONF = cfg.CONF
LOG = logging.getLogger(__name__)


class Launcher(object):
    """Launch one or more services and wait for them to complete."""

    def __init__(self):
        """Initialize the service launcher.

        :returns: None

        """
        self._services = threadgroup.ThreadGroup('launcher')
        eventlet_backdoor.initialize_if_enabled()
Example #33
0
# Licensed under either the Apache License, Version 2.0 or the BSD 3-clause
# license at the users choice. A copy of both licenses are available in the
# project source as Apache-2.0 and BSD. You may not use this file except in
# compliance with one of these two licences.
# 
# Unless required by applicable law or agreed to in writing, software
# distributed under these licenses is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
# license you chose for the specific language governing permissions and
# limitations under that license.

"""In memory storage of test results."""

from extras import try_import

OrderedDict = try_import('collections.OrderedDict', dict)
from io import BytesIO
from operator import methodcaller

import subunit
import testtools

from testrepository.repository import (
    AbstractRepository,
    AbstractRepositoryFactory,
    AbstractTestRun,
    RepositoryNotFound,
    )


class RepositoryFactory(AbstractRepositoryFactory):
Example #34
0
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""In memory storage of test results."""

from extras import try_import

from io import BytesIO
from operator import methodcaller

import subunit
import testtools

from stestr.repository import abstract as repository

OrderedDict = try_import('collections.OrderedDict', dict)


class RepositoryFactory(repository.AbstractRepositoryFactory):
    """A factory that can initialise and open memory repositories.

    This is used for testing where a repository may be created and later
    opened, but tests should not see each others repositories.
    """
    def __init__(self):
        self.repos = {}

    def initialise(self, url):
        self.repos[url] = Repository()
        return self.repos[url]
Example #35
0
#!/usr/bin/env python
"""Distutils installer for extras."""

from setuptools import setup
import os.path

import extras
testtools_cmd = extras.try_import('testtools.TestCommand')


def get_version():
    """Return the version of extras that we are building."""
    version = '.'.join(str(component) for component in extras.__version__[0:3])
    return version


def get_long_description():
    readme_path = os.path.join(os.path.dirname(__file__), 'README.rst')
    return open(readme_path).read()


cmdclass = {}

if testtools_cmd is not None:
    cmdclass['test'] = testtools_cmd

setup(name='extras',
      author='Testing cabal',
      author_email='*****@*****.**',
      url='https://github.com/testing-cabal/extras',
      description=('Useful extra bits for Python - things that shold be '
Example #36
0
    'content_from_file',
    'content_from_stream',
    'json_content',
    'text_content',
    'TracebackContent',
    ]

import codecs
import inspect
import json
import os
import sys

from extras import try_import
# To let setup.py work, make this a conditional import.
traceback = try_import('traceback2')

from testtools.compat import (
    _b,
    _u,
    istext,
    str_is_unicode,
)
from testtools.content_type import ContentType, JSON, UTF8_TEXT


functools = try_import('functools')

_join_b = _b("").join

Example #37
0
# project source as Apache-2.0 and BSD. You may not use this file except in
# compliance with one of these two licences.
#
# Unless required by applicable law or agreed to in writing, software
# distributed under these licenses is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
# license you chose for the specific language governing permissions and
# limitations under that license.

"""Handling of lists of tests - common code to --load-list etc."""

from io import BytesIO

from extras import try_import

bytestream_to_streamresult = try_import("subunit.ByteStreamToStreamResult")
stream_result = try_import("testtools.testresult.doubles.StreamResult")

from testtools.compat import _b, _u


def write_list(stream, test_ids):
    """Write test_ids out to stream.

    :param stream: A file-like object.
    :param test_ids: An iterable of test ids.
    """
    # May need utf8 explicitly?
    stream.write(_b("\n".join(list(test_ids) + [""])))

    KeysEqual,
    MatchesDict,
    MatchesException,
    MatchesListwise,
    Not,
    Raises,
)
from testtools.runtest import RunTest
from testtools.testresult.doubles import ExtendedTestResult
from testtools.tests.helpers import (
    AsText,
    MatchesEvents,
)
from ._helpers import NeedsTwistedTestCase

DebugTwisted = try_import(
    'testtools.twistedsupport._deferreddebug.DebugTwisted')

assert_fails_with = try_import('testtools.twistedsupport.assert_fails_with')
AsynchronousDeferredRunTest = try_import(
    'testtools.twistedsupport.AsynchronousDeferredRunTest')
flush_logged_errors = try_import(
    'testtools.twistedsupport.flush_logged_errors')
SynchronousDeferredRunTest = try_import(
    'testtools.twistedsupport.SynchronousDeferredRunTest')

defer = try_import('twisted.internet.defer')
failure = try_import('twisted.python.failure')
log = try_import('twisted.python.log')
DelayedCall = try_import('twisted.internet.base.DelayedCall')
_get_global_publisher_and_observers = try_import(
    'testtools.twistedsupport._runtest._get_global_publisher_and_observers')
Example #39
0
import codecs
import io
import locale
import os
import re
import sys
import traceback
import unicodedata

from extras import try_import, try_imports

BytesIO = try_imports(['StringIO.StringIO', 'io.BytesIO'])
StringIO = try_imports(['StringIO.StringIO', 'io.StringIO'])
# To let setup.py work, make this a conditional import.
linecache = try_import('linecache2')

try:
    from testtools import _compat2x as _compat
except SyntaxError:
    from testtools import _compat3x as _compat

reraise = _compat.reraise


__u_doc = """A function version of the 'u' prefix.

This is needed becayse the u prefix is not usable in Python 3 but is required
in Python 2 to get a unicode object.

To migrate code that was written as u'\u1234' in Python 2 to 2+3 change
# Copyright (c) testtools developers. See LICENSE for details.
"""Tests for testtools._deferred."""

from extras import try_import

from testtools.matchers import (
    Equals,
    MatchesException,
    Raises,
)
from ._helpers import NeedsTwistedTestCase

DeferredNotFired = try_import(
    'testtools.twistedsupport._deferred.DeferredNotFired')
extract_result = try_import(
    'testtools.twistedsupport._deferred.extract_result')

defer = try_import('twisted.internet.defer')
Failure = try_import('twisted.python.failure.Failure')


class TestExtractResult(NeedsTwistedTestCase):
    """Tests for ``extract_result``."""
    def test_not_fired(self):
        # _spinner.extract_result raises _spinner.DeferredNotFired if it's
        # given a Deferred that has not fired.
        self.assertThat(lambda: extract_result(defer.Deferred()),
                        Raises(MatchesException(DeferredNotFired)))

    def test_success(self):
        # _spinner.extract_result returns the value of the Deferred if it has
Example #41
0
 def test_nonexistent_submodule(self):
     # try_import('thing.another', foo) imports 'thing' and returns foo if
     # 'another' doesn't exist.
     marker = object()
     result = try_import('os.doesntexist', marker)
     self.assertThat(result, Is(marker))
Example #42
0
from extras import try_import

from testtools import (
    TestCase,
    content,
    content_type,
)
from testtools.compat import _b, _u
from testtools.matchers import (
    Contains,
    Equals,
)
from testtools.testresult.doubles import (
    ExtendedTestResult, )

fixtures = try_import('fixtures')
LoggingFixture = try_import('fixtures.tests.helpers.LoggingFixture')


class TestFixtureSupport(TestCase):
    def setUp(self):
        super(TestFixtureSupport, self).setUp()
        if fixtures is None or LoggingFixture is None:
            self.skipTest("Need fixtures")

    def test_useFixture(self):
        fixture = LoggingFixture()

        class SimpleTest(TestCase):
            def test_foo(self):
                self.useFixture(fixture)
Example #43
0
 def test_object_from_module(self):
     # try_import('thing.object') imports 'thing' and returns
     # 'thing.object' if 'thing' is a module and 'object' is not.
     result = try_import('os.path.join')
     import os
     self.assertThat(result, Is(os.path.join))
Example #44
0
    )
from testtools.matchers._basic import _FlippedEquals
from testtools.monkey import patch
from testtools.runtest import (
    MultipleExceptions,
    RunTest,
    )
from testtools.testresult import (
    ExtendedToOriginalDecorator,
    TestResult,
    )


class TestSkipped(Exception):
    """Raised within TestCase.run() when a test is skipped."""
TestSkipped = try_import('unittest.case.SkipTest', TestSkipped)


class _UnexpectedSuccess(Exception):
    """An unexpected success was raised.

    Note that this exception is private plumbing in testtools' testcase
    module.
    """
_UnexpectedSuccess = try_import(
    'unittest.case._UnexpectedSuccess', _UnexpectedSuccess)


class _ExpectedFailure(Exception):
    """An expected failure occurred.
Example #45
0
 def test_doesnt_exist(self):
     # try_import('thing', foo) returns foo if 'thing' doesn't exist.
     marker = object()
     result = try_import('doesntexist', marker)
     self.assertThat(result, Is(marker))
Example #46
0
import abc
import argparse
import configparser
import daemon
import extras
import io
import logging
import logging.config
import os
import signal
import socket
import sys
import traceback
import threading

yappi = extras.try_import('yappi')
objgraph = extras.try_import('objgraph')

# as of python-daemon 1.6 it doesn't bundle pidlockfile anymore
# instead it depends on lockfile-0.9.1 which uses pidfile.
pid_file_module = extras.try_imports(['daemon.pidlockfile', 'daemon.pidfile'])

from zuul.ansible import logconfig
import zuul.lib.connections
from zuul.lib.config import get_default


def stack_dump_handler(signum, frame):
    signal.signal(signal.SIGUSR2, signal.SIG_IGN)
    log = logging.getLogger("zuul.stack_dump")
    log.debug("Beginning debug handler")
Example #47
0
 def test_None_is_default_alternative(self):
     # try_import('thing') returns None if 'thing' doesn't exist.
     result = try_import('doesntexist')
     self.assertThat(result, Is(None))
Example #48
0
# Copyright (c) 2010 testtools developers. See LICENSE for details.

"""Tests for the test runner logic."""

import doctest
from unittest import TestSuite
import sys
from textwrap import dedent

from extras import try_import
fixtures = try_import('fixtures')
testresources = try_import('testresources')
import unittest2

import testtools
from testtools import TestCase, run, skipUnless
from testtools.compat import (
    _b,
    _u,
    StringIO,
    )
from testtools.matchers import (
    Contains,
    DocTestMatches,
    MatchesRegex,
    )


if fixtures:
    class SampleTestFixture(fixtures.Fixture):
        """Creates testtools.runexample temporarily."""
Example #49
0
 def test_existing_module(self):
     # try_import('thing', foo) imports 'thing' and returns it if it's a
     # module that exists.
     result = try_import('os', object())
     import os
     self.assertThat(result, Is(os))
Example #50
0
import signal
import sys
import time

import eventlet
import extras
import logging as std_logging

from openwlee.openstack.common import cfg
from openwlee.openstack.common import eventlet_backdoor
from openwlee.openstack.common.gettextutils import _
from openwlee.openstack.common import log as logging
from openwlee.openstack.common import threadgroup


rpc = extras.try_import('openwlee.openstack.common.rpc')
CONF = cfg.CONF
LOG = logging.getLogger(__name__)


class Launcher(object):
    """Launch one or more services and wait for them to complete."""

    def __init__(self):
        """Initialize the service launcher.

        :returns: None

        """
        self._services = threadgroup.ThreadGroup('launcher')
        eventlet_backdoor.initialize_if_enabled()
Example #51
0
 def test_existing_submodule(self):
     # try_import('thing.another', foo) imports 'thing' and returns it if
     # it's a module that exists.
     result = try_import('os.path', object())
     import os
     self.assertThat(result, Is(os.path))
Example #52
0
from testtools import (
    ConcurrentTestSuite,
    ConcurrentStreamTestSuite,
    iterate_tests,
    PlaceHolder,
    TestByTestResult,
    TestCase,
    )
from testtools.compat import _b, _u
from testtools.matchers import DocTestMatches
from testtools.testsuite import FixtureSuite, iterate_tests, sorted_tests
from testtools.tests.helpers import LoggingResult
from testtools.testresult.doubles import StreamResult as LoggingStream

FunctionFixture = try_import('fixtures.FunctionFixture')

class Sample(TestCase):
    def __hash__(self):
        return id(self)
    def test_method1(self):
        pass
    def test_method2(self):
        pass


class TestConcurrentTestSuiteRun(TestCase):

    def test_broken_test(self):
        log = []
        def on_test(test, status, start_time, stop_time, tags, details):
Example #53
0
    KeysEqual,
    MatchesDict,
    MatchesException,
    MatchesListwise,
    Not,
    Raises,
    )
from testtools.runtest import RunTest
from testtools.testresult.doubles import ExtendedTestResult
from testtools.tests.helpers import (
    AsText,
    MatchesEvents,
)
from ._helpers import NeedsTwistedTestCase

DebugTwisted = try_import(
    'testtools.twistedsupport._deferreddebug.DebugTwisted')

assert_fails_with = try_import('testtools.twistedsupport.assert_fails_with')
AsynchronousDeferredRunTest = try_import(
    'testtools.twistedsupport.AsynchronousDeferredRunTest')
flush_logged_errors = try_import(
    'testtools.twistedsupport.flush_logged_errors')
SynchronousDeferredRunTest = try_import(
    'testtools.twistedsupport.SynchronousDeferredRunTest')

defer = try_import('twisted.internet.defer')
failure = try_import('twisted.python.failure')
log = try_import('twisted.python.log')
DelayedCall = try_import('twisted.internet.base.DelayedCall')
_get_global_publisher_and_observers = try_import(
    'testtools.twistedsupport._runtest._get_global_publisher_and_observers')
Example #54
0
# Copyright (c) 2010 testtools developers. See LICENSE for details.
"""Tests for the test runner logic."""

import doctest
from unittest import TestSuite
import sys
from textwrap import dedent

from extras import try_import
fixtures = try_import('fixtures')
testresources = try_import('testresources')
import unittest2

import testtools
from testtools import TestCase, run, skipUnless
from testtools.compat import (
    _b,
    _u,
    StringIO,
)
from testtools.matchers import (
    Contains,
    DocTestMatches,
    MatchesRegex,
)

if fixtures:

    class SampleTestFixture(fixtures.Fixture):
        """Creates testtools.runexample temporarily."""
        def __init__(self, broken=False):
Example #55
0
import signal
import sys
import time

import eventlet
import extras
import logging as std_logging

from heat.openstack.common import cfg
from heat.openstack.common import eventlet_backdoor
from heat.openstack.common.gettextutils import _
from heat.openstack.common import log as logging
from heat.openstack.common import threadgroup


rpc = extras.try_import('heat.openstack.common.rpc')
CONF = cfg.CONF
LOG = logging.getLogger(__name__)


class Launcher(object):
    """Launch one or more services and wait for them to complete."""

    def __init__(self):
        """Initialize the service launcher.

        :returns: None

        """
        self._services = threadgroup.ThreadGroup('launcher')
        eventlet_backdoor.initialize_if_enabled()
Example #56
0
import traceback

from extras import try_import

from testtools.compat import (
    _b,
    _format_exception_only,
    _format_stack_list,
    _TB_HEADER,
    _u,
    str_is_unicode,
)
from testtools.content_type import ContentType, JSON, UTF8_TEXT


functools = try_import('functools')

_join_b = _b("").join


DEFAULT_CHUNK_SIZE = 4096

STDOUT_LINE = '\nStdout:\n%s'
STDERR_LINE = '\nStderr:\n%s'


def _iter_chunks(stream, chunk_size, seek_offset=None, seek_whence=0):
    """Read 'stream' in chunks of 'chunk_size'.

    :param stream: A file-like object to read from.
    :param chunk_size: The size of each read from 'stream'.
Example #57
0
# Licensed under either the Apache License, Version 2.0 or the BSD 3-clause
# license at the users choice. A copy of both licenses are available in the
# project source as Apache-2.0 and BSD. You may not use this file except in
# compliance with one of these two licences.
#
# Unless required by applicable law or agreed to in writing, software
# distributed under these licenses is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
# license you chose for the specific language governing permissions and
# limitations under that license.
"""Handling of lists of tests - common code to --load-list etc."""

from io import BytesIO

from extras import try_import
bytestream_to_streamresult = try_import('subunit.ByteStreamToStreamResult')
stream_result = try_import('testtools.testresult.doubles.StreamResult')

from testtools.compat import _b, _u


def write_list(stream, test_ids):
    """Write test_ids out to stream.

    :param stream: A file-like object.
    :param test_ids: An iterable of test ids.
    """
    # May need utf8 explicitly?
    stream.write(_b('\n'.join(list(test_ids) + [''])))