Skip to content

Commit

Permalink
Pylint related cleanups.
Browse files Browse the repository at this point in the history
  • Loading branch information
jenisys committed Oct 29, 2016
1 parent 204103c commit f5c84fa
Show file tree
Hide file tree
Showing 32 changed files with 246 additions and 227 deletions.
1 change: 1 addition & 0 deletions behave/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
from behave.step_registry import * # pylint: disable=wildcard-import
from behave.matchers import use_step_matcher, step_matcher, register_type

# pylint: disable=undefined-all-variable
__all__ = [
"given", "when", "then", "step", "use_step_matcher", "register_type",
"Given", "When", "Then", "Step",
Expand Down
10 changes: 7 additions & 3 deletions behave/_stepimport.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,15 @@
instead of using the global module specific variables.
"""

from behave import step_registry as _step_registry
# from behave import matchers as _matchers
from __future__ import absolute_import
from contextlib import contextmanager
from threading import Lock
from types import ModuleType
import os.path
import sys
from behave import step_registry as _step_registry
# from behave import matchers as _matchers
import six
from types import ModuleType


# -----------------------------------------------------------------------------
Expand Down Expand Up @@ -53,6 +54,7 @@ class StepRegistryModule(FakeModule):
]

def __init__(self, step_registry):
super(StepRegistryModule, self).__init__()
self.registry = step_registry
setup_api_with_step_decorators(self, step_registry)

Expand All @@ -61,6 +63,7 @@ class StepMatchersModule(FakeModule):
__all__ = ["use_step_matcher", "register_type", "step_matcher"]

def __init__(self, matcher_factory):
super(StepMatchersModule, self).__init__()
self.matcher_factory = matcher_factory
setup_api_with_matcher_functions(self, matcher_factory)
self.use_default_step_matcher = matcher_factory.use_default_step_matcher
Expand Down Expand Up @@ -100,6 +103,7 @@ def __init__(self, step_registry, matcher_factory=None):
if matcher_factory is None:
matcher_factory = step_registry.step_matcher_factory
assert matcher_factory is not None
super(BehaveModule, self).__init__()
setup_api_with_step_decorators(self, step_registry)
setup_api_with_matcher_functions(self, matcher_factory)
self.use_default_step_matcher = matcher_factory.use_default_step_matcher
Expand Down
3 changes: 2 additions & 1 deletion behave/_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ def has_traceback(cls, exception):
def describe(cls, exception, use_traceback=False, prefix=""):
# -- NORMAL CASE:
text = u"{prefix}{0}: {1}\n".format(exception.__class__.__name__,
exception, prefix=prefix)
exception, prefix=prefix)
if use_traceback:
exc_traceback = cls.get_traceback(exception)
if exc_traceback:
Expand Down Expand Up @@ -84,6 +84,7 @@ def set_cause(exception, exc_cause):
assert isinstance(exc_cause, Exception) or exc_cause is None
exception.__cause__ = exc_cause

# pylint: disable=arguments-differ
@classmethod
def describe(cls, exception, use_traceback=False, prefix="", style="reversed"):
"""Describes an exception, optionally together with its traceback info.
Expand Down
23 changes: 14 additions & 9 deletions behave/api/async_step.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
# -*- coding: UTF-8 -*-
# pylint: disable=line-too-long
"""
This module provides functionality to support "async steps" (coroutines)
in a step-module with behave. This functionality simplifies to test
Expand Down Expand Up @@ -40,13 +41,18 @@ def step_async_step_waits_seconds2(context, duration):
.. _asyncio.coroutines: https://docs.python.org/3/library/asyncio-task.html#coroutines
"""
# pylint: enable=line-too-long

from __future__ import print_function
# -- REQUIRES: Python >= 3.4
# MAYBE BACKPORT: trollius
import asyncio
import functools
from six import string_types
try:
import asyncio
has_asyncio = True
except ImportError:
has_asyncio = False

# -----------------------------------------------------------------------------
# ASYNC STEP DECORATORS:
Expand Down Expand Up @@ -121,7 +127,7 @@ def step_decorator(astep_func, context, *args, **kwargs):
# MAYBE: should_close = True
task = loop.create_task(astep_func(context, *args, **kwargs))
done, pending = loop.run_until_complete(
asyncio.wait([task], timeout=timeout))
asyncio.wait([task], timeout=timeout))
assert not pending, "TIMEOUT-OCCURED: timeout=%s" % timeout
finally:
if loop and should_close:
Expand All @@ -135,11 +141,10 @@ def wrapped_decorator1(astep_func):
@functools.wraps(astep_func)
def wrapped_decorator2(context, *args, **kwargs):
return step_decorator(astep_func, context, *args,
_loop=loop,
_timeout=timeout,
_async_context=async_context,
_should_close=should_close,
**kwargs)
_loop=loop,
_timeout=timeout,
_async_context=async_context,
_should_close=should_close, **kwargs)
assert callable(astep_func)
return wrapped_decorator2
return wrapped_decorator1
Expand All @@ -159,6 +164,7 @@ def wrapped_decorator(context, *args, **kwargs):
# ASYNC STEP UTILITY CLASSES:
# -----------------------------------------------------------------------------
class AsyncContext(object):
# pylint: disable=line-too-long
"""Provides a context object for "async steps" to keep track:
* which event loop is used
Expand Down Expand Up @@ -210,6 +216,7 @@ async def my_async_func(param):
await asyncio.sleep(0.5)
return param.upper()
"""
# pylint: enable=line-too-long
default_name = "async_context"

def __init__(self, loop=None, name=None, should_close=False, tasks=None):
Expand Down Expand Up @@ -274,5 +281,3 @@ async def my_async_func(param):
assert isinstance(async_context, AsyncContext)
assert getattr(context, async_context.name) is async_context
return async_context


2 changes: 1 addition & 1 deletion behave/compat/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,4 @@
"""
Used for behave as compatibility layer between different Python versions
and implementations.
"""
"""
2 changes: 1 addition & 1 deletion behave/compat/collections.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

from __future__ import absolute_import
import warnings

# pylint: disable=unused-import
try:
# -- SINCE: Python2.7
from collections import OrderedDict
Expand Down
19 changes: 11 additions & 8 deletions behave/contrib/scenario_autoretry.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
# -*- coding: UTF -*-
# pylint: disable=line-too-long
"""
Provides support functionality to retry scenarios a number of times before
their failure is accepted. This functionality can be helpful when you use
Provides support functionality to retry scenarios a number of times before
their failure is accepted. This functionality can be helpful when you use
behave tests in a unreliable server/network infrastructure.
EXAMPLE:
Expand All @@ -27,19 +28,19 @@ def before_feature(context, feature):
if "autoretry" in scenario.effective_tags:
patch_scenario_with_autoretry(scenario, max_attempts=2)
.. seealso::
.. seealso::
* https://github.com/behave/behave/pull/328
* https://github.com/hypothesis/smokey/blob/sauce-reliability/smokey/features/environment.py
"""

from __future__ import print_function
from behave.model import ScenarioOutline
import functools
from behave.model import ScenarioOutline


def patch_scenario_with_autoretry(scenario, max_attempts=3):
"""Monkey-patches :func:`~behave.model.Scenario.run()` to auto-retry a
scenario that fails. The scenario is retried a number of times
"""Monkey-patches :func:`~behave.model.Scenario.run()` to auto-retry a
scenario that fails. The scenario is retried a number of times
before its failure is accepted.
This is helpful when the test infrastructure (server/network environment)
Expand All @@ -52,12 +53,14 @@ def scenario_run_with_retries(scenario_run, *args, **kwargs):
for attempt in range(1, max_attempts+1):
if not scenario_run(*args, **kwargs):
if attempt > 1:
print(u"AUTO-RETRY SCENARIO PASSED (after {0} attempts)".format(attempt))
message = u"AUTO-RETRY SCENARIO PASSED (after {0} attempts)"
print(message.format(attempt))
return False # -- NOT-FAILED = PASSED
# -- SCENARIO FAILED:
if attempt < max_attempts:
print(u"AUTO-RETRY SCENARIO (attempt {0})".format(attempt))
print(u"AUTO-RETRY SCENARIO FAILED (after {0} attempts)".format(max_attempts))
message = u"AUTO-RETRY SCENARIO FAILED (after {0} attempts)"
print(message.format(max_attempts))
return True

if isinstance(scenario, ScenarioOutline):
Expand Down
1 change: 0 additions & 1 deletion behave/formatter/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,3 @@
# MODULE-INIT:
# -----------------------------------------------------------------------------
_builtins.setup_formatters()

1 change: 1 addition & 0 deletions behave/formatter/_builtins.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
# -----------------------------------------------------------------------------
# SCHEMA: formatter.name, formatter.class(_name)
_BUILTIN_FORMATS = [
# pylint: disable=bad-whitespace
("plain", "behave.formatter.plain:PlainFormatter"),
("pretty", "behave.formatter.pretty:PrettyFormatter"),
("json", "behave.formatter.json:JSONFormatter"),
Expand Down
13 changes: 7 additions & 6 deletions behave/formatter/_registry.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
# -*- coding: utf-8 -*-

import sys
import warnings
from behave.formatter.base import Formatter, StreamOpener
from behave.importer import LazyDict, LazyObject, parse_scoped_name, load_module
import six
import sys
import warnings


# -----------------------------------------------------------------------------
Expand Down Expand Up @@ -33,7 +33,8 @@ def register_as(name, formatter_class):
"""
if not isinstance(name, six.string_types):
# -- REORDER-PARAMS: Used old ordering before behave-1.2.5 (2015).
warnings.warn("Use parameter ordering: name, formatter_class (for: %s)" % formatter_class)
warnings.warn("Use parameter ordering: name, formatter_class (for: %s)"\
% formatter_class)
_formatter_class = name
name = formatter_class
formatter_class = _formatter_class
Expand All @@ -49,12 +50,12 @@ def register_as(name, formatter_class):
def register(formatter_class):
register_as(formatter_class.name, formatter_class)

def register_formats(format_items):
def register_formats(formats):
"""Register many format items into the registry.
:param format_items: List of format items (as: (name, class|class_name)).
:param formats: List of format items (as: (name, class|class_name)).
"""
for formatter_name, formatter_class_name in format_items:
for formatter_name, formatter_class_name in formats:
register_as(formatter_name, formatter_class_name)

def load_formatter_class(scoped_class_name):
Expand Down
67 changes: 34 additions & 33 deletions behave/formatter/ansi_escapes.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,45 +8,45 @@
import re

colors = {
'black': u"\x1b[30m",
'red': u"\x1b[31m",
'green': u"\x1b[32m",
'yellow': u"\x1b[33m",
'blue': u"\x1b[34m",
'magenta': u"\x1b[35m",
'cyan': u"\x1b[36m",
'white': u"\x1b[37m",
'grey': u"\x1b[90m",
'bold': u"\x1b[1m",
"black": u"\x1b[30m",
"red": u"\x1b[31m",
"green": u"\x1b[32m",
"yellow": u"\x1b[33m",
"blue": u"\x1b[34m",
"magenta": u"\x1b[35m",
"cyan": u"\x1b[36m",
"white": u"\x1b[37m",
"grey": u"\x1b[90m",
"bold": u"\x1b[1m",
}

aliases = {
'untested': 'cyan', # SAME-COLOR AS: skipped
'undefined': 'yellow',
'pending': 'yellow',
'executing': 'grey',
'failed': 'red',
'passed': 'green',
'outline': 'cyan',
'skipped': 'cyan',
'comments': 'grey',
'tag': 'cyan',
"untested": "cyan", # SAME-COLOR AS: skipped
"undefined": "yellow",
"pending": "yellow",
"executing": "grey",
"failed": "red",
"passed": "green",
"outline": "cyan",
"skipped": "cyan",
"comments": "grey",
"tag": "cyan",
}

escapes = {
'reset': u'\x1b[0m',
'up': u'\x1b[1A',
"reset": u"\x1b[0m",
"up": u"\x1b[1A",
}

if 'GHERKIN_COLORS' in os.environ:
new_aliases = [p.split('=') for p in os.environ['GHERKIN_COLORS'].split(':')]
if "GHERKIN_COLORS" in os.environ:
new_aliases = [p.split("=") for p in os.environ["GHERKIN_COLORS"].split(":")]
aliases.update(dict(new_aliases))

for alias in aliases:
escapes[alias] = ''.join([colors[c] for c in aliases[alias].split(',')])
arg_alias = alias + '_arg'
arg_seq = aliases.get(arg_alias, aliases[alias] + ',bold')
escapes[arg_alias] = ''.join([colors[c] for c in arg_seq.split(',')])
escapes[alias] = "".join([colors[c] for c in aliases[alias].split(",")])
arg_alias = alias + "_arg"
arg_seq = aliases.get(arg_alias, aliases[alias] + ",bold")
escapes[arg_alias] = "".join([colors[c] for c in arg_seq.split(",")])


def up(n):
Expand All @@ -72,19 +72,20 @@ def use_ansi_escape_colorbold_composites(): # pragma: no cover
Reapply aliases to ANSI escapes mapping.
"""
global escapes
# NOT-NEEDED: global escapes
color_codes = {}
for color_name, color_escape in colors.items():
color_code = color_escape.replace(u"\x1b[", u"").replace(u"m", u"")
color_codes[color_name] = color_code

# pylint: disable=redefined-outer-name
for alias in aliases:
parts = [ color_codes[c] for c in aliases[alias].split(',') ]
parts = [color_codes[c] for c in aliases[alias].split(",")]
composite_escape = u"\x1b[{0}m".format(u";".join(parts))
escapes[alias] = composite_escape

arg_alias = alias + '_arg'
arg_seq = aliases.get(arg_alias, aliases[alias] + ',bold')
parts = [ color_codes[c] for c in arg_seq.split(',') ]
arg_alias = alias + "_arg"
arg_seq = aliases.get(arg_alias, aliases[alias] + ",bold")
parts = [color_codes[c] for c in arg_seq.split(",")]
composite_escape = u"\x1b[{0}m".format(u";".join(parts))
escapes[arg_alias] = composite_escape
3 changes: 2 additions & 1 deletion behave/formatter/formatters.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,9 @@
Deprecated, use "behave.formatter._registry" or "behave.formatter._builtin".
"""

from behave.formatter import _registry
from __future__ import absolute_import
import warnings
from behave.formatter import _registry

warnings.simplefilter("once", DeprecationWarning)
warnings.warn("Use 'behave.formatter._registry' instead.", DeprecationWarning)
Expand Down
6 changes: 3 additions & 3 deletions behave/formatter/json.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,9 @@
"""

from __future__ import absolute_import
import base64
from behave.formatter.base import Formatter
from behave.model_core import Status
import base64
import six
try:
import json
Expand Down Expand Up @@ -102,7 +102,7 @@ def scenario(self, scenario):
def make_table(cls, table):
table_data = {
"headings": table.headings,
"rows": [ list(row) for row in table.rows ]
"rows": [list(row) for row in table.rows]
}
return table_data

Expand Down Expand Up @@ -250,4 +250,4 @@ class PrettyJSONFormatter(JSONFormatter):
"""
name = "json.pretty"
description = "JSON dump of test run (human readable)"
dumps_kwargs = { "indent": 2, "sort_keys": True }
dumps_kwargs = {"indent": 2, "sort_keys": True}

0 comments on commit f5c84fa

Please sign in to comment.