new examples

This commit is contained in:
Lex Berezhny 2019-04-06 15:33:19 -04:00
parent 93220c3874
commit 1871c94003
2 changed files with 1276 additions and 294 deletions

File diff suppressed because it is too large Load diff

View file

@ -3,12 +3,28 @@ import re
import json import json
import inspect import inspect
import tempfile import tempfile
import asyncio
from docopt import docopt from docopt import docopt
from textwrap import indent
from lbrynet.extras.cli import set_kwargs, get_argument_parser from lbrynet.extras.cli import set_kwargs, get_argument_parser
from lbrynet.extras.daemon.Daemon import Daemon, jsonrpc_dumps_pretty from lbrynet.extras.daemon.Daemon import (
Daemon, jsonrpc_dumps_pretty, encode_pagination_doc
)
from lbrynet.extras.daemon.json_response_encoder import (
encode_tx_doc, encode_txo_doc, encode_account_doc, encode_file_doc
)
from lbrynet.testcase import CommandTestCase from lbrynet.testcase import CommandTestCase
RETURN_DOCS = {
'Account': encode_account_doc(),
'File': encode_file_doc(),
'Transaction': encode_tx_doc(),
'Output': encode_txo_doc(),
'Address': 'an address in base58'
}
class ExampleRecorder: class ExampleRecorder:
def __init__(self, test): def __init__(self, test):
self.test = test self.test = test
@ -21,10 +37,16 @@ class ExampleRecorder:
api_method_name = args.api_method_name api_method_name = args.api_method_name
parsed = docopt(args.doc, command_args) parsed = docopt(args.doc, command_args)
kwargs = set_kwargs(parsed) kwargs = set_kwargs(parsed)
for k, v in kwargs.items():
if v and isinstance(v, str) and (v[0], v[-1]) == ('"', '"'):
kwargs[k] = v[1:-1]
params = json.dumps({"method": api_method_name, "params": kwargs}) params = json.dumps({"method": api_method_name, "params": kwargs})
method = getattr(self.test.daemon, f'jsonrpc_{api_method_name}') method = getattr(self.test.daemon, f'jsonrpc_{api_method_name}')
output = jsonrpc_dumps_pretty(await method(**kwargs), ledger=self.test.daemon.ledger) result = method(**kwargs)
if asyncio.iscoroutine(result):
result = await result
output = jsonrpc_dumps_pretty(result, ledger=self.test.daemon.ledger)
self.examples.setdefault(api_method_name, []).append({ self.examples.setdefault(api_method_name, []).append({
'title': title, 'title': title,
'curl': f"curl -d'{params}' http://localhost:5279/", 'curl': f"curl -d'{params}' http://localhost:5279/",
@ -49,32 +71,127 @@ class Examples(CommandTestCase):
'account', 'list' 'account', 'list'
) )
account = await r(
'Create an account.',
'account', 'create', '"generated account"'
)
await r(
'Remove an account.',
'account', 'remove', account['id']
)
await r(
'Add an account from seed.',
'account', 'add', '"new account"', f"--seed=\"{account['seed']}\""
)
await r(
'Modify maximum number of times a change address can be reused.',
'account', 'set', account['id'], '--change_max_uses=10'
)
channel = await r(
'Create a channel claim.',
'channel', 'create', '@channel', '1.0'
)
await self.on_transaction_dict(channel)
await self.generate(1)
await self.on_transaction_dict(channel)
channel = await r(
'Update a channel claim.',
'channel', 'update', channel['outputs'][0]['claim_id'], '--title="New Channel"'
)
await self.on_transaction_dict(channel)
await self.generate(1)
await self.on_transaction_dict(channel)
with tempfile.NamedTemporaryFile() as file: with tempfile.NamedTemporaryFile() as file:
file.write(b'hello world') file.write(b'hello world')
file.flush() file.flush()
claim = await r( stream = await r(
'Publish a file.', 'Create a stream claim.',
'publish', 'aname', '1.0', f'--file_path={file.name}' 'stream', 'create', 'astream', '1.0', file.name
) )
self.assertTrue(claim['success']) await self.on_transaction_dict(stream)
await self.on_transaction_dict(claim['tx'])
await self.generate(1) await self.generate(1)
await self.on_transaction_dict(claim['tx']) await self.on_transaction_dict(stream)
stream = await r(
'Update a stream claim to add channel.',
'stream', 'update', stream['outputs'][0]['claim_id'],
f"--channel_id={channel['outputs'][0]['claim_id']}"
)
await self.on_transaction_dict(stream)
await self.generate(1)
await self.on_transaction_dict(stream)
await r( await r(
'List your claims.', 'List all your claims.',
'claim', 'list_mine' 'claim', 'list'
) )
await r( await r(
'Abandon a published file.', 'Paginate your claims.',
'claim', 'abandon', claim['claim_id'] 'claim', 'list', '--page=1', '--page_size=20'
) )
await r(
'List all your stream claims.',
'stream', 'list'
)
await r(
'Paginate your stream claims.',
'stream', 'list', '--page=1', '--page_size=20'
)
await r(
'List all your channel claims.',
'channel', 'list'
)
await r(
'Paginate your channel claims.',
'channel', 'list', '--page=1', '--page_size=20'
)
abandon_stream = await r(
'Abandon a stream claim.',
'stream', 'abandon', stream['outputs'][0]['claim_id']
)
await self.on_transaction_dict(abandon_stream)
await self.generate(1)
await self.on_transaction_dict(abandon_stream)
abandon_channel = await r(
'Abandon a channel claim.',
'channel', 'abandon', channel['outputs'][0]['claim_id']
)
await self.on_transaction_dict(abandon_channel)
await self.generate(1)
await self.on_transaction_dict(abandon_channel)
with tempfile.NamedTemporaryFile() as file:
file.write(b'hello world')
file.flush()
stream = await r(
'Publish a file.',
'publish', 'a-new-stream', '--bid=1.0', f'--file_path={file.name}'
)
await self.on_transaction_dict(stream)
await self.generate(1)
await self.on_transaction_dict(stream)
def get_examples(): def get_examples():
player = Examples('play') player = Examples('play')
player.run() result = player.run()
if result.errors:
for error in result.errors:
print(error[1])
raise Exception('See above for errors while running the examples.')
return player.recorder.examples return player.recorder.examples
@ -84,6 +201,25 @@ ARGUMENT_NAME = re.compile("--([^=]+)")
ARGUMENT_TYPE = re.compile("\s*\((.*?)\)(.*)") ARGUMENT_TYPE = re.compile("\s*\((.*?)\)(.*)")
def get_return_def(returns):
result = returns.strip()
if (result[0], result[-1]) == ('{', '}'):
obj_type = result[1:-1]
if '[' in obj_type:
sub_type = obj_type[obj_type.index('[')+1:-1]
obj_type = obj_type[:obj_type.index('[')]
if obj_type == 'Paginated':
obj_def = encode_pagination_doc(RETURN_DOCS[sub_type])
elif obj_type == 'List':
obj_def = [RETURN_DOCS[sub_type]]
else:
raise NameError(f'Unknown return type: {obj_type}')
else:
obj_def = RETURN_DOCS[obj_type]
return indent(json.dumps(obj_def, indent=4), ' '*12)
return result
def get_api(name, examples): def get_api(name, examples):
obj = Daemon.callable_methods[name] obj = Daemon.callable_methods[name]
docstr = inspect.getdoc(obj).strip() docstr = inspect.getdoc(obj).strip()
@ -122,7 +258,7 @@ def get_api(name, examples):
'name': name, 'name': name,
'description': description.strip(), 'description': description.strip(),
'arguments': arguments, 'arguments': arguments,
'returns': returns.strip(), 'returns': get_return_def(returns),
'examples': examples 'examples': examples
} }