Merge pull request #193 from gcarq/feature/ci-enforce-pep8

CI: enforce PEP8 conform code
This commit is contained in:
Janne Sinivirta 2017-12-17 07:42:23 +02:00 committed by GitHub
commit 80ef2cfed4
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
12 changed files with 45 additions and 21 deletions

View File

@ -15,12 +15,12 @@ install:
- tar zxvf ta-lib-0.4.0-src.tar.gz - tar zxvf ta-lib-0.4.0-src.tar.gz
- cd ta-lib && ./configure && sudo make && sudo make install && cd .. - cd ta-lib && ./configure && sudo make && sudo make install && cd ..
- export LD_LIBRARY_PATH=/usr/local/lib:$LD_LIBRARY_PATH - export LD_LIBRARY_PATH=/usr/local/lib:$LD_LIBRARY_PATH
- pip install coveralls - pip install flake8 coveralls
- pip install -r requirements.txt - pip install -r requirements.txt
script: script:
- pytest --cov=freqtrade --cov-config=.coveragerc freqtrade/tests/ - pytest --cov=freqtrade --cov-config=.coveragerc freqtrade/tests/
after_success: after_success:
- coveralls - flake8 freqtrade && coveralls
notifications: notifications:
slack: slack:
secure: bKLXmOrx8e2aPZl7W8DA5BdPAXWGpI5UzST33oc1G/thegXcDVmHBTJrBs4sZak6bgAclQQrdZIsRd2eFYzHLalJEaw6pk7hoAw8SvLnZO0ZurWboz7qg2+aZZXfK4eKl/VUe4sM9M4e/qxjkK+yWG7Marg69c4v1ypF7ezUi1fPYILYw8u0paaiX0N5UX8XNlXy+PBlga2MxDjUY70MuajSZhPsY2pDUvYnMY1D/7XN3cFW0g+3O8zXjF0IF4q1Z/1ASQe+eYjKwPQacE+O8KDD+ZJYoTOFBAPllrtpO1jnOPFjNGf3JIbVMZw4bFjIL0mSQaiSUaUErbU3sFZ5Or79rF93XZ81V7uEZ55vD8KMfR2CB1cQJcZcj0v50BxLo0InkFqa0Y8Nra3sbpV4fV5Oe8pDmomPJrNFJnX6ULQhQ1gTCe0M5beKgVms5SITEpt4/Y0CmLUr6iHDT0CUiyMIRWAXdIgbGh1jfaWOMksybeRevlgDsIsNBjXmYI1Sw2ZZR2Eo2u4R6zyfyjOMLwYJ3vgq9IrACv2w5nmf0+oguMWHf6iWi2hiOqhlAN1W74+3HsYQcqnuM3LGOmuCnPprV1oGBqkPXjIFGpy21gNx4vHfO1noLUyJnMnlu2L7SSuN1CdLsnjJ1hVjpJjPfqB4nn8g12x87TqM1bOm+3Q= secure: bKLXmOrx8e2aPZl7W8DA5BdPAXWGpI5UzST33oc1G/thegXcDVmHBTJrBs4sZak6bgAclQQrdZIsRd2eFYzHLalJEaw6pk7hoAw8SvLnZO0ZurWboz7qg2+aZZXfK4eKl/VUe4sM9M4e/qxjkK+yWG7Marg69c4v1ypF7ezUi1fPYILYw8u0paaiX0N5UX8XNlXy+PBlga2MxDjUY70MuajSZhPsY2pDUvYnMY1D/7XN3cFW0g+3O8zXjF0IF4q1Z/1ASQe+eYjKwPQacE+O8KDD+ZJYoTOFBAPllrtpO1jnOPFjNGf3JIbVMZw4bFjIL0mSQaiSUaUErbU3sFZ5Or79rF93XZ81V7uEZ55vD8KMfR2CB1cQJcZcj0v50BxLo0InkFqa0Y8Nra3sbpV4fV5Oe8pDmomPJrNFJnX6ULQhQ1gTCe0M5beKgVms5SITEpt4/Y0CmLUr6iHDT0CUiyMIRWAXdIgbGh1jfaWOMksybeRevlgDsIsNBjXmYI1Sw2ZZR2Eo2u4R6zyfyjOMLwYJ3vgq9IrACv2w5nmf0+oguMWHf6iWi2hiOqhlAN1W74+3HsYQcqnuM3LGOmuCnPprV1oGBqkPXjIFGpy21gNx4vHfO1noLUyJnMnlu2L7SSuN1CdLsnjJ1hVjpJjPfqB4nn8g12x87TqM1bOm+3Q=

View File

@ -248,5 +248,5 @@ $ pytest freqtrade
Feel like our bot is missing a feature? We welcome your pull requests! Few pointers for contributions: Feel like our bot is missing a feature? We welcome your pull requests! Few pointers for contributions:
- Create your PR against the `develop` branch, not `master`. - Create your PR against the `develop` branch, not `master`.
- New features need to contain unit tests. - New features need to contain unit tests and must be PEP8 conform (`max-line-length = 100`).
- If you are unsure, discuss the feature on [slack](https://join.slack.com/t/highfrequencybot/shared_invite/enQtMjQ5NTM0OTYzMzY3LWMxYzE3M2MxNDdjMGM3ZTYwNzFjMGIwZGRjNTc3ZGU3MGE3NzdmZGMwNmU3NDM5ZTNmM2Y3NjRiNzk4NmM4OGE) or in a [issue](https://github.com/gcarq/freqtrade/issues) before a PR. - If you are unsure, discuss the feature on [slack](https://join.slack.com/t/highfrequencybot/shared_invite/enQtMjQ5NTM0OTYzMzY3LWMxYzE3M2MxNDdjMGM3ZTYwNzFjMGIwZGRjNTc3ZGU3MGE3NzdmZGMwNmU3NDM5ZTNmM2Y3NjRiNzk4NmM4OGE) or in a [issue](https://github.com/gcarq/freqtrade/issues) before a PR.

View File

@ -60,7 +60,10 @@ def _process(dynamic_whitelist: Optional[int] = 0) -> bool:
try: try:
# Refresh whitelist based on wallet maintenance # Refresh whitelist based on wallet maintenance
refresh_whitelist( refresh_whitelist(
gen_pair_whitelist(_CONF['stake_currency'], topn = dynamic_whitelist) if dynamic_whitelist else None gen_pair_whitelist(
_CONF['stake_currency'],
topn=dynamic_whitelist
) if dynamic_whitelist else None
) )
# Query trades from persistence layer # Query trades from persistence layer
trades = Trade.query.filter(Trade.is_open.is_(True)).all() trades = Trade.query.filter(Trade.is_open.is_(True)).all()
@ -329,7 +332,9 @@ def main() -> None:
if args.dry_run_db: if args.dry_run_db:
if _CONF.get('dry_run', False): if _CONF.get('dry_run', False):
_CONF.update({'dry_run_db': True}) _CONF.update({'dry_run_db': True})
logger.info('Dry_run will use the DB file: "tradesv3.dry_run.sqlite". (--dry_run_db detected)') logger.info(
'Dry_run will use the DB file: "tradesv3.dry_run.sqlite". (--dry_run_db detected)'
)
else: else:
logger.info('Dry run is disabled. (--dry_run_db ignored)') logger.info('Dry run is disabled. (--dry_run_db ignored)')

View File

@ -112,7 +112,7 @@ def parse_args(args: List[str]):
) )
parser.add_argument( parser.add_argument(
'--dynamic-whitelist', '--dynamic-whitelist',
help='dynamically generate and update whitelist based on 24h BaseVolume (Default 20 currencies)', help='dynamically generate and update whitelist based on 24h BaseVolume (Default 20 currencies)', # noqa
dest='dynamic_whitelist', dest='dynamic_whitelist',
const=20, const=20,
type=int, type=int,
@ -122,7 +122,7 @@ def parse_args(args: List[str]):
parser.add_argument( parser.add_argument(
'--dry-run-db', '--dry-run-db',
help='Force dry run to use a local DB "tradesv3.dry_run.sqlite" instead of memory DB. Work only if dry_run is \ help='Force dry run to use a local DB "tradesv3.dry_run.sqlite" instead of memory DB. Work only if dry_run is \
enabled.', enabled.', # noqa
action='store_true', action='store_true',
dest='dry_run_db', dest='dry_run_db',
) )

View File

@ -35,7 +35,8 @@ def get_timeframe(data: Dict[str, Dict]) -> Tuple[arrow.Arrow, arrow.Arrow]:
return arrow.get(min_date), arrow.get(max_date) return arrow.get(min_date), arrow.get(max_date)
def generate_text_table(data: Dict[str, Dict], results: DataFrame, stake_currency, ticker_interval) -> str: def generate_text_table(
data: Dict[str, Dict], results: DataFrame, stake_currency, ticker_interval) -> str:
""" """
Generates and returns a text table for the given backtest data and the results dataframe Generates and returns a text table for the given backtest data and the results dataframe
:return: pretty printed table with tabulate as str :return: pretty printed table with tabulate as str

View File

@ -50,7 +50,7 @@ OPTIMIZE_CONFIG = {
} }
# Monkey patch config # Monkey patch config
from freqtrade import main from freqtrade import main # noqa
main._CONF = OPTIMIZE_CONFIG main._CONF = OPTIMIZE_CONFIG
@ -103,6 +103,7 @@ SPACE = {
]), ]),
} }
def log_results(results): def log_results(results):
"if results is better than _TO_BEAT show it" "if results is better than _TO_BEAT show it"
@ -119,6 +120,7 @@ def log_results(results):
print('.', end='') print('.', end='')
sys.stdout.flush() sys.stdout.flush()
def optimizer(params): def optimizer(params):
global _CURRENT_TRIES global _CURRENT_TRIES
@ -149,7 +151,7 @@ def optimizer(params):
'result': result, 'result': result,
'results': results 'results': results
} }
# logger.info('{:5d}/{}: {}'.format(_CURRENT_TRIES, TOTAL_TRIES, result)) # logger.info('{:5d}/{}: {}'.format(_CURRENT_TRIES, TOTAL_TRIES, result))
log_results(result_data) log_results(result_data)

View File

@ -93,7 +93,7 @@ def authorized_only(command_handler: Callable[[Bot, Update], None]) -> Callable[
:return: decorated function :return: decorated function
""" """
def wrapper(*args, **kwargs): def wrapper(*args, **kwargs):
bot, update = kwargs.get('bot') or args[0], kwargs.get('update') or args[1] update = kwargs.get('update') or args[1]
# Reject unauthorized messages # Reject unauthorized messages
chat_id = int(_CONF['telegram']['chat_id']) chat_id = int(_CONF['telegram']['chat_id'])
@ -551,7 +551,10 @@ def send_msg(msg: str, bot: Bot = None, parse_mode: ParseMode = ParseMode.MARKDO
try: try:
try: try:
bot.send_message(_CONF['telegram']['chat_id'], msg, parse_mode=parse_mode, reply_markup=reply_markup) bot.send_message(
_CONF['telegram']['chat_id'], msg,
parse_mode=parse_mode, reply_markup=reply_markup
)
except NetworkError as network_err: except NetworkError as network_err:
# Sometimes the telegram server resets the current connection, # Sometimes the telegram server resets the current connection,
# if this is the case we send the message again. # if this is the case we send the message again.
@ -559,6 +562,9 @@ def send_msg(msg: str, bot: Bot = None, parse_mode: ParseMode = ParseMode.MARKDO
'Got Telegram NetworkError: %s! Trying one more time.', 'Got Telegram NetworkError: %s! Trying one more time.',
network_err.message network_err.message
) )
bot.send_message(_CONF['telegram']['chat_id'], msg, parse_mode=parse_mode, reply_markup=reply_markup) bot.send_message(
_CONF['telegram']['chat_id'], msg,
parse_mode=parse_mode, reply_markup=reply_markup
)
except TelegramError as telegram_err: except TelegramError as telegram_err:
logger.warning('Got TelegramError: %s! Giving up on that message.', telegram_err.message) logger.warning('Got TelegramError: %s! Giving up on that message.', telegram_err.message)

View File

@ -137,7 +137,9 @@ def test_create_trade_minimal_amount(default_conf, ticker, mocker):
mocker.patch.dict('freqtrade.main._CONF', default_conf) mocker.patch.dict('freqtrade.main._CONF', default_conf)
mocker.patch.multiple('freqtrade.rpc', init=MagicMock(), send_msg=MagicMock()) mocker.patch.multiple('freqtrade.rpc', init=MagicMock(), send_msg=MagicMock())
mocker.patch('freqtrade.main.get_signal', side_effect=lambda s, t: True) mocker.patch('freqtrade.main.get_signal', side_effect=lambda s, t: True)
buy_mock = mocker.patch('freqtrade.main.exchange.buy', MagicMock(return_value='mocked_limit_buy')) buy_mock = mocker.patch(
'freqtrade.main.exchange.buy', MagicMock(return_value='mocked_limit_buy')
)
mocker.patch.multiple('freqtrade.main.exchange', mocker.patch.multiple('freqtrade.main.exchange',
validate_pairs=MagicMock(), validate_pairs=MagicMock(),
get_ticker=ticker) get_ticker=ticker)

View File

@ -60,11 +60,13 @@ def test_parse_args_dynamic_whitelist():
assert args is not None assert args is not None
assert args.dynamic_whitelist is 20 assert args.dynamic_whitelist is 20
def test_parse_args_dynamic_whitelist_10(): def test_parse_args_dynamic_whitelist_10():
args = parse_args(['--dynamic-whitelist', '10']) args = parse_args(['--dynamic-whitelist', '10'])
assert args is not None assert args is not None
assert args.dynamic_whitelist is 10 assert args.dynamic_whitelist is 10
def test_parse_args_dynamic_whitelist_invalid_values(): def test_parse_args_dynamic_whitelist_invalid_values():
with pytest.raises(SystemExit, match=r'2'): with pytest.raises(SystemExit, match=r'2'):
parse_args(['--dynamic-whitelist', 'abc']) parse_args(['--dynamic-whitelist', 'abc'])

View File

@ -10,6 +10,7 @@ import os
import pytest import pytest
def test_backtest(default_conf, mocker): def test_backtest(default_conf, mocker):
mocker.patch.dict('freqtrade.main._CONF', default_conf) mocker.patch.dict('freqtrade.main._CONF', default_conf)
exchange._API = Bittrex({'key': '', 'secret': ''}) exchange._API = Bittrex({'key': '', 'secret': ''})

View File

@ -341,6 +341,7 @@ def test_performance_handle(
assert 'Performance' in msg_mock.call_args_list[0][0][0] assert 'Performance' in msg_mock.call_args_list[0][0][0]
assert '<code>BTC_ETH\t10.05%</code>' in msg_mock.call_args_list[0][0][0] assert '<code>BTC_ETH\t10.05%</code>' in msg_mock.call_args_list[0][0][0]
def test_daily_handle( def test_daily_handle(
default_conf, update, ticker, limit_buy_order, limit_sell_order, mocker): default_conf, update, ticker, limit_buy_order, limit_sell_order, mocker):
mocker.patch.dict('freqtrade.main._CONF', default_conf) mocker.patch.dict('freqtrade.main._CONF', default_conf)
@ -355,7 +356,7 @@ def test_daily_handle(
validate_pairs=MagicMock(), validate_pairs=MagicMock(),
get_ticker=ticker) get_ticker=ticker)
init(default_conf, create_engine('sqlite://')) init(default_conf, create_engine('sqlite://'))
# Create some test data # Create some test data
create_trade(15.0) create_trade(15.0)
trade = Trade.query.first() trade = Trade.query.first()
@ -370,22 +371,22 @@ def test_daily_handle(
trade.close_date = datetime.utcnow() trade.close_date = datetime.utcnow()
trade.is_open = False trade.is_open = False
#try valid data # try valid data
update.message.text = '/daily 7' update.message.text = '/daily 7'
_daily(bot=MagicMock(), update=update) _daily(bot=MagicMock(), update=update)
assert msg_mock.call_count == 1 assert msg_mock.call_count == 1
assert 'Daily' in msg_mock.call_args_list[0][0][0] assert 'Daily' in msg_mock.call_args_list[0][0][0]
assert str(date.today()) + ' 1.50701325 BTC' in msg_mock.call_args_list[0][0][0] assert str(date.today()) + ' 1.50701325 BTC' in msg_mock.call_args_list[0][0][0]
#try invalid data # try invalid data
msg_mock.reset_mock() msg_mock.reset_mock()
update_state(State.RUNNING) update_state(State.RUNNING)
update.message.text = '/daily -2' update.message.text = '/daily -2'
_daily(bot=MagicMock(), update=update) _daily(bot=MagicMock(), update=update)
assert msg_mock.call_count == 1 assert msg_mock.call_count == 1
assert 'must be an integer greater than 0' in msg_mock.call_args_list[0][0][0] assert 'must be an integer greater than 0' in msg_mock.call_args_list[0][0][0]
def test_count_handle(default_conf, update, ticker, mocker): def test_count_handle(default_conf, update, ticker, mocker):
mocker.patch.dict('freqtrade.main._CONF', default_conf) mocker.patch.dict('freqtrade.main._CONF', default_conf)
mocker.patch('freqtrade.main.get_signal', side_effect=lambda s, t: True) mocker.patch('freqtrade.main.get_signal', side_effect=lambda s, t: True)

4
setup.cfg Normal file
View File

@ -0,0 +1,4 @@
[flake8]
#ignore =
max-line-length = 100
max-complexity = 12