Skip to content

Commit

Permalink
Bugfix; tests; release v0.1.0
Browse files Browse the repository at this point in the history
  • Loading branch information
Alexey Poryadin committed Aug 18, 2024
1 parent e4b39cb commit 6465976
Show file tree
Hide file tree
Showing 9 changed files with 106 additions and 12 deletions.
4 changes: 2 additions & 2 deletions abci/abc/handlers.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,11 +86,11 @@ async def offer_snapshot(self, req: RequestOfferSnapshot) -> ResponseOfferSnapsh
to offer the snapshot to the Application. """

@abstractmethod
async def load_snapshotChunk(self, req: RequestLoadSnapshotChunk) -> ResponseLoadSnapshotChunk:
async def load_snapshot_chunk(self, req: RequestLoadSnapshotChunk) -> ResponseLoadSnapshotChunk:
""" Used by CometBFT to retrieve snapshot chunks from the Application to send to peers.
"""

@abstractmethod
async def apply_snapshot_cChunk(self, req: RequestApplySnapshotChunk) -> ResponseApplySnapshotChunk:
async def apply_snapshot_chunk(self, req: RequestApplySnapshotChunk) -> ResponseApplySnapshotChunk:
""" Used by CometBFT to hand snapshot chunks to the Application.
"""
4 changes: 2 additions & 2 deletions abci/samples.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,8 +64,8 @@ async def list_snapshots(self, req: RequestListSnapshots) -> ResponseListSnapsho
async def offer_snapshot(self, req: RequestOfferSnapshot) -> ResponseOfferSnapshot:
return ResponseOfferSnapshot()

async def load_snapshotChunk(self, req: RequestLoadSnapshotChunk) -> ResponseLoadSnapshotChunk:
async def load_snapshot_chunk(self, req: RequestLoadSnapshotChunk) -> ResponseLoadSnapshotChunk:
return ResponseLoadSnapshotChunk()

async def apply_snapshot_cChunk(self, req: RequestApplySnapshotChunk) -> ResponseApplySnapshotChunk:
async def apply_snapshot_chunk(self, req: RequestApplySnapshotChunk) -> ResponseApplySnapshotChunk:
return ResponseApplySnapshotChunk()
12 changes: 11 additions & 1 deletion demo/README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,16 @@
## `KVStore` sample ABCI application

To run the KVStore example, do the following:

* If you are running it for the first time, you need to initialize the home directory of
the single CometBFT node: `cometbft init --home ./.cometbft`
* Run a single CometBFT node with the following parameters: `cometbft start --home ./.cometbft`
* From this directory, launch the application: `python -m abci.server kvstore:app`
* From this directory, launch the application: `python -m abci.server kvstore:app`
* The `pyABCI` package must be installed.

Check it:

```shell
curl -s 'localhost:26657/broadcast_tx_commit?tx="name=satoshi"'
curl -s 'localhost:26657/abci_query?data="name"'
```
9 changes: 5 additions & 4 deletions demo/kvstore.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,14 @@ class KVStore(SimpleApp):

def __init__(self):
super().__init__(lambda value: self._store.__setitem__('__last_block_height', value))
self._store = dict()
self._filename = os.path.join(os.path.dirname(__file__), 'kvstore.csv')
self._store = dict() # type: dict[str, str]
self._filename = os.path.join(os.path.curdir, 'kvstore.csv')
if os.path.exists(self._filename):
with open(self._filename, 'r') as f:
csv_reader = csv.reader(f)
self._store = dict((key, value) for key, value in csv_reader)
else:
self._store['__last_block_height'] = 0
self._store['__last_block_height'] = '0'

@property
def last_block_height(self):
Expand All @@ -32,7 +32,7 @@ async def query(self, req):
resp = await super().query(req)
if resp.key:
if value := self._store.get(resp.key.decode('utf8')):
resp.value = value
resp.value = value.encode('utf8')
resp.log = "exists"
return resp

Expand All @@ -43,6 +43,7 @@ async def check_tx(self, req: RequestCheckTx):
raise
except:
return ResponseCheckTx(code=1, log="Wrong key=value")
return ResponseCheckTx(code=0)

async def finalize_block(self, req: RequestFinalizeBlock):
for tx in req.txs:
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ namespaces = true

[tool.setuptools.dynamic]
dependencies = { file = ["requirements.txt"] }
optional-dependencies.dev = { file = ["tests/requirements.txt"] }
optional-dependencies.tests = { file = ["tests/requirements.txt"] }

[tool.setuptools_scm]

Expand Down
2 changes: 1 addition & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
@@ -1 +1 @@
pure-protobuf @ git+https://github.com/Alesh/pure-protobuf.git@master
pure-protobuf>=3.1.2
1 change: 1 addition & 0 deletions tests/requirements.txt
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
pytest
pytest-asyncio
httpx
82 changes: 82 additions & 0 deletions tests/test_kvstore.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
import asyncio
import logging
import subprocess
import os.path
import tempfile
from base64 import b64decode

import httpx
import pytest
import pytest_asyncio

import abci.server
import abci.utils


@pytest.fixture()
def cometbft():
args = ['docker', 'run', '--net=host', '-d', 'cometbft/cometbft:v0.38.x',
'start', '--proxy_app', 'tcp://127.0.0.1:26658']
proc = subprocess.run(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
if proc.returncode != 0:
logging.error(proc.stderr.decode('utf8'))
assert proc.returncode == 0
container_id = proc.stdout.decode('utf8').strip()
yield container_id[:12]
subprocess.run(['docker', 'rm', '-f', container_id], stdout=subprocess.PIPE, stderr=subprocess.PIPE)


@pytest_asyncio.fixture()
async def kvstore():
curr_path = os.path.abspath(os.path.curdir)
filename = os.path.join(os.path.dirname(__file__), '..', 'demo', 'kvstore.py')
app = abci.utils.resolve_app(f'{filename}:app')
assert app
with tempfile.TemporaryDirectory() as tmpdir:
os.chdir(tmpdir)
srv = abci.server.Server(app)
await srv.start()
count_down = 10
while count_down:
await asyncio.sleep(1)
if len(srv.connections):
break
count_down -= 1
yield srv
srv.stop()
await srv
os.chdir(curr_path)

@pytest.mark.asyncio
async def test_kvstore(cometbft, kvstore):
assert cometbft
assert kvstore
async with httpx.AsyncClient(base_url='http://localhost:26657') as client:
resp = await client.get('/status')
assert resp.status_code == 200
result = resp.json()
assert result['result']['node_info']['protocol_version']['app'] == '100'

resp = await client.get('/broadcast_tx_commit?tx="name=satoshi"')
assert resp.status_code == 200
result = resp.json()
assert result['result']['tx_result']['code'] == 0

resp = await client.get('/abci_query?data="name"')
assert resp.status_code == 200
result = resp.json()
assert result['result']['response']['code'] == 0
assert b64decode(result['result']['response']['value']).decode() == 'satoshi'


resp = await client.get('/broadcast_tx_commit?tx="my=Alesh"')
assert resp.status_code == 200
result = resp.json()
assert result['result']['tx_result']['code'] == 0

resp = await client.get('/abci_query?data="my"')
assert resp.status_code == 200
result = resp.json()
assert result['result']['response']['code'] == 0
assert b64decode(result['result']['response']['value']).decode() == 'Alesh'

2 changes: 1 addition & 1 deletion tests/messages.py → tests/test_messages.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from abci.proto.tendermint import (
from abci.types import (
Request, RequestInfo, RequestFlush, RequestEcho, Response, ResponseEcho, ResponseFlush,
ResponseInfo
)
Expand Down

0 comments on commit 6465976

Please sign in to comment.