Esempio n. 1
0
def disable_colors():
    """
    Fixture to disable colors
    """
    colorful.disable()
    yield
    colorful.use_8_ansi_colors()
Esempio n. 2
0
def cli(**kwargs):
    """radish - The root from red to green. BDD tooling for Python.

    radish-test can be used to perform tests for the Steps
    implemented in a radish base directory.

    Use the `MATCHER_CONFIGS` to pass configuration
    files containing the Step matchers.
    """
    config = Config(kwargs)

    # turn of ANSI colors if requested
    if config.no_ansi:
        cf.disable()

    logger.debug("Basedirs: %s", ", ".join(str(d) for d in config.basedirs))
    logger.debug("Loading all modules from the basedirs")
    loaded_modules = loader.load_modules(config.basedirs)
    logger.debug(
        "Loaded %d modules from the basedirs: %s",
        len(loaded_modules),
        ", ".join(str(m) for m in loaded_modules),
    )

    logger.debug("Matcher configs: %s",
                 ", ".join(str(m) for m in config.matcher_configs))

    coverage_config = CoverageConfig(config.show_missing,
                                     config.show_missing_templates)

    run_matcher_tests(config.matcher_configs, coverage_config, step_registry)
Esempio n. 3
0
def init(args):
    """Initialise the UI, including logging"""

    if args["--vverbose"]:
        level = "DEBUG"
    elif args["--verbose"]:
        level = "INFO"
    else:
        level = None

    global QUIET
    global VERBOSE
    QUIET = args["--quiet"]
    VERBOSE = args["--verbose"] or args["--vverbose"]

    root_logger = logging.getLogger("hark_lang")

    if not args["--no-colours"]:
        import coloredlogs

        cf.use_true_colors()
        cf.use_palette(UI_COLORS)
        cf.update_palette(UI_COLORS)
        if level:
            coloredlogs.install(
                fmt="[%(asctime)s.%(msecs)03d] %(name)-25s %(message)s",
                datefmt="%H:%M:%S",
                level=level,
                logger=root_logger,
            )
    else:
        cf.disable()
        # FIXME Logger doesn't have basicConfig
        if level:
            root_logger.basicConfig(level=level)
Esempio n. 4
0
def cli(**kwargs):
    """radish - The root from red to green. BDD tooling for Python.

    Parse and Pretty Print the raw radish AST for the given Feature Files

    Provide the Feature Files to run in FEATURE_FILES.
    """
    config = Config(kwargs)
    world.config = config

    # turn of ANSI colors if requested
    if config.no_ansi:
        cf.disable()

    parser = FeatureFileParser(
        ast_transformer=None,
        resolve_preconditions=config.resolve_preconditions)

    for feature_file in config.feature_files:
        logger.info("Parsing Feature File %s", feature_file)
        try:
            feature_ast = parser.parse(feature_file)
            if feature_ast:
                print(feature_ast.pretty())
        except RadishError as exc:
            print("", flush=True)
            print(
                "An error occured while parsing the Feature File {}:".format(
                    feature_file),
                flush=True,
            )
            print(exc, flush=True)
            sys.exit(1)
Esempio n. 5
0
def disable_colors():
    """
    Fixture to disable colors
    """
    colorful.disable()
    yield
    colorful.use_8_ansi_colors()
Esempio n. 6
0
def disable_ansi_colors(world_default_config):
    """Fixture to disable ANSI colors"""
    orig_colormode = cf.colormode
    cf.disable()
    world_default_config.no_ansi = True
    yield
    cf.colormode = orig_colormode
Esempio n. 7
0
def main():
    """Converts a given url with the specified arguments."""

    options = get_options()

    cf.use_style("solarized")
    if options["nocolor"]:
        cf.disable()

    newline()
    header("Thumbor v%s (of %s)" % (__version__, __release_date__))

    newline()
    print(
        "Thumbor doctor will analyze your install and verify if everything is working as expected."
    )

    errors = check_modules()
    errors += check_compiled_extensions()
    errors += check_filters()
    errors += check_extensions()

    newline()

    if errors:
        print(
            cf.bold_red(
                "😞 Oh no! We found some things that could improve... 😞"))
        newline()
        print("\n".join(["* %s" % str(err) for err in errors]))
        newline()
        newline()
        print(
            cf.cyan(
                "If you don't know how to fix them, please open an issue with thumbor."
            ))
        print(
            cf.cyan(
                "Don't forget to copy this log and add it to the description of your issue."
            ))
        print("Open an issue at https://github.com/thumbor/thumbor/issues/new")
        sys.exit(1)
        return

    print(cf.bold_green("🎉 Congratulations! No errors found! 🎉"))
Esempio n. 8
0
    def detect_colors(self):
        """Update color output settings.

        Parse the `color_mode` string and optionally disable or force-enable
        color output
        (8-color ANSI if no terminal detected to be safe) in colorful.
        """
        if self.color_mode == "true":
            if self._autodetected_cf_colormode != cf.NO_COLORS:
                cf.colormode = self._autodetected_cf_colormode
            else:
                cf.colormode = cf.ANSI_8_COLORS
            return
        if self.color_mode == "false":
            cf.disable()
            return
        if self.color_mode == "auto":
            # colorful autodetects tty settings
            return

        raise ValueError("Invalid log color setting: " + self.color_mode)
Esempio n. 9
0
def main():
    args = docopt.docopt(__doc__)

    variables = {}
    if args['--vars']:
        for var in args['--vars'].split(' '):
            name, value = var.split('=')
            variables[name] = value

    reporter = SilentReporter()
    if args['--verbose']:
        reporter = VerboseReporter()
    if args['--nocolor']:
        colorful.disable()  # pylint: disable=no-member

    root = os.path.dirname(os.path.abspath(args['<pipeline>']))
    jinja_env = jinja2.Environment(loader=jinja2.FileSystemLoader(root))
    jinja_env.filters['basename'] = os.path.basename
    jinja_env.filters['dirname'] = os.path.dirname

    # Load the stream of tasks
    stream = load(jinja_env, {
        'pipeline': os.path.basename(args['<pipeline>']),
        'params': {
            'vars': variables,
            'gisdbase': args['--gisdbase'],
            'location': args['--location'],
            'mapset': args['--mapset'],
        }
    })

    session_exists = bool(os.environ.get('GISRC'))

    # Check the first item in the stream for a location event
    event = next(stream, None)
    if isinstance(event, LocationEvent):
        gisdbase = event.gisdbase
        location = event.location
        mapset = event.mapset
    else:
        stream = itertools.chain(iter([event]), stream)

    if session_exists:
        from ._grass import gcore
        env = gcore.gisenv()
        gisdbase = gisdbase or env['GISDBASE']
        location = location or env['LOCATION_NAME']
        mapset = mapset or env['MAPSET']

    # Load previous state
    state = State.load(os.path.join(
        gisdbase, location, mapset or 'PERMANENT', 'stitches.state.json'
    ))

    platform = Platform()

    # Analyse the stream of events with the previous state
    stream = analyse(stream, platform, state.history,
                     force=args['--force'],
                     skip=[a for a in (args['--skip'] or '').split(',') if a],
                     only=args['--only'])

    (code, stdout, stderr) = (0, StringIO(), StringIO())
    try:
        os.environ['GRASS_MESSAGE_FORMAT'] = 'plain'
        with session(gisdbase, location, mapset=mapset, skip=session_exists):
            for event in execute(stream, stdout, stderr):
                if isinstance(event, TaskCompleteEvent):
                    state.save()
                reporter(event)
            state.save()
    except Exception:  # pylint: disable=broad-except
        stack_trace = traceback.format_exc()
        reporter(TaskFatalEvent(stack_trace))
        if not args['--log']:
            uniq = datetime.datetime.now().strftime('%H_%M_%S_%f')
            args['--log'] = 'stitches.grass-{}.log'.format(uniq)
        code = 1

    if args['--log']:
        outlog = stdout.getvalue()
        errlog = stderr.getvalue()
        with open(args['--log'], 'w') as fp:
            print('****STDOUT****', file=fp)
            fp.write(outlog)
            print('****STDERR****', file=fp)
            fp.write(errlog)
        stdout.close()
        stderr.close()

    sys.exit(code)
Esempio n. 10
0
File: main.py Progetto: cle-b/radish
def main(args=None):
    """
    Entrypont to radish.
    Setup up configuration, loads extensions, reads feature files and runs
    radish
    """

    if args is None:
        args = sys.argv[1:]

    # note: using doc string for usage, messes up Sphinx documantation
    usage = """
Usage:
    radish show <features>
           [--expand]
           [--no-ansi]
    radish <features>...
           [-b=<basedir> | --basedir=<basedir>...]
           [-e | --early-exit]
           [--debug-steps]
           [-t | --with-traceback]
           [-m=<marker> | --marker=<marker>]
           [-p=<profile> | --profile=<profile>]
           [-d | --dry-run]
           [-s=<scenarios> | --scenarios=<scenarios>]
           [--shuffle]
           [--tags=<tags>]
           {0}
    radish (-h | --help)
    radish (-v | --version)

Arguments:
    features                                    feature files to run

Options:
    -h --help                                   show this screen
    -v --version                                show version
    -e --early-exit                             stop the run after the first failed step
    --debug-steps                               debugs each step
    -t --with-traceback                         show the Exception traceback when a step fails
    -m=<marker> --marker=<marker>               specify the marker for this run [default: time.time()]
    -p=<profile> --profile=<profile>            specify the profile which can be used in the step/hook implementation
    -b=<basedir> --basedir=<basedir>...         set base dir from where the step.py and terrain.py will be loaded. [default: $PWD/radish]
                                                You can specify -b|--basedir multiple times. All files will be imported.
    -d --dry-run                                make dry run for the given feature files
    -s=<scenarios> --scenarios=<scenarios>      only run the specified scenarios (comma separated list)
    --shuffle                                   shuttle run order of features and scenarios
    --tags=<feature_tags>                       only run Scenarios with the given tags
    --expand                                    expand the feature file (all preconditions)
    {1}

(C) Copyright by Timo Furrer <*****@*****.**>
    """

    warnings.simplefilter('always', DeprecationWarning)

    # load extensions
    load_modules(os.path.join(os.path.dirname(__file__), "extensions"))

    extensions = ExtensionRegistry()
    # add arguments from extensions to the usage
    usage = usage.format(extensions.get_options(),
                         extensions.get_option_description())

    sys.excepthook = catch_unhandled_exception

    # add version to the usage
    arguments = docopt("radish {0}\n{1}".format(__VERSION__, usage),
                       argv=args,
                       version=__VERSION__)

    # store all arguments to configuration dict in terrain.world
    setup_config(arguments)

    # disable colors if necessary
    if world.config.no_ansi:
        colorful.disable()
    else:
        colorful.use_8_ansi_colors()

    # load needed extensions
    extensions.load(world.config)

    core = Core()

    if world.config.profile:
        msg = (
            'Command line argument -p/--profile will be removed in a future version.  Please '
            'use -u/--user-data instead.')
        warnings.warn(msg, DeprecationWarning, stacklevel=1)

    feature_files = []
    for given_feature in world.config.features:
        if not os.path.exists(given_feature):
            raise FeatureFileNotFoundError(given_feature)

        if os.path.isdir(given_feature):
            feature_files.extend(
                utils.recursive_glob(given_feature, "*.feature"))
            continue

        feature_files.append(given_feature)

    # parse tag expressions
    tag_expression = None
    if world.config.tags:
        tag_expression = tagexpressions.parse(world.config.tags)

    core.parse_features(feature_files, tag_expression)

    if not core.features or sum(len(f.scenarios) for f in core.features) == 0:
        print(
            colorful.bold_red('Error: ') +
            colorful.red('please specify at least one feature to run'))
        if tag_expression:
            print(
                colorful.red(
                    'You have specified a tag expression. Make sure those are valid and actually yield some Scenarios to run.'
                ))
        return 1

    argument_dispatcher = [((lambda: world.config.show), show_features),
                           ((lambda: True), run_features)]

    # radish command dispatching
    for to_run, method in argument_dispatcher:
        if to_run():
            return method(core)
Esempio n. 11
0
import click
import colorful

colorful.disable()
colorful.use_8_ansi_colors()


class Emoji:
    package = "\U0001F4E6"
    check_mark = "\U00002714"
    cross_mark = "\U00002716"
    info = "\U00002139"


class Reporter:
    def info(self, message: str):
        click.echo(" {} {}\033[K".format(colorful.bold_cyan(Emoji.info),
                                         message))

    def error(self, error: str):
        click.echo(f" {colorful.bold_red(Emoji.cross_mark)} {error}", err=True)

    def success(self, message: str):
        click.echo(f" {colorful.bold_green(Emoji.check_mark)} {message}")


reporter = Reporter()
Esempio n. 12
0
def cli(**kwargs):
    """radish - The root from red to green. BDD tooling for Python.

    Use radish to run your Feature File.

    Provide the Feature Files to run in FEATURE_FILES.
    """
    config = Config(kwargs)
    world.config = config

    # turn of ANSI colors if requested
    if config.no_ansi:
        cf.disable()

    logger.debug(
        "Loaded %d built-in extension modules: %s",
        len(loaded_built_in_extensions),
        ", ".join(str(e) for e in loaded_built_in_extensions),
    )
    logger.debug("Feature Files: %s",
                 ", ".join(str(p) for p in config.feature_files))
    logger.debug("Basedirs: %s", ", ".join(str(d) for d in config.basedirs))

    logger.debug("Loading extensions")
    loaded_extensions = extension_registry.load_extensions(config)
    logger.debug(
        "Loaded %d extensions: %s",
        len(loaded_extensions),
        ", ".join(type(e).__name__ for e in loaded_extensions),
    )

    parser = FeatureFileParser()

    features = []
    for feature_file in config.feature_files:
        logger.debug("Parsing Feature File %s", feature_file)
        try:
            feature_ast = parser.parse(feature_file)
            if feature_ast:
                features.append(feature_ast)
        except RadishError as exc:
            print("", flush=True)
            print(
                "An error occured while parsing the Feature File {}:".format(
                    feature_file),
                flush=True,
            )
            print(exc, flush=True)
            sys.exit(1)

    logger.debug("Loading all modules from the basedirs")
    loaded_modules = loader.load_modules(config.basedirs)
    logger.debug(
        "Loaded %d modules from the basedirs: %s",
        len(loaded_modules),
        ", ".join(str(m) for m in loaded_modules),
    )

    exit_status = 0
    try:
        runner = Runner(config,
                        step_registry=step_registry,
                        hook_registry=hook_registry)
        logger.debug(
            "Starting Runner WIP mode: %r, Dry-Run mode: %r",
            config.wip_mode,
            config.dry_run_mode,
        )
        success = runner.start(features)
        logger.debug("Finished Runner with status %s", success)

        exit_status = 0 if success else 1
    except RadishError as exc:
        print("", flush=True)
        print("An error occured while running the Feature Files:", flush=True)
        print(exc, flush=True)
        exit_status = 1

    sys.exit(exit_status)
Esempio n. 13
0
def disable_coloring():
    cf.disable()
Esempio n. 14
0
def main(args=None):
    """
    Entrypont to radish.
    Setup up configuration, loads extensions, reads feature files and runs
    radish
    """

    if args is None:
        args = sys.argv[1:]

    # note: using doc string for usage, messes up Sphinx documantation
    usage = """
Usage:
    radish show <features>
           [--expand]
           [--no-ansi]
    radish <features>...
           [-b=<basedir> | --basedir=<basedir>...]
           [-e | --early-exit]
           [--debug-steps]
           [-t | --with-traceback]
           [-m=<marker> | --marker=<marker>]
           [-p=<profile> | --profile=<profile>]
           [-d | --dry-run]
           [-s=<scenarios> | --scenarios=<scenarios>]
           [--shuffle]
           [--tags=<tags>]
           [--wip]
           [-f=<formatter> | --formatter=<formatter>]
           {0}
    radish (-h | --help)
    radish (-v | --version)

Arguments:
    features                                    feature files to run

Options:
    -h --help                                   show this screen
    -v --version                                show version
    -e --early-exit                             stop the run after the first failed step
    --debug-steps                               debugs each step
    -t --with-traceback                         show the Exception traceback when a step fails
    -m=<marker> --marker=<marker>               specify the marker for this run [default: time.time()]
    -p=<profile> --profile=<profile>            specify the profile which can be used in the step/hook implementation
    -b=<basedir> --basedir=<basedir>...         set base dir from where the step.py and terrain.py will be loaded. [default: $PWD/radish]
                                                You can specify -b|--basedir multiple times or split multiple paths with a colon (:) similar to $PATH. All files will be imported.
    -d --dry-run                                make dry run for the given feature files
    -s=<scenarios> --scenarios=<scenarios>      only run the specified scenarios (comma separated list)
    --shuffle                                   shuttle run order of features and scenarios
    --tags=<feature_tags>                       only run Scenarios with the given tags
    --wip                                       expects all tests to fail instead of succeeding
    -f=<formatter> --formatter=<formatter>      the output formatter which should be used. [default: gherkin]
    --expand                                    expand the feature file (all preconditions)
    {1}

(C) Copyright by Timo Furrer <*****@*****.**>
    """

    warnings.simplefilter("always", DeprecationWarning)

    # load extensions
    load_modules(os.path.join(os.path.dirname(__file__), "extensions"))

    extensions = ExtensionRegistry()
    # add arguments from extensions to the usage
    usage = usage.format(extensions.get_options(), extensions.get_option_description())

    sys.excepthook = catch_unhandled_exception

    # add version to the usage
    arguments = docopt(
        "radish {0}\n{1}".format(__VERSION__, usage), argv=args, version=__VERSION__
    )

    # store all arguments to configuration dict in terrain.world
    setup_config(arguments)

    # disable colors if necessary
    if world.config.no_ansi:
        colorful.disable()
    else:
        colorful.use_8_ansi_colors()

    # load needed extensions
    extensions.load(world.config)

    core = Core()

    if world.config.profile:
        msg = (
            "Command line argument -p/--profile will be removed in a future version.  Please "
            "use -u/--user-data instead."
        )
        warnings.warn(msg, DeprecationWarning, stacklevel=1)

    feature_files = []
    for given_feature in world.config.features:
        if not os.path.exists(given_feature):
            raise FeatureFileNotFoundError(given_feature)

        if os.path.isdir(given_feature):
            feature_files.extend(utils.recursive_glob(given_feature, "*.feature"))
            continue

        feature_files.append(given_feature)

    # parse tag expressions
    tag_expression = None
    if world.config.tags:
        tag_expression = tagexpressions.parse(world.config.tags)

    core.parse_features(feature_files, tag_expression)

    if not core.features or sum(len(f.scenarios) for f in core.features) == 0:
        utils.console_write(colorful.bold_red("Error: ")
            + colorful.red("No feature or no scenario specified in at least one of the given feature files")
        )
        if tag_expression:
            utils.console_write(colorful.red(
                    "You have specified a tag expression. Make sure those are valid and actually yield some Scenarios to run."
                )
            )
        return 1

    argument_dispatcher = [
        ((lambda: world.config.show), show_features),
        ((lambda: True), run_features),
    ]

    # radish command dispatching
    for to_run, method in argument_dispatcher:
        if to_run():
            return method(core)
Esempio n. 15
0
from __future__ import annotations

import sys
from typing import List

import colorful as cf

__all__: List[str] = []

cf.use_style('solarized')
if not sys.stdout.isatty() or not sys.stderr.isatty():
    # Output is piped or redirected.
    cf.disable()