You're Invited:Meet the Socket Team at RSAC and BSidesSF 2026, March 23–26.RSVP
Socket
Book a DemoSign in
Socket

clustercron

Package Overview
Dependencies
Maintainers
1
Versions
42
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

clustercron - pypi Package Compare versions

Comparing version
1.0.0
to
1.0.1
+1
-1
.github/workflows/ci.yml

@@ -84,2 +84,2 @@ ---

- name: Import package
run: python -c 'import clustercron'
run: python -c 'from clustercron.version import get_version; print(get_version())'

@@ -26,3 +26,3 @@ # .pre-commit-config.yaml

- repo: https://github.com/pycqa/isort
rev: 5.9.3
rev: 5.10.1
hooks:

@@ -33,3 +33,3 @@ - id: isort

- repo: https://github.com/psf/black
rev: 21.9b0
rev: 21.11b1
hooks:

@@ -44,3 +44,3 @@ - id: black

- repo: https://github.com/asottile/setup-cfg-fmt
rev: v1.18.0
rev: v1.20.0
hooks:

@@ -47,0 +47,0 @@ - id: setup-cfg-fmt

@@ -18,4 +18,4 @@ # .readthedocs.yaml

python:
version: "3.8"
version: "3.9"
install:
- requirements: docs/requirements.txt

@@ -55,2 +55,10 @@ clustercron package

clustercron.version module
--------------------------
.. automodule:: clustercron.version
:members:
:undoc-members:
:show-inheritance:
Module contents

@@ -57,0 +65,0 @@ ---------------

# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from clustercron.version import get_version

@@ -25,11 +25,11 @@ #

project = 'Clustercron'
copyright = '2019, Maarten'
author = 'Maarten'
project = "Clustercron"
copyright = "2021, Maarten"
author = "Maarten"
# The short X.Y version
version = '0.5'
# The full version, including alpha/beta/rc tags
release = '0.5.4'
release = get_version()
# The short X.Y version
version = ".".join(release.split(".")[:2])

@@ -46,7 +46,7 @@ # -- General configuration ---------------------------------------------------

extensions = [
'sphinx.ext.autodoc',
"sphinx.ext.autodoc",
]
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
templates_path = ["_templates"]

@@ -57,6 +57,6 @@ # The suffix(es) of source filenames.

# source_suffix = ['.rst', '.md']
source_suffix = '.rst'
source_suffix = ".rst"
# The master toctree document.
master_doc = 'index'
master_doc = "index"

@@ -73,6 +73,6 @@ # The language for content autogenerated by Sphinx. Refer to documentation

# This pattern also affects html_static_path and html_extra_path.
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']
exclude_patterns = ["_build", "Thumbs.db", ".DS_Store"]
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
pygments_style = "sphinx"

@@ -85,3 +85,3 @@

#
html_theme = 'sphinx_rtd_theme'
html_theme = "sphinx_rtd_theme"

@@ -97,3 +97,3 @@ # Theme options are theme-specific and customize the look and feel of a theme

# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
html_static_path = ["_static"]

@@ -114,3 +114,3 @@ # Custom sidebar templates, must be a dictionary that maps document names

# Output file base name for HTML help builder.
htmlhelp_basename = 'Clustercrondoc'
htmlhelp_basename = "Clustercrondoc"

@@ -141,6 +141,6 @@

master_doc,
'Clustercron.tex',
'Clustercron Documentation',
'Maarten',
'manual',
"Clustercron.tex",
"Clustercron Documentation",
"Maarten",
"manual",
),

@@ -155,3 +155,3 @@ ]

man_pages = [
(master_doc, 'clustercron', 'Clustercron Documentation', [author], 1)
(master_doc, "clustercron", "Clustercron Documentation", [author], 1)
]

@@ -168,8 +168,8 @@

master_doc,
'Clustercron',
'Clustercron Documentation',
"Clustercron",
"Clustercron Documentation",
author,
'Clustercron',
'One line description of project.',
'Miscellaneous',
"Clustercron",
"One line description of project.",
"Miscellaneous",
),

@@ -194,5 +194,5 @@ ]

# A list of files that should not be packed into the epub file.
epub_exclude_files = ['search.html']
epub_exclude_files = ["search.html"]
# -- Extension configuration -------------------------------------------------

@@ -71,3 +71,3 @@ # Makefile

test: ## Run tests quickly with the default Python.
pytest --cov=$(PACKAGE)
python -m pytest --cov=$(PACKAGE)

@@ -80,6 +80,6 @@ .PHONY: tox

coverage: clean-test ## Check code coverage quickly with the default Python.
coverage erase
coverage run --source $(PACKAGE) -m pytest
coverage report -m
coverage html
python -m coverage erase
python -m coverage run --source $(PACKAGE) -m pytest
python -m coverage report -m
python -m coverage html
$(BROWSER) htmlcov/index.html

@@ -97,3 +97,3 @@

upload: ## Upload package to Python Package Index (PyPI).
twine upload dist/*
python -m twine upload dist/*

@@ -107,6 +107,6 @@ .PHONY: build

devenv: ## Install package development mode + dependencies.
pip install -U pip wheel setuptools
pip install -e ".[dev]"
python -m pip install -U pip wheel setuptools
python -m pip install -e ".[dev]"
.PHONY: release
release: clean tox build upload ## Release package: test, build and upload to PyPI.
Metadata-Version: 2.1
Name: clustercron
Version: 1.0.0
Version: 1.0.1
Summary: Cron job wrapper that ensures a script gets run from one node in the cluster.

@@ -5,0 +5,0 @@ Home-page: https://github.com/maartenq/clustercron

@@ -9,3 +9,2 @@ # pyproject.toml

line-length = 79
skip-string-normalization = true

@@ -12,0 +11,0 @@ [tool.isort]

@@ -40,3 +40,3 @@ [metadata]

setup_requires =
setuptools_scm
setuptools-scm
test_suite = tests

@@ -43,0 +43,0 @@ zip_safe = False

Metadata-Version: 2.1
Name: clustercron
Version: 1.0.0
Version: 1.0.1
Summary: Cron job wrapper that ensures a script gets run from one node in the cluster.

@@ -5,0 +5,0 @@ Home-page: https://github.com/maartenq/clustercron

# -*- coding: utf-8 -*-
# vim: ts=4 et sw=4 sts=4 ft=python fenc=UTF-8 ai
__author__ = 'Maarten'
__email__ = 'ikmaarten@gmail.com'
__author__ = "Maarten"
__email__ = "ikmaarten@gmail.com"

@@ -5,3 +5,3 @@ # clustercron/alb.py

'''
"""
clustercron.alb

@@ -11,3 +11,3 @@ ---------------

Modules holds class for AWS ElasticLoadBalancing v2 (ALB)
'''
"""

@@ -29,12 +29,12 @@ from __future__ import unicode_literals

target_health = []
logger.debug('Get instance health states')
logger.debug("Get instance health states")
try:
client = boto3.client('elbv2')
client = boto3.client("elbv2")
except NoRegionError as error:
if self.region_name is None:
logger.error('%s', error)
logger.error("%s", error)
return target_health
else:
client = boto3.client(
'elbv2',
"elbv2",
region_name=self.region_name,

@@ -46,3 +46,3 @@ )

logger.error(
'Could not get TargetGroup `%s`: %s',
"Could not get TargetGroup `%s`: %s",
self.name,

@@ -53,8 +53,8 @@ error,

try:
targetgroup_arn = targetgroups.get('TargetGroups')[0][
'TargetGroupArn'
targetgroup_arn = targetgroups.get("TargetGroups")[0][
"TargetGroupArn"
]
except Exception as error:
logger.error(
'Could not get TargetGroupArn for `%s`: %s',
"Could not get TargetGroupArn for `%s`: %s",
self.name,

@@ -64,3 +64,3 @@ error,

else:
logger.debug('targetgroup_arn: %s' % targetgroup_arn)
logger.debug("targetgroup_arn: %s" % targetgroup_arn)
try:

@@ -71,3 +71,3 @@ target_health = client.describe_target_health(

except Exception as error:
logger.error('Could not get target health: %s', error)
logger.error("Could not get target health: %s", error)
return target_health

@@ -79,15 +79,15 @@

if target_health:
logger.debug('Instance health states: %s', target_health)
logger.debug("Instance health states: %s", target_health)
try:
healty_instances = sorted(
x['Target']['Id']
for x in target_health.get('TargetHealthDescriptions')
if x['TargetHealth']['State'] == 'healthy'
x["Target"]["Id"]
for x in target_health.get("TargetHealthDescriptions")
if x["TargetHealth"]["State"] == "healthy"
)
except Exception as error:
logger.error('Could not parse healty_instances: %s', error)
logger.error("Could not parse healty_instances: %s", error)
else:
logger.info(
'Healty instances: %s', ', '.join(healty_instances)
"Healty instances: %s", ", ".join(healty_instances)
)
return healty_instances

@@ -5,6 +5,6 @@ # clustercron/cache.py

'''
"""
clustercron.cache
-----------------
'''
"""

@@ -36,9 +36,9 @@ from __future__ import unicode_literals

self.master = False
self.dct = {'master': self.master, 'isodate': datetime(1970, 1, 1)}
self.dct = {"master": self.master, "isodate": datetime(1970, 1, 1)}
@staticmethod
def json_serial(obj):
'''
"""
JSON serializer for objects not serializable by default json code
'''
"""
if isinstance(obj, datetime):

@@ -52,9 +52,9 @@ serial = obj.isoformat()

try:
dct['isodate'] = datetime.strptime(
dct['isodate'], '%Y-%m-%dT%H:%M:%S.%f'
dct["isodate"] = datetime.strptime(
dct["isodate"], "%Y-%m-%dT%H:%M:%S.%f"
)
except ValueError as error:
logger.warning('Different isodate JSON format: %s', error)
dct['isodate'] = datetime.strptime(
dct['isodate'], '%Y-%m-%dT%H:%M:%S'
logger.warning("Different isodate JSON format: %s", error)
dct["isodate"] = datetime.strptime(
dct["isodate"], "%Y-%m-%dT%H:%M:%S"
)

@@ -65,4 +65,4 @@ return dct

self.dct = {
'master': self.master,
'isodate': datetime.now(),
"master": self.master,
"isodate": datetime.now(),
}

@@ -72,3 +72,3 @@

self.dct = json.load(fp, object_hook=self.iso2datetime_hook)
self.master = self.dct['master']
self.master = self.dct["master"]

@@ -85,3 +85,3 @@ def safe_json(self, fp):

def expired(self, expire_time):
return datetime.now() - self.dct['isodate'] > timedelta(
return datetime.now() - self.dct["isodate"] > timedelta(
seconds=int(expire_time)

@@ -98,4 +98,4 @@ )

try:
logger.debug('Open cache file for read/write (try %s).', i + 1)
fp = io.open(filename, 'r+')
logger.debug("Open cache file for read/write (try %s).", i + 1)
fp = io.open(filename, "r+")
file_exists = True

@@ -105,6 +105,6 @@ except IOError as error:

raise
logger.debug('No cache file. Open new cache file for write.')
fp = io.open(filename, 'w')
logger.debug("No cache file. Open new cache file for write.")
fp = io.open(filename, "w")
try:
logger.debug('Lock cache file.')
logger.debug("Lock cache file.")
fcntl.flock(fp, fcntl.LOCK_EX | fcntl.LOCK_NB)

@@ -114,13 +114,13 @@ except IOError as error:

raise
logger.debug('Cache file is locked.')
logger.debug("Cache file is locked.")
retry = True
else:
if file_exists:
logger.debug('Read cache from existing file.')
logger.debug("Read cache from existing file.")
cache.load_json(fp)
if cache.expired(expire_time):
logger.debug('Cache expired, do check.')
logger.debug("Cache expired, do check.")
cache.master = master_check()
cache.set_now()
logger.debug('Write cache to existing file.')
logger.debug("Write cache to existing file.")
fp.seek(0)

@@ -130,16 +130,16 @@ cache.safe_json(fp)

else:
logger.debug('Cache not expired.')
logger.debug("Cache not expired.")
else:
logger.debug('Do check.')
logger.debug("Do check.")
cache.master = master_check()
cache.set_now()
logger.debug('Write cache to new file.')
logger.debug("Write cache to new file.")
cache.safe_json(fp)
finally:
logger.debug('Unlock cache file.')
logger.debug("Unlock cache file.")
fcntl.flock(fp, fcntl.LOCK_UN)
logger.debug('Close cache file.')
logger.debug("Close cache file.")
fp.close()
if retry:
logger.debug('Sleep 1 second before retry.')
logger.debug("Sleep 1 second before retry.")
time.sleep(1)

@@ -149,3 +149,3 @@ continue

break
logger.debug('Is master: %s,', cache.master)
logger.debug("Is master: %s,", cache.master)
return cache.master

@@ -15,6 +15,6 @@ # clustercron/config.py

_config = {
'cache': {
'filename': '/tmp/clustercron_cache.json',
'expire_time': 59,
'max_iter': 20,
"cache": {
"filename": "/tmp/clustercron_cache.json",
"expire_time": 59,
"max_iter": 20,
}

@@ -25,6 +25,6 @@ }

def _update_config_from_conf():
basename = 'clustercron.ini'
basename = "clustercron.ini"
filenames = (
os.path.join('/etc/', basename),
os.path.join(os.path.expanduser("~"), '.' + basename),
os.path.join("/etc/", basename),
os.path.join(os.path.expanduser("~"), "." + basename),
)

@@ -31,0 +31,0 @@ parser = configparser.ConfigParser()

@@ -5,3 +5,3 @@ # clustercron/elb.py

'''
"""
clustercron.elb

@@ -11,3 +11,3 @@ ---------------

Modules holds class for AWS ElasticLoadBalancing (ELB)
'''
"""

@@ -28,13 +28,13 @@ from __future__ import unicode_literals

def _get_instance_health(self):
inst_health = {'InstanceStates': []}
logger.debug('Get instance health ')
inst_health = {"InstanceStates": []}
logger.debug("Get instance health ")
try:
client = boto3.client('elb')
client = boto3.client("elb")
except NoRegionError as error:
if self.region_name is None:
logger.error('%s', error)
logger.error("%s", error)
return inst_health
else:
client = boto3.client(
'elb',
"elb",
region_name=self.region_name,

@@ -47,3 +47,3 @@ )

except Exception as error:
logger.error('Could not get instance health: %s', error)
logger.error("Could not get instance health: %s", error)
return inst_health

@@ -54,15 +54,15 @@

inst_health = self._get_instance_health()
logger.debug('Instance health states: %s', inst_health)
logger.debug("Instance health states: %s", inst_health)
try:
healty_instances = sorted(
[
x['InstanceId']
for x in inst_health['InstanceStates']
if x['State'] == 'InService'
x["InstanceId"]
for x in inst_health["InstanceStates"]
if x["State"] == "InService"
]
)
except Exception as error:
logger.error('Could not parse healty_instances: %s', error)
logger.error("Could not parse healty_instances: %s", error)
else:
logger.info('Healty instances: %s', ', '.join(healty_instances))
logger.info("Healty instances: %s", ", ".join(healty_instances))
return healty_instances

@@ -5,3 +5,3 @@ # clustercron/lb.py

'''
"""
clustercron.lb

@@ -11,3 +11,3 @@ ---------------

Modules holds base class for AWS ElasticLoadBalancing classes
'''
"""

@@ -25,5 +25,5 @@ from __future__ import unicode_literals

def __init__(self, name):
'''
"""
:param name: name of load balancer or target group
'''
"""
self.name = name

@@ -36,9 +36,9 @@ self._get_instance_meta_data()

except Exception as error:
logger.error('Could not get instance data: %s', error)
data = {'document': {}}
self.region_name = data['document'].get('region')
self.instance_id = data['document'].get('instanceId')
logger.error("Could not get instance data: %s", error)
data = {"document": {}}
self.region_name = data["document"].get("region")
self.instance_id = data["document"].get("instanceId")
logger.info('self.region_name: %s', self.region_name)
logger.info('self.instance_id: %s', self.instance_id)
logger.info("self.region_name: %s", self.region_name)
logger.info("self.instance_id: %s", self.instance_id)

@@ -49,5 +49,5 @@ def get_healty_instances(self):

def master(self):
logger.debug('Check if instance is master')
logger.debug("Check if instance is master")
if self.instance_id is None:
logger.error('No Instanced Id')
logger.error("No Instanced Id")
else:

@@ -54,0 +54,0 @@ healty_instances = self.get_healty_instances()

@@ -5,6 +5,6 @@ # clustercron/clustercron.py

'''
"""
clustercron.main
----------------------
'''
"""

@@ -29,3 +29,3 @@

def clustercron(lb_type, name, command, output, use_cache):
'''
"""
API clustercron

@@ -37,8 +37,8 @@

:param output: Boolean
'''
if lb_type == 'elb':
"""
if lb_type == "elb":
from . import elb
lb = elb.Elb(name)
elif lb_type == 'alb':
elif lb_type == "alb":
from . import alb

@@ -56,3 +56,3 @@

if command:
logger.info('run command: %s', ' '.join(command))
logger.info("run command: %s", " ".join(command))
try:

@@ -73,5 +73,5 @@ proc = subprocess.Popen(

print(stderr.strip(), file=sys.stderr)
logger.info('stdout: %s', stdout)
logger.info('stderr: %s', stderr)
logger.info('returncode: %d', return_code)
logger.info("stdout: %s", stdout)
logger.info("stderr: %s", stderr)
logger.info("returncode: %d", return_code)
return return_code

@@ -85,7 +85,7 @@ else:

class Optarg(object):
'''
"""
Parse arguments from `sys.argv[0]` list.
Set usage string.
Set properties from arguments.
'''
"""

@@ -95,13 +95,13 @@ def __init__(self, arg_list):

self.args = {
'version': False,
'help': False,
'output': False,
'verbose': 0,
'syslog': False,
'cache': False,
'lb_type': None,
'name': None,
'command': [],
"version": False,
"help": False,
"output": False,
"verbose": 0,
"syslog": False,
"cache": False,
"lb_type": None,
"name": None,
"command": [],
}
self.usage = '''Clustercron, cluster cronjob wrapper.
self.usage = """Clustercron, cluster cronjob wrapper.

@@ -125,3 +125,3 @@ Usage:

is the `master` in the cluster and will return 0 if so.
'''
"""

@@ -133,36 +133,36 @@ def parse(self):

arg = arg_list.pop()
if arg == '-h' or arg == '--help':
self.args['help'] = True
if arg == "-h" or arg == "--help":
self.args["help"] = True
break
if arg == '--version':
self.args['version'] = True
if arg == "--version":
self.args["version"] = True
break
if arg in ('-v', '--verbose'):
self.args['verbose'] += 1
if arg in ('-o', '--output'):
self.args['output'] = True
if arg in ('-s', '--syslog'):
self.args['syslog'] = True
if arg in ('-c', '--cache'):
self.args['cache'] = True
if arg in ('elb', 'alb'):
self.args['lb_type'] = arg
if arg in ("-v", "--verbose"):
self.args["verbose"] += 1
if arg in ("-o", "--output"):
self.args["output"] = True
if arg in ("-s", "--syslog"):
self.args["syslog"] = True
if arg in ("-c", "--cache"):
self.args["cache"] = True
if arg in ("elb", "alb"):
self.args["lb_type"] = arg
try:
self.args['name'] = arg_list.pop()
self.args["name"] = arg_list.pop()
except IndexError:
pass
arg_list.reverse()
self.args['command'] = list(arg_list)
self.args["command"] = list(arg_list)
break
if self.args['name'] and self.args['name'].startswith('-'):
self.args['name'] = None
if self.args['command'] and self.args['command'][0].startswith('-'):
self.args['command'] = []
logger.debug('verbose: %s', self.args['verbose'])
if self.args["name"] and self.args["name"].startswith("-"):
self.args["name"] = None
if self.args["command"] and self.args["command"][0].startswith("-"):
self.args["command"] = []
logger.debug("verbose: %s", self.args["verbose"])
def setup_logging(verbose, syslog):
'''
"""
Sets up logging.
'''
"""
logger = logging.getLogger()

@@ -182,8 +182,8 @@ # Make sure no handlers hangin' round

handler = logging.StreamHandler()
formatter = logging.Formatter(fmt='%(levelname)-8s %(name)s : %(message)s')
formatter = logging.Formatter(fmt="%(levelname)-8s %(name)s : %(message)s")
if syslog:
unix_socket = {
'linux2': os.path.realpath('/dev/log'),
'darwin': os.path.realpath('/var/run/syslog'),
}.get(sys.platform, '')
"linux2": os.path.realpath("/dev/log"),
"darwin": os.path.realpath("/var/run/syslog"),
}.get(sys.platform, "")
if os.path.exists(unix_socket) and stat.S_ISSOCK(

@@ -194,3 +194,3 @@ os.stat(unix_socket).st_mode

formatter = logging.Formatter(
fmt='%(name)s [%(process)d]: %(message)s', datefmt=None
fmt="%(name)s [%(process)d]: %(message)s", datefmt=None
)

@@ -203,19 +203,19 @@ handler.setFormatter(formatter)

def command():
'''
"""
Entry point for the package, as defined in setup.py.
'''
"""
optarg = Optarg(sys.argv[1:])
optarg.parse()
if optarg.args['version']:
if optarg.args["version"]:
print(get_version())
exitcode = 2
elif optarg.args['lb_type'] and optarg.args['name']:
setup_logging(optarg.args['verbose'], optarg.args['syslog'])
logger.debug('Command line arguments: %s', optarg.args)
elif optarg.args["lb_type"] and optarg.args["name"]:
setup_logging(optarg.args["verbose"], optarg.args["syslog"])
logger.debug("Command line arguments: %s", optarg.args)
exitcode = clustercron(
optarg.args['lb_type'],
optarg.args['name'],
optarg.args['command'],
optarg.args['output'],
optarg.args['cache'],
optarg.args["lb_type"],
optarg.args["name"],
optarg.args["command"],
optarg.args["output"],
optarg.args["cache"],
)

@@ -222,0 +222,0 @@ else:

@@ -33,14 +33,14 @@ """

def communicate(self):
return ('stdout message', 'stderr message')
return ("stdout message", "stderr message")
def test_clustercron_returns_None_when_lb_type_is_not_elb():
'''
"""
Test if `main.clustercron` returns None when `lb_type` is not 'elb'.
'''
"""
assert (
main.clustercron(
'really_not_elb',
'mylbname',
'command',
"really_not_elb",
"mylbname",
"command",
False,

@@ -54,27 +54,27 @@ False,

def test_clustercron_returns_2_when_master_and_command_exits_2(monkeypatch):
'''
"""
Test if `main.clustercron` returns 2 when `lb.master` and command exits
with 2.
'''
monkeypatch.setattr(elb, 'Elb', ElbMock)
monkeypatch.setattr('subprocess.Popen', PopenMock)
"""
monkeypatch.setattr(elb, "Elb", ElbMock)
monkeypatch.setattr("subprocess.Popen", PopenMock)
assert main.clustercron('elb', 'mylbname', 'a_command', False, False) == 2
assert main.clustercron("elb", "mylbname", "a_command", False, False) == 2
def test_clustercron_returns_0_when_master_and_command_is_none(monkeypatch):
'''
"""
Test if `main.clustercron` returns 0 when `lb.master` and `command` is
None.
'''
monkeypatch.setattr(elb, 'Elb', ElbMock)
"""
monkeypatch.setattr(elb, "Elb", ElbMock)
assert main.clustercron('elb', 'mylbname', None, False, False) == 0
assert main.clustercron("elb", "mylbname", None, False, False) == 0
def test_clustercron_returns_0_when_master_output_stderr_stdout(monkeypatch):
'''
"""
Test if `main.clustercron` returns 0 when `lb.master` and outputs stderr
and stdout.
'''
"""

@@ -86,11 +86,11 @@ class PopenMock(object):

def communicate(self):
return ('stdout message', 'stderr message')
return ("stdout message", "stderr message")
monkeypatch.setattr(elb, 'Elb', ElbMock)
monkeypatch.setattr('subprocess.Popen', PopenMock)
monkeypatch.setattr('sys.stderr', StringIO())
monkeypatch.setattr('sys.stdout', StringIO())
monkeypatch.setattr(elb, "Elb", ElbMock)
monkeypatch.setattr("subprocess.Popen", PopenMock)
monkeypatch.setattr("sys.stderr", StringIO())
monkeypatch.setattr("sys.stdout", StringIO())
assert (
main.clustercron('elb', 'mylbname', ['echo' 'stdout'], True, False)
main.clustercron("elb", "mylbname", ["echo" "stdout"], True, False)
== 0

@@ -100,10 +100,10 @@ )

sys.stderr.seek(0)
assert sys.stdout.read().strip() == 'stdout message'
assert sys.stderr.read().strip() == 'stderr message'
assert sys.stdout.read().strip() == "stdout message"
assert sys.stderr.read().strip() == "stderr message"
def test_clustercron_returns_1_when_not_master(monkeypatch):
'''
"""
Test if `main.clustercron` returns 1 when not `lb.master`
'''
"""

@@ -117,5 +117,5 @@ class ElbMock(object):

monkeypatch.setattr(elb, 'Elb', ElbMock)
monkeypatch.setattr(elb, "Elb", ElbMock)
assert main.clustercron('elb', 'mylbname', None, False, False) == 1
assert main.clustercron("elb", "mylbname", None, False, False) == 1

@@ -127,11 +127,11 @@

assert opt_arg_parser.args == {
'version': False,
'help': False,
'output': False,
'verbose': 0,
'lb_type': None,
'name': None,
'command': [],
'syslog': False,
'cache': False,
"version": False,
"help": False,
"output": False,
"verbose": 0,
"lb_type": None,
"name": None,
"command": [],
"syslog": False,
"cache": False,
}

@@ -144,3 +144,3 @@

opt_arg_parser.usage
== '''Clustercron, cluster cronjob wrapper.
== """Clustercron, cluster cronjob wrapper.

@@ -164,3 +164,3 @@ Usage:

is the `master` in the cluster and will return 0 if so.
'''
"""
)

@@ -170,3 +170,3 @@

@pytest.mark.parametrize(
'arg_list,args',
"arg_list,args",
[

@@ -176,221 +176,221 @@ (

{
'version': False,
'help': False,
'output': False,
'verbose': 0,
'lb_type': None,
'name': None,
'command': [],
'syslog': False,
'cache': False,
"version": False,
"help": False,
"output": False,
"verbose": 0,
"lb_type": None,
"name": None,
"command": [],
"syslog": False,
"cache": False,
},
),
(
['-h'],
["-h"],
{
'version': False,
'help': True,
'output': False,
'verbose': 0,
'lb_type': None,
'name': None,
'command': [],
'syslog': False,
'cache': False,
"version": False,
"help": True,
"output": False,
"verbose": 0,
"lb_type": None,
"name": None,
"command": [],
"syslog": False,
"cache": False,
},
),
(
['whatever', 'nonsense', 'lives', 'here', '-h'],
["whatever", "nonsense", "lives", "here", "-h"],
{
'version': False,
'help': True,
'output': False,
'verbose': 0,
'lb_type': None,
'name': None,
'command': [],
'syslog': False,
'cache': False,
"version": False,
"help": True,
"output": False,
"verbose": 0,
"lb_type": None,
"name": None,
"command": [],
"syslog": False,
"cache": False,
},
),
(
['--help'],
["--help"],
{
'version': False,
'help': True,
'output': False,
'verbose': 0,
'lb_type': None,
'name': None,
'command': [],
'syslog': False,
'cache': False,
"version": False,
"help": True,
"output": False,
"verbose": 0,
"lb_type": None,
"name": None,
"command": [],
"syslog": False,
"cache": False,
},
),
(
['--help', 'whatever', 'nonsense', 'lives', 'here'],
["--help", "whatever", "nonsense", "lives", "here"],
{
'version': False,
'help': True,
'output': False,
'verbose': 0,
'lb_type': None,
'name': None,
'command': [],
'syslog': False,
'cache': False,
"version": False,
"help": True,
"output": False,
"verbose": 0,
"lb_type": None,
"name": None,
"command": [],
"syslog": False,
"cache": False,
},
),
(
['--version'],
["--version"],
{
'version': True,
'help': False,
'output': False,
'verbose': 0,
'lb_type': None,
'name': None,
'command': [],
'syslog': False,
'cache': False,
"version": True,
"help": False,
"output": False,
"verbose": 0,
"lb_type": None,
"name": None,
"command": [],
"syslog": False,
"cache": False,
},
),
(
['whatever', 'nonsense', '--version', 'lives', 'here', 'elb'],
["whatever", "nonsense", "--version", "lives", "here", "elb"],
{
'version': True,
'help': False,
'output': False,
'verbose': 0,
'lb_type': None,
'name': None,
'command': [],
'syslog': False,
'cache': False,
"version": True,
"help": False,
"output": False,
"verbose": 0,
"lb_type": None,
"name": None,
"command": [],
"syslog": False,
"cache": False,
},
),
(
['-v', 'elb', 'my_lb_name', 'update', '-r', 'thing'],
["-v", "elb", "my_lb_name", "update", "-r", "thing"],
{
'version': False,
'help': False,
'output': False,
'verbose': 1,
'lb_type': 'elb',
'name': 'my_lb_name',
'command': ['update', '-r', 'thing'],
'syslog': False,
'cache': False,
"version": False,
"help": False,
"output": False,
"verbose": 1,
"lb_type": "elb",
"name": "my_lb_name",
"command": ["update", "-r", "thing"],
"syslog": False,
"cache": False,
},
),
(
['-v', '-v', 'elb', 'my_lb_name', 'update', '-r', 'thing'],
["-v", "-v", "elb", "my_lb_name", "update", "-r", "thing"],
{
'version': False,
'help': False,
'output': False,
'verbose': 2,
'lb_type': 'elb',
'name': 'my_lb_name',
'command': ['update', '-r', 'thing'],
'syslog': False,
'cache': False,
"version": False,
"help": False,
"output": False,
"verbose": 2,
"lb_type": "elb",
"name": "my_lb_name",
"command": ["update", "-r", "thing"],
"syslog": False,
"cache": False,
},
),
(
['elb', 'my_lb_name', 'update', '-r', 'thing'],
["elb", "my_lb_name", "update", "-r", "thing"],
{
'version': False,
'help': False,
'output': False,
'verbose': 0,
'lb_type': 'elb',
'name': 'my_lb_name',
'command': ['update', '-r', 'thing'],
'syslog': False,
'cache': False,
"version": False,
"help": False,
"output": False,
"verbose": 0,
"lb_type": "elb",
"name": "my_lb_name",
"command": ["update", "-r", "thing"],
"syslog": False,
"cache": False,
},
),
(
['elb', 'my_lb_name'],
["elb", "my_lb_name"],
{
'version': False,
'help': False,
'output': False,
'verbose': 0,
'lb_type': 'elb',
'name': 'my_lb_name',
'command': [],
'syslog': False,
'cache': False,
"version": False,
"help": False,
"output": False,
"verbose": 0,
"lb_type": "elb",
"name": "my_lb_name",
"command": [],
"syslog": False,
"cache": False,
},
),
(
['elb'],
["elb"],
{
'version': False,
'help': False,
'output': False,
'verbose': 0,
'lb_type': 'elb',
'name': None,
'command': [],
'syslog': False,
'cache': False,
"version": False,
"help": False,
"output": False,
"verbose": 0,
"lb_type": "elb",
"name": None,
"command": [],
"syslog": False,
"cache": False,
},
),
(
['elb', '-v'],
["elb", "-v"],
{
'version': False,
'help': False,
'output': False,
'verbose': 0,
'lb_type': 'elb',
'name': None,
'command': [],
'syslog': False,
'cache': False,
"version": False,
"help": False,
"output": False,
"verbose": 0,
"lb_type": "elb",
"name": None,
"command": [],
"syslog": False,
"cache": False,
},
),
(
['elb', 'my_lb_name', '-v'],
["elb", "my_lb_name", "-v"],
{
'version': False,
'help': False,
'output': False,
'verbose': 0,
'lb_type': 'elb',
'name': 'my_lb_name',
'command': [],
'syslog': False,
'cache': False,
"version": False,
"help": False,
"output": False,
"verbose": 0,
"lb_type": "elb",
"name": "my_lb_name",
"command": [],
"syslog": False,
"cache": False,
},
),
(
['-v', '-v', '-s', 'elb', 'my_lb_name', 'test', '-v'],
["-v", "-v", "-s", "elb", "my_lb_name", "test", "-v"],
{
'version': False,
'help': False,
'output': False,
'verbose': 2,
'lb_type': 'elb',
'name': 'my_lb_name',
'command': ['test', '-v'],
'syslog': True,
'cache': False,
"version": False,
"help": False,
"output": False,
"verbose": 2,
"lb_type": "elb",
"name": "my_lb_name",
"command": ["test", "-v"],
"syslog": True,
"cache": False,
},
),
(
['-o', '-s', 'elb', 'my_lb_name', 'test', '-v'],
["-o", "-s", "elb", "my_lb_name", "test", "-v"],
{
'version': False,
'help': False,
'output': True,
'verbose': 0,
'lb_type': 'elb',
'name': 'my_lb_name',
'command': ['test', '-v'],
'syslog': True,
'cache': False,
"version": False,
"help": False,
"output": True,
"verbose": 0,
"lb_type": "elb",
"name": "my_lb_name",
"command": ["test", "-v"],
"syslog": True,
"cache": False,
},

@@ -408,6 +408,6 @@ ),

def test_command_version(monkeypatch):
'''
"""
Test if `cluster.command` returns 2 with '--version'
'''
monkeypatch.setattr('sys.argv', ['clustercron', '--version'])
"""
monkeypatch.setattr("sys.argv", ["clustercron", "--version"])
assert main.command() == 2

@@ -417,11 +417,11 @@

def test_command_elb_name_a_command_arguments(monkeypatch):
'''
"""
Test if `cluster.command` returns 1 with 'elb', 'name' and 'a_command'
arguments.
'''
"""
monkeypatch.setattr(
'sys.argv', ['clustercron', 'elb', 'name', 'a_command']
"sys.argv", ["clustercron", "elb", "name", "a_command"]
)
monkeypatch.setattr(
main, 'clustercron', lambda lb_type, name, commmand, output, cache: 0
main, "clustercron", lambda lb_type, name, commmand, output, cache: 0
)

@@ -433,4 +433,4 @@ assert main.command() == 0

monkeypatch.setattr(
'sys.argv',
['clustercron', 'bla', 'ara', 'dada', '-r', 'thing'],
"sys.argv",
["clustercron", "bla", "ara", "dada", "-r", "thing"],
)

@@ -441,3 +441,3 @@ assert main.command() == 3

@pytest.mark.parametrize(
'verbose,syslog,log_level',
"verbose,syslog,log_level",
[

@@ -444,0 +444,0 @@ (0, False, logging.ERROR),

@@ -15,3 +15,3 @@ [tox]

commands =
pytest --cov=clustercron
python -m pytest --cov=clustercron

@@ -18,0 +18,0 @@ [testenv:lint]