Esempio n. 1
0
def list_jobs(filter_prj=None, filter_cmd=None, by_id=None):
    db_results = []
    if by_id:
        job = rms_db.get(doc_id=by_id)
        if job:
            db_results.append(rms_db.get(doc_id=by_id))
        else:
            print(colorful.bold_red(f"  no job with id {by_id} found"))
    else:
        db_results = rms_db.all()
        if filter_cmd:
            db_results = rms_db.search(Query()["<command>"] == filter_cmd)
        if filter_prj:
            db_results = [r for r in db_results if filter_prj in r["<project_code>"]]
    if db_results:
        print(colorful.cyan("id".rjust(6)),
              colorful.cyan("project_code".ljust(18)),
              colorful.cyan("command".ljust(14)),
              colorful.cyan("start_time".rjust(12)),
              colorful.cyan("timeout".rjust(8)),
              )
        for job in db_results:
            job_id = job.doc_id
            job_timeout = job.get("timeout")
            if not job_timeout:
                job_timeout = 60
            print(str(job_id).rjust(6),
                  job["<project_code>"].ljust(18),
                  job["<command>"].ljust(14),
                  job[">start_time"].rjust(12),
                  str(job_timeout).rjust(8),
                  )
    else:
        print(colorful.bold_red("  no matching entries found."))
Esempio n. 2
0
def test_step_not_match(sentence, expected_not_matching_step, steps):
    step_to_print = (
        colorful.cyan(expected_not_matching_step)
        if expected_not_matching_step
        else "ANY"
    )
    sys.stdout.write(
        '{0} STEP "{1}" SHOULD NOT MATCH {2}    '.format(
            colorful.yellow(">>"), colorful.cyan(sentence), step_to_print
        )
    )

    result = match_step(sentence, steps)
    if result:
        if (
            not expected_not_matching_step
            or result.func.__name__ == expected_not_matching_step
        ):
            output_failure(
                None,
                [
                    "Expected sentence did match {0} but it shouldn't".format(
                        expected_not_matching_step
                    )
                ],
            )
            return False

    print(u(colorful.bold_green("✔")))
    return True
Esempio n. 3
0
def test_step_match(sentence, expected_step, expected_arguments, steps):
    sys.stdout.write('{0} STEP "{1}" SHOULD MATCH {2}    '.format(
        colorful.yellow('>>'), colorful.cyan(sentence),
        colorful.cyan(expected_step)))

    result = match_step(sentence, steps)
    if not result:
        output_failure(
            None, ['Expected sentence didn\'t match any step implementation'])
        return False

    if expected_step != result.func.__name__:
        output_failure(result.func, [
            'Expected sentence matched {0} instead of {1}'.format(
                result.func.__name__, expected_step)
        ])
        return False

    if expected_arguments:
        arguments = merge_step_args(result)
        expected_arguments = {
            k: v
            for expected_arguments in expected_arguments
            for k, v in expected_arguments.items()
        }
        argument_errors = check_step_arguments(expected_arguments, arguments)
        if argument_errors:
            output_failure(result.func, argument_errors)
            return False

    print(u(colorful.bold_green(u'✔')))
    return True
Esempio n. 4
0
def test_step_matches(match_config, steps):
    """
    Test if the given match config matches the actual
    matched step implementations.
    """
    failed = 0
    passed = 0

    for item in match_config:
        validate_config_item(item)

        sentence = item['sentence']
        expected_step = item['should_match']

        sys.stdout.write('{0} STEP "{1}" SHOULD MATCH {2}    '.format(
            colorful.yellow('>>'), colorful.cyan(sentence),
            colorful.cyan(expected_step)))

        result = match_step(item['sentence'], steps)
        if not result:
            output_failure(
                None,
                ['Expected sentence didn\'t match any step implementation'])
            failed += 1
            continue

        if expected_step != result.func.__name__:
            output_failure(result.func, [
                'Expected sentence matched {0} instead of {1}'.format(
                    result.func.__name__, expected_step)
            ])
            failed += 1
            continue

        expected_arguments = item.get('with_arguments')

        if expected_arguments:
            arguments = merge_step_args(result)
            expected_arguments = {
                k: v
                for expected_arguments in expected_arguments
                for k, v in expected_arguments.items()
            }
            argument_errors = check_step_arguments(expected_arguments,
                                                   arguments)
            if argument_errors:
                output_failure(result.func, argument_errors)
                failed += 1
                continue

        # check if arguments match
        print(u(colorful.bold_green(u'✔')))
        passed += 1

    return failed, passed
Esempio n. 5
0
def show():
    """
    Show the modifiers and colors
    """
    # modifiers
    sys.stdout.write(colorful.bold('bold') + ' ')
    sys.stdout.write(colorful.dimmed('dimmed') + ' ')
    sys.stdout.write(colorful.italic('italic') + ' ')
    sys.stdout.write(colorful.underlined('underlined') + ' ')
    sys.stdout.write(colorful.inversed('inversed') + ' ')
    sys.stdout.write(colorful.concealed('concealed') + ' ')
    sys.stdout.write(colorful.struckthrough('struckthrough') + '\n')

    # foreground colors
    sys.stdout.write(colorful.red('red') + ' ')
    sys.stdout.write(colorful.green('green') + ' ')
    sys.stdout.write(colorful.yellow('yellow') + ' ')
    sys.stdout.write(colorful.blue('blue') + ' ')
    sys.stdout.write(colorful.magenta('magenta') + ' ')
    sys.stdout.write(colorful.cyan('cyan') + ' ')
    sys.stdout.write(colorful.white('white') + '\n')

    # background colors
    sys.stdout.write(colorful.on_red('red') + ' ')
    sys.stdout.write(colorful.on_green('green') + ' ')
    sys.stdout.write(colorful.on_yellow('yellow') + ' ')
    sys.stdout.write(colorful.on_blue('blue') + ' ')
    sys.stdout.write(colorful.on_magenta('magenta') + ' ')
    sys.stdout.write(colorful.on_cyan('cyan') + ' ')
    sys.stdout.write(colorful.on_white('white') + '\n')
Esempio n. 6
0
def first_run_tui():
    '''
    first setups and creating key's and personal passwords
    '''
    import os
    if (platform.system() == "Darwin"):
        pass
    if (platform.system() == "Windows"):
        os.system("pip install -r requirements.txt")
        # pass
    if (platform.system() == "Linux"):
        pass
    from cryptography.fernet import Fernet

    cryptocut_art = text2art("cRYPTOcUT", "confused3")
    setup_art = text2art("setup")
    print('\n', cf.green(cryptocut_art))
    print(cf.cyan(setup_art))
    user_pass = input(
        cf.yellow("enter your password for symmetric encryption : "))
    user_key = (create_user_key(user_pass))
    # generate a random secret for user using crypto lib
    fernet = Fernet(user_key)
    random_key = Fernet.generate_key()
    symmetric_key = fernet.encrypt(random_key)
    # write the random secret as symmetric_key in symmetric.key
    # TODO : we can use a diffrent path for this
    with open("symmetric.key", "wb") as key_file:
        key_file.write(symmetric_key)
    print(cf.green("done! \nsuccessfully initialized the symmetric key"))
Esempio n. 7
0
    def console_writer_before_each_feature(self, feature):
        """
            Writes feature header to the console

            :param Feature feature: the feature to write to the console
        """
        output = ""
        for tag in feature.tags:
            output += colorful.cyan(u"@{0}{1}\n".format(
                tag.name, "({0})".format(tag.arg) if tag.arg else ""))

        leading = "\n    " if feature.description else ""

        output += u"{0}{1}: {2}  # {3}{4}{5}".format(
            self.get_id_sentence_prefix(feature, colorful.bold_cyan),
            colorful.bold_white(feature.keyword),
            colorful.bold_white(feature.sentence),
            colorful.bold_black(feature.path), leading,
            colorful.white("\n    ".join(feature.description)))

        if feature.background:
            output += u"\n\n    {0}: {1}".format(
                colorful.bold_white(feature.background.keyword),
                colorful.bold_white(feature.background.sentence))
            for step in feature.background.all_steps:
                output += '\n' + self._get_step_before_output(
                    step, colorful.cyan)

        write(output)
Esempio n. 8
0
    def console_writer_before_each_feature(self, feature):
        """
            Writes feature header to the console

            :param Feature feature: the feature to write to the console
        """
        output = ""
        for tag in feature.tags:
            output += colorful.cyan(
                "@{0}{1}\n".format(tag.name, "({0})".format(tag.arg) if tag.arg else "")
            )

        leading = "\n    " if feature.description else ""

        output += "{0}{1}: {2}  # {3}{4}{5}".format(
            self.get_id_sentence_prefix(feature, colorful.bold_cyan),
            colorful.bold_white(feature.keyword),
            colorful.bold_white(feature.sentence),
            colorful.bold_black(feature.path),
            leading,
            colorful.white("\n    ".join(feature.description)),
        )

        if feature.background:
            output += "\n\n    {0}: {1}".format(
                colorful.bold_white(feature.background.keyword),
                colorful.bold_white(feature.background.sentence),
            )
            for step in feature.background.all_steps:
                output += "\n" + self._get_step_before_output(step, colorful.cyan)

        write(output)
Esempio n. 9
0
def test_step_not_match(sentence, expected_not_matching_step, steps):
    step_to_print = colorful.cyan(
        expected_not_matching_step) if expected_not_matching_step else 'ANY'
    sys.stdout.write('{0} STEP "{1}" SHOULD NOT MATCH {2}    '.format(
        colorful.yellow('>>'), colorful.cyan(sentence), step_to_print))

    result = match_step(sentence, steps)
    if result:
        if not expected_not_matching_step or result.func.__name__ == expected_not_matching_step:
            output_failure(None, [
                'Expected sentence did match {0} but it shouldn\'t'.format(
                    expected_not_matching_step)
            ])
            return False

    print(u(colorful.bold_green(u'✔')))
    return True
Esempio n. 10
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. 11
0
    def labeled_value(self, key, msg, *args, **kwargs):
        """Displays a key-value pair with special formatting.

        Args:
            key (str): Label that is prepended to the message.

        For other arguments, see `_format_msg`.
        """
        self._print(
            cf.cyan(key) + ": " + _format_msg(cf.bold(msg), *args, **kwargs))
Esempio n. 12
0
 def format(self, record):
     levelname = record.levelname
     if levelname in ('NOTSET', 'DEBUG'):
         record.levelname = colorful.cyan(levelname)
     elif levelname in ('INFO', ):
         record.levelname = colorful.green(levelname)
     elif levelname in ('WARNING', ):
         record.levelname = colorful.bold_yellow(levelname)
     elif levelname in ('ERROR', 'CRITICAL'):
         record.levelname = colorful.bold_red(levelname)
     return logging.Formatter.format(self, record)
Esempio n. 13
0
def test_step_not_match(sentence, expected_not_matching_step, steps):
    step_to_print = (colorful.cyan(expected_not_matching_step)
                     if expected_not_matching_step else "ANY")
    sys.stdout.write('{0} STEP "{1}" SHOULD NOT MATCH {2}    '.format(
        colorful.yellow(">>"), colorful.cyan(sentence), step_to_print))

    result = match_step(sentence, steps)
    if result:
        if (not expected_not_matching_step
                or result.func.__name__ == expected_not_matching_step):
            output_failure(
                None,
                [
                    "Expected sentence did match {0} but it shouldn't".format(
                        expected_not_matching_step)
                ],
            )
            return False

    print(u(colorful.bold_green("✔")))
    return True
Esempio n. 14
0
    def console_writer_before_each_scenario(self, scenario):
        """
            Writes the scenario header to the console

            :param Scenario scenario: the scenario to write to the console
        """
        output = "\n"
        if isinstance(scenario.parent, ScenarioOutline):
            if world.config.write_steps_once:
                return

            id_prefix = self.get_id_sentence_prefix(
                scenario, colorful.bold_yellow, len(scenario.parent.scenarios))
            colored_pipe = colorful.bold_white("|")
            output = "        {0}{1} {2} {1}".format(
                id_prefix,
                colored_pipe,
                (" {0} ").format(colored_pipe).join(
                    str(
                        colorful.bold_yellow("{1: <{0}}".format(
                            scenario.parent.get_column_width(i), x)))
                    for i, x in enumerate(scenario.example.data)),
            )
        elif isinstance(scenario.parent, ScenarioLoop):
            if world.config.write_steps_once:
                return

            id_prefix = self.get_id_sentence_prefix(
                scenario, colorful.bold_yellow, len(scenario.parent.scenarios))
            colored_pipe = colorful.bold_white("|")
            output = "        {0}{1} {2: <18} {1}".format(
                id_prefix, colored_pipe,
                str(colorful.bold_yellow(scenario.iteration)))
        else:
            id_prefix = self.get_id_sentence_prefix(scenario,
                                                    colorful.bold_cyan)
            for tag in scenario.tags:
                if (
                        tag.name == "precondition" and world.config.expand
                        and world.config.show
                ):  # exceptional for show command when scenario steps expand and tag is a precondition -> comment it out
                    output += colorful.white("    # @{0}{1}\n".format(
                        tag.name, "({0})".format(tag.arg) if tag.arg else ""))
                else:
                    output += colorful.cyan("    @{0}{1}\n".format(
                        tag.name, "({0})".format(tag.arg) if tag.arg else ""))
            output += "    {0}{1}: {2}".format(
                id_prefix,
                colorful.bold_white(scenario.keyword),
                colorful.bold_white(scenario.sentence),
            )
        write(output)
Esempio n. 15
0
    def _get_step_before_output(self, step, color_func=None):
        if color_func is None:
            color_func = colorful.bold_yellow
        output = "\r        {0}{1}".format(
            self.get_id_sentence_prefix(step, color_func), color_func(step.sentence)
        )

        if step.text:
            id_padding = self.get_id_padding(len(step.parent.steps))
            output += colorful.bold_white('\n            {0}"""'.format(id_padding))
            output += colorful.cyan(
                "".join(
                    [
                        "\n                {0}{1}".format(id_padding, l)
                        for l in step.raw_text
                    ]
                )
            )
            output += colorful.bold_white('\n            {0}"""'.format(id_padding))

        if step.table_header:
            colored_pipe = colorful.bold_white("|")
            col_widths = self.get_table_col_widths(
                [step.table_header] + step.table_data
            )

            # output table header
            output += "\n          {0} {1} {0}".format(
                colored_pipe,
                (" {0} ")
                .format(colored_pipe)
                .join(
                    str(colorful.white("{1: <{0}}".format(col_widths[i], x)))
                    for i, x in enumerate(step.table_header)
                ),
            )

            # output table data
            for row in step.table_data:
                output += "\n          {0} {1} {0}".format(
                    colored_pipe,
                    (" {0} ")
                    .format(colored_pipe)
                    .join(
                        str(color_func("{1: <{0}}".format(col_widths[i], x)))
                        for i, x in enumerate(row)
                    ),
                )

        return output
def test_evaluate_deck():
    set_infos = load_card_csv()

    for test_number, (expected_performance,
                      test_deck) in enumerate(load_test_cases(), start=1):
        print(
            colorful.dimmed_blue(f'Evaluating test deck {test_number} ') +
            colorful.cyan(f'(Expected to be "{expected_performance}")'))
        deck_summary = summarize_deck(test_deck, set_infos=set_infos)
        print(f'Deck summary: {colorful.yellow(deck_summary)}')
        penalties = evaluate_deck(deck_summary)
        print(f'Evaluation: {colorful.orange(penalties)}')
        print(f'Total Penalty: {colorful.bold_red(sum(penalties))}')
        print()
Esempio n. 17
0
def test_step_match(sentence, expected_step, expected_arguments, steps):
    sys.stdout.write(
        '{0} STEP "{1}" SHOULD MATCH {2}    '.format(
            colorful.yellow(">>"), colorful.cyan(sentence), colorful.cyan(expected_step)
        )
    )

    result = match_step(sentence, steps)
    if not result:
        output_failure(None, ["Expected sentence didn't match any step implementation"])
        return False

    if expected_step != result.func.__name__:
        output_failure(
            result.func,
            [
                "Expected sentence matched {0} instead of {1}".format(
                    result.func.__name__, expected_step
                )
            ],
        )
        return False

    if expected_arguments:
        arguments = merge_step_args(result)
        expected_arguments = {
            k: v
            for expected_arguments in expected_arguments
            for k, v in expected_arguments.items()
        }
        argument_errors = check_step_arguments(expected_arguments, arguments)
        if argument_errors:
            output_failure(result.func, argument_errors)
            return False

    print(u(colorful.bold_green("✔")))
    return True
Esempio n. 18
0
def remove_db_job_by_id(preset=None):
    """
    removes rms job from db by id
    """
    print("  please enter job_id to remove from db")
    job_id = prompt("> remove_job_by_db_id> ", **sub_prompt_options)
    job_id = int(job_id)
    job = rms_db.get(doc_id=job_id)
    if job:
        list_jobs(by_id=job_id)
        cmd_str = serdes(job=job)
        print(colorful.cyan("  got removed from db"))
        job = rms_db.remove(doc_ids=[job_id])
    else:
        print("  no job with this id found")
Esempio n. 19
0
def show_db_job_by_id(preset=None):
    """
    show config details of rms job from db by id
    """
    if not preset:
        print("  please enter job_id to show details")
        job_id = prompt("> show_job_by_db_id> ", **sub_prompt_options)
        job_id = int(job_id)
    else:
        job_id = int(preset)
    job = rms_db.get(doc_id=job_id)
    if job:
        list_jobs(by_id=job_id)
        cmd_str = serdes(job=job)
        print(colorful.cyan("\n  command:"))
        print(cmd_str)
        return
    else:
        print("  no job with this id found")
Esempio n. 20
0
    def _get_step_before_output(self, step, color_func=None):
        if color_func is None:
            color_func = colorful.bold_yellow
        output = "\r        {0}{1}".format(
            self.get_id_sentence_prefix(step, color_func),
            color_func(step.sentence))

        if step.text:
            id_padding = self.get_id_padding(len(step.parent.steps))
            output += colorful.bold_white(
                '\n            {0}"""'.format(id_padding))
            output += colorful.cyan("".join([
                "\n                {0}{1}".format(id_padding, l)
                for l in step.raw_text
            ]))
            output += colorful.bold_white(
                '\n            {0}"""'.format(id_padding))

        if step.table_header:
            colored_pipe = colorful.bold_white("|")
            col_widths = self.get_table_col_widths([step.table_header] +
                                                   step.table_data)

            # output table header
            output += "\n          {0} {1} {0}".format(
                colored_pipe,
                (" {0} ").format(colored_pipe).join(
                    str(colorful.white("{1: <{0}}".format(col_widths[i], x)))
                    for i, x in enumerate(step.table_header)),
            )

            # output table data
            for row in step.table_data:
                output += "\n          {0} {1} {0}".format(
                    colored_pipe,
                    (" {0} ").format(colored_pipe).join(
                        str(color_func("{1: <{0}}".format(col_widths[i], x)))
                        for i, x in enumerate(row)),
                )

        return output
Esempio n. 21
0
def main():
    pa = ArgumentParser()
    pa.add_argument('location', help='The location to lookup.')
    pa.add_argument('--unit',
                    help='The unit to be used. Default is Celsius.',
                    default='c',
                    nargs='?',
                    choices=['c', 'f'])
    pa.add_argument('--log',
                    help='Pass this argument to output logging',
                    default=False,
                    action='store_true',
                    dest='log')
    pa.add_argument("--start", nargs="?", help="The forecast start")
    pa.add_argument("--end", nargs="?", help="The forecast end")
    args = pa.parse_args()
    weather = Weather(args.unit, args.log)
    loc = weather.lookup_by_location(args.location)
    condition = loc.condition
    print(
        colorful.bold("Weather report for %s, %s" %
                      (loc.location.city, loc.location.country)))
    row = PrettyTable()
    row.field_names = ["Condition", "Temperature"]
    row.align = 'l'
    row.add_row([condition.text, condition.temp])
    print(row)
    print(colorful.cyan("Weather Forecasts"))
    row = PrettyTable()
    row.field_names = ["Date", "Condition", "High", "Low"]
    row.align = 'l'
    start = 0 if not args.start else int(args.start)
    end = len(loc.forecast) if not args.end else int(args.end)
    for forecast in loc.forecast[start:end]:
        row.add_row(
            [forecast.date, forecast.text, forecast.high, forecast.low])
    print(row)
Esempio n. 22
0
 def _row_(self,
           row: Sequence[Any],
           left: str = '│',
           middle: str = '│',
           right: str = '│',
           fill: str = ' ',
           bold: bool = False,
           odd: int = 0) -> str:
     columns = []
     for index in range(self.size):
         value = row[index]
         if isinstance(value, int):
             cell = str(value).rjust(self.widths[index], fill)
             value = colorful.cyan(cell)
         elif isinstance(value, float):
             cell = f'{value:.2f}'.rjust(self.widths[index], fill)
             value = (colorful.green if value > 0 else colorful.red)(cell)
         else:
             value = str(value).ljust(self.widths[index], fill)
         columns.append(fill + value + fill)
     middle = middle.join(columns)
     if odd:
         middle = colorful.on_black(middle)
     return left + middle + right
Esempio n. 23
0
def main():
    args = docopt(__doc__)

    # check if file exits
    if not os.path.exists(args["FILE"]):
        print(cf.red("{} doesn't exist\n".format(args["FILE"])))
        exit(1)

    # create the output file
    of = args["-o"]
    open(of, "w").close()

    f = open(args["FILE"])
    grammar = f.read()
    f.close()

    # clear console
    clear()

    # print banner
    print(cf.yellow_bold(BANNER))

    print(cf.bold_white("Input Grammar:\n"))
    pgrammar = gm.parse(grammar)
    orignal = pgrammar
    gm.pprint(pgrammar)
    print()

    write_to_output(of, "Input Grammar", gm.str_pgrammar(pgrammar))

    choices = [
        "Remove Null Productions",
        "Remove Unit Productions",
        "Remove Left Recursion",
        "First Sets",
        "Follow Sets",
        "Parsing Table",
    ]

    misc_choices = [
        "Restore Original Grammar",
        "Print Current Grammar",
        "Clear",
        "Exit",
    ]

    question = {
        "type": "list",
        "name": "ops",
        "message": "Which operation would you like to perform?",
        "choices": choices + [Separator()] + misc_choices,
    }

    reuse_confirm = {
        "type": "confirm",
        "name": "last_grammar",
        "message": "Use this grammar output for subsequent operations?",
        "default": True,
    }

    reverse_confirm = {
        "type": "confirm",
        "name": "reverse_grammar",
        "message": "Reverse Non-Terminal ordering?",
        "default": True,
    }

    start_input = {
        "type": "input",
        "name": "start_sym",
        "message": "Enter Start Symbol:",
    }

    # will contain the last output
    output = None
    # if last output was a grammar (as opposed to follow sets)
    output_grammar = False

    while True:
        answer = prompt(question)
        choice = answer["ops"]

        if choice == misc_choices[0]:
            pgrammar = orignal
            print(cf.white_bold("\nRestored\n"))
            gm.pprint(pgrammar)
            print()
            write_to_output(of, choice, gm.str_pgrammar(pgrammar))
            continue

        elif choice == misc_choices[1]:
            print()
            gm.pprint(pgrammar)
            print()
            continue

        elif choice == misc_choices[2]:
            clear()
            continue

        if choice == misc_choices[3]:
            print(cf.cyan("Bye!"))
            print("Remember! Logs are saved in", of)
            print()
            break

        # --------

        if choice == choices[0]:
            output = elim_null(pgrammar)

        elif choice == choices[1]:
            output = elim_unit(pgrammar)
            output = remove_same_rules(output, False, False)

        elif choice == choices[2]:
            continuel = False
            for rule in pgrammar.values():
                if "eps" in rule:
                    print(
                        cf.red(
                            "\nGrammar contains null productions. This operation can't"
                            " be performed\n"))
                    continuel = True
                    break

            if continuel:
                continue

            answer = prompt(reverse_confirm)
            reverse = answer["reverse_grammar"]
            if reverse:
                print(
                    "\nReversing the order of non-terminals for Left Recursion Removal."
                )

                ng = gm.reverse_grammar(pgrammar)
            else:
                ng = pgrammar

            ng = elim_lr(ng)
            if reverse:
                ng = gm.reverse_grammar(ng)
            output = ng

        elif choice == choices[3]:
            fs = first_sets(pgrammar)
            output = fs

        elif choice == choices[4]:
            start_input["validate"] = lambda x: x in pgrammar.keys()
            answer = prompt(start_input)
            fs = first_sets(pgrammar)
            fls = follow_sets(answer["start_sym"], pgrammar, fs)
            output = fls

        elif choice == choices[5]:
            start_input["validate"] = lambda x: x in pgrammar.keys()
            answer = prompt(start_input)
            fs = first_sets(pgrammar)
            fls = follow_sets(answer["start_sym"], pgrammar, fs)

            output = parsing_table(pgrammar, fs, fls)

        if choice != choices[5]:

            # flag to check if the last operation output a pgrammar
            # only the first 3 operations output a grammar
            output_grammar = choices.index(choice) in range(3)

            # print output
            print(cf.bold_green("\n=>\n"))

            (gm.pprint if output_grammar else gm.set_print)(output)

            # log to the output file
            write_to_output(
                of,
                choice,
                (gm.str_pgrammar if output_grammar else gm.str_set)(output),
            )

            print()

            # ask to use grammar from last operation
            if output_grammar:
                answer = prompt(reuse_confirm)
                if answer["last_grammar"]:
                    pgrammar = output

        else:
            # print parsing table
            print("\n" + output + "\n")
            write_to_output(
                of,
                choice,
                output,
            )
Esempio n. 24
0
def test_step_matches_configs(match_config_files,
                              basedirs,
                              cover_min_percentage=None,
                              cover_show_missing=False):
    """
    Test if the given match config files matches the actual
    matched step implementations.
    """
    if cover_min_percentage is not None and float(cover_min_percentage) > 100:
        sys.stderr.write(
            str(
                colorful.magenta(
                    'You are a little cocky to think you can reach a minimum coverage of {0:.2f}%\n'
                    .format(float(cover_min_percentage)))))
        return 3

    # load user's custom python files
    for basedir in basedirs:
        load_modules(basedir)

    steps = StepRegistry().steps

    if not steps:
        sys.stderr.write(
            str(
                colorful.magenta(
                    'No step implementations found in {0}, thus doesn\'t make sense to continue'
                    .format(basedirs))))
        return 4

    failed = 0
    passed = 0
    covered_steps = set()

    for match_config_file in match_config_files:
        # load the given match config file
        with codecs.open(match_config_file, "r", "utf-8") as f:
            match_config = yaml.safe_load(f)

        if not match_config:
            print(
                colorful.magenta(
                    'No sentences found in {0} to test against'.format(
                        match_config_file)))
            return 5

        print(
            colorful.yellow('Testing sentences from {0}:'.format(
                colorful.bold_yellow(match_config_file))))
        failed_sentences, passed_senteces = test_step_matches(
            match_config, steps)
        failed += failed_sentences
        passed += passed_senteces

        covered_steps = covered_steps.union(x['should_match']
                                            for x in match_config
                                            if 'should_match' in x)

        # newline
        sys.stdout.write('\n')

    report = colorful.bold_white('{0} sentences ('.format(failed + passed))
    if passed > 0:
        report += colorful.bold_green('{0} passed'.format(passed))

    if passed > 0 and failed > 0:
        report += colorful.bold_white(', ')

    if failed > 0:
        report += colorful.bold_red('{0} failed'.format(failed))
    report += colorful.bold_white(')')
    print(report)

    step_coverage = 100.0 / len(steps) * len(covered_steps)
    coverage_report = colorful.bold_white(
        'Covered {0} of {1} step implementations'.format(
            len(covered_steps), len(steps)))

    ret = 0 if failed == 0 else 1

    if cover_min_percentage:
        coverage_color = colorful.bold_green if step_coverage >= float(
            cover_min_percentage) else colorful.bold_red
        coverage_report += colorful.bold_white(' (coverage: ')
        coverage_report += coverage_color('{0:.2f}%'.format(step_coverage))
        if float(cover_min_percentage) > step_coverage:
            coverage_report += colorful.bold_white(
                ', expected a minimum of {0}'.format(
                    colorful.bold_green(cover_min_percentage + '%')))
            if failed == 0:
                ret = 2
            # if tests have passed and coverage is too low we fail with exit code 2
        coverage_report += colorful.bold_white(')')

    print(coverage_report)

    if cover_show_missing:
        missing_steps = get_missing_steps(steps, covered_steps)
        if missing_steps:
            missing_step_report = colorful.bold_yellow('Missing steps:\n')
            for step in missing_steps:
                missing_step_report += '- {0} at '.format(
                    colorful.cyan(step[0]))
                missing_step_report += colorful.cyan(step[1]) + '\n'
            sys.stdout.write(missing_step_report)

    return ret
Esempio n. 25
0
    def console_writer_after_each_scenario(self, scenario):
        """
            If the scenario is a ExampleScenario it will write the Examples header

            :param Scenario scenario: the scenario which was ran.
        """
        output = ""
        if isinstance(scenario, ScenarioOutline):
            output += "\n    {0}:\n".format(
                colorful.bold_white(scenario.example_keyword)
            )
            output += colorful.bold_white(
                "        {0}| {1} |".format(
                    self.get_id_padding(len(scenario.scenarios), offset=2),
                    " | ".join(
                        "{1: <{0}}".format(scenario.get_column_width(i), x)
                        for i, x in enumerate(scenario.examples_header)
                    ),
                )
            )
        elif isinstance(scenario, ScenarioLoop):
            output += "\n    {0}: {1}".format(
                colorful.bold_white(scenario.iterations_keyword),
                colorful.cyan(scenario.iterations),
            )
        elif isinstance(scenario.parent, ScenarioOutline):
            colored_pipe = colorful.bold_white("|")
            color_func = self.get_color_func(scenario.state)
            output += "{0}        {1}{2} {3} {2}".format(
                self.get_line_jump_seq(),
                self.get_id_sentence_prefix(
                    scenario, colorful.bold_cyan, len(scenario.parent.scenarios)
                ),
                colored_pipe,
                (" {0} ")
                .format(colored_pipe)
                .join(
                    str(
                        color_func(
                            "{1: <{0}}".format(scenario.parent.get_column_width(i), x)
                        )
                    )
                    for i, x in enumerate(scenario.example.data)
                ),
            )

            if scenario.state == Step.State.FAILED:
                failed_step = scenario.failed_step
                if world.config.with_traceback:
                    output += "\n          {0}{1}".format(
                        self.get_id_padding(len(scenario.parent.scenarios)),
                        "\n          ".join(
                            [
                                str(colorful.red(l))
                                for l in failed_step.failure.traceback.split("\n")[:-2]
                            ]
                        ),
                    )
                output += "\n          {0}{1}: {2}".format(
                    self.get_id_padding(len(scenario.parent.scenarios)),
                    colorful.bold_red(failed_step.failure.name),
                    colorful.red(failed_step.failure.reason),
                )
        elif isinstance(scenario.parent, ScenarioLoop):
            colored_pipe = colorful.bold_white("|")
            color_func = self.get_color_func(scenario.state)
            output += "{0}        {1}{2} {3: <18} {2}".format(
                self.get_line_jump_seq(),
                self.get_id_sentence_prefix(
                    scenario, colorful.bold_cyan, len(scenario.parent.scenarios)
                ),
                colored_pipe,
                str(color_func(scenario.iteration)),
            )

            if scenario.state == Step.State.FAILED:
                failed_step = scenario.failed_step
                if world.config.with_traceback:
                    output += "\n          {0}{1}".format(
                        self.get_id_padding(len(scenario.parent.scenarios)),
                        "\n          ".join(
                            [
                                str(colorful.red(l))
                                for l in failed_step.failure.traceback.split("\n")[:-2]
                            ]
                        ),
                    )
                output += "\n          {0}{1}: {2}".format(
                    self.get_id_padding(len(scenario.parent.scenarios)),
                    colorful.bold_red(failed_step.failure.name),
                    colorful.red(failed_step.failure.reason),
                )

        if output:
            write(output)
Esempio n. 26
0
 def labeled_value(self, key, msg, *args, **kwargs):
     self._print(
         cf.cyan(key) + ": " + _format_msg(cf.bold(msg), *args, **kwargs))
Esempio n. 27
0
def _(value: Union[None, Number],
      seen: Set[int],
      show_values: bool = True,
      indent: int = 0,
      batch_dims: Optional[Tuple[Optional[int], ...]] = None) -> str:
    return cf.cyan(str(value)) + "\n"
Esempio n. 28
0
    def console_writer_after_each_step(self, step):
        """
            Writes the step to the console after it was run

            :param Step step: the step to write to the console
        """
        if not isinstance(step.parent.parent, Feature):
            return

        color_func = self.get_color_func(step.state)
        line_jump_seq = self.get_line_jump_seq() * (
            ((len(step.raw_text) + 3) if step.text else 1)
            + (len(step.table) + 1 if step.table_header else 0)
        )
        output = "{0}        ".format(line_jump_seq)

        if isinstance(step.parent, ScenarioOutline):
            # Highlight ScenarioOutline placeholders e.g. '<method>'
            output += "".join(
                str(
                    colorful.white(item)
                    if (
                        self._placeholder_regex.search(item)
                        and item.strip("<>") in step.parent.examples_header
                    )
                    else color_func(item)
                )
                for item in self._placeholder_regex.split(step.sentence)
            )
        else:
            output += "{0}{1}".format(
                self.get_id_sentence_prefix(step, colorful.bold_cyan),
                color_func(step.sentence),
            )

        if step.text:
            id_padding = self.get_id_padding(len(step.parent.steps))
            output += colorful.bold_white('\n            {0}"""'.format(id_padding))
            output += colorful.cyan(
                "".join(
                    [
                        "\n                {0}{1}".format(id_padding, l)
                        for l in step.raw_text
                    ]
                )
            )
            output += colorful.bold_white('\n            {0}"""'.format(id_padding))

        if step.table_header:
            colored_pipe = colorful.bold_white("|")
            col_widths = self.get_table_col_widths(
                [step.table_header] + step.table_data
            )

            # output table header
            output += "\n          {0} {1} {0}".format(
                colored_pipe,
                (" {0} ")
                .format(colored_pipe)
                .join(
                    str(colorful.white("{1: <{0}}".format(col_widths[i], x)))
                    for i, x in enumerate(step.table_header)
                ),
            )

            # output table data
            for row in step.table_data:
                output += "\n          {0} {1} {0}".format(
                    colored_pipe,
                    (" {0} ")
                    .format(colored_pipe)
                    .join(
                        str(color_func("{1: <{0}}".format(col_widths[i], x)))
                        for i, x in enumerate(row)
                    ),
                )

        if step.state == step.State.FAILED:
            if world.config.with_traceback:
                output += "\n          {0}{1}".format(
                    self.get_id_padding(len(step.parent.steps) - 2),
                    "\n          ".join(
                        [
                            str(colorful.red(l))
                            for l in step.failure.traceback.split("\n")[:-2]
                        ]
                    ),
                )
            output += "\n          {0}{1}: {2}".format(
                self.get_id_padding(len(step.parent.steps) - 2),
                colorful.bold_red(step.failure.name),
                colorful.red(step.failure.reason),
            )

        write(output)
Esempio n. 29
0
def test_step_matches_configs(
    match_config_files, basedirs, cover_min_percentage=None, cover_show_missing=False
):
    """
    Test if the given match config files matches the actual
    matched step implementations.
    """
    if cover_min_percentage is not None and float(cover_min_percentage) > 100:
        sys.stderr.write(
            str(
                colorful.magenta(
                    "You are a little cocky to think you can reach a minimum coverage of {0:.2f}%\n".format(
                        float(cover_min_percentage)
                    )
                )
            )
        )
        return 3

    # load user's custom python files
    for basedir in basedirs:
        load_modules(basedir)

    steps = StepRegistry().steps

    if not steps:
        sys.stderr.write(
            str(
                colorful.magenta(
                    "No step implementations found in {0}, thus doesn't make sense to continue".format(
                        basedirs
                    )
                )
            )
        )
        return 4

    failed = 0
    passed = 0
    covered_steps = set()

    for match_config_file in match_config_files:
        # load the given match config file
        with codecs.open(match_config_file, "r", "utf-8") as f:
            match_config = yaml.safe_load(f)

        if not match_config:
            print(
                colorful.magenta(
                    "No sentences found in {0} to test against".format(
                        match_config_file
                    )
                )
            )
            return 5

        print(
            colorful.yellow(
                "Testing sentences from {0}:".format(
                    colorful.bold_yellow(match_config_file)
                )
            )
        )
        failed_sentences, passed_senteces = test_step_matches(match_config, steps)
        failed += failed_sentences
        passed += passed_senteces

        covered_steps = covered_steps.union(
            x["should_match"] for x in match_config if "should_match" in x
        )

        # newline
        sys.stdout.write("\n")

    report = colorful.bold_white("{0} sentences (".format(failed + passed))
    if passed > 0:
        report += colorful.bold_green("{0} passed".format(passed))

    if passed > 0 and failed > 0:
        report += colorful.bold_white(", ")

    if failed > 0:
        report += colorful.bold_red("{0} failed".format(failed))
    report += colorful.bold_white(")")
    print(report)

    step_coverage = 100.0 / len(steps) * len(covered_steps)
    coverage_report = colorful.bold_white(
        "Covered {0} of {1} step implementations".format(len(covered_steps), len(steps))
    )

    ret = 0 if failed == 0 else 1

    if cover_min_percentage:
        coverage_color = (
            colorful.bold_green
            if step_coverage >= float(cover_min_percentage)
            else colorful.bold_red
        )
        coverage_report += colorful.bold_white(" (coverage: ")
        coverage_report += coverage_color("{0:.2f}%".format(step_coverage))
        if float(cover_min_percentage) > step_coverage:
            coverage_report += colorful.bold_white(
                ", expected a minimum of {0}".format(
                    colorful.bold_green(cover_min_percentage + "%")
                )
            )
            if failed == 0:
                ret = 2
            # if tests have passed and coverage is too low we fail with exit code 2
        coverage_report += colorful.bold_white(")")

    print(coverage_report)

    if cover_show_missing:
        missing_steps = get_missing_steps(steps, covered_steps)
        if missing_steps:
            missing_step_report = colorful.bold_yellow("Missing steps:\n")
            for step in missing_steps:
                missing_step_report += "- {0} at ".format(colorful.cyan(step[0]))
                missing_step_report += colorful.cyan(step[1]) + "\n"
            sys.stdout.write(missing_step_report)

    return ret
Esempio n. 30
0
    def console_writer_before_each_scenario(self, scenario):
        """
            Writes the scenario header to the console

            :param Scenario scenario: the scenario to write to the console
        """
        output = "\n"
        if isinstance(scenario.parent, ScenarioOutline):
            if world.config.write_steps_once:
                return

            id_prefix = self.get_id_sentence_prefix(
                scenario, colorful.bold_yellow, len(scenario.parent.scenarios)
            )
            colored_pipe = colorful.bold_white("|")
            output = "        {0}{1} {2} {1}".format(
                id_prefix,
                colored_pipe,
                (" {0} ")
                .format(colored_pipe)
                .join(
                    str(
                        colorful.bold_yellow(
                            "{1: <{0}}".format(scenario.parent.get_column_width(i), x)
                        )
                    )
                    for i, x in enumerate(scenario.example.data)
                ),
            )
        elif isinstance(scenario.parent, ScenarioLoop):
            if world.config.write_steps_once:
                return

            id_prefix = self.get_id_sentence_prefix(
                scenario, colorful.bold_yellow, len(scenario.parent.scenarios)
            )
            colored_pipe = colorful.bold_white("|")
            output = "        {0}{1} {2: <18} {1}".format(
                id_prefix, colored_pipe, str(colorful.bold_yellow(scenario.iteration))
            )
        else:
            id_prefix = self.get_id_sentence_prefix(scenario, colorful.bold_cyan)
            for tag in scenario.tags:
                if (
                    tag.name == "precondition"
                    and world.config.expand
                    and world.config.show
                ):  # exceptional for show command when scenario steps expand and tag is a precondition -> comment it out
                    output += colorful.white(
                        "    # @{0}{1}\n".format(
                            tag.name, "({0})".format(tag.arg) if tag.arg else ""
                        )
                    )
                else:
                    output += colorful.cyan(
                        "    @{0}{1}\n".format(
                            tag.name, "({0})".format(tag.arg) if tag.arg else ""
                        )
                    )
            output += "    {0}{1}: {2}".format(
                id_prefix,
                colorful.bold_white(scenario.keyword),
                colorful.bold_white(scenario.sentence),
            )
        write(output)
Esempio n. 31
0
from collections import namedtuple
import colorful

colorful.use_style("solarized")

SIZE = 9
LINE_LENGTH = (SIZE * 3) + 3
EMPTY = "-"
SHIP = "S"
HIT = "H"
MISS = "M"
SUNK = "Sunk"

BOARD_COLOURS = {
    SHIP: colorful.blue,
    HIT: colorful.red,
    MISS: colorful.violet,
    EMPTY: colorful.base02,
    "recent": colorful.yellow,
}

SEPERATOR = "  "
BOARD_SEPERATOR = colorful.cyan("  --|--  ")

PROMPT = colorful.orange(">>> ")

START_SHIPS = [7, 5, 4, 4, 3, 2]

Point = namedtuple("Point", "x y")
Ship = namedtuple("Ship", "position length orientation")
Esempio n. 32
0
print(cf.bold & cf.red | 'Hello World')

# use true colors
cf.use_true_colors()

# extend default color palette
cf.update_palette({'mint': '#c5e8c8'})
print(cf.mint_on_snow('Wow, this is actually mint'))

# choose a predefined style
cf.use_style('solarized')
# print the official solarized colors
print(cf.yellow('yellow'), cf.orange('orange'),
    cf.red('red'), cf.magenta('magenta'),
    cf.violet('violet'), cf.blue('blue'),
    cf.cyan('cyan'), cf.green('green'))

# directly print with colors
cf.print('{c.bold_blue}Hello World{c.reset}')

# choose specific color mode for one block
with cf.with_8_ansi_colors() as c:
    print(c.bold_green('colorful is awesome!'))

# create and choose your own color palette
MY_COMPANY_PALETTE = {
    'companyOrange': '#f4b942',
    'companyBaige': '#e8dcc5'
}
with cf.with_palette(my_company_palette) as c:
    print(c.companyOrange_on_companyBaige('Thanks for choosing our product!'))
Esempio n. 33
0
    def console_writer_after_each_scenario(self, scenario):
        """
            If the scenario is a ExampleScenario it will write the Examples header

            :param Scenario scenario: the scenario which was ran.
        """
        output = ""
        if isinstance(scenario, ScenarioOutline):
            output += u"\n    {0}:\n".format(
                colorful.bold_white(scenario.example_keyword))
            output += colorful.bold_white(u"        {0}| {1} |".format(
                self.get_id_padding(len(scenario.scenarios), offset=2),
                u" | ".join("{1: <{0}}".format(scenario.get_column_width(i), x)
                            for i, x in enumerate(scenario.examples_header))))
        elif isinstance(scenario, ScenarioLoop):
            output += u"\n    {0}: {1}".format(
                colorful.bold_white(scenario.iterations_keyword),
                colorful.cyan(scenario.iterations))
        elif isinstance(scenario.parent, ScenarioOutline):
            colored_pipe = colorful.bold_white("|")
            color_func = self.get_color_func(scenario.state)
            output += u"{0}        {1}{2} {3} {2}".format(
                self.get_line_jump_seq(),
                self.get_id_sentence_prefix(scenario, colorful.bold_cyan,
                                            len(scenario.parent.scenarios)),
                colored_pipe, (u" {0} ").format(colored_pipe).join(
                    str(
                        color_func(u"{1: <{0}}".format(
                            scenario.parent.get_column_width(i), x)))
                    for i, x in enumerate(scenario.example.data)))

            if scenario.state == Step.State.FAILED:
                failed_step = scenario.failed_step
                if world.config.with_traceback:
                    output += u"\n          {0}{1}".format(
                        self.get_id_padding(len(scenario.parent.scenarios)),
                        "\n          ".join([
                            str(colorful.red(l)) for l in
                            failed_step.failure.traceback.split("\n")[:-2]
                        ]))
                output += u"\n          {0}{1}: {2}".format(
                    self.get_id_padding(len(scenario.parent.scenarios)),
                    colorful.bold_red(failed_step.failure.name),
                    colorful.red(failed_step.failure.reason))
        elif isinstance(scenario.parent, ScenarioLoop):
            colored_pipe = colorful.bold_white("|")
            color_func = self.get_color_func(scenario.state)
            output += u"{0}        {1}{2} {3: <18} {2}".format(
                self.get_line_jump_seq(),
                self.get_id_sentence_prefix(scenario, colorful.bold_cyan,
                                            len(scenario.parent.scenarios)),
                colored_pipe, str(color_func(scenario.iteration)))

            if scenario.state == Step.State.FAILED:
                failed_step = scenario.failed_step
                if world.config.with_traceback:
                    output += u"\n          {0}{1}".format(
                        self.get_id_padding(len(scenario.parent.scenarios)),
                        "\n          ".join([
                            str(colorful.red(l)) for l in
                            failed_step.failure.traceback.split("\n")[:-2]
                        ]))
                output += u"\n          {0}{1}: {2}".format(
                    self.get_id_padding(len(scenario.parent.scenarios)),
                    colorful.bold_red(failed_step.failure.name),
                    colorful.red(failed_step.failure.reason))

        if output:
            write(output)
Esempio n. 34
0
    def console_writer_after_each_step(self, step):
        """
            Writes the step to the console after it was run

            :param Step step: the step to write to the console
        """
        if not isinstance(step.parent.parent, Feature):
            return

        color_func = self.get_color_func(step.state)
        line_jump_seq = self.get_line_jump_seq() * (
            ((len(step.raw_text) + 3) if step.text else 1) +
            (len(step.table) + 1 if step.table_header else 0))
        output = u'{0}        '.format(line_jump_seq)

        if isinstance(step.parent, ScenarioOutline):
            # Highlight ScenarioOutline placeholders e.g. '<method>'
            output += (u''.join(
                str(
                    colorful.white(item) if (
                        self._placeholder_regex.search(item)
                        and item.strip('<>') in step.parent.examples_header
                    ) else color_func(item))
                for item in self._placeholder_regex.split(step.sentence)))
        else:
            output += u"{0}{1}".format(
                self.get_id_sentence_prefix(step, colorful.bold_cyan),
                color_func(step.sentence))

        if step.text:
            id_padding = self.get_id_padding(len(step.parent.steps))
            output += colorful.bold_white(
                u'\n            {0}"""'.format(id_padding))
            output += colorful.cyan(u"".join([
                "\n                {0}{1}".format(id_padding, l)
                for l in step.raw_text
            ]))
            output += colorful.bold_white(
                u'\n            {0}"""'.format(id_padding))

        if step.table_header:
            colored_pipe = colorful.bold_white("|")
            col_widths = self.get_table_col_widths([step.table_header] +
                                                   step.table_data)

            # output table header
            output += u"\n          {0} {1} {0}".format(
                colored_pipe, (" {0} ").format(colored_pipe).join(
                    str(colorful.white(u"{1: <{0}}".format(col_widths[i], x)))
                    for i, x in enumerate(step.table_header)))

            # output table data
            for row in step.table_data:
                output += u"\n          {0} {1} {0}".format(
                    colored_pipe, (" {0} ").format(colored_pipe).join(
                        str(color_func(u"{1: <{0}}".format(col_widths[i], x)))
                        for i, x in enumerate(row)))

        if step.state == step.State.FAILED:
            if world.config.with_traceback:
                output += u"\n          {0}{1}".format(
                    self.get_id_padding(len(step.parent.steps) - 2),
                    "\n          ".join([
                        str(colorful.red(l))
                        for l in step.failure.traceback.split("\n")[:-2]
                    ]))
            output += u"\n          {0}{1}: {2}".format(
                self.get_id_padding(len(step.parent.steps) - 2),
                colorful.bold_red(step.failure.name),
                colorful.red(step.failure.reason))

        write(output)
Esempio n. 35
0
    def console_write(self, features, marker):
        """
            Writes the endreport for all features

            :param list features: all features
        """
        stats = {
            "features": {"amount": 0, "passed": 0, "failed": 0, "skipped": 0, "untested": 0, "pending": 0},
            "scenarios": {"amount": 0, "passed": 0, "failed": 0, "skipped": 0, "untested": 0, "pending": 0},
            "steps": {"amount": 0, "passed": 0, "failed": 0, "skipped": 0, "untested": 0, "pending": 0},
        }
        pending_steps = []
        duration = timedelta()
        for feature in features:
            if not feature.has_to_run(world.config.scenarios):
                continue
            stats["features"]["amount"] += 1
            stats["features"][feature.state] += 1

            if feature.state in [Step.State.PASSED, Step.State.FAILED]:
                duration += feature.duration

            for scenario in feature.all_scenarios:
                if not scenario.has_to_run(world.config.scenarios):
                    continue

                if isinstance(scenario, ScenarioOutline):  # skip ScenarioOutlines
                    continue
                if isinstance(scenario, ScenarioLoop):  # skip ScenarioLoop
                    continue

                stats["scenarios"]["amount"] += 1
                stats["scenarios"][scenario.state] += 1
                for step in scenario.steps:
                    stats["steps"]["amount"] += 1
                    stats["steps"][step.state] += 1

                    if step.state == Step.State.PENDING:
                        pending_steps.append(step)

        colored_closing_paren = colorful.bold_white(")")
        colored_comma = colorful.bold_white(", ")
        passed_word = colorful.bold_green("{0} passed")
        failed_word = colorful.bold_red("{0} failed")
        skipped_word = colorful.cyan("{0} skipped")
        pending_word = colorful.bold_yellow("{0} pending")

        output = colorful.bold_white("{0} features (".format(stats["features"]["amount"]))
        output += passed_word.format(stats["features"]["passed"])
        if stats["features"]["failed"]:
            output += colored_comma + failed_word.format(stats["features"]["failed"])
        if stats["features"]["skipped"]:
            output += colored_comma + skipped_word.format(stats["features"]["skipped"])
        if stats["features"]["pending"]:
            output += colored_comma + pending_word.format(stats["features"]["pending"])
        output += colored_closing_paren

        output += "\n"
        output += colorful.bold_white("{} scenarios (".format(stats["scenarios"]["amount"]))
        output += passed_word.format(stats["scenarios"]["passed"])
        if stats["scenarios"]["failed"]:
            output += colored_comma + failed_word.format(stats["scenarios"]["failed"])
        if stats["scenarios"]["skipped"]:
            output += colored_comma + skipped_word.format(stats["scenarios"]["skipped"])
        if stats["scenarios"]["pending"]:
            output += colored_comma + pending_word.format(stats["scenarios"]["pending"])
        output += colored_closing_paren

        output += "\n"
        output += colorful.bold_white("{} steps (".format(stats["steps"]["amount"]))
        output += passed_word.format(stats["steps"]["passed"])
        if stats["steps"]["failed"]:
            output += colored_comma + failed_word.format(stats["steps"]["failed"])
        if stats["steps"]["skipped"]:
            output += colored_comma + skipped_word.format(stats["steps"]["skipped"])
        if stats["steps"]["pending"]:
            output += colored_comma + pending_word.format(stats["steps"]["pending"])
        output += colored_closing_paren

        if pending_steps:
            sr = StepRegistry()
            pending_step_implementations = make_unique_obj_list(pending_steps, lambda x: x.definition_func)
            output += colorful.white("\nYou have {0} pending step implementation{1} affecting {2} step{3}:\n  {4}\n\nNote: this could be the reason for some failing subsequent steps".format(
                len(pending_step_implementations),
                "s" if len(pending_step_implementations) is not 1 else "",
                len(pending_steps),
                "s" if len(pending_steps) is not 1 else "",
                "\n  ".join(["-  '{0}' @ {1}".format(sr.get_pattern(s.definition_func), get_func_code(s.definition_func).co_filename) for s in pending_step_implementations])
            ))

        output += "\n"
        output += colorful.cyan("Run {0} finished within {1}".format(marker, humanize.naturaldelta(duration)))

        write(output)
Esempio n. 36
0
    def console_write(self, features, marker):
        """
            Writes the endreport for all features

            :param list features: all features
        """
        stats = {
            "features": {
                "amount": 0,
                "passed": 0,
                "failed": 0,
                "skipped": 0,
                "untested": 0,
                "pending": 0,
            },
            "scenarios": {
                "amount": 0,
                "passed": 0,
                "failed": 0,
                "skipped": 0,
                "untested": 0,
                "pending": 0,
            },
            "steps": {
                "amount": 0,
                "passed": 0,
                "failed": 0,
                "skipped": 0,
                "untested": 0,
                "pending": 0,
            },
        }
        pending_steps = []
        duration = timedelta()
        for feature in features:
            if not feature.has_to_run(world.config.scenarios):
                continue
            stats["features"]["amount"] += 1
            stats["features"][feature.state] += 1

            if feature.state in [Step.State.PASSED, Step.State.FAILED]:
                duration += feature.duration

            for scenario in feature.all_scenarios:
                if not scenario.has_to_run(world.config.scenarios):
                    continue

                if isinstance(scenario, ScenarioOutline):  # skip ScenarioOutlines
                    continue
                if isinstance(scenario, ScenarioLoop):  # skip ScenarioLoop
                    continue

                stats["scenarios"]["amount"] += 1
                stats["scenarios"][scenario.state] += 1
                for step in scenario.steps:
                    stats["steps"]["amount"] += 1
                    stats["steps"][step.state] += 1

                    if step.state == Step.State.PENDING:
                        pending_steps.append(step)

        colored_closing_paren = colorful.bold_white(")")
        colored_comma = colorful.bold_white(", ")
        passed_word = colorful.bold_green("{0} passed")
        failed_word = colorful.bold_red("{0} failed")
        skipped_word = colorful.cyan("{0} skipped")
        pending_word = colorful.bold_yellow("{0} pending")

        output = colorful.bold_white(
            "{0} features (".format(stats["features"]["amount"])
        )
        output += passed_word.format(stats["features"]["passed"])
        if stats["features"]["failed"]:
            output += colored_comma + failed_word.format(stats["features"]["failed"])
        if stats["features"]["skipped"]:
            output += colored_comma + skipped_word.format(stats["features"]["skipped"])
        if stats["features"]["pending"]:
            output += colored_comma + pending_word.format(stats["features"]["pending"])
        output += colored_closing_paren

        output += "\n"
        output += colorful.bold_white(
            "{} scenarios (".format(stats["scenarios"]["amount"])
        )
        output += passed_word.format(stats["scenarios"]["passed"])
        if stats["scenarios"]["failed"]:
            output += colored_comma + failed_word.format(stats["scenarios"]["failed"])
        if stats["scenarios"]["skipped"]:
            output += colored_comma + skipped_word.format(stats["scenarios"]["skipped"])
        if stats["scenarios"]["pending"]:
            output += colored_comma + pending_word.format(stats["scenarios"]["pending"])
        output += colored_closing_paren

        output += "\n"
        output += colorful.bold_white("{} steps (".format(stats["steps"]["amount"]))
        output += passed_word.format(stats["steps"]["passed"])
        if stats["steps"]["failed"]:
            output += colored_comma + failed_word.format(stats["steps"]["failed"])
        if stats["steps"]["skipped"]:
            output += colored_comma + skipped_word.format(stats["steps"]["skipped"])
        if stats["steps"]["pending"]:
            output += colored_comma + pending_word.format(stats["steps"]["pending"])
        output += colored_closing_paren

        if pending_steps:
            sr = StepRegistry()
            pending_step_implementations = make_unique_obj_list(
                pending_steps, lambda x: x.definition_func
            )
            output += colorful.white(
                "\nYou have {0} pending step implementation{1} affecting {2} step{3}:\n  {4}\n\nNote: this could be the reason for some failing subsequent steps".format(
                    len(pending_step_implementations),
                    "s" if len(pending_step_implementations) is not 1 else "",
                    len(pending_steps),
                    "s" if len(pending_steps) is not 1 else "",
                    "\n  ".join(
                        [
                            "-  '{0}' @ {1}".format(
                                sr.get_pattern(s.definition_func),
                                get_func_code(s.definition_func).co_filename,
                            )
                            for s in pending_step_implementations
                        ]
                    ),
                )
            )

        output += "\n"

        if world.config.wip:
            if stats["scenarios"]["passed"] > 0:
                output += colorful.red(
                    "\nThe --wip switch was used, so I didn't expect anything to pass. These scenarios passed:\n"
                )

                has_passed_scenarios = False
                for feature in features:
                    passed_scenarios = list(
                        filter(
                            lambda s: s.state == Step.State.PASSED,
                            feature.all_scenarios,
                        )
                    )
                    for scenario in passed_scenarios:
                        output += colorful.red(
                            "\n - {}: {}".format(feature.path, scenario.sentence)
                        )
                        has_passed_scenarios = True

                if has_passed_scenarios:
                    output += "\n"
            else:
                output += colorful.green(
                    "\nThe --wip switch was used, so the failures were expected. All is good.\n"
                )

        output += colorful.cyan(
            "Run {0} finished within {1}".format(
                marker, humanize.naturaldelta(duration)
            )
        )

        write(output)
Esempio n. 37
0
def add_keyboards(config):
  for key, value in config["keyboards"].items():
      logger.info("Running script to add keyboard for keyboard " + colorful.cyan(key) + "...")
      print("")  # Padding
      system("cd " + getcwd() + " && python3 -m " + MODULE_NAME + " add " + key)
      print("")  # Padding
Esempio n. 38
0
 def debug(self, text):
     if not self.silent and self.isDebug:
         print(
             colorful.magenta(self.name) + " " + colorful.cyan("debug") +
             " " + str(text))
Esempio n. 39
0
def style_prompt(text):
    return colorful.bold_cyan(f'{text}', nested=True)


def style_text(text):
    return colorful.white(f'{text}', nested=True)


def style_highlight(text):
    return colorful.bold(f'{text}', nested=True)


NOT = 'NOT'
NEW_LINE = '\n'
ARROW = colorful.cyan('>', nested=True) + colorful.cyanLight(
    '>', nested=True) + style_text('>')


def info(text):
    print(NEW_LINE + style_info(text) + NEW_LINE)


def warn(text):
    print(NEW_LINE + style_warn(text) + NEW_LINE)


def error(text):
    print(NEW_LINE + style_error(text) + NEW_LINE)