Skip to content

Commit

Permalink
Merge pull request #13 from heavenshell/feature/flake8
Browse files Browse the repository at this point in the history
Add flake8
  • Loading branch information
heavenshell authored Sep 22, 2019
2 parents 69f64f6 + a070af9 commit daef052
Show file tree
Hide file tree
Showing 10 changed files with 102 additions and 46 deletions.
13 changes: 11 additions & 2 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
dist: xenial
language: python
cache:
pip: true
directories:
- "$TRAVIS_BUILD_DIR/.tox"

python:
- 2.7
Expand All @@ -9,6 +14,10 @@ env:
global:
MACKEREL_APIKEY='xxxxxxxx'

before_install: pip install -r requirements.txt
before_install:
- pip install -U -r requirements.txt
before_script:
- flake8 --verbose --jobs=8

script: python setup.py test
script:
- python setup.py test
1 change: 1 addition & 0 deletions mackerel/__init__.py
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
# -*- coding: utf-8 -*-
__import__('pkg_resources').declare_namespace(__name__)
11 changes: 6 additions & 5 deletions mackerel/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
:license: BSD, see LICENSE for more details.
"""
import logging

import requests
import simplejson as json
from mackerel.host import Host
Expand All @@ -25,7 +26,7 @@ class MackerelClientError(Exception):
class Client(object):

#: Mackerel apikey error message.
ERROR_MESSAGE_FOR_API_KEY_ABSENCE = 'API key is absent. Set your API key in a environment variable called MACKEREL_APIKEY.'
ERROR_MESSAGE_FOR_API_KEY_ABSENCE = 'API key is absent. Set your API key in a environment variable called MACKEREL_APIKEY.' # noqa E501
#: Log format.
debug_log_format = (
'[%(asctime)s %(levelname)s][%(pathname)s:%(lineno)d]: %(message)s'
Expand All @@ -44,8 +45,7 @@ def __init__(self, logger=None, **kwargs):

self.api_key = api_key
if logger is None:
logging.basicConfig(level=logging.INFO,
format=self.debug_log_format)
logging.basicConfig(level=logging.INFO, format=self.debug_log_format)
self.logger = logging.getLogger('mackerel.client')
else:
self.logger = logger
Expand Down Expand Up @@ -176,8 +176,9 @@ def _request(self, uri, method='GET', headers=None, params=None):
message = '{0} is not supported.'.format(method)
raise NotImplementedError(message)

self.logger.debug('Response from {0} is {1}'.format(self.origin,
res.status_code))
self.logger.debug(
'Response from {0} is {1}'.format(self.origin, res.status_code),
)
if res.status_code != 200:
message = '{0} {1} failed: {2}'.format(method, uri, res.status_code)
raise MackerelClientError(message)
Expand Down
16 changes: 13 additions & 3 deletions mackerel/host.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,10 +57,20 @@ def mac_addr(self):
return i['macAddress']

def __repr__(self):
"""Host instance."""
repr = '<Host('
repr += 'name={0}, meta={1}, type={2}, status={3}, memo={4},'
repr += 'is_retired={5}, id={6}, created_at={7}, roles={8},'
repr += 'interfaces={9})'
return repr.format(self.name, self.meta, self.type, self.status,
self.memo, self.is_retired, self.id,
self.created_at, self.roles, self.interfaces)
return repr.format(
self.name,
self.meta,
self.type,
self.status,
self.memo,
self.is_retired,
self.id,
self.created_at,
self.roles,
self.interfaces,
)
3 changes: 2 additions & 1 deletion mackerel/runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,9 @@
:copyright: (c) 2015 Shinya Ohyanagi, All rights reserved.
:license: BSD, see LICENSE for more details.
"""
import os
import logging
import os

import click
from mackerel.client import Client

Expand Down
9 changes: 9 additions & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,12 @@ requests==2.22.0
click==7.0
simplejson==3.16.0
mock==3.0.5
flake8==3.7.8
flake8-coding==1.3.2
flake8-commas==2.0.0
flake8-comprehensions==1.4.1 # pyup: <2.0
flake8-debugger==3.1.0
flake8-docstrings==1.4.0
flake8-import-order==0.18.1
flake8-print==3.1.0
flake8-string-format==0.2.3
15 changes: 15 additions & 0 deletions setup.cfg
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
[flake8]
max-line-length = 120
exclude =
.cache,
.git,
.tox,
build,
migrations,
venv,
__pycache__
ignore = D100,D101,D102,D103,D104,D106,D107,D205,D208,D400
import-order-style = smarkets

[wheel]
universal = 1
10 changes: 7 additions & 3 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,11 @@
:license: BSD, see LICENSE for more details.
"""
import os
from setuptools import setup, find_packages

from setuptools import (
find_packages,
setup,
)

requires = ['requests', 'simplejson', 'click']

Expand Down Expand Up @@ -41,12 +45,12 @@
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python'
'Programming Language :: Python',
],
entry_points="""
[console_scripts]
mkr.py = mackerel.runner:main
""",
tests_require=['requests', 'simplejson', 'mock'],
test_suite='tests'
test_suite='tests',
)
62 changes: 34 additions & 28 deletions tests/test_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,15 @@
:license: BSD, see LICENSE for more details.
"""
import os
import requests
from unittest import TestCase
from mock import patch
from mackerel.client import Client, MackerelClientError

import requests
from mackerel.client import (
Client,
MackerelClientError,
)
from mackerel.host import Host
from mock import patch


def dummy_response(m, filename, status_code=200):
Expand All @@ -37,22 +41,22 @@ def setUpClass(cls):

@patch('mackerel.client.requests.get')
def test_should_get_hosts(self, m):
""" Client().get_hosts() should get host list. """
"""Client().get_hosts() should get host list."""
dummy_response(m, 'fixtures/get_hosts.json')
hosts = self.client.get_hosts()
for host in hosts:
self.assertTrue(isinstance(host, Host))

@patch('mackerel.client.requests.get')
def test_should_get_host(self, m):
""" Client().get_hosts() should get host. """
"""Client().get_hosts() should get host."""
dummy_response(m, 'fixtures/get_host.json')
host = self.client.get_host(self.id)
self.assertTrue(isinstance(host, Host))

@patch('mackerel.client.requests.post')
def test_should_update_host_poweroff(self, m):
""" Client().update_host_status('poweroff') should return success. """
"""Client().update_host_status('poweroff') should return success."""
dummy_response(m, 'fixtures/success.json')
ret = self.client.update_host_status(self.id, 'poweroff')
self.assertEqual(ret['success'], True)
Expand All @@ -63,7 +67,7 @@ def test_should_update_host_poweroff(self, m):

@patch('mackerel.client.requests.post')
def test_should_update_host_standby(self, m):
""" Client().update_host_status('standby') should return success. """
"""Client().update_host_status('standby') should return success."""
dummy_response(m, 'fixtures/success.json')
ret = self.client.update_host_status(self.id, 'standby')
self.assertEqual(ret['success'], True)
Expand All @@ -75,7 +79,7 @@ def test_should_update_host_standby(self, m):

@patch('mackerel.client.requests.post')
def test_should_update_host_working(self, m):
""" Client().update_host_status('working') should return success. """
"""Client().update_host_status('working') should return success."""
dummy_response(m, 'fixtures/success.json')
ret = self.client.update_host_status('2k48zsCx8ij', 'working')
self.assertEqual(ret['success'], True)
Expand All @@ -86,7 +90,7 @@ def test_should_update_host_working(self, m):

@patch('mackerel.client.requests.post')
def test_should_update_host_maintenance(self, m):
""" Client().update_host_status('maintenance') should return success. """
"""Client().update_host_status('maintenance') should return success."""
dummy_response(m, 'fixtures/success.json')
ret = self.client.update_host_status(self.id, 'maintenance')
self.assertEqual(ret['success'], True)
Expand All @@ -96,75 +100,77 @@ def test_should_update_host_maintenance(self, m):
self.assertEqual(host.status, 'maintenance')

def test_should_update_host_invalid(self):
""" Client().update_host_status('foo') should raise error. """
"""Client().update_host_status('foo') should raise error."""
with self.assertRaises(MackerelClientError):
self.client.update_host_status(self.id, 'foo')

@patch('mackerel.client.requests.post')
def test_should_retire(self, m):
""" Client().retire_host() should return success. """
"""Client().retire_host() should return success."""
dummy_response(m, 'fixtures/success.json')
ret = self.client.retire_host(self.id)
self.assertEqual(ret['success'], True)

@patch('mackerel.client.requests.get')
def test_should_get_latest_metrics(self, m):
""" Client().get_latest_metrics() should get metrics. """
"""Client().get_latest_metrics() should get metrics."""
dummy_response(m, 'fixtures/get_latest_metrics.json')
ret = self.client.get_latest_metrics([self.id],
['loadavg5', 'memory.free'])
ret = self.client.get_latest_metrics(
[self.id],
['loadavg5', 'memory.free'],
)
for k in ['loadavg5', 'memory.free']:
self.assertTrue(k in ret['tsdbLatest'][self.id].keys())

@patch('mackerel.client.requests.post')
def test_should_post_metrics(self, m):
""" Client().post_metrics() should return success. """
"""Client().post_metrics() should return success."""
dummy_response(m, 'fixtures/success.json')
id = self.id
metrics = [
{
'hostId': id, 'name': 'custom.metrics.loadavg',
'time': 1401537844, 'value': 1.4
'time': 1401537844, 'value': 1.4,
},
{
'hostId': id, 'name': 'custom.metrics.uptime',
'time': 1401537844, 'value': 500
}
'time': 1401537844, 'value': 500,
},

]
ret = self.client.post_metrics(metrics)
self.assertEqual(ret['success'], True)

@patch('mackerel.client.requests.post')
def test_should_post_service_metrics(self, m):
""" Client().post_service_metrics() should return success. """
"""Client().post_service_metrics() should return success."""
dummy_response(m, 'fixtures/success.json')
metrics = [
{
'name': 'custom.metrics.latency',
'time': 1401537844, 'value': 0.5
'time': 1401537844, 'value': 0.5,
},
{
'name': 'custom.metrics.uptime',
'time': 1401537844, 'value': 500
}
'time': 1401537844, 'value': 500,
},
]
ret = self.client.post_service_metrics('service_name', metrics)
self.assertEqual(ret['success'], True)

@patch('mackerel.client.requests.post')
def test_should_raise_error_when_service_not_found(self, m):
""" Client().post_service_metrics() should raise error when service name not found. """
"""Client().post_service_metrics() should raise error when service name not found."""
dummy_response(m, 'fixtures/error.json', 404)
metrics = [
{
'name': 'custom.metrics.latency',
'time': 1401537844, 'value': 0.5
'time': 1401537844, 'value': 0.5,
},
{
'name': 'custom.metrics.uptime',
'time': 1401537844, 'value': 500
}
'time': 1401537844, 'value': 500,
},
]
with self.assertRaises(MackerelClientError):
self.client.post_service_metrics('foobarbaz', metrics)
Expand All @@ -179,14 +185,14 @@ def setUpClass(cls):

@patch('mackerel.client.requests.get')
def test_should_get_ipaddress(self, m):
""" Host().ip_addr() should get ipaddress. """
"""Host().ip_addr() should get ipaddress."""
dummy_response(m, 'fixtures/get_host.json')
host = self.client.get_host(self.id)
self.assertEqual(host.ip_addr(), '10.0.2.15')

@patch('mackerel.client.requests.get')
def test_should_get_macaddress(self, m):
""" Host().mac_addr() should get ipaddress. """
"""Host().mac_addr() should get ipaddress."""
dummy_response(m, 'fixtures/get_host.json')
host = self.client.get_host(self.id)
self.assertEqual(host.mac_addr(), '08:00:27:96:ed:36')
8 changes: 4 additions & 4 deletions tox.ini
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
[tox]
envlist = py27,py36,py37,pycodestyle
envlist = py27,py36,py37,flake8

[testenv]
commands=python setup.py test
Expand All @@ -8,6 +8,6 @@ deps=
simplejson
mock

[testenv:pycodestyle]
deps = pycodestyle
commands = pycodestyle --repeat --ignore=E501 --show-source mackerel tests setup.py
[testenv:flake8]
deps = flake8
commands = flake8 mackerel tests setup.py

0 comments on commit daef052

Please sign in to comment.