How to use step_command_output_should_not_contain_log_records_from_categories 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.

steps.py

Source: steps.py Github

copy
1"""
2Provides step definitions to perform tests with the Python logging subsystem.
3"""
4
5import logging
6
7from behave import step, then
8from behave.configuration import LogLevel
9from behave4cmd0.command_steps import (
10    step_file_should_contain_multiline_text,
11    step_file_should_not_contain_multiline_text,
12)
13
14
15def make_log_record(category, level, message):
16    if category in ("root", "__ROOT__"):
17        category = None
18    logger = logging.getLogger(category)
19    logger.log(level, message)
20
21
22def make_log_record_output(
23    category, level, message, format=None, datefmt=None, **kwargs
24):
25    """
26    Create the output for a log record, like performed by :mod:`logging` module.
27
28    :param category:    Name of the logger (as string or None).
29    :param level:       Log level (as number).
30    :param message:     Log message to use.
31    :returns: Log record output (as string)
32    """
33    if not category or (category == "__ROOT__"):
34        category = "root"
35    levelname = logging.getLevelName(level)
36    record_data = dict(name=category, levelname=levelname, msg=message)
37    record_data.update(kwargs)
38    record = logging.makeLogRecord(record_data)
39    formatter = logging.Formatter(format, datefmt=datefmt)
40    return formatter.format(record)
41
42
43class LogRecordTable(object):
44    @classmethod
45    def make_output_for_row(cls, row, format=None, datefmt=None, **kwargs):
46        category = row.get("category", None)
47        level = LogLevel.parse_type(row.get("level", "INFO"))
48        message = row.get("message", "__UNDEFINED__")
49        return make_log_record_output(
50            category, level, message, format, datefmt, **kwargs
51        )
52
53    @staticmethod
54    def annotate_with_row_schema(table, row_schema):
55        """
56        Annotate/extend a table of log-records with additional columns from
57        the log-record schema if columns are missing.
58
59        :param table:   Table w/ log-records (as :class:`behave.model.Table`)
60        :param row_schema:  Log-record row schema (as dict).
61        """
62        for column, value in row_schema.items():
63            if column not in table.headings:
64                table.add_column(column, default_value=value)
65
66
67@step("I create log records with")
68def step_I_create_logrecords_with_table(context):
69    """
70    Step definition that creates one more log records by using a table.
71
72    .. code-block: gherkin
73
74        When I create log records with:
75            | category | level | message   |
76            |  foo     | ERROR | Hello Foo |
77            |  foo.bar | WARN  | Hello Foo.Bar |
78
79    Table description
80    ------------------
81
82    | Column   | Type     | Required | Description |
83    | category | string   | yes      | Category (or logger) to use. |
84    | level    | LogLevel | yes      | Log level to use.   |
85    | message  | string   | yes      | Log message to use. |
86
87    .. code-block: python
88
89        import logging
90        from behave.configuration import LogLevel
91        for row in table.rows:
92            logger = logging.getLogger(row.category)
93            level  = LogLevel.parse_type(row.level)
94            logger.log(level, row.message)
95    """
96    assert context.table, "REQUIRE: context.table"
97    context.table.require_columns(["category", "level", "message"])
98    for row in context.table.rows:
99        category = row["category"]
100        if category == "__ROOT__":
101            category = None
102        level = LogLevel.parse_type(row["level"])
103        message = row["message"]
104        make_log_record(category, level, message)
105
106
107@step("I create a log record with")
108def step_I_create_logrecord_with_table(context):
109    """
110    Create an log record by using a table to provide the parts.
111
112    .. seealso: :func:`step_I_create_logrecords_with_table()`
113    """
114    assert context.table, "REQUIRE: context.table"
115    assert len(context.table.rows) == 1, "REQUIRE: table.row.size == 1"
116    step_I_create_logrecords_with_table(context)
117
118
119@step("I define the log record schema")
120def step_I_define_logrecord_schema_with_table(context):
121    assert context.table, "REQUIRE: context.table"
122    context.table.require_columns(["category", "level", "message"])
123    assert len(context.table.rows) == 1, "REQUIRE: context.table.rows.size(%s) == 1" % (
124        len(context.table.rows)
125    )
126
127    row = context.table.rows[0]
128    row_schema = {
129        "category": row["category"],
130        "level": row["level"],
131        "message": row["message"],
132    }
133    context.log_record_row_schema = row_schema
134
135
136@then("the command output should contain the following log records")
137def step_command_output_should_contain_log_records(context):
138    """
139    Verifies that the command output contains the specified log records
140    (in any order).
141
142    .. code-block: gherkin
143
144        Then the command output should contain the following log records:
145            | category | level   | message |
146            | bar      | CURRENT | xxx     |
147    """
148    assert context.table, "REQUIRE: context.table"
149    context.table.require_columns(["category", "level", "message"])
150    format = getattr(context, "log_record_format", context.config.logging_format)
151    for row in context.table.rows:
152        output = LogRecordTable.make_output_for_row(row, format)
153        context.execute_steps(
154            u'''
155            Then the command output should contain:
156                """
157                {expected_output}
158                """
159            '''.format(
160                expected_output=output
161            )
162        )
163
164
165@then("the command output should not contain the following log records")
166def step_command_output_should_not_contain_log_records(context):
167    """
168    Verifies that the command output contains the specified log records
169    (in any order).
170
171    .. code-block: gherkin
172
173        Then the command output should contain the following log records:
174            | category | level   | message |
175            | bar      | CURRENT | xxx     |
176    """
177    assert context.table, "REQUIRE: context.table"
178    context.table.require_columns(["category", "level", "message"])
179    format = getattr(context, "log_record_format", context.config.logging_format)
180    for row in context.table.rows:
181        output = LogRecordTable.make_output_for_row(row, format)
182        context.execute_steps(
183            u'''
184            Then the command output should not contain:
185                """
186                {expected_output}
187                """
188            '''.format(
189                expected_output=output
190            )
191        )
192
193
194@then("the command output should contain the following log record")
195def step_command_output_should_contain_log_record(context):
196    assert context.table, "REQUIRE: context.table"
197    assert len(context.table.rows) == 1, "REQUIRE: table.row.size == 1"
198    step_command_output_should_contain_log_records(context)
199
200
201@then("the command output should not contain the following log record")
202def step_command_output_should_not_contain_log_record(context):
203    assert context.table, "REQUIRE: context.table"
204    assert len(context.table.rows) == 1, "REQUIRE: table.row.size == 1"
205    step_command_output_should_not_contain_log_records(context)
206
207
208@then("the command output should contain log records from categories")
209def step_command_output_should_contain_log_records_from_categories(context):
210    """
211    Verifies that the command output contains the specified log records
212    (in any order).
213
214    .. code-block: gherkin
215
216        Given I define a log record schema:
217            | category | level | message |
218            | root     | ERROR | __LOG_MESSAGE__ |
219        Then the command output should contain log records from categories:
220            | category |
221            | bar      |
222    """
223    assert context.table, "REQUIRE: context.table"
224    context.table.require_column("category")
225    record_schema = context.log_record_row_schema
226    LogRecordTable.annotate_with_row_schema(context.table, record_schema)
227    step_command_output_should_contain_log_records(context)
228    context.table.remove_columns(["level", "message"])
229
230
231@then("the command output should not contain log records from categories")
232def step_command_output_should_not_contain_log_records_from_categories(context):
233    """
234    Verifies that the command output contains not log records from
235    the provided log categories (in any order).
236
237    .. code-block: gherkin
238
239        Given I define the log record schema:
240            | category | level | message |
241            | root     | ERROR | __LOG_MESSAGE__ |
242        Then the command output should not contain log records from categories:
243            | category |
244            | bar      |
245    """
246    assert context.table, "REQUIRE: context.table"
247    context.table.require_column("category")
248    record_schema = context.log_record_row_schema
249    LogRecordTable.annotate_with_row_schema(context.table, record_schema)
250    step_command_output_should_not_contain_log_records(context)
251    context.table.remove_columns(["level", "message"])
252
253
254@then('the file "{filename}" should contain the log records')
255def step_file_should_contain_log_records(context, filename):
256    """
257    Verifies that the command output contains the specified log records
258    (in any order).
259
260    .. code-block: gherkin
261
262        Then the file "xxx.log" should contain the log records:
263            | category | level   | message |
264            | bar      | CURRENT | xxx     |
265    """
266    assert context.table, "REQUIRE: context.table"
267    context.table.require_columns(["category", "level", "message"])
268    format = getattr(context, "log_record_format", context.config.logging_format)
269    for row in context.table.rows:
270        output = LogRecordTable.make_output_for_row(row, format)
271        context.text = output
272        step_file_should_contain_multiline_text(context, filename)
273
274
275@then('the file "{filename}" should not contain the log records')
276def step_file_should_not_contain_log_records(context, filename):
277    """
278    Verifies that the command output contains the specified log records
279    (in any order).
280
281    .. code-block: gherkin
282
283        Then the file "xxx.log" should not contain the log records:
284            | category | level   | message |
285            | bar      | CURRENT | xxx     |
286    """
287    assert context.table, "REQUIRE: context.table"
288    context.table.require_columns(["category", "level", "message"])
289    format = getattr(context, "log_record_format", context.config.logging_format)
290    for row in context.table.rows:
291        output = LogRecordTable.make_output_for_row(row, format)
292        context.text = output
293        step_file_should_not_contain_multiline_text(context, filename)
294
295
296@step('I use "{log_record_format}" as log record format')
297def step_use_log_record_format_text(context, log_record_format):
298    context.log_record_format = log_record_format
299
300
301@step("I use the log record configuration")
302def step_use_log_record_configuration(context):
303    """
304    Define log record configuration parameters.
305
306    .. code-block: gherkin
307
308        Given I use the log record configuration:
309            | property | value |
310            | format   |       |
311            | datefmt  |       |
312    """
313    assert context.table, "REQUIRE: context.table"
314    context.table.require_columns(["property", "value"])
315    for row in context.table.rows:
316        property_name = row["property"]
317        value = row["value"]
318        if property_name == "format":
319            context.log_record_format = value
320        elif property_name == "datefmt":
321            context.log_record_datefmt = value
322        else:
323            raise KeyError("Unknown property=%s" % property_name)
324
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)