Skip to content

Commit

Permalink
docstrings: fix newly reported pep257 violations
Browse files Browse the repository at this point in the history
Change-Id: I129ea28b43375131876479f505b3431341cf20d1
  • Loading branch information
volans- committed Jul 19, 2019
1 parent ce88641 commit 988d3f3
Show file tree
Hide file tree
Showing 10 changed files with 62 additions and 23 deletions.
5 changes: 5 additions & 0 deletions cumin/backends/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ def __init__(self, config):
Arguments:
config (dict): a dictionary with the parsed configuration file.
"""
self.config = config
self.logger = logging.getLogger('.'.join((self.__module__, self.__class__.__name__)))
Expand Down Expand Up @@ -61,13 +62,15 @@ def _parse_token(self, token):
Arguments:
token (pyparsing.ParseResults): a single token returned by the grammar parsing.
"""

def _build(self, query_string):
"""Parse the query string according to the grammar and build the query for later execution.
Arguments:
query_string (str): the query string to be parsed.
"""
self.logger.trace('Parsing query: %s', query_string)
parsed = self.grammar.parseString(query_string.strip(), parseAll=True)
Expand Down Expand Up @@ -156,6 +159,7 @@ def _loop_stack(self, hosts, stack_element):
hosts (ClusterShell.NodeSet.NodeSet): the hosts to be updated with the current stack element results. This
object is updated in place by reference.
stack_element (dict): the stack element to iterate.
"""
if stack_element['hosts'] is None:
element_hosts = nodeset()
Expand All @@ -176,6 +180,7 @@ def _aggregate_hosts(self, hosts, element_hosts, bool_operator):
``bool_operator``.
bool_operator (str, None): the boolean operator to apply while aggregating the two NodeSet. It must be
:py:data:`None` when adding the first hosts.
"""
self.logger.trace("Aggregating: %s | %s | %s", hosts, bool_operator, element_hosts)

Expand Down
4 changes: 3 additions & 1 deletion cumin/backends/puppetdb.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,9 +35,10 @@ class ParsedString:
def __init__(self, string, is_quoted):
"""Constructor for ParsedString.
Args:
Arguments:
string (str): The string to store in this object.
is_quoted (bool): Whether the output should be quoted when this is converted to a string.
"""
self.string = str(string)
self.is_quoted = is_quoted
Expand Down Expand Up @@ -360,6 +361,7 @@ def _add_hosts(self, hosts, neg=False):
Arguments:
hosts (ClusterShell.NodeSet.NodeSet): with the list of hosts to search.
neg (bool, optional): whether the token must be negated.
"""
if not hosts:
return
Expand Down
7 changes: 7 additions & 0 deletions cumin/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -220,6 +220,8 @@ def setup_logging(filename, debug=False, trace=False):
Arguments:
filename: the filename of the log file
debug: whether to set logging level to DEBUG [optional, default: False]
trace: whether to set logging level to TRACE [optional, default: False]
"""
file_path = os.path.dirname(filename)
if file_path and not os.path.exists(file_path):
Expand Down Expand Up @@ -288,6 +290,7 @@ def stderr(message, end='\n'):
Arguments:
message: the message to print to sys.stderr
end: the character to use at the end of the message. [optional, default: \n]
"""
tqdm.write('{color}{message}{reset}'.format(
color=colorama.Fore.YELLOW, message=message, reset=colorama.Style.RESET_ALL), file=sys.stderr, end=end)
Expand All @@ -299,6 +302,7 @@ def get_hosts(args, config):
Arguments:
args: ArgumentParser instance with parsed command line arguments
config: a dictionary with the parsed configuration file
"""
hosts = query.Query(config).execute(args.hosts)

Expand Down Expand Up @@ -346,6 +350,7 @@ def print_output(output_format, worker):
Arguments:
output_format: the output format to use, one of: 'txt', 'json'.
worker: the Transport worker instance to retrieve the results from.
"""
if output_format not in OUTPUT_FORMATS:
raise cumin.CuminError("Got invalid output format '{fmt}', expected one of {allowed}".format(
Expand All @@ -372,6 +377,7 @@ def run(args, config):
Arguments:
args: ArgumentParser instance with parsed command line arguments
config: a dictionary with the parsed configuration file
"""
hosts = get_hosts(args, config)
if not hosts:
Expand Down Expand Up @@ -427,6 +433,7 @@ def main(argv=None):
Arguments:
argv: the list of command line arguments to use. If not specified it will be automatically taken from sys.argv
[optional, default: None]
"""
if argv is None:
argv = sys.argv[1:]
Expand Down
2 changes: 2 additions & 0 deletions cumin/tests/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ def get_fixture(path, as_string=False):
Arguments:
path: the relative path to the test's fixture directory to be opened.
as_string: return the content as a multiline string instead of a list of lines [optional, default: False]
"""
with open(get_fixture_path(path)) as f:
if as_string:
Expand All @@ -28,5 +29,6 @@ def get_fixture_path(path):
Arguments:
path: the relative path to the test's fixture directory.
"""
return os.path.join(_TESTS_BASE_PATH, 'fixtures', path)
8 changes: 7 additions & 1 deletion cumin/tests/integration/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ def make_method(name, commands_set):

@pytest.mark.variant_params(params)
def test_variant(self, capsys):
"""Test variant generated function"""
"""Test variant generated function."""
argv = self.default_params + params['params'] + [self.all_nodes] + params['commands']
rc = cli.main(argv=argv)
out, err = capsys.readouterr()
Expand Down Expand Up @@ -195,6 +195,7 @@ def get_rc(params):
Arguments:
params: a dictionary with all the parameters passed to the variant_function
"""
return_value = 2
if '-p' in params['params'] and '--global-timeout' not in params['params']:
Expand All @@ -208,6 +209,7 @@ def get_global_timeout_expected_lines(params): # pylint: disable=invalid-name
Arguments:
params: a dictionary with all the parameters passed to the variant_function
"""
expected = []
if '--global-timeout' not in params['params']:
Expand All @@ -226,6 +228,7 @@ def get_timeout_expected_lines(params):
Arguments:
params: a dictionary with all the parameters passed to the variant_function
"""
expected = []
if '-t' not in params['params']:
Expand All @@ -252,6 +255,7 @@ def get_date_expected_lines(params):
Arguments:
params: a dictionary with all the parameters passed to the variant_function
"""
expected = []
if 'ls -la /tmp/non_existing' in params['commands']:
Expand All @@ -273,6 +277,7 @@ def get_ls_expected_lines(params):
Arguments:
params: a dictionary with all the parameters passed to the variant_function
"""
expected = []
if 'ls -la /tmp' in params['commands']:
Expand Down Expand Up @@ -321,6 +326,7 @@ def _get_nodes(self, nodes):
Arguments:
nodes: a string with the NodeSet nodes selection
"""
if nodes is None:
return self.all_nodes
Expand Down
2 changes: 1 addition & 1 deletion cumin/tests/unit/transports/__init__.py
Original file line number Diff line number Diff line change
@@ -1 +1 @@
"""Transport specific tests"""
"""Transport specific tests."""
12 changes: 6 additions & 6 deletions cumin/tests/unit/transports/test_clustershell.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ class TestClusterShellWorker:

@mock.patch('cumin.transports.clustershell.Task.task_self')
def setup_method(self, _, task_self): # pylint: disable=arguments-differ
"""Initialize default properties and instances"""
"""Initialize default properties and instances."""
self.config = {
'clustershell': {
'ssh_options': ['-o StrictHostKeyChecking=no', '-o BatchMode=yes'],
Expand Down Expand Up @@ -137,13 +137,13 @@ def test_get_results(self):
assert output == 'output 9'

def test_handler_getter(self):
"""Access to handler property should return the handler class or None"""
"""Access to handler property should return the handler class or None."""
assert self.worker.handler is None
self.worker.handler = 'sync'
assert self.worker._handler == clustershell.DEFAULT_HANDLERS['sync']

def test_handler_setter_invalid(self):
"""Raise WorkerError if trying to set it to an invalid class or value"""
"""Raise WorkerError if trying to set it to an invalid class or value."""
class InvalidClass:
"""Invalid class."""

Expand All @@ -156,17 +156,17 @@ class InvalidClass:
self.worker.handler = InvalidClass

def test_handler_setter_default_sync(self):
"""Should set the handler to the default handler for the sync mode"""
"""Should set the handler to the default handler for the sync mode."""
self.worker.handler = 'sync'
assert self.worker._handler == clustershell.DEFAULT_HANDLERS['sync']

def test_handler_setter_default_async(self):
"""Should set the handler to the default handler for the async mode"""
"""Should set the handler to the default handler for the async mode."""
self.worker.handler = 'async'
assert self.worker._handler == clustershell.DEFAULT_HANDLERS['async']

def test_handler_setter_custom(self):
"""Should set the handler to the given custom class that inherit from BaseEventHandler"""
"""Should set the handler to the given custom class that inherit from BaseEventHandler."""
self.worker.handler = ConcreteBaseEventHandler
assert self.worker._handler == ConcreteBaseEventHandler

Expand Down
18 changes: 9 additions & 9 deletions cumin/tests/unit/transports/test_init.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,20 +16,20 @@ class ConcreteBaseWorker(transports.BaseWorker):
"""Concrete class for BaseWorker."""

def execute(self):
"""Required by BaseWorker"""
"""Required by BaseWorker."""

def get_results(self):
"""Required by BaseWorker"""
"""Required by BaseWorker."""
yield "node", "output"

@property
def handler(self):
"""Required by BaseWorker"""
"""Required by BaseWorker."""
return self._handler

@handler.setter
def handler(self, value):
"""Required by BaseWorker"""
"""Required by BaseWorker."""
self._handler = value


Expand Down Expand Up @@ -542,10 +542,10 @@ def test_raise_error(self):

@mock.patch('cumin.transports.tqdm')
class TestProgressBars:
"""A class that tests ProgressBars"""
"""A class that tests ProgressBars."""

def test_init_intialize_progress_bars_with_correct_size(self, tqdm):
"""Progress bars are initialized at the correct size"""
"""Progress bars are initialized at the correct size."""
progress = ProgressBars()
progress.init(10)

Expand All @@ -554,7 +554,7 @@ def test_init_intialize_progress_bars_with_correct_size(self, tqdm):
assert kwargs['total'] == 10

def test_progress_bars_are_closed(self, tqdm): # pylint: disable=unused-argument
"""Progress bars are closed"""
"""Progress bars are closed."""
progress = ProgressBars()
progress.init(10)

Expand All @@ -564,7 +564,7 @@ def test_progress_bars_are_closed(self, tqdm): # pylint: disable=unused-argumen
assert progress.pbar_ko.close.called # pylint: disable=no-member

def test_progress_bar_is_updated_on_success(self, tqdm): # pylint: disable=unused-argument
"""Progress bar is updated on success"""
"""Progress bar is updated on success."""
progress = ProgressBars()
progress.init(10)

Expand All @@ -573,7 +573,7 @@ def test_progress_bar_is_updated_on_success(self, tqdm): # pylint: disable=unus
assert progress.pbar_ok.update.called_once_with(5) # pylint: disable=no-member

def test_progress_bar_is_updated_on_failure(self, tqdm): # pylint: disable=unused-argument
"""Progress bar is updated on failure"""
"""Progress bar is updated on failure."""
progress = ProgressBars()
progress.init(10)

Expand Down
17 changes: 12 additions & 5 deletions cumin/transports/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ def __init__(self, command, timeout=None, ok_codes=None):
ok_codes (list, optional): a list of exit codes to be considered successful for the command.
The exit code zero is considered successful by default, if this option is set it override it. If set
to an empty list ``[]``, it means that any code is considered successful.
"""
self.command = command
self._timeout = None
Expand Down Expand Up @@ -388,7 +389,8 @@ def _cmp(self, other):
Raises ValueError if the comparing object is not an instance of State or an integer.
Arguments:
other -- the object to compare the current instance to
other (mixed): the object to compare the current instance to.
"""
if isinstance(other, int):
return self._state - other
Expand Down Expand Up @@ -510,6 +512,7 @@ def __init__(self, config, target):
Arguments:
config (dict): a dictionary with the parsed configuration file.
target (Target): a Target instance.
"""
self.config = config
self.target = target
Expand Down Expand Up @@ -716,6 +719,7 @@ def raise_error(property_name, message, value):
property_name (str): the name of the property that raised the exception.
message (str): the message to use for the exception.
value (mixed): the value that raised the exception.
"""
raise WorkerError("{property_name} {message}, got '{value_type}': {value}".format(
property_name=property_name, message=message, value_type=type(value), value=value))
Expand Down Expand Up @@ -744,6 +748,7 @@ def init(self, num_hosts):
Arguments:
num_hosts (int): the total number of hosts
"""
self.pbar_ok = tqdm(desc='PASS', total=num_hosts, leave=True, unit='hosts', dynamic_ncols=True,
bar_format=colorama.Fore.GREEN + self.bar_format, file=sys.stderr)
Expand All @@ -762,6 +767,7 @@ def update_success(self, num_hosts=1):
Arguments:
num_hosts (int): increment to the number of hosts that have completed successfully
"""
self.pbar_ok.update(num_hosts)

Expand All @@ -770,6 +776,7 @@ def update_failed(self, num_hosts=1):
Arguments:
num_hosts (int): increment to the number of hosts that have completed in error
"""
self.pbar_ko.update(num_hosts)

Expand All @@ -778,13 +785,13 @@ class NoProgress:
"""Used as a null object to disable the display of progress bars."""

def init(self, num_hosts):
"""Does nothing"""
"""Does nothing."""

def close(self):
"""Does nothing"""
"""Does nothing."""

def update_success(self, num_hosts=1):
"""Does nothing"""
"""Does nothing."""

def update_failed(self, num_hosts=1):
"""Does nothing"""
"""Does nothing."""

0 comments on commit 988d3f3

Please sign in to comment.