Skip to content

Commit

Permalink
Fix and update tests
Browse files Browse the repository at this point in the history
  • Loading branch information
m-bo-one committed Oct 1, 2017
1 parent ff17964 commit 131ca23
Show file tree
Hide file tree
Showing 11 changed files with 232 additions and 31 deletions.
File renamed without changes.
File renamed without changes.
7 changes: 7 additions & 0 deletions MANIFEST.in
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
include LICENSE
include README.rst
include CHANGES.rst
graft ethereumd
graft examples
graft tests
global-exclude *.pyc
4 changes: 2 additions & 2 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -146,8 +146,8 @@ TODO
* Track orphaned blocks;


.. |release| image:: https://img.shields.io/badge/release-v0.2.0-brightgreen.svg
:target: https://github.com/DeV1doR/ethereumd-proxy/releases/tag/v0.2.0
.. |release| image:: https://img.shields.io/badge/release-v0.3.0-brightgreen.svg
:target: https://github.com/DeV1doR/ethereumd-proxy/releases/tag/v0.3.0
:alt: Release

.. |coverage| image:: https://codecov.io/gh/DeV1doR/ethereumd-proxy/branch/master/graph/badge.svg
Expand Down
34 changes: 22 additions & 12 deletions ethereumd/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,17 @@ def __init__(self, ethpconnect='127.0.0.1', ethpport=9500,
self._log = logging.getLogger('rpc_server')
self.routes()

@property
def endpoint(self):
schema = 'http'
if self._tls:
schema += 's'

return ('{0}://{1}:{2}'.format(
schema, self._rpc_host, self._rpc_port)
if not self._unix_socket
else 'unix://{0}'.format(self._unix_socket))

@property
def cmds(self):
cmds = {}
Expand All @@ -64,14 +75,8 @@ def cmds(self):
def before_server_start(self):
@self._app.listener('before_server_start')
async def initialize_scheduler(app, loop):
schema = 'http'
if self._tls:
schema += 's'

uri = ('{0}://{1}:{2}'.format(
schema, self._rpc_host, self._rpc_port)
if not self._unix_socket else self._unix_socket)
self._proxy = await create_ethereumd_proxy(uri, loop=loop)
self._proxy = await create_ethereumd_proxy(self.endpoint,
loop=loop)
self._poller = Poller(self._proxy, self.cmds, loop=loop)
self._scheduler = AsyncIOScheduler({'event_loop': loop})
if self._poller.has_blocknotify:
Expand All @@ -84,6 +89,7 @@ async def initialize_scheduler(app, loop):
seconds=1)
if self._scheduler.get_jobs():
self._scheduler.start()
return initialize_scheduler

def routes(self):
self._app.add_route(self.handler_index, '/',
Expand All @@ -94,14 +100,15 @@ def routes(self):
async def handler_index(self, request):
data = request.json
try:
id_, method, params = data['id'], data['method'], data['params']
id_, method, params, _ = data['id'], \
data['method'], data['params'], data['jsonrpc']
except KeyError:
return response.json({
'id': data.get('id', 0),
'result': None,
'error': {
'message': 'Invalid rpc 2.0 structure',
'code': -40001
'code': -32602
}
})
try:
Expand Down Expand Up @@ -147,7 +154,7 @@ async def handler_log(self, request):
request.args, request.body)
return response.json({'status': 'OK'})

def run(self):
def serve(self):
self.before_server_start()
self._log.info(GREETING)
server_settings = self._app._helper(
Expand All @@ -158,7 +165,10 @@ def run(self):
backlog=100,
run_async=True,
has_log=False)
self._loop.run_until_complete(serve(**server_settings))
return serve(**server_settings)

def run(self):
self._loop.run_until_complete(self.serve())
try:
self._log.warning('Starting server on http://%s:%s/...',
self._host, self._port)
Expand Down
2 changes: 1 addition & 1 deletion setup.cfg
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,4 @@ testpaths = tests

[metadata]
description-file = README.rst
license_file = LICENSE.md
license_file = LICENSE
10 changes: 9 additions & 1 deletion setup.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,16 @@
import os
import sys
import re

from setuptools import find_packages, setup


if sys.version_info >= (3, 5):
pass
else:
raise RuntimeError("ethereumd doesn't support Python version prior 3.5")


def read(*parts):
with open(os.path.join(*parts), 'rt') as f:
return f.read().strip()
Expand All @@ -28,13 +35,14 @@ def read_version():
version=read_version(),
description='Proxy client-server for Ethereum node using '
'JSON-RPC interface.',
long_description="\n\n".join((read('README.rst'), read('CHANGES.txt'))),
long_description="\n\n".join((read('README.rst'), read('CHANGES.rst'))),
py_modules=['ethereum_cli'],
author='Bogdan Kurinnyi',
author_email='bogdankurinniy.dev1@gmail.com',
url='https://github.com/DeV1doR/ethereumd-proxy',
license='MIT',
packages=find_packages(),
include_package_data=True,
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
Expand Down
14 changes: 13 additions & 1 deletion tests/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ def is_hex(s):
# TODO: replace from proxy call in future
async def quick_unlock_account(proxy, duration=5):
return await proxy._rpc.personal_unlockAccount(
(await proxy._rpc.eth_accounts()[0]), 'admin', duration)
(await proxy._rpc.eth_accounts())[0], 'admin', duration)


def setup_proxies(fn):
Expand All @@ -40,6 +40,18 @@ async def _wrapper(self, event_loop, *args, **kwargs):
self.ipc_proxy = await create_ethereumd_proxy(
'unix://%s' % UNIX_PATH, loop=event_loop)
self.proxies.append(self.ipc_proxy)

# wait first mined block
attempt = 0
while True:
number = await self.rpc_proxy._rpc.eth_blockNumber()
if number:
break
print('Waiting block, attempts left %s' % (10 - attempt))
attempt += 1
if attempt == 10:
assert False, 'Chain not synchronized'
await asyncio.sleep(1)
return await fn(self, *args, **kwargs)

return _wrapper
Expand Down
81 changes: 71 additions & 10 deletions tests/test_proxy.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from ethereumd.utils import hex_to_dec, gwei_to_ether
from aioethereum.errors import BadResponseError

from .base import BaseTestRunner, is_hex, setup_proxies
from .base import BaseTestRunner, is_hex, setup_proxies, quick_unlock_account


class TestBaseProxy(BaseTestRunner):
Expand Down Expand Up @@ -43,13 +43,55 @@ async def test_call_getbalance(self):
response = await proxy.getbalance()
assert isinstance(response, (int, float))

@pytest.mark.asyncio
@setup_proxies
async def test_call_validateaddress(self):
for proxy in self.proxies:
response = await proxy.validateaddress(
'0x6cace0528324a8afc2b157ceba3cdd2a27c4e21f')
assert response['isvalid'] is True, \
'Must be valid address, got invalid'

response = await proxy.validateaddress(
'6cace0528324a8afc2b157ceba3cdd2a27c4e21f')
assert response['isvalid'] is True, \
'Must be valid address, got invalid'

response = await proxy.validateaddress(
'0x6caceafc2b157ceba3cdd2a27c4e21f')
assert response['isvalid'] is False, \
'Must be invalid address, got valid'

@pytest.mark.asyncio
@setup_proxies
async def test_call_listsinceblock(self):
for proxy in self.proxies:
block = await proxy._rpc.eth_getBlockByNumber()
response = await proxy.listsinceblock(block['hash'])
assert isinstance(response, Mapping)
# default 1 account on start
assert len(response) == 2
assert response.get('transactions') is not None
assert response.get('lastblock') is not None

@pytest.mark.asyncio
@setup_proxies
async def test_call_getdifficulty(self):
for proxy in self.proxies:
response = await proxy.getdifficulty()
assert isinstance(response, (int, float))

@pytest.mark.asyncio
@setup_proxies
async def test_call_sendfrom(self):
for proxy in self.proxies:
coinbase = await proxy._rpc.eth_coinbase()
await quick_unlock_account(proxy)
response = await proxy.sendfrom(
coinbase, '0xc729d1e61e94e0029865d759327667a6abf0cdc5',
amount=1)
assert isinstance(response, str)

@pytest.mark.asyncio
@setup_proxies
async def test_call_settxfee_as_dont_called(self):
Expand Down Expand Up @@ -101,14 +143,24 @@ async def test_call_gettransaction_not_exist(self):
await proxy.gettransaction(txhash)
assert '-5' in str(excinfo)

# @pytest.mark.asyncio
# @setup_proxies
# async def test_call_sendtoaddress(self):
# for proxy in self.proxies:
# await quick_unlock_account(proxy)
# response = await proxy.sendtoaddress(
# '0x69ea6b31ef305d6b99bb2d4c9d99456fa108b02a', 0.1)
# assert isinstance(response, str)
@pytest.mark.asyncio
@setup_proxies
async def test_call_gettransaction_exist(self):
for proxy in self.proxies:
await quick_unlock_account(proxy)
txhash = await proxy.sendtoaddress(
'0x69ea6b31ef305d6b99bb2d4c9d99456fa108b02a', 0.1)
response = await proxy.gettransaction(txhash)
assert response['txid'] == txhash

@pytest.mark.asyncio
@setup_proxies
async def test_call_sendtoaddress(self):
for proxy in self.proxies:
await quick_unlock_account(proxy)
response = await proxy.sendtoaddress(
'0x69ea6b31ef305d6b99bb2d4c9d99456fa108b02a', 0.1)
assert isinstance(response, str)

@pytest.mark.asyncio
@setup_proxies
Expand All @@ -126,9 +178,18 @@ async def test_call_getbestblockhash(self):

@pytest.mark.asyncio
@setup_proxies
async def test_call_getblock(self):
async def test_call_getblock_not_exist(self):
for proxy in self.proxies:
bhash = '0x12b5f772e7764cdfd140d098db6fcee56bfbc0cb2dcac67aadfb8755b1b56f6d'
with pytest.raises(BadResponseError) as excinfo:
await proxy.getblock(bhash)
assert '-5' in str(excinfo)

@pytest.mark.asyncio
@setup_proxies
async def test_call_getblock_exist(self):
for proxy in self.proxies:
block = await proxy._rpc.eth_getBlockByNumber()
response = await proxy.getblock(block['hash'])
assert response['hash'] == block['hash'], \
'Hash not belongs to requested block'
Loading

0 comments on commit 131ca23

Please sign in to comment.