How to use print_formatters method in Behave

Best Python code snippet using behave

Run Behave automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

editor.py

Source: editor.py Github

copy
1import sys
2from itertools import chain
3
4
5class MarkDown:
6    def __init__(self) -> None:
7        self.user_input = ""
8        self.formatted = []
9        self.commands = ["!help", "!done"]
10        self.help = [
11            "Available formatters: plain bold italic header link inline-code ordered-list unordered-list new-line",
12            "Special commands: !help !done",
13        ]
14        self.formatters = {
15            "plain": self.plain,
16            "bold": self.bold,
17            "italic": self.italic,
18            "header": self.header,
19            "link": self.link,
20            "inline-code": self.inline,
21            "ordered-list": self.list,
22            "unordered-list": self.list,
23            "new-line": self.new_line,
24        }
25
26    def handle_user_input(self) -> None:
27        while "!done" not in (user_input := input("- Choose a formatter: ")):
28            self.user_input = user_input
29
30            if self.user_input not in chain(self.commands, self.formatters):
31                print("Unknown formatting type or command. Please try again")
32                continue
33            elif self.user_input == self.commands[0]:
34                print(*self.help, sep="\n")
35            elif self.user_input in self.formatters:
36                self.handle_formatters_call()
37
38        self.save_file()
39
40        self.exit_program()
41
42    def print_formatters(self) -> None:
43        print(*self.formatted, sep="")
44
45    def handle_formatters_call(self) -> None:
46        self.formatters[self.user_input]()
47        self.print_formatters()
48
49    def plain(self) -> None:
50        self.formatted.append(input("- Text: "))
51
52    def bold(self) -> None:
53        string_formatted = f"**{input('- Text: ')}**"
54        self.formatted.append(string_formatted)
55
56    def italic(self) -> None:
57        string_formatted = f"*{input('- Text: ')}*"
58        self.formatted.append(string_formatted)
59
60    def header(self) -> None:
61        header_level = "#" * int(input("- Level: "))
62        string_formatted = f"{header_level} {input('- Text: ')}\n"
63        self.formatted.append(string_formatted)
64
65    def link(self) -> None:
66        label = input("- Label: ")
67        url = input("- URL: ")
68        string_formatted = f"[{label}]({url})"
69        self.formatted.append(string_formatted)
70
71    def inline(self) -> None:
72        string_formatted = f"`{input('- Text: ')}`"
73        self.formatted.append(string_formatted)
74
75    def list(self) -> None:
76        while True:
77            try:
78                rows = int(input("- Number of rows: "))
79                if rows < 1:
80                    raise ValueError
81
82            except ValueError:
83                print("The number of rows should be greater than zero")
84                continue
85
86            is_ordered = self.user_input == "ordered-list"
87
88            for n in range(rows):
89                number = n + 1
90                text = f"{input(f'- Row #{number}: ')}"
91                string_formatted = (
92                    f"{number}. {text}\n" if is_ordered else f"* {text}\n"
93                )
94                self.formatted.append(string_formatted)
95
96            break
97
98    def new_line(self) -> None:
99        self.formatted.append("\n")
100
101    def save_file(self):
102        with open("output.md", "w") as file:
103            file.writelines(self.formatted)
104
105    @staticmethod
106    def exit_program() -> None:
107        sys.exit()
108
109
110if __name__ == "__main__":
111    md = MarkDown()
112    md.handle_user_input()
113
Full Screen

__main__.py

Source: __main__.py Github

copy
1# -*- coding: utf-8 -*-
2
3from __future__ import absolute_import, print_function
4from behave import __version__
5from behave.configuration import Configuration, ConfigError
6from behave.parser import ParserError
7from behave.runner import Runner
8from behave.runner_util import print_undefined_step_snippets, \
9    InvalidFileLocationError, InvalidFilenameError, FileNotFoundError
10from behave.textutil import text as _text
11import sys
12
13
14TAG_HELP = """
15Scenarios inherit tags declared on the Feature level. The simplest
16TAG_EXPRESSION is simply a tag::
17
18    --tags @dev
19
20You may even leave off the "@" - behave doesn't mind.
21
22When a tag in a tag expression starts with a ~, this represents boolean NOT::
23
24    --tags [email protected]
25
26A tag expression can have several tags separated by a comma, which represents
27logical OR::
28
29    --tags @dev,@wip
30
31The --tags option can be specified several times, and this represents logical
32AND, for instance this represents the boolean expression
33"(@foo or not @bar) and @zap"::
34
35    --tags @foo,[email protected] --tags @zap.
36
37Beware that if you want to use several negative tags to exclude several tags
38you have to use logical AND::
39
40    --tags [email protected] --tags [email protected]
41""".strip()
42
43# TODO
44# Positive tags can be given a threshold to limit the number of occurrences.
45# Which can be practical if you are practicing Kanban or CONWIP. This will fail
46# if there are more than 3 occurrences of the @qa tag:
47#
48# --tags @qa:3
49# """.strip()
50
51
52def main(args=None):
53    config = Configuration(args)
54    if config.version:
55        print("behave " + __version__)
56        return 0
57
58    if config.tags_help:
59        print(TAG_HELP)
60        return 0
61
62    if config.lang_list:
63        from behave.i18n import languages
64        iso_codes = languages.keys()
65        iso_codes.sort()
66        print("Languages available:")
67        for iso_code in iso_codes:
68            native = languages[iso_code]['native'][0]
69            name = languages[iso_code]['name'][0]
70            print(u'%s: %s / %s' % (iso_code, native, name))
71        return 0
72
73    if config.lang_help:
74        from behave.i18n import languages
75        if config.lang_help not in languages:
76            print('%s is not a recognised language: try --lang-list' % \
77                    config.lang_help)
78            return 1
79        trans = languages[config.lang_help]
80        print(u"Translations for %s / %s" % (trans['name'][0],
81                                             trans['native'][0]))
82        for kw in trans:
83            if kw in 'name native'.split():
84                continue
85            print(u'%16s: %s' % (kw.title().replace('_', ' '),
86                  u', '.join(w for w in trans[kw] if w != '*')))
87        return 0
88
89    if not config.format:
90        config.format = [ config.default_format ]
91    elif config.format and "format" in config.defaults:
92        # -- CASE: Formatter are specified in behave configuration file.
93        #    Check if formatter are provided on command-line, too.
94        if len(config.format) == len(config.defaults["format"]):
95            # -- NO FORMATTER on command-line: Add default formatter.
96            config.format.append(config.default_format)
97    if 'help' in config.format:
98        print_formatters("Available formatters:")
99        return 0
100
101    if len(config.outputs) > len(config.format):
102        print('CONFIG-ERROR: More outfiles (%d) than formatters (%d).' % \
103              (len(config.outputs), len(config.format)))
104        return 1
105
106    failed = True
107    runner = Runner(config)
108    try:
109        failed = runner.run()
110    except ParserError as e:
111        print(u"ParseError: %s" % e)
112    except ConfigError as e:
113        print(u"ConfigError: %s" % e)
114    except FileNotFoundError as e:
115        print(u"FileNotFoundError: %s" % e)
116    except InvalidFileLocationError as e:
117        print(u"InvalidFileLocationError: %s" % e)
118    except InvalidFilenameError as e:
119        print(u"InvalidFilenameError: %s" % e)
120    except Exception as e:
121        # -- DIAGNOSTICS:
122        text = _text(e)
123        print(u"Exception %s: %s" % (e.__class__.__name__, text))
124        raise
125
126    if config.show_snippets and runner.undefined_steps:
127        print_undefined_step_snippets(runner.undefined_steps,
128                                      colored=config.color)
129
130    return_code = 0
131    if failed:
132        return_code = 1
133    return return_code
134
135def print_formatters(title=None, stream=None):
136    """
137    Prints the list of available formatters and their description.
138
139    :param title:   Optional title (as string).
140    :param stream:  Optional, output stream to use (default: sys.stdout).
141    """
142    from behave.formatter._registry  import format_items
143    from behave.textutil import compute_words_maxsize, text as _text
144    from operator import itemgetter
145
146    if stream is None:
147        stream = sys.stdout
148    if title:
149        stream.write(u"%s\n" % title)
150
151    format_items = sorted(format_items(resolved=True), key=itemgetter(0))
152    format_names = [item[0]  for item in format_items]
153    column_size = compute_words_maxsize(format_names)
154    schema = u"  %-"+ _text(column_size) +"s  %s\n"
155    for name, formatter_class in format_items:
156        formatter_description = getattr(formatter_class, "description", "")
157        stream.write(schema % (name, formatter_description))
158
159
160if __name__ == '__main__':
161    # -- EXAMPLE: main("--version")
162    sys.exit(main())
163
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

Run Python Tests on LambdaTest Cloud Grid

Execute automation tests with Behave on a cloud-based Grid of 3000+ real browsers and operating systems for both web and mobile applications.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)