Example #1
0
def get_output_formats():
    """Get information regarding the different output formats supported.

    :returns: dict of supported formats and appropriate construct functions

    """
    supported_formats = {}

    supported_formats['text'] = _construct_text

    if try_import('junitxml'):
        supported_formats['xml'] = _construct_xml
    if try_import('subunit'):
        supported_formats['subunit'] = _construct_subunit
    return supported_formats
def run_django(port):
    """Start django server for running local self-tests."""
    here = os.path.abspath(os.path.dirname(__file__))
    manage_file = os.path.abspath(
        os.path.join(here, '../../testproject/manage.py'))
    url = 'http://localhost:%s/' % port

    if not os.path.isfile(manage_file):
        print 'Error: can not find the django testproject.'
        print '%r does not exist' % manage_file
        print 'you must run self-tests from the dev branch or package source.'
        sys.exit(1)

    django = testtools.try_import('django')
    if django is None:
        print 'Error: can not find django module.'
        print 'you must have django installed to run the test project.'
        # FIXME: Using sys.exit() makes it hard to test in isolation. Moreover
        # this error path is not covered by a test. Both points may be related
        # ;) -- vila 2013-05-10
        sys.exit(1)
    proc = subprocess.Popen([manage_file, 'runserver', port],
                            stderr=open(os.devnull, 'w'),
                            stdout=open(os.devnull, 'w')
                            )
    print '--------------------------------------------------------------'
    print 'waiting for django to come up...'
    attempts = 30
    for count in xrange(attempts):
        try:
            resp = urllib.urlopen(url)
            if resp.code == 200:
                break
        except IOError:
            time.sleep(0.2)
            if count >= attempts - 1:  # timeout
                print 'Error: can not get response from %r' % url
                raise
    print 'django found. continuing...'
    return proc
Example #3
0
#
#       http://www.apache.org/licenses/LICENSE-2.0
#
#   Unless required by applicable law or agreed to in writing, software
#   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.
#

import os
import sys

import testtools

testtools.try_import('selenium')

from sst import (
    browsers,
    command,
    runtests,
)


def main():
    cmd_opts, args = command.get_opts_remote()

    results_directory = os.path.abspath('results')
    command.reset_directory(results_directory,
                            cmd_opts.skip_clean_results)
Example #4
0
from fixtures import (
    Fixture,
    EnvironmentVariable,
)

from testtools import try_import

from charmtest.paths import find_code_dir
from charmtest.juju.hooktools import (
    ConfigGet,
    JujuLog,
    OpenPort,
    UnitGet,
)

hookenv = try_import("charmhelpers.core.hookenv")


class FakeJuju(Fixture):

    def __init__(self, filesystem, processes):
        super(Fixture, self).__init__()
        self._fs = filesystem
        self._processes = processes

    def _setUp(self):
        code_dir = find_code_dir()
        unit_name = self._unit_name(code_dir)
        charm_dir = self._charm_dir(unit_name)

        self.config = self._default_config(code_dir)
Example #5
0
#   Unless required by applicable law or agreed to in writing, software
#   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.
#

import os
import subprocess
import sys
import time
import urllib

import testtools

testtools.try_import('selenium')
testtools.try_import('django')

import sst
from sst import (
    browsers,
    command,
    runtests,
    tests,
)

package_dir = os.path.dirname(os.path.dirname(__file__))


def main():
    cmd_opts, args = command.get_opts_run()
Example #6
0
import os
import shutil
import tempfile
import subprocess

from testtools import try_import

from charmhelpers.core import hookenv

# XXX Wrap this import with try_import since layers code won't be available
#     when running unit tests for this layer (and in such case import errors
#     can be safely ignored since we're stubbing out these objects).
apt = try_import("charms.apt")

APT_DEPENDENCIES = ["daemon", "default-jre-headless"]
APT_SOURCE = "deb http://pkg.jenkins-ci.org/%s binary/"
APT_KEY = "http://pkg.jenkins-ci.org/%s/jenkins-ci.org.key"


class Packages(object):
    """Manage Jenkins package dependencies."""

    def __init__(self, apt=apt):
        """
        @param apt: An object implementing the charms.apt API from the apt
            charm layer (for testing).
        """
        self._apt = apt

    def install_dependencies(self):
        """Install the deb dependencies of the Jenkins package."""
Example #7
0
class TestDrivers(testtools.TestCase):
    def setUp(self):
        super(TestDrivers, self).setUp()
        self.logger = self.useFixture(
            fixtures.FakeLogger(
                format="%(levelname)8s [%(name)s] %(message)s",
                level=logging.DEBUG,
                nuke_handlers=True,
            ))

    def _run(self, cmd):
        self.assertEqual(0, os.system(cmd + " >/dev/null 2>&1"))

    def _do_test_stuck(self, cmd):
        d = drivers.Driver(debug=True)
        d.setUp()
        c, _ = d._exec(cmd, wait_for_line="started")
        parent = psutil.Process(c.pid)
        procs = parent.children(recursive=True)
        procs.append(parent)
        d._kill(c)
        gone, alive = psutil.wait_procs(procs, timeout=0)
        self.assertEqual([], alive)

    def test_stuck_no_sigterm_with_children(self):
        self._do_test_stuck(["python", "-u", unkillable])

    def test_stuck_no_sigterm_in_children_only(self):
        self._do_test_stuck(["python", "-u", unkillable, "--child-only"])

    def test_stuck_no_sigterm_and_parent_exited(self):
        self._do_test_stuck(["python", "-u", unkillable, "--exited-parent"])

    def test_stuck_simple(self):
        self._do_test_stuck(
            ["bash", "-c", "trap ':' TERM ; echo started; sleep 10000"])

    @testtools.skip("Driver need rework, it won't work with travis or "
                    "Ubuntu xenial or Debian strech package")
    @testtools.skipUnless(spawn.find_executable("elasticsearch"),
                          "elasticsearch not found")
    def test_elasticsearch(self):
        port = 9201
        self.useFixture(elasticsearch.ElasticsearchDriver(port=port))
        self.assertEqual("es://*****:*****@testtools.skipUnless(spawn.find_executable("etcd"), "etcd not found")
    def test_etcd(self):
        port = 4005
        peer_port = 4006
        self.useFixture(etcd.EtcdDriver(port=port, peer_port=peer_port))
        self.assertEqual("etcd://*****:*****@testtools.skipUnless(spawn.find_executable("etcd"), "etcd not found")
    def test_etcd_cluster(self):
        port = 4007
        peer_port = 4008
        self.useFixture(
            etcd.EtcdDriver(port=port, peer_port=peer_port, cluster=True))
        self.assertEqual("etcd://*****:*****@testtools.skipUnless(spawn.find_executable("consul"), "consul not found")
    def test_consul(self):
        port = 8601
        host = consul.ConsulDriver.DEFAULT_HOST
        self.useFixture(consul.ConsulDriver(port=port))
        self.assertEqual("consul://%s:%d" % (host, port),
                         os.getenv("PIFPAF_URL"))
        self.assertEqual(str(port), os.getenv("PIFPAF_CONSUL_PORT"))
        r = requests.get("http://%s:%d/v1/status/leader" % (host, port))
        self.assertEqual(200, r.status_code)

    @testtools.skipUnless(spawn.find_executable("influxd"),
                          "influxd not found")
    def test_influxdb(self):
        port = 51236
        database = 'foobar'
        self.useFixture(influxdb.InfluxDBDriver(port=port, database='foobar'))
        self.assertEqual("influxdb://*****:*****@testtools.skipUnless(spawn.find_executable("memcached"),
                          "memcached not found")
    def test_memcached(self):
        port = 11213
        self.useFixture(memcached.MemcachedDriver(port=port))
        self.assertEqual("memcached://*****:*****@testtools.skipUnless(spawn.find_executable("vault"), "vault not found")
    def test_vault(self):
        listen_address = "localhost:5049"
        self.useFixture(vault.VaultDriver(listen_address=listen_address))
        self.assertEqual("http://%s" % listen_address, os.getenv("PIFPAF_URL"))
        self.assertEqual("http://%s" % listen_address,
                         os.getenv("PIFPAF_VAULT_ADDR"))
        self.assertTrue(len(os.getenv("PIFPAF_ROOT_TOKEN")) > 0)

    @testtools.skipUnless(spawn.find_executable("fakes3"), "fakes3 not found")
    def test_fakes3(self):
        port = 8990
        self.useFixture(fakes3.FakeS3Driver(port=port))
        self.assertEqual("s3://localhost:%d" % port, os.getenv("PIFPAF_URL"))
        self.assertEqual(str(port), os.getenv("PIFPAF_FAKES3_PORT"))

    @testtools.skipUnless(spawn.find_executable("s3rver"), "s3rver not found")
    def test_s3rver(self):
        port = 4569
        self.useFixture(s3rver.S3rverDriver(port=port))
        self.assertEqual("s3://localhost:%d" % port, os.getenv("PIFPAF_URL"))
        self.assertEqual("http://*****:*****@testtools.skipUnless(spawn.find_executable("mongod"), "mongod not found")
    def test_mongodb(self):
        port = 29002
        self.useFixture(mongodb.MongoDBDriver(port=port))
        self.assertEqual("mongodb://*****:*****@testtools.skipUnless(spawn.find_executable("mysqld"), "mysqld not found")
    def test_mysql(self):
        f = self.useFixture(mysql.MySQLDriver())
        self.assertEqual(
            "mysql://root@localhost/pifpaf?unix_socket=%s/mysql.socket" %
            f.tempdir, os.getenv("PIFPAF_URL"))
        self.assertEqual(
            "mysql://root@localhost/pifpaf?unix_socket=%s/mysql.socket" %
            f.tempdir, f.url)
        self._run("mysql --no-defaults -S %s -e 'SHOW TABLES;' pifpaf" %
                  f.socket)

    @testtools.skipUnless(spawn.find_executable("pg_config"),
                          "pg_config not found")
    def test_postgresql(self):
        port = 9825
        f = self.useFixture(postgresql.PostgreSQLDriver(port=port))
        self.assertEqual(
            "postgresql://localhost/postgres?host=%s&port=%d" %
            (f.tempdir, port), os.getenv("PIFPAF_URL"))
        self._run("psql template1 -c 'CREATE TABLE FOOBAR();'")

    @testtools.skipUnless(spawn.find_executable("pg_config"),
                          "pg_config not found")
    def test_postgresql_async(self):
        port = 9825
        f = self.useFixture(postgresql.PostgreSQLDriver(port=port, sync=False))
        self.assertEqual(
            "postgresql://localhost/postgres?host=%s&port=%d" %
            (f.tempdir, port), os.getenv("PIFPAF_URL"))
        self._run("psql template1 -c 'CREATE TABLE FOOBAR();'")

    @testtools.skipUnless(spawn.find_executable("redis-server"),
                          "redis-server not found")
    def test_redis(self):
        port = 6384
        f = self.useFixture(redis.RedisDriver(port=port))
        self.assertEqual("redis://*****:*****@testtools.skipUnless(spawn.find_executable("redis-sentinel"),
                          "redis-sentinel not found")
    def test_redis_sentinel(self):
        port = 6385
        f = self.useFixture(redis.RedisDriver(sentinel=True, port=port))
        self.assertEqual("redis://localhost:%d" % port,
                         os.getenv("PIFPAF_URL"))
        self.assertEqual(str(port), os.getenv("PIFPAF_REDIS_PORT"))
        self.assertEqual("6380", os.getenv("PIFPAF_REDIS_SENTINEL_PORT"))
        self._run("redis-cli -p %d sentinel master pifpaf" % f.sentinel_port)

    @testtools.skipUnless(
        spawn.find_executable("zkServer.sh",
                              path=":".join(zookeeper.ZooKeeperDriver.PATH)),
        "ZooKeeper not found")
    def test_zookeeper(self):
        port = 2182
        f = self.useFixture(zookeeper.ZooKeeperDriver(port=port))
        self.assertEqual("zookeeper://*****:*****@testtools.skipUnless(spawn.find_executable("gnocchi-api"),
                          "Gnocchi not found")
    def test_gnocchi(self):
        port = gnocchi.GnocchiDriver.DEFAULT_PORT
        self.useFixture(gnocchi.GnocchiDriver())
        self.assertEqual("gnocchi://*****:*****@testtools.skipUnless(spawn.find_executable("redis-server"),
                          "redis-server not found")
    @testtools.skipUnless(spawn.find_executable("gnocchi-api"),
                          "Gnocchi not found")
    def test_gnocchi_with_redis_coordinator(self):
        self.useFixture(
            gnocchi.GnocchiDriver(coordination_driver="redis", port=8043))
        self.assertEqual("gnocchi://*****:*****@testtools.skipUnless(spawn.find_executable("gnocchi-api"),
                          "Gnocchi not found")
    def test_gnocchi_with_existing_indexer(self):
        port = gnocchi.GnocchiDriver.DEFAULT_PORT + 15
        pg = self.useFixture(postgresql.PostgreSQLDriver(port=9833))
        self.useFixture(gnocchi.GnocchiDriver(indexer_url=pg.url, port=port))
        self.assertEqual("gnocchi://*****:*****@testtools.skipUnless(spawn.find_executable("gnocchi-api"),
                          "Gnocchi not found")
    @testtools.skipUnless(spawn.find_executable("swift-proxy-server"),
                          "Swift not found")
    def test_gnocchi_with_existing_swift(self):
        tmp_rootdir = self._get_tmpdir_for_xattr()
        self.useFixture(swift.SwiftDriver(tmp_rootdir=tmp_rootdir))
        self.useFixture(
            gnocchi.GnocchiDriver(storage_url=os.getenv("PIFPAF_URL")))
        self.assertEqual("gnocchi://*****:*****@testtools.skipUnless(spawn.find_executable("gnocchi-api"),
                          "Gnocchi not found")
    @testtools.skipUnless(spawn.find_executable("s3rver"), "s3rver not found")
    def test_gnocchi_with_existing_s3rver(self):
        s3 = self.useFixture(s3rver.S3rverDriver(port=4569))
        port = gnocchi.GnocchiDriver.DEFAULT_PORT + 12
        self.useFixture(
            gnocchi.GnocchiDriver(
                storage_url="s3://gnocchi:pass@localhost:%d" % s3.port,
                port=port))
        self.assertEqual("gnocchi://*****:*****@testtools.skipUnless(spawn.find_executable("gnocchi-api"),
                          "Gnocchi not found")
    @testtools.skipUnless(spawn.find_executable("ceph-mon"),
                          "Ceph Monitor not found")
    @testtools.skipUnless(spawn.find_executable("ceph-osd"),
                          "Ceph OSD not found")
    @testtools.skipUnless(spawn.find_executable("ceph"),
                          "Ceph client not found")
    def test_gnocchi_with_existing_ceph(self):
        port = gnocchi.GnocchiDriver.DEFAULT_PORT + 10
        tmp_rootdir = self._get_tmpdir_for_xattr()
        ceph_driver = ceph.CephDriver(tmp_rootdir=tmp_rootdir)
        self.useFixture(ceph_driver)

        ceph_driver._exec(
            ["rados", "-c",
             os.getenv("CEPH_CONF"), "mkpool", "gnocchi"]),

        self.useFixture(
            gnocchi.GnocchiDriver(storage_url="ceph://%s" %
                                  os.getenv("CEPH_CONF"),
                                  port=port))
        self.assertEqual("gnocchi://*****:*****@testtools.skipUnless(spawn.find_executable("pg_config"),
                          "pg_config not found")
    @testtools.skipUnless(spawn.find_executable("gnocchi-api"),
                          "Gnocchi not found")
    @testtools.skipUnless(spawn.find_executable("aodh-api"), "Aodh not found")
    def test_aodh_with_existing_db(self):
        pg = self.useFixture(postgresql.PostgreSQLDriver(port=12345))
        a = self.useFixture(aodh.AodhDriver(database_url=pg.url))
        self.assertEqual("aodh://*****:*****@testtools.skipUnless(spawn.find_executable("gnocchi-api"),
                          "Gnocchi not found")
    @testtools.skipUnless(spawn.find_executable("aodh-api"), "Aodh not found")
    def test_aodh(self):
        a = self.useFixture(aodh.AodhDriver())
        self.assertEqual("aodh://*****:*****@testtools.skipUnless(spawn.find_executable("keystone-manage"),
                          "Keystone not found")
    def test_keystone(self):
        self.skipTest("Keystone does not provide configuration files in venv")
        a = self.useFixture(keystone.KeystoneDriver())
        self.assertEqual("keystone://*****:*****@testtools.skipUnless(spawn.find_executable("ceph-mon"),
                          "Ceph Monitor not found")
    @testtools.skipUnless(spawn.find_executable("ceph-osd"),
                          "Ceph OSD not found")
    @testtools.skipUnless(spawn.find_executable("ceph"),
                          "Ceph client not found")
    def test_ceph(self):
        tmp_rootdir = self._get_tmpdir_for_xattr()
        a = self.useFixture(ceph.CephDriver(tmp_rootdir=tmp_rootdir))
        self.assertEqual("ceph://*****:*****@testtools.skipUnless(spawn.find_executable("rabbitmq-server"),
                          "RabbitMQ not found")
    def test_rabbitmq(self):
        a = self.useFixture(rabbitmq.RabbitMQDriver())
        self.assertEqual(
            "rabbit://%s:%s@localhost:%d//" % (a.username, a.password, a.port),
            os.getenv("PIFPAF_URL"))
        self.assertEqual(a.nodename + "@localhost",
                         os.getenv("PIFPAF_RABBITMQ_NODENAME"))
        self.assertEqual(str(a.port), os.getenv("PIFPAF_RABBITMQ_PORT"))

    @testtools.skipUnless(spawn.find_executable("rabbitmq-server"),
                          "RabbitMQ not found")
    def test_rabbitmq_cluster(self):
        a = self.useFixture(rabbitmq.RabbitMQDriver(cluster=True, port=12345))
        self.assertEqual(
            "rabbit://%(user)s:%(pass)s@localhost:%(port1)d,"
            "%(user)s:%(pass)s@localhost:%(port2)d,"
            "%(user)s:%(pass)s@localhost:%(port3)d//" % {
                "user": a.username,
                "pass": a.password,
                "port1": a.port,
                "port2": a.port + 1,
                "port3": a.port + 2
            }, os.getenv("PIFPAF_URL"))
        self.assertEqual(a.nodename + "-1@localhost",
                         os.getenv("PIFPAF_RABBITMQ_NODENAME"))
        self.assertEqual(a.nodename + "-1@localhost",
                         os.getenv("PIFPAF_RABBITMQ_NODENAME1"))
        self.assertEqual(a.nodename + "-2@localhost",
                         os.getenv("PIFPAF_RABBITMQ_NODENAME2"))
        self.assertEqual(a.nodename + "-3@localhost",
                         os.getenv("PIFPAF_RABBITMQ_NODENAME3"))
        self.assertEqual(str(a.port), os.getenv("PIFPAF_RABBITMQ_PORT"))

        a.kill_node(a.nodename + "-2@localhost")
        a.stop_node(a.nodename + "-3@localhost")
        a.start_node(a.nodename + "-3@localhost")
        a.start_node(a.nodename + "-2@localhost")

    @testtools.skipUnless(spawn.find_executable("couchdb"),
                          "CouchDB not found")
    def test_couchdb(self):
        port = 6984
        self.useFixture(couchdb.CouchDBDriver(port=port))
        self.assertEqual("couchdb://*****:*****@testtools.skipUnless(spawn.find_executable("artemis"),
                          "Artemis not found")
    def test_artemis(self):
        self.useFixture(artemis.ArtemisDriver(port=54321))
        self.assertEqual("amqp://*****:*****@testtools.skipUnless(spawn.find_executable("qdrouterd"),
                          "Qdrouterd not found")
    def test_qdrouterd(self):
        a = self.useFixture(qdrouterd.QdrouterdDriver(port=54321))
        self.assertEqual(
            "amqp://%s:%s@localhost:54321" % (a.username, a.password),
            os.getenv("PIFPAF_URL"))
        self.assertEqual("54321", os.getenv("PIFPAF_QDROUTERD_PORT"))
        self.assertEqual("amqp://*****:*****@testtools.skipUnless(spawn.find_executable("kafka-server-start.sh"),
                          "Kafka not found")
    def test_kafka(self):
        a = self.useFixture(kafka.KafkaDriver(port=54321,
                                              zookeeper_port=12345))
        self.assertEqual("kafka://*****:*****@testtools.skipUnless(spawn.find_executable("swift-proxy-server"),
                          "Swift not found")
    def test_swift(self):
        tmp_rootdir = self._get_tmpdir_for_xattr()
        a = self.useFixture(swift.SwiftDriver(tmp_rootdir=tmp_rootdir))
        self.assertEqual("http://*****:*****@localhost:8080/auth/v1.0",
            os.getenv("PIFPAF_SWIFT_URL"))
        self.assertEqual(
            "swift://test%3Atester:testing@localhost:8080/auth/v1.0",
            os.getenv("PIFPAF_URL"))

    @testtools.skipUnless(testtools.try_import('httpbin'), "httpbin not found")
    def test_httpbin(self):
        port = 6666
        a = self.useFixture(httpbin.HttpBinDriver(port=port))
        self.assertEqual(port, a.port)
        r = requests.get("http://127.0.0.1:%d/ip" % port)
        self.assertEqual(r.status_code, 200)
        self.assertEqual(r.json()["origin"], "127.0.0.1")

    def _get_tmpdir_for_xattr(self):
        tmp_rootdir = os.getenv("TMPDIR_FOR_XATTR")
        # NOTE(sileht): Don't skip test if user have explicitly set a directory
        if not tmp_rootdir:
            try:
                d = drivers.Driver(tmp_rootdir=tmp_rootdir)
                self.useFixture(d)
                d._ensure_xattr_support()
            except RuntimeError as e:
                self.skipTest(str(e))
        return tmp_rootdir
Example #8
0
import unittest

from testtools import (
    content,
    try_import,
    )
from testtools.compat import advance_iterator
from testtools.matchers import (
    Annotate,
    Equals,
    )
from testtools.monkey import patch
from testtools.runtest import RunTest
from testtools.testresult import TestResult

wraps = try_import('functools.wraps')

class TestSkipped(Exception):
    """Raised within TestCase.run() when a test is skipped."""
testSkipped = try_import('unittest2.case.SkipTest', TestSkipped)
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(
    'unittest2.case._UnexpectedSuccess', _UnexpectedSuccess)
Example #9
0
    'Content',
    'content_from_file',
    'content_from_stream',
    'text_content',
    'TracebackContent',
]

import codecs
import os

from testtools import try_import
from testtools.compat import _b
from testtools.content_type import ContentType, UTF8_TEXT
from testtools.testresult import TestResult

functools = try_import('functools')

_join_b = _b("").join

DEFAULT_CHUNK_SIZE = 4096


def _iter_chunks(stream, chunk_size):
    """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'.
    """
    chunk = stream.read(chunk_size)
    while chunk:
        yield chunk
Example #10
0
    try_import,
)
from testtools.monkey import MonkeyPatcher

from fixtures import FakeLogger

from twisted.internet.utils import getProcessOutput
from twisted.internet.epollreactor import EPollReactor

from txfixtures._twisted.threading import CallFromThreadTimeout

from txfixtures.reactor import Reactor

TIMEOUT = 5

asyncio = try_import("asyncio")

AsyncioSelectorReactor = try_import(
    "twisted.internet.asyncioreactor.AsyncioSelectorReactor")


class ReactorPatcher(MonkeyPatcher):
    """Monkey patch reactor methods to simulate various failure scenarios."""
    def __init__(self, reactor):
        super(ReactorPatcher, self).__init__()
        self.reactor = reactor
        self._originalMainLoop = reactor.mainLoop
        self._originalCallFromThread = reactor.callFromThread

        self.add_patch(reactor, "mainLoop", self._mainLoop)
        self.add_patch(reactor, "callFromThread", self._callFromThread)
Example #11
0
from tempest.common import waiters
from tempest.lib.common.utils import data_utils
from tempest.lib import decorators
from tempest.lib import exceptions as lib_exc

from neutron_tempest_plugin.api import base as base_api
from neutron_tempest_plugin import config
from neutron_tempest_plugin.scenario import base
from neutron_tempest_plugin.scenario import constants


CONF = config.CONF

# Note(jh): Need to do a bit of juggling here in order to avoid failures
# when designate_tempest_plugin is not available
dns_base = testtools.try_import('designate_tempest_plugin.tests.base')
dns_waiters = testtools.try_import('designate_tempest_plugin.common.waiters')
if dns_base:
    DNSMixin = dns_base.BaseDnsV2Test
else:
    DNSMixin = object


class BaseDNSIntegrationTests(base.BaseTempestTestCase, DNSMixin):
    credentials = ['primary']

    @classmethod
    def setup_clients(cls):
        super(BaseDNSIntegrationTests, cls).setup_clients()
        cls.dns_client = cls.os_tempest.zones_client
        cls.query_client = cls.os_tempest.query_client
Example #12
0
 def _depends_on_inner(self, *a, **kw):
     for name in names:
         if try_import(name) is None:
             self.skipTest('"{}" dependency missing'.format(name))
     return f(self, *a, **kw)
Example #13
0
    'text_content',
    'TracebackContent',
    ]

import codecs
import json
import os
import sys
import traceback

from testtools import try_import
from testtools.compat import _b, _format_exc_info, str_is_unicode, _u
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 #14
0
from hyperlink import URL
from testtools import TestCase, try_import
from testtools.matchers import AfterPreprocessing as After
from testtools.matchers import ContainsDict, Equals, Is
from twisted.web.test.requesthelper import DummyChannel

from fugue.interceptors.nevow import _nevow_request_to_request_map
from fugue.test.util import depends_on
from fugue.util import url_path

NevowRequest = try_import('nevow.appserver.NevowRequest')


def fake_nevow_request(method='GET',
                       body=b'',
                       is_secure=False,
                       uri=b'http://example.com/one',
                       request_headers=None,
                       Request=NevowRequest):
    """
    Create a fake `NevowRequest` instance for the purposes of testing.
    """
    uri = URL.from_text(uri.decode('utf-8')).to_uri()
    channel = DummyChannel()
    if is_secure:
        channel.transport = DummyChannel.SSL()
    request = Request(channel=channel)
    request.method = method
    request.uri = url_path(uri)
    request.clientproto = b'HTTP/1.1'
    request.client = channel.transport.getPeer()
Example #15
0
    Annotate,
    Contains,
    Equals,
    MatchesAll,
    MatchesException,
    MismatchError,
    Is,
    IsInstance,
    Not,
    Raises,
)
from testtools.monkey import patch
from testtools.runtest import RunTest
from testtools.testresult import TestResult

wraps = try_import("functools.wraps")


class TestSkipped(Exception):
    """Raised within TestCase.run() when a test is skipped."""


testSkipped = try_import("unittest2.case.SkipTest", TestSkipped)
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.
Example #16
0
import shutil
import subprocess
import tempfile

from glob import glob
from testtools import try_import
from pkg_resources import parse_version
from charmhelpers.core import hookenv, host
from charms.layer.jenkins import paths

from jenkins_plugin_manager.core import JenkinsCore

# XXX Wrap this import with try_import since layers code won't be available
#     when running unit tests for this layer (and in such case import errors
#     can be safely ignored since we're stubbing out these objects).
apt = try_import("charms.apt")

APT_DEPENDENCIES = {
    "xenial": ["daemon", "default-jre-headless"],
    "bionic": ["daemon", "openjdk-8-jre-headless"],
    "focal": ["daemon", "openjdk-8-jre-headless"],
}
APT_SOURCE = "deb http://pkg.jenkins-ci.org/%s binary/"


class Packages(object):
    """Manage Jenkins package dependencies."""
    def __init__(self, apt=apt, ch_host=None):
        """
        @param apt: An object implementing the charms.apt API from the apt
            charm layer (for testing).
Example #17
0
import platform

from pbr.version import VersionInfo

from testtools import try_import

from .fixture import CharmFakes
from .testing import CharmTest

__all__ = [
    "CharmFakes",
    "CharmTest",
]

_v = VersionInfo("charm-test").semantic_version()
__version__ = _v.release_string()
version_info = _v.version_tuple()

# XXX Force 'ubuntu' as platform, since charmhelpers.core.host doesn't like
# 'debian' (which is what you get on Travis).
platform.linux_distribution = lambda: ('Ubuntu', '16.04', 'xenial')

# XXX Force systemd as init system, since Travis doesn't yet support xenial.
host = try_import("charmhelpers.core.host")

if host:
    host.init_is_systemd = lambda: True