Exemplo n.º 1
0
def get_test_client():
    config = Mock()
    config.storage = DummyStore(
        "",
        data={
            "defaults": {
                "pony": "gravity"
            },
            "active-experiments": ["foo"],
            "experiments/foo": {
                "id": "foo",
                "constraints": {
                    "excluded_tags": ["excluded"]
                },
                "branches": [{
                    "id": "bar",
                    "settings": {
                        "pony": "horse"
                    }
                }],
            },
        },
    )
    now = datetime.datetime.now(dateutil.tz.tzutc())
    config.directory = DummyDirectory(users=(
        UserEntry(id=1, join_date=now, tags=("excluded", )),
        UserEntry(id=2, join_date=now, tags=("excluded", )),
        UserEntry(id=3, join_date=now, tags=()),
    ))

    wsgi = get_wsgi_app(config)
    return werkzeug.test.Client(wsgi)
Exemplo n.º 2
0
    def _get_run_target(self, config, options):
        """
        Get the 'run target' out from options.

        This is a nullary callable which is expected to raise an exception -
        the exception we are needing to debug.

        For the command case it's a wrapped version of the command, which
        silences stdout and stderr.

        For the URL case it's a call with a WSGI client which catches 4xx and
        5xx status codes turning them into ValueErrors.
        """
        if options.command:

            def target():
                out_stream = io.StringIO()

                with contextlib.ExitStack() as context:
                    context.enter_context(
                        contextlib.redirect_stdout(out_stream))
                    context.enter_context(
                        contextlib.redirect_stderr(out_stream))

                    run_command(options.command, config)

        elif options.url:
            app = get_wsgi_app(config)
            test_client = Client(app, BaseResponse)

            def target():
                result = test_client.get(options.url)

                status_class = str(result.status_code)[0]

                if status_class in ("4", "5"):
                    raise ValueError(
                        "Status: {code}".format(code=result.status_code))

        else:
            raise AssertionError("No target type")

        return target
Exemplo n.º 3
0
    def handle(self, config, options):
        """Run command."""
        app = get_wsgi_app(config)

        reload_and_debug = True

        if options.profile is not None:
            options.profile.mkdir(parents=True, exist_ok=True)
            reload_and_debug = False
            app = werkzeug.contrib.profiler.ProfilerMiddleware(
                app=app, profile_dir=str(options.profile))

        werkzeug.serving.run_simple(
            options.bind,
            options.port,
            app,
            use_reloader=reload_and_debug,
            use_debugger=reload_and_debug,
            use_evalex=reload_and_debug,
            threaded=False,
            processes=1,
        )
Exemplo n.º 4
0
to target, picking up the WSGI application from `app`.

In this case, the configuration file can be specified through the environment
variable `JACQUARD_CONFIG`; if left unspecified, the file 'config.cfg' in the
current working directory is assumed.
"""

import os
import logging

from jacquard.utils import check_keys
from jacquard.config import load_config
from jacquard.service import get_wsgi_app
from jacquard.constants import DEFAULT_CONFIG_FILE_PATH

LOG_LEVEL = os.environ.get("JACQUARD_LOG_LEVEL", "info").lower()
KNOWN_LOG_LEVELS = {
    "debug": logging.DEBUG, "info": logging.INFO, "errors": logging.ERROR
}

check_keys((LOG_LEVEL,), KNOWN_LOG_LEVELS, RuntimeError)

logging.basicConfig(level=KNOWN_LOG_LEVELS[LOG_LEVEL])

wsgi_logger = logging.getLogger("jacquard.wsgi")
wsgi_logger.warning("Logging warnings in Jacquard")
wsgi_logger.info("Logging informational messages in Jacquard")
wsgi_logger.debug("Emitting debug messages from Jacquard")

app = get_wsgi_app(load_config(DEFAULT_CONFIG_FILE_PATH))
Exemplo n.º 5
0
def test_integration(test_file):
    with (INTEGRATION_TESTS_ROOT / test_file).open("r") as f:
        test_config = yaml.safe_load(f)

    config = load_config(io.StringIO(TEST_CONFIG))
    config = unittest.mock.Mock(wraps=config)
    config.directory = DummyDirectory(users=(
        UserEntry(
            id="1",
            join_date=datetime.datetime(2017, 1, 1,
                                        tzinfo=dateutil.tz.tzutc()),
            tags=(),
        ),
        UserEntry(
            id="2",
            join_date=datetime.datetime(2017, 1, 2,
                                        tzinfo=dateutil.tz.tzutc()),
            tags=("tag1", "tag2"),
        ),
    ))

    wsgi = get_wsgi_app(config)
    test_client = werkzeug.test.Client(wsgi)

    for step in test_config:
        if "command" in step:
            stdout = io.StringIO()
            stderr = io.StringIO()

            args = shlex.split(step["command"])

            try:
                with contextlib.redirect_stdout(stdout):
                    with contextlib.redirect_stderr(stderr):
                        with _temporary_working_directory(JACQUARD_ROOT):
                            main(args, config=config)
            except SystemExit:
                pass

            output = stdout.getvalue()

            if "expect_error" in step:
                error_message = stderr.getvalue()
            else:
                assert not stderr.getvalue()

        elif "get" in step:
            path = step["get"]

            data, status, headers = test_client.get(path)

            assert status == "200 OK"

            output = b"".join(data).decode("utf-8")

        if "expect" in step:
            expected_output = textwrap.dedent(step["expect"]).strip()
            actual_output = textwrap.dedent(output).strip()

            assert actual_output == expected_output

        if "expect_yaml" in step:
            expected_output = step["expect_yaml"]
            actual_output = yaml.safe_load(output)

            assert actual_output == expected_output

        if "expect_yaml_keys" in step:
            expected_keys = step["expect_yaml_keys"]
            actual_output = yaml.safe_load(output)

            assert set(actual_output.keys()) == set(expected_keys)

        if "expect_error" in step:
            expected_error = textwrap.dedent(step["expect_error"].strip())
            actual_error = textwrap.dedent(error_message).strip()

            assert actual_error == expected_error