bigchaindb/tests/web/test_transactions.py

446 lines
17 KiB
Python
Raw Normal View History

# Copyright BigchainDB GmbH and BigchainDB contributors
# SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0)
# Code is Apache-2.0 and docs are CC-BY-4.0
2016-02-24 02:38:30 +01:00
import json
from unittest.mock import Mock, patch
2016-02-24 02:38:30 +01:00
2017-11-25 01:04:50 +01:00
import base58
2016-02-23 03:37:33 +01:00
import pytest
2017-11-25 01:04:50 +01:00
from cryptoconditions import Ed25519Sha256
from sha3 import sha3_256
from bigchaindb.common import crypto
2016-02-23 03:37:33 +01:00
2016-02-29 18:28:04 +01:00
TX_ENDPOINT = '/api/v1/transactions/'
@pytest.mark.abci
def test_get_transaction_endpoint(client, posted_create_tx):
res = client.get(TX_ENDPOINT + posted_create_tx.id)
assert posted_create_tx.to_dict() == res.json
2016-08-23 17:43:08 +02:00
assert res.status_code == 200
2016-02-24 02:38:30 +01:00
2016-06-08 18:39:40 +02:00
def test_get_transaction_returns_404_if_not_found(client):
res = client.get(TX_ENDPOINT + '123')
assert res.status_code == 404
2016-08-23 17:43:08 +02:00
res = client.get(TX_ENDPOINT + '123/')
assert res.status_code == 404
2016-06-08 18:39:40 +02:00
@pytest.mark.abci
2016-02-24 02:38:30 +01:00
def test_post_create_transaction_endpoint(b, client):
Rebase/feat/586/integrate tx model (#641) * Adjust imports to bigchaindb_common * Adjust get_spent function signature * Adjust block serialization * Fix BigchainApi Test * Fix TestTransactionValidation tests * Fix TestBlockValidation tests * WIP: TestMultipleInputs * Adjust tests to tx-model interface changes - Fix old tests - Fix tests in TestMultipleInputs class * Remove fulfillment message tests * Fix TransactionMalleability tests * Remove Cryptoconditions tests * Remove create_transaction * Remove signing logic * Remove consensus plugin * Fix block_creation pipeline * Fix election pipeline * Replace some util functions with bdb_common ones - timestamp ==> gen_timestamp - serialize. * Implement Block model * Simplify function signatures for vote functions Change parameter interface for the following functions: - has_previous_vote - verify_vote_signature - block_election_status so that they take a block's id and voters instead of a fake block. * Integrate Block and Transaction model * Fix leftover tests and cleanup conftest * Add bigchaindb-common to install_requires * Delete transactions after block is written (#609) * delete transactions after block is written * cleanup transaction_exists * check for duplicate transactions * delete invalid tx from backlog * test duplicate transaction * Remove dead code * Test processes.py * Test invalid tx in on server * Fix tests for core.py * Fix models tests * Test commands main fn * Add final coverage to vote pipeline * Add more tests to voting pipeline * Remove consensus plugin docs and misc * Post rebase fixes * Fix rebase mess * Remove extra blank line * Improve docstring * Remove comment handled in bigchaindb/cryptoconditions#27; see https://github.com/bigchaindb/cryptoconditions/issues/27 * Fix block serialization in block creation * Add signed_ prefix to transfer_tx * Improve docs * Add library documentation page on pipelines * PR feedback for models.py * Impr. readability of get_last_voted_block * Use dict comprehension * Add docker-compose file to build and serve docs locally for development purposes * Change private_key for signing_key * Improve docstrings * Remove consensus docs * Document new consensus module * Create different transactions for the block * Cleanup variable names in block.py * Create different transactions for the block * Cleanup variable names in block.py
2016-09-29 10:29:41 +02:00
from bigchaindb.models import Transaction
user_priv, user_pub = crypto.generate_key_pair()
tx = Transaction.create([user_pub], [([user_pub], 1)])
Rebase/feat/586/integrate tx model (#641) * Adjust imports to bigchaindb_common * Adjust get_spent function signature * Adjust block serialization * Fix BigchainApi Test * Fix TestTransactionValidation tests * Fix TestBlockValidation tests * WIP: TestMultipleInputs * Adjust tests to tx-model interface changes - Fix old tests - Fix tests in TestMultipleInputs class * Remove fulfillment message tests * Fix TransactionMalleability tests * Remove Cryptoconditions tests * Remove create_transaction * Remove signing logic * Remove consensus plugin * Fix block_creation pipeline * Fix election pipeline * Replace some util functions with bdb_common ones - timestamp ==> gen_timestamp - serialize. * Implement Block model * Simplify function signatures for vote functions Change parameter interface for the following functions: - has_previous_vote - verify_vote_signature - block_election_status so that they take a block's id and voters instead of a fake block. * Integrate Block and Transaction model * Fix leftover tests and cleanup conftest * Add bigchaindb-common to install_requires * Delete transactions after block is written (#609) * delete transactions after block is written * cleanup transaction_exists * check for duplicate transactions * delete invalid tx from backlog * test duplicate transaction * Remove dead code * Test processes.py * Test invalid tx in on server * Fix tests for core.py * Fix models tests * Test commands main fn * Add final coverage to vote pipeline * Add more tests to voting pipeline * Remove consensus plugin docs and misc * Post rebase fixes * Fix rebase mess * Remove extra blank line * Improve docstring * Remove comment handled in bigchaindb/cryptoconditions#27; see https://github.com/bigchaindb/cryptoconditions/issues/27 * Fix block serialization in block creation * Add signed_ prefix to transfer_tx * Improve docs * Add library documentation page on pipelines * PR feedback for models.py * Impr. readability of get_last_voted_block * Use dict comprehension * Add docker-compose file to build and serve docs locally for development purposes * Change private_key for signing_key * Improve docstrings * Remove consensus docs * Document new consensus module * Create different transactions for the block * Cleanup variable names in block.py * Create different transactions for the block * Cleanup variable names in block.py
2016-09-29 10:29:41 +02:00
tx = tx.sign([user_priv])
res = client.post(TX_ENDPOINT, data=json.dumps(tx.to_dict()))
assert res.status_code == 202
assert res.json['inputs'][0]['owners_before'][0] == user_pub
assert res.json['outputs'][0]['public_keys'][0] == user_pub
2016-02-24 02:38:30 +01:00
Rebase/feat/586/integrate tx model (#641) * Adjust imports to bigchaindb_common * Adjust get_spent function signature * Adjust block serialization * Fix BigchainApi Test * Fix TestTransactionValidation tests * Fix TestBlockValidation tests * WIP: TestMultipleInputs * Adjust tests to tx-model interface changes - Fix old tests - Fix tests in TestMultipleInputs class * Remove fulfillment message tests * Fix TransactionMalleability tests * Remove Cryptoconditions tests * Remove create_transaction * Remove signing logic * Remove consensus plugin * Fix block_creation pipeline * Fix election pipeline * Replace some util functions with bdb_common ones - timestamp ==> gen_timestamp - serialize. * Implement Block model * Simplify function signatures for vote functions Change parameter interface for the following functions: - has_previous_vote - verify_vote_signature - block_election_status so that they take a block's id and voters instead of a fake block. * Integrate Block and Transaction model * Fix leftover tests and cleanup conftest * Add bigchaindb-common to install_requires * Delete transactions after block is written (#609) * delete transactions after block is written * cleanup transaction_exists * check for duplicate transactions * delete invalid tx from backlog * test duplicate transaction * Remove dead code * Test processes.py * Test invalid tx in on server * Fix tests for core.py * Fix models tests * Test commands main fn * Add final coverage to vote pipeline * Add more tests to voting pipeline * Remove consensus plugin docs and misc * Post rebase fixes * Fix rebase mess * Remove extra blank line * Improve docstring * Remove comment handled in bigchaindb/cryptoconditions#27; see https://github.com/bigchaindb/cryptoconditions/issues/27 * Fix block serialization in block creation * Add signed_ prefix to transfer_tx * Improve docs * Add library documentation page on pipelines * PR feedback for models.py * Impr. readability of get_last_voted_block * Use dict comprehension * Add docker-compose file to build and serve docs locally for development purposes * Change private_key for signing_key * Improve docstrings * Remove consensus docs * Document new consensus module * Create different transactions for the block * Cleanup variable names in block.py * Create different transactions for the block * Cleanup variable names in block.py
2016-09-29 10:29:41 +02:00
@pytest.mark.abci
2017-11-27 16:22:33 +01:00
@pytest.mark.parametrize('nested', [False, True])
@pytest.mark.parametrize('language,expected_status_code', [
('danish', 202), ('dutch', 202), ('english', 202), ('finnish', 202),
('french', 202), ('german', 202), ('hungarian', 202), ('italian', 202),
('norwegian', 202), ('portuguese', 202), ('romanian', 202), ('none', 202),
('russian', 202), ('spanish', 202), ('swedish', 202), ('turkish', 202),
('da', 202), ('nl', 202), ('en', 202), ('fi', 202), ('fr', 202),
('de', 202), ('hu', 202), ('it', 202), ('nb', 202), ('pt', 202),
('ro', 202), ('ru', 202), ('es', 202), ('sv', 202), ('tr', 202),
('any', 400)
2017-10-31 05:42:16 +01:00
])
@pytest.mark.language
def test_post_create_transaction_with_language(b, client, nested, language,
expected_status_code):
2017-10-31 05:42:16 +01:00
from bigchaindb.models import Transaction
from bigchaindb.backend.localmongodb.connection import LocalMongoDBConnection
2017-10-31 05:42:16 +01:00
if isinstance(b.connection, LocalMongoDBConnection):
2017-10-31 05:42:16 +01:00
user_priv, user_pub = crypto.generate_key_pair()
lang_obj = {'language': language}
if nested:
asset = {'root': lang_obj}
else:
asset = lang_obj
2017-10-31 05:42:16 +01:00
tx = Transaction.create([user_pub], [([user_pub], 1)],
asset=asset)
2017-10-31 05:42:16 +01:00
tx = tx.sign([user_priv])
res = client.post(TX_ENDPOINT, data=json.dumps(tx.to_dict()))
assert res.status_code == expected_status_code
if res.status_code == 400:
expected_error_message = (
'Invalid transaction (ValidationError): MongoDB does not support '
'text search for the language "{}". If you do not understand this '
'error message then please rename key/field "language" to something '
'else like "lang".').format(language)
assert res.json['message'] == expected_error_message
@pytest.mark.abci
2017-11-23 10:50:19 +01:00
@pytest.mark.parametrize('field', ['asset', 'metadata'])
@pytest.mark.parametrize('value,err_key,expected_status_code', [
({'bad.key': 'v'}, 'bad.key', 400),
({'$bad.key': 'v'}, '$bad.key', 400),
({'$badkey': 'v'}, '$badkey', 400),
({'bad\x00key': 'v'}, 'bad\x00key', 400),
({'good_key': {'bad.key': 'v'}}, 'bad.key', 400),
({'good_key': 'v'}, 'good_key', 202)
2017-10-31 10:46:59 +01:00
])
def test_post_create_transaction_with_invalid_key(b, client, field, value,
err_key, expected_status_code):
2017-10-31 10:46:59 +01:00
from bigchaindb.models import Transaction
from bigchaindb.backend.localmongodb.connection import LocalMongoDBConnection
2017-10-31 10:46:59 +01:00
user_priv, user_pub = crypto.generate_key_pair()
if isinstance(b.connection, LocalMongoDBConnection):
if field == 'asset':
tx = Transaction.create([user_pub], [([user_pub], 1)],
asset=value)
elif field == 'metadata':
tx = Transaction.create([user_pub], [([user_pub], 1)],
metadata=value)
2017-10-31 10:46:59 +01:00
tx = tx.sign([user_priv])
res = client.post(TX_ENDPOINT, data=json.dumps(tx.to_dict()))
assert res.status_code == expected_status_code
2017-10-31 10:46:59 +01:00
if res.status_code == 400:
expected_error_message = (
'Invalid transaction (ValidationError): Invalid key name "{}" '
'in {} object. The key name cannot contain characters '
'".", "$" or null characters').format(err_key, field)
2017-10-31 10:46:59 +01:00
assert res.json['message'] == expected_error_message
@pytest.mark.abci
2017-03-13 17:55:11 +01:00
@patch('bigchaindb.web.views.base.logger')
def test_post_create_transaction_with_invalid_id(mock_logger, b, client):
2016-12-08 14:29:30 +01:00
from bigchaindb.common.exceptions import InvalidHash
Rebase/feat/586/integrate tx model (#641) * Adjust imports to bigchaindb_common * Adjust get_spent function signature * Adjust block serialization * Fix BigchainApi Test * Fix TestTransactionValidation tests * Fix TestBlockValidation tests * WIP: TestMultipleInputs * Adjust tests to tx-model interface changes - Fix old tests - Fix tests in TestMultipleInputs class * Remove fulfillment message tests * Fix TransactionMalleability tests * Remove Cryptoconditions tests * Remove create_transaction * Remove signing logic * Remove consensus plugin * Fix block_creation pipeline * Fix election pipeline * Replace some util functions with bdb_common ones - timestamp ==> gen_timestamp - serialize. * Implement Block model * Simplify function signatures for vote functions Change parameter interface for the following functions: - has_previous_vote - verify_vote_signature - block_election_status so that they take a block's id and voters instead of a fake block. * Integrate Block and Transaction model * Fix leftover tests and cleanup conftest * Add bigchaindb-common to install_requires * Delete transactions after block is written (#609) * delete transactions after block is written * cleanup transaction_exists * check for duplicate transactions * delete invalid tx from backlog * test duplicate transaction * Remove dead code * Test processes.py * Test invalid tx in on server * Fix tests for core.py * Fix models tests * Test commands main fn * Add final coverage to vote pipeline * Add more tests to voting pipeline * Remove consensus plugin docs and misc * Post rebase fixes * Fix rebase mess * Remove extra blank line * Improve docstring * Remove comment handled in bigchaindb/cryptoconditions#27; see https://github.com/bigchaindb/cryptoconditions/issues/27 * Fix block serialization in block creation * Add signed_ prefix to transfer_tx * Improve docs * Add library documentation page on pipelines * PR feedback for models.py * Impr. readability of get_last_voted_block * Use dict comprehension * Add docker-compose file to build and serve docs locally for development purposes * Change private_key for signing_key * Improve docstrings * Remove consensus docs * Document new consensus module * Create different transactions for the block * Cleanup variable names in block.py * Create different transactions for the block * Cleanup variable names in block.py
2016-09-29 10:29:41 +02:00
from bigchaindb.models import Transaction
user_priv, user_pub = crypto.generate_key_pair()
tx = Transaction.create([user_pub], [([user_pub], 1)])
Rebase/feat/586/integrate tx model (#641) * Adjust imports to bigchaindb_common * Adjust get_spent function signature * Adjust block serialization * Fix BigchainApi Test * Fix TestTransactionValidation tests * Fix TestBlockValidation tests * WIP: TestMultipleInputs * Adjust tests to tx-model interface changes - Fix old tests - Fix tests in TestMultipleInputs class * Remove fulfillment message tests * Fix TransactionMalleability tests * Remove Cryptoconditions tests * Remove create_transaction * Remove signing logic * Remove consensus plugin * Fix block_creation pipeline * Fix election pipeline * Replace some util functions with bdb_common ones - timestamp ==> gen_timestamp - serialize. * Implement Block model * Simplify function signatures for vote functions Change parameter interface for the following functions: - has_previous_vote - verify_vote_signature - block_election_status so that they take a block's id and voters instead of a fake block. * Integrate Block and Transaction model * Fix leftover tests and cleanup conftest * Add bigchaindb-common to install_requires * Delete transactions after block is written (#609) * delete transactions after block is written * cleanup transaction_exists * check for duplicate transactions * delete invalid tx from backlog * test duplicate transaction * Remove dead code * Test processes.py * Test invalid tx in on server * Fix tests for core.py * Fix models tests * Test commands main fn * Add final coverage to vote pipeline * Add more tests to voting pipeline * Remove consensus plugin docs and misc * Post rebase fixes * Fix rebase mess * Remove extra blank line * Improve docstring * Remove comment handled in bigchaindb/cryptoconditions#27; see https://github.com/bigchaindb/cryptoconditions/issues/27 * Fix block serialization in block creation * Add signed_ prefix to transfer_tx * Improve docs * Add library documentation page on pipelines * PR feedback for models.py * Impr. readability of get_last_voted_block * Use dict comprehension * Add docker-compose file to build and serve docs locally for development purposes * Change private_key for signing_key * Improve docstrings * Remove consensus docs * Document new consensus module * Create different transactions for the block * Cleanup variable names in block.py * Create different transactions for the block * Cleanup variable names in block.py
2016-09-29 10:29:41 +02:00
tx = tx.sign([user_priv]).to_dict()
Schema definition (#798) Commit messages for posterity: * wip transaction schema definition * test for SchemaObject * test SchemaObject definions meta property * schema documentation updates * test for basic validation * commit before change to .json file definiton + rst generation * move to straight .json schema, test for additionalProperties on each object * add asset to transaction definiton * remove outdated tx validation * make all tests pass * create own exception for validation error and start validating transactions * more tx validation fixes * move to yaml file for schema * automatic schema documentation generator * remove redundant section * use YAML safe loading * change current_owners to owners_before in tx schema * re-run tests and make correct yaml schema * fix some broken tests * update Release_Process.md * move tx validation into it's own method * add jsonschema dependency * perform schema validation after ID validation on Transaction * Release_Process.md, markdown auto numbering * remove old transaction.json * resolve remaining TODOs in schema docuementation * add `id` and `$schema` to transaction.yaml * add transaction.yaml to setup.py so it gets copied * address some concernes in PR for transaction.yaml * address more PR concerns in transaction.yaml * refactor validtion exceptions and move transaction schema validation into it's own function in bigchaindb.common.schema.__init__ * add note to generated schema.rst indicating when and how it's generated * move tx schema validation back above ID validation in Transaction.validate_structure, test that structurally invalid transaction gets caught and 400 returned in TX POST handler * remove timestamp from transaction schema index * Add README.md to bigchaindb.common.schema for introduction to JSON Schema and reasons for YAML * Use constant for schema definitions' base prefix * Move import of ValidationError exception into only the tests that require it * Move validate transaction test helper to tests/common/util.py * move ordered transaction schema load to generate_schema_documentation.py where it's needed * use double backticks to render terms in schema docs * change more backticks and change transaction version description in transaction schema * make details a mandatory property of condition * Many more documentation fixes * rename schema.rst to schema/transaction.rst * Fix documentation for Metadata * Add more links to documentation * Various other documentation fixes * Rename section titles in rendered documentation * use to manage file handle * fix extrenuous comma in test_tx_serialization_with_incorrect_hash args * 'a' * 64 * remove schema validation until we can analyze properly impact on downstream consumers * fix flake8 error * use `with` always
2016-11-22 11:17:06 +01:00
tx['id'] = 'abcd' * 16
2016-02-24 02:38:30 +01:00
2016-02-29 18:28:04 +01:00
res = client.post(TX_ENDPOINT, data=json.dumps(tx))
2017-01-17 11:32:30 +01:00
expected_status_code = 400
expected_error_message = (
2017-03-13 17:55:11 +01:00
"Invalid transaction ({}): The transaction's id '{}' isn't equal to "
"the hash of its body, i.e. it's not valid."
2017-01-17 11:32:30 +01:00
).format(InvalidHash.__name__, tx['id'])
assert res.status_code == expected_status_code
assert res.json['message'] == expected_error_message
2017-03-13 17:55:11 +01:00
assert mock_logger.error.called
assert (
'HTTP API error: %(status)s - %(method)s:%(path)s - %(message)s' in
2017-03-13 17:55:11 +01:00
mock_logger.error.call_args[0]
)
assert (
{
'message': expected_error_message, 'status': expected_status_code,
'method': 'POST', 'path': TX_ENDPOINT
} in mock_logger.error.call_args[0]
2017-03-13 17:55:11 +01:00
)
# TODO put back caplog based asserts once possible
# assert caplog.records[0].args['status'] == expected_status_code
# assert caplog.records[0].args['message'] == expected_error_message
@pytest.mark.abci
2017-03-13 17:55:11 +01:00
@patch('bigchaindb.web.views.base.logger')
def test_post_create_transaction_with_invalid_signature(mock_logger,
b,
client):
2016-12-08 14:29:30 +01:00
from bigchaindb.common.exceptions import InvalidSignature
Rebase/feat/586/integrate tx model (#641) * Adjust imports to bigchaindb_common * Adjust get_spent function signature * Adjust block serialization * Fix BigchainApi Test * Fix TestTransactionValidation tests * Fix TestBlockValidation tests * WIP: TestMultipleInputs * Adjust tests to tx-model interface changes - Fix old tests - Fix tests in TestMultipleInputs class * Remove fulfillment message tests * Fix TransactionMalleability tests * Remove Cryptoconditions tests * Remove create_transaction * Remove signing logic * Remove consensus plugin * Fix block_creation pipeline * Fix election pipeline * Replace some util functions with bdb_common ones - timestamp ==> gen_timestamp - serialize. * Implement Block model * Simplify function signatures for vote functions Change parameter interface for the following functions: - has_previous_vote - verify_vote_signature - block_election_status so that they take a block's id and voters instead of a fake block. * Integrate Block and Transaction model * Fix leftover tests and cleanup conftest * Add bigchaindb-common to install_requires * Delete transactions after block is written (#609) * delete transactions after block is written * cleanup transaction_exists * check for duplicate transactions * delete invalid tx from backlog * test duplicate transaction * Remove dead code * Test processes.py * Test invalid tx in on server * Fix tests for core.py * Fix models tests * Test commands main fn * Add final coverage to vote pipeline * Add more tests to voting pipeline * Remove consensus plugin docs and misc * Post rebase fixes * Fix rebase mess * Remove extra blank line * Improve docstring * Remove comment handled in bigchaindb/cryptoconditions#27; see https://github.com/bigchaindb/cryptoconditions/issues/27 * Fix block serialization in block creation * Add signed_ prefix to transfer_tx * Improve docs * Add library documentation page on pipelines * PR feedback for models.py * Impr. readability of get_last_voted_block * Use dict comprehension * Add docker-compose file to build and serve docs locally for development purposes * Change private_key for signing_key * Improve docstrings * Remove consensus docs * Document new consensus module * Create different transactions for the block * Cleanup variable names in block.py * Create different transactions for the block * Cleanup variable names in block.py
2016-09-29 10:29:41 +02:00
from bigchaindb.models import Transaction
user_priv, user_pub = crypto.generate_key_pair()
2016-08-23 17:43:08 +02:00
2017-11-25 01:04:50 +01:00
tx = Transaction.create([user_pub], [([user_pub], 1)]).to_dict()
2017-06-14 18:42:07 +02:00
tx['inputs'][0]['fulfillment'] = 64 * '0'
2017-11-25 01:04:50 +01:00
tx['id'] = sha3_256(
json.dumps(
tx,
sort_keys=True,
separators=(',', ':'),
ensure_ascii=False,
).encode(),
).hexdigest()
2016-08-23 17:43:08 +02:00
Rebase/feat/586/integrate tx model (#641) * Adjust imports to bigchaindb_common * Adjust get_spent function signature * Adjust block serialization * Fix BigchainApi Test * Fix TestTransactionValidation tests * Fix TestBlockValidation tests * WIP: TestMultipleInputs * Adjust tests to tx-model interface changes - Fix old tests - Fix tests in TestMultipleInputs class * Remove fulfillment message tests * Fix TransactionMalleability tests * Remove Cryptoconditions tests * Remove create_transaction * Remove signing logic * Remove consensus plugin * Fix block_creation pipeline * Fix election pipeline * Replace some util functions with bdb_common ones - timestamp ==> gen_timestamp - serialize. * Implement Block model * Simplify function signatures for vote functions Change parameter interface for the following functions: - has_previous_vote - verify_vote_signature - block_election_status so that they take a block's id and voters instead of a fake block. * Integrate Block and Transaction model * Fix leftover tests and cleanup conftest * Add bigchaindb-common to install_requires * Delete transactions after block is written (#609) * delete transactions after block is written * cleanup transaction_exists * check for duplicate transactions * delete invalid tx from backlog * test duplicate transaction * Remove dead code * Test processes.py * Test invalid tx in on server * Fix tests for core.py * Fix models tests * Test commands main fn * Add final coverage to vote pipeline * Add more tests to voting pipeline * Remove consensus plugin docs and misc * Post rebase fixes * Fix rebase mess * Remove extra blank line * Improve docstring * Remove comment handled in bigchaindb/cryptoconditions#27; see https://github.com/bigchaindb/cryptoconditions/issues/27 * Fix block serialization in block creation * Add signed_ prefix to transfer_tx * Improve docs * Add library documentation page on pipelines * PR feedback for models.py * Impr. readability of get_last_voted_block * Use dict comprehension * Add docker-compose file to build and serve docs locally for development purposes * Change private_key for signing_key * Improve docstrings * Remove consensus docs * Document new consensus module * Create different transactions for the block * Cleanup variable names in block.py * Create different transactions for the block * Cleanup variable names in block.py
2016-09-29 10:29:41 +02:00
res = client.post(TX_ENDPOINT, data=json.dumps(tx))
2017-01-17 11:32:30 +01:00
expected_status_code = 400
expected_error_message = (
'Invalid transaction ({}): Fulfillment URI '
'couldn\'t been parsed'
2017-01-17 11:32:30 +01:00
).format(InvalidSignature.__name__)
assert res.status_code == expected_status_code
assert res.json['message'] == expected_error_message
2017-03-13 17:55:11 +01:00
assert mock_logger.error.called
assert (
'HTTP API error: %(status)s - %(method)s:%(path)s - %(message)s' in
2017-03-13 17:55:11 +01:00
mock_logger.error.call_args[0]
)
assert (
{
'message': expected_error_message, 'status': expected_status_code,
'method': 'POST', 'path': TX_ENDPOINT
} in mock_logger.error.call_args[0]
2017-03-13 17:55:11 +01:00
)
# TODO put back caplog based asserts once possible
# assert caplog.records[0].args['status'] == expected_status_code
# assert caplog.records[0].args['message'] == expected_error_message
2016-08-23 17:43:08 +02:00
@pytest.mark.abci
Schema definition (#798) Commit messages for posterity: * wip transaction schema definition * test for SchemaObject * test SchemaObject definions meta property * schema documentation updates * test for basic validation * commit before change to .json file definiton + rst generation * move to straight .json schema, test for additionalProperties on each object * add asset to transaction definiton * remove outdated tx validation * make all tests pass * create own exception for validation error and start validating transactions * more tx validation fixes * move to yaml file for schema * automatic schema documentation generator * remove redundant section * use YAML safe loading * change current_owners to owners_before in tx schema * re-run tests and make correct yaml schema * fix some broken tests * update Release_Process.md * move tx validation into it's own method * add jsonschema dependency * perform schema validation after ID validation on Transaction * Release_Process.md, markdown auto numbering * remove old transaction.json * resolve remaining TODOs in schema docuementation * add `id` and `$schema` to transaction.yaml * add transaction.yaml to setup.py so it gets copied * address some concernes in PR for transaction.yaml * address more PR concerns in transaction.yaml * refactor validtion exceptions and move transaction schema validation into it's own function in bigchaindb.common.schema.__init__ * add note to generated schema.rst indicating when and how it's generated * move tx schema validation back above ID validation in Transaction.validate_structure, test that structurally invalid transaction gets caught and 400 returned in TX POST handler * remove timestamp from transaction schema index * Add README.md to bigchaindb.common.schema for introduction to JSON Schema and reasons for YAML * Use constant for schema definitions' base prefix * Move import of ValidationError exception into only the tests that require it * Move validate transaction test helper to tests/common/util.py * move ordered transaction schema load to generate_schema_documentation.py where it's needed * use double backticks to render terms in schema docs * change more backticks and change transaction version description in transaction schema * make details a mandatory property of condition * Many more documentation fixes * rename schema.rst to schema/transaction.rst * Fix documentation for Metadata * Add more links to documentation * Various other documentation fixes * Rename section titles in rendered documentation * use to manage file handle * fix extrenuous comma in test_tx_serialization_with_incorrect_hash args * 'a' * 64 * remove schema validation until we can analyze properly impact on downstream consumers * fix flake8 error * use `with` always
2016-11-22 11:17:06 +01:00
def test_post_create_transaction_with_invalid_structure(client):
res = client.post(TX_ENDPOINT, data='{}')
assert res.status_code == 400
@pytest.mark.abci
2017-03-13 17:55:11 +01:00
@patch('bigchaindb.web.views.base.logger')
def test_post_create_transaction_with_invalid_schema(mock_logger, client):
from bigchaindb.models import Transaction
user_priv, user_pub = crypto.generate_key_pair()
2017-11-25 01:04:50 +01:00
tx = Transaction.create([user_pub], [([user_pub], 1)]).to_dict()
del tx['version']
2017-11-25 01:04:50 +01:00
ed25519 = Ed25519Sha256(public_key=base58.b58decode(user_pub))
message = json.dumps(
tx,
sort_keys=True,
separators=(',', ':'),
ensure_ascii=False,
).encode()
ed25519.sign(message, base58.b58decode(user_priv))
tx['inputs'][0]['fulfillment'] = ed25519.serialize_uri()
tx['id'] = sha3_256(
json.dumps(
tx,
sort_keys=True,
separators=(',', ':'),
ensure_ascii=False,
).encode(),
).hexdigest()
res = client.post(TX_ENDPOINT, data=json.dumps(tx))
2017-01-17 11:32:30 +01:00
expected_status_code = 400
expected_error_message = (
"Invalid transaction schema: 'version' is a required property")
2017-01-17 11:32:30 +01:00
assert res.status_code == expected_status_code
assert res.json['message'] == expected_error_message
2017-03-13 17:55:11 +01:00
assert mock_logger.error.called
assert (
'HTTP API error: %(status)s - %(method)s:%(path)s - %(message)s' in
2017-03-13 17:55:11 +01:00
mock_logger.error.call_args[0]
)
assert (
{
'message': expected_error_message, 'status': expected_status_code,
'method': 'POST', 'path': TX_ENDPOINT
} in mock_logger.error.call_args[0]
2017-03-13 17:55:11 +01:00
)
# TODO put back caplog based asserts once possible
# assert caplog.records[0].args['status'] == expected_status_code
# assert caplog.records[0].args['message'] == expected_error_message
@pytest.mark.abci
2016-12-08 14:29:30 +01:00
@pytest.mark.parametrize('exc,msg', (
('AmountError', 'Do the math again!'),
('DoubleSpend', 'Nope! It is gone now!'),
('InvalidHash', 'Do not smoke that!'),
('InvalidSignature', 'Falsche Unterschrift!'),
('ValidationError', 'Create and transfer!'),
('InputDoesNotExist', 'Hallucinations?'),
2016-12-08 14:29:30 +01:00
('TransactionOwnerError', 'Not yours!'),
('ValidationError', '?'),
2016-12-08 14:29:30 +01:00
))
2017-03-13 17:55:11 +01:00
@patch('bigchaindb.web.views.base.logger')
def test_post_invalid_transaction(mock_logger, client, exc, msg, monkeypatch,):
2016-12-08 14:29:30 +01:00
from bigchaindb.common import exceptions
exc_cls = getattr(exceptions, exc)
2016-12-08 14:29:30 +01:00
def mock_validation(self_, tx):
raise exc_cls(msg)
TransactionMock = Mock(validate=mock_validation)
2016-12-08 14:29:30 +01:00
monkeypatch.setattr(
'bigchaindb.models.Transaction.from_dict', lambda tx: TransactionMock)
2016-12-08 14:29:30 +01:00
res = client.post(TX_ENDPOINT, data=json.dumps({}))
2017-01-17 11:32:30 +01:00
expected_status_code = 400
expected_error_message = 'Invalid transaction ({}): {}'.format(exc, msg)
assert res.status_code == expected_status_code
2016-12-08 14:29:30 +01:00
assert (res.json['message'] ==
'Invalid transaction ({}): {}'.format(exc, msg))
2017-03-13 17:55:11 +01:00
assert mock_logger.error.called
assert (
'HTTP API error: %(status)s - %(method)s:%(path)s - %(message)s' in
2017-03-13 17:55:11 +01:00
mock_logger.error.call_args[0]
)
assert (
{
'message': expected_error_message, 'status': expected_status_code,
'method': 'POST', 'path': TX_ENDPOINT
} in mock_logger.error.call_args[0]
2017-03-13 17:55:11 +01:00
)
# TODO put back caplog based asserts once possible
# assert caplog.records[2].args['status'] == expected_status_code
# assert caplog.records[2].args['message'] == expected_error_message
2016-12-08 14:29:30 +01:00
@pytest.mark.abci
def test_post_transfer_transaction_endpoint(client, user_pk, user_sk, posted_create_tx):
Rebase/feat/586/integrate tx model (#641) * Adjust imports to bigchaindb_common * Adjust get_spent function signature * Adjust block serialization * Fix BigchainApi Test * Fix TestTransactionValidation tests * Fix TestBlockValidation tests * WIP: TestMultipleInputs * Adjust tests to tx-model interface changes - Fix old tests - Fix tests in TestMultipleInputs class * Remove fulfillment message tests * Fix TransactionMalleability tests * Remove Cryptoconditions tests * Remove create_transaction * Remove signing logic * Remove consensus plugin * Fix block_creation pipeline * Fix election pipeline * Replace some util functions with bdb_common ones - timestamp ==> gen_timestamp - serialize. * Implement Block model * Simplify function signatures for vote functions Change parameter interface for the following functions: - has_previous_vote - verify_vote_signature - block_election_status so that they take a block's id and voters instead of a fake block. * Integrate Block and Transaction model * Fix leftover tests and cleanup conftest * Add bigchaindb-common to install_requires * Delete transactions after block is written (#609) * delete transactions after block is written * cleanup transaction_exists * check for duplicate transactions * delete invalid tx from backlog * test duplicate transaction * Remove dead code * Test processes.py * Test invalid tx in on server * Fix tests for core.py * Fix models tests * Test commands main fn * Add final coverage to vote pipeline * Add more tests to voting pipeline * Remove consensus plugin docs and misc * Post rebase fixes * Fix rebase mess * Remove extra blank line * Improve docstring * Remove comment handled in bigchaindb/cryptoconditions#27; see https://github.com/bigchaindb/cryptoconditions/issues/27 * Fix block serialization in block creation * Add signed_ prefix to transfer_tx * Improve docs * Add library documentation page on pipelines * PR feedback for models.py * Impr. readability of get_last_voted_block * Use dict comprehension * Add docker-compose file to build and serve docs locally for development purposes * Change private_key for signing_key * Improve docstrings * Remove consensus docs * Document new consensus module * Create different transactions for the block * Cleanup variable names in block.py * Create different transactions for the block * Cleanup variable names in block.py
2016-09-29 10:29:41 +02:00
from bigchaindb.models import Transaction
transfer_tx = Transaction.transfer(posted_create_tx.to_inputs(),
[([user_pk], 1)],
asset_id=posted_create_tx.id)
Rebase/feat/586/integrate tx model (#641) * Adjust imports to bigchaindb_common * Adjust get_spent function signature * Adjust block serialization * Fix BigchainApi Test * Fix TestTransactionValidation tests * Fix TestBlockValidation tests * WIP: TestMultipleInputs * Adjust tests to tx-model interface changes - Fix old tests - Fix tests in TestMultipleInputs class * Remove fulfillment message tests * Fix TransactionMalleability tests * Remove Cryptoconditions tests * Remove create_transaction * Remove signing logic * Remove consensus plugin * Fix block_creation pipeline * Fix election pipeline * Replace some util functions with bdb_common ones - timestamp ==> gen_timestamp - serialize. * Implement Block model * Simplify function signatures for vote functions Change parameter interface for the following functions: - has_previous_vote - verify_vote_signature - block_election_status so that they take a block's id and voters instead of a fake block. * Integrate Block and Transaction model * Fix leftover tests and cleanup conftest * Add bigchaindb-common to install_requires * Delete transactions after block is written (#609) * delete transactions after block is written * cleanup transaction_exists * check for duplicate transactions * delete invalid tx from backlog * test duplicate transaction * Remove dead code * Test processes.py * Test invalid tx in on server * Fix tests for core.py * Fix models tests * Test commands main fn * Add final coverage to vote pipeline * Add more tests to voting pipeline * Remove consensus plugin docs and misc * Post rebase fixes * Fix rebase mess * Remove extra blank line * Improve docstring * Remove comment handled in bigchaindb/cryptoconditions#27; see https://github.com/bigchaindb/cryptoconditions/issues/27 * Fix block serialization in block creation * Add signed_ prefix to transfer_tx * Improve docs * Add library documentation page on pipelines * PR feedback for models.py * Impr. readability of get_last_voted_block * Use dict comprehension * Add docker-compose file to build and serve docs locally for development purposes * Change private_key for signing_key * Improve docstrings * Remove consensus docs * Document new consensus module * Create different transactions for the block * Cleanup variable names in block.py * Create different transactions for the block * Cleanup variable names in block.py
2016-09-29 10:29:41 +02:00
transfer_tx = transfer_tx.sign([user_sk])
2016-02-24 02:38:30 +01:00
Rebase/feat/586/integrate tx model (#641) * Adjust imports to bigchaindb_common * Adjust get_spent function signature * Adjust block serialization * Fix BigchainApi Test * Fix TestTransactionValidation tests * Fix TestBlockValidation tests * WIP: TestMultipleInputs * Adjust tests to tx-model interface changes - Fix old tests - Fix tests in TestMultipleInputs class * Remove fulfillment message tests * Fix TransactionMalleability tests * Remove Cryptoconditions tests * Remove create_transaction * Remove signing logic * Remove consensus plugin * Fix block_creation pipeline * Fix election pipeline * Replace some util functions with bdb_common ones - timestamp ==> gen_timestamp - serialize. * Implement Block model * Simplify function signatures for vote functions Change parameter interface for the following functions: - has_previous_vote - verify_vote_signature - block_election_status so that they take a block's id and voters instead of a fake block. * Integrate Block and Transaction model * Fix leftover tests and cleanup conftest * Add bigchaindb-common to install_requires * Delete transactions after block is written (#609) * delete transactions after block is written * cleanup transaction_exists * check for duplicate transactions * delete invalid tx from backlog * test duplicate transaction * Remove dead code * Test processes.py * Test invalid tx in on server * Fix tests for core.py * Fix models tests * Test commands main fn * Add final coverage to vote pipeline * Add more tests to voting pipeline * Remove consensus plugin docs and misc * Post rebase fixes * Fix rebase mess * Remove extra blank line * Improve docstring * Remove comment handled in bigchaindb/cryptoconditions#27; see https://github.com/bigchaindb/cryptoconditions/issues/27 * Fix block serialization in block creation * Add signed_ prefix to transfer_tx * Improve docs * Add library documentation page on pipelines * PR feedback for models.py * Impr. readability of get_last_voted_block * Use dict comprehension * Add docker-compose file to build and serve docs locally for development purposes * Change private_key for signing_key * Improve docstrings * Remove consensus docs * Document new consensus module * Create different transactions for the block * Cleanup variable names in block.py * Create different transactions for the block * Cleanup variable names in block.py
2016-09-29 10:29:41 +02:00
res = client.post(TX_ENDPOINT, data=json.dumps(transfer_tx.to_dict()))
2016-02-24 02:38:30 +01:00
assert res.status_code == 202
assert res.json['inputs'][0]['owners_before'][0] == user_pk
assert res.json['outputs'][0]['public_keys'][0] == user_pk
2016-02-24 02:38:30 +01:00
@pytest.mark.abci
def test_post_invalid_transfer_transaction_returns_400(client, user_pk, posted_create_tx):
Rebase/feat/586/integrate tx model (#641) * Adjust imports to bigchaindb_common * Adjust get_spent function signature * Adjust block serialization * Fix BigchainApi Test * Fix TestTransactionValidation tests * Fix TestBlockValidation tests * WIP: TestMultipleInputs * Adjust tests to tx-model interface changes - Fix old tests - Fix tests in TestMultipleInputs class * Remove fulfillment message tests * Fix TransactionMalleability tests * Remove Cryptoconditions tests * Remove create_transaction * Remove signing logic * Remove consensus plugin * Fix block_creation pipeline * Fix election pipeline * Replace some util functions with bdb_common ones - timestamp ==> gen_timestamp - serialize. * Implement Block model * Simplify function signatures for vote functions Change parameter interface for the following functions: - has_previous_vote - verify_vote_signature - block_election_status so that they take a block's id and voters instead of a fake block. * Integrate Block and Transaction model * Fix leftover tests and cleanup conftest * Add bigchaindb-common to install_requires * Delete transactions after block is written (#609) * delete transactions after block is written * cleanup transaction_exists * check for duplicate transactions * delete invalid tx from backlog * test duplicate transaction * Remove dead code * Test processes.py * Test invalid tx in on server * Fix tests for core.py * Fix models tests * Test commands main fn * Add final coverage to vote pipeline * Add more tests to voting pipeline * Remove consensus plugin docs and misc * Post rebase fixes * Fix rebase mess * Remove extra blank line * Improve docstring * Remove comment handled in bigchaindb/cryptoconditions#27; see https://github.com/bigchaindb/cryptoconditions/issues/27 * Fix block serialization in block creation * Add signed_ prefix to transfer_tx * Improve docs * Add library documentation page on pipelines * PR feedback for models.py * Impr. readability of get_last_voted_block * Use dict comprehension * Add docker-compose file to build and serve docs locally for development purposes * Change private_key for signing_key * Improve docstrings * Remove consensus docs * Document new consensus module * Create different transactions for the block * Cleanup variable names in block.py * Create different transactions for the block * Cleanup variable names in block.py
2016-09-29 10:29:41 +02:00
from bigchaindb.models import Transaction
2017-01-17 11:32:30 +01:00
from bigchaindb.common.exceptions import InvalidSignature
Rebase/feat/586/integrate tx model (#641) * Adjust imports to bigchaindb_common * Adjust get_spent function signature * Adjust block serialization * Fix BigchainApi Test * Fix TestTransactionValidation tests * Fix TestBlockValidation tests * WIP: TestMultipleInputs * Adjust tests to tx-model interface changes - Fix old tests - Fix tests in TestMultipleInputs class * Remove fulfillment message tests * Fix TransactionMalleability tests * Remove Cryptoconditions tests * Remove create_transaction * Remove signing logic * Remove consensus plugin * Fix block_creation pipeline * Fix election pipeline * Replace some util functions with bdb_common ones - timestamp ==> gen_timestamp - serialize. * Implement Block model * Simplify function signatures for vote functions Change parameter interface for the following functions: - has_previous_vote - verify_vote_signature - block_election_status so that they take a block's id and voters instead of a fake block. * Integrate Block and Transaction model * Fix leftover tests and cleanup conftest * Add bigchaindb-common to install_requires * Delete transactions after block is written (#609) * delete transactions after block is written * cleanup transaction_exists * check for duplicate transactions * delete invalid tx from backlog * test duplicate transaction * Remove dead code * Test processes.py * Test invalid tx in on server * Fix tests for core.py * Fix models tests * Test commands main fn * Add final coverage to vote pipeline * Add more tests to voting pipeline * Remove consensus plugin docs and misc * Post rebase fixes * Fix rebase mess * Remove extra blank line * Improve docstring * Remove comment handled in bigchaindb/cryptoconditions#27; see https://github.com/bigchaindb/cryptoconditions/issues/27 * Fix block serialization in block creation * Add signed_ prefix to transfer_tx * Improve docs * Add library documentation page on pipelines * PR feedback for models.py * Impr. readability of get_last_voted_block * Use dict comprehension * Add docker-compose file to build and serve docs locally for development purposes * Change private_key for signing_key * Improve docstrings * Remove consensus docs * Document new consensus module * Create different transactions for the block * Cleanup variable names in block.py * Create different transactions for the block * Cleanup variable names in block.py
2016-09-29 10:29:41 +02:00
transfer_tx = Transaction.transfer(posted_create_tx.to_inputs(),
[([user_pk], 1)],
asset_id=posted_create_tx.id)
2017-11-25 01:04:50 +01:00
transfer_tx._hash()
Rebase/feat/586/integrate tx model (#641) * Adjust imports to bigchaindb_common * Adjust get_spent function signature * Adjust block serialization * Fix BigchainApi Test * Fix TestTransactionValidation tests * Fix TestBlockValidation tests * WIP: TestMultipleInputs * Adjust tests to tx-model interface changes - Fix old tests - Fix tests in TestMultipleInputs class * Remove fulfillment message tests * Fix TransactionMalleability tests * Remove Cryptoconditions tests * Remove create_transaction * Remove signing logic * Remove consensus plugin * Fix block_creation pipeline * Fix election pipeline * Replace some util functions with bdb_common ones - timestamp ==> gen_timestamp - serialize. * Implement Block model * Simplify function signatures for vote functions Change parameter interface for the following functions: - has_previous_vote - verify_vote_signature - block_election_status so that they take a block's id and voters instead of a fake block. * Integrate Block and Transaction model * Fix leftover tests and cleanup conftest * Add bigchaindb-common to install_requires * Delete transactions after block is written (#609) * delete transactions after block is written * cleanup transaction_exists * check for duplicate transactions * delete invalid tx from backlog * test duplicate transaction * Remove dead code * Test processes.py * Test invalid tx in on server * Fix tests for core.py * Fix models tests * Test commands main fn * Add final coverage to vote pipeline * Add more tests to voting pipeline * Remove consensus plugin docs and misc * Post rebase fixes * Fix rebase mess * Remove extra blank line * Improve docstring * Remove comment handled in bigchaindb/cryptoconditions#27; see https://github.com/bigchaindb/cryptoconditions/issues/27 * Fix block serialization in block creation * Add signed_ prefix to transfer_tx * Improve docs * Add library documentation page on pipelines * PR feedback for models.py * Impr. readability of get_last_voted_block * Use dict comprehension * Add docker-compose file to build and serve docs locally for development purposes * Change private_key for signing_key * Improve docstrings * Remove consensus docs * Document new consensus module * Create different transactions for the block * Cleanup variable names in block.py * Create different transactions for the block * Cleanup variable names in block.py
2016-09-29 10:29:41 +02:00
res = client.post(TX_ENDPOINT, data=json.dumps(transfer_tx.to_dict()))
2017-01-17 11:32:30 +01:00
expected_status_code = 400
expected_error_message = 'Invalid transaction ({}): {}'.format(
InvalidSignature.__name__, 'Transaction signature is invalid.')
assert res.status_code == expected_status_code
assert res.json['message'] == expected_error_message
@pytest.mark.abci
def test_post_wrong_asset_division_transfer_returns_400(b, client, user_pk):
from bigchaindb.models import Transaction
from bigchaindb.common.exceptions import AmountError
priv_key, pub_key = crypto.generate_key_pair()
create_tx = Transaction.create([pub_key],
[([pub_key], 10)],
asset={'test': 'asset'}).sign([priv_key])
res = client.post(TX_ENDPOINT + '?mode=commit', data=json.dumps(create_tx.to_dict()))
assert res.status_code == 202
transfer_tx = Transaction.transfer(create_tx.to_inputs(),
[([pub_key], 20)], # 20 > 10
asset_id=create_tx.id).sign([priv_key])
res = client.post(TX_ENDPOINT + '?mode=commit', data=json.dumps(transfer_tx.to_dict()))
expected_error_message = \
f'Invalid transaction ({AmountError.__name__}): ' + \
'The amount used in the inputs `10` needs to be same as the amount used in the outputs `20`'
assert res.status_code == 400
assert res.json['message'] == expected_error_message
def test_transactions_get_list_good(client):
from functools import partial
2017-01-18 17:13:38 +01:00
def get_txs_patched(conn, **args):
"""Patch `get_transactions_filtered` so that rather than return an array
of transactions it returns an array of shims with a to_dict() method
that reports one of the arguments passed to `get_transactions_filtered`.
"""
return [type('', (), {'to_dict': partial(lambda a: a, arg)})
for arg in sorted(args.items())]
asset_id = '1' * 64
Refactor tendermint directory to project root (#2401) * Problem: core.py contains an unused class, `Bigchain` Solution: Remove core.py. Refactor BigchainDB Class to remove inheritance from Bigchain. * Problem: core.py contains an unused class, `Bigchain` Solution: Remove core.py. Refactor BigchainDB Class to remove inheritance from Bigchain. * Fixed flake8 complaint about too many blank lines * Attempting to fix Sphinx docs. This may result in some redundant commits, as I don't know what I'm doing, and I can't experiment without running the CI... Sorry in advance! * Attempting to fix Sphinx docs. This may result in some redundant commits, as I don't know what I'm doing, and I can't experiment without running the CI... Sorry in advance! * Updating from master changed BigchainDB.process_post_response to a private method, so I had to align with that. * Fixed a couple stale references to bigchaindb.Bigchain in docstrings * Missed a reference to `Bigchain` in a patch call... * Problem: BigchainDB class should be part of project root Solution: Removed the /tendermint directory and moved its contents to project root * Problem: Flake8 complained that imports were not at the top of the file Solution: Had to play around with the order of imports to avoid cyclic dependencies, but its working and style compliant now * Problem: Stale reference to /tendermint directory in the index Solution: Removed the references to /tendermint * Problem: Flake8 complaining of unused import in __init__.py Solution: The import is there so I can import App directly from bigchaindb, rather than from bigchaindb.core (which I think improves code readability. I added a # noqa to silence Flake8. * Problem: Stale references to `bigchaindb.tendermint.BigchainDB` in the rst files cause Sphinx to fail Solution: Updated the autodoc files to use `bigchaindb.BigchainDB` instead * Problem: Stale reference to the `tendermint` directory in an @patch in a disabled test Solution: Updated the @patch for completeness * Problem: BigchainDB class should be part of project root Solution: Removed the /tendermint directory and moved its contents to project root * Problem: Flake8 complained that imports were not at the top of the file Solution: Had to play around with the order of imports to avoid cyclic dependencies, but its working and style compliant now * Problem: Stale reference to /tendermint directory in the index Solution: Removed the references to /tendermint * Problem: Flake8 complaining of unused import in __init__.py Solution: The import is there so I can import App directly from bigchaindb, rather than from bigchaindb.core (which I think improves code readability. I added a # noqa to silence Flake8. * Problem: Stale references to `bigchaindb.tendermint.BigchainDB` in the rst files cause Sphinx to fail Solution: Updated the autodoc files to use `bigchaindb.BigchainDB` instead * Problem: Stale reference to the `tendermint` directory in an @patch in a disabled test Solution: Updated the @patch for completeness
2018-07-25 16:59:25 +02:00
with patch('bigchaindb.BigchainDB.get_transactions_filtered', get_txs_patched):
2017-02-22 12:33:10 +01:00
url = TX_ENDPOINT + '?asset_id=' + asset_id
assert client.get(url).json == [
['asset_id', asset_id],
['operation', None]
]
2017-02-22 12:33:10 +01:00
url = TX_ENDPOINT + '?asset_id=' + asset_id + '&operation=CREATE'
assert client.get(url).json == [
['asset_id', asset_id],
['operation', 'CREATE']
]
def test_transactions_get_list_bad(client):
2017-01-18 17:13:38 +01:00
def should_not_be_called():
assert False
Refactor tendermint directory to project root (#2401) * Problem: core.py contains an unused class, `Bigchain` Solution: Remove core.py. Refactor BigchainDB Class to remove inheritance from Bigchain. * Problem: core.py contains an unused class, `Bigchain` Solution: Remove core.py. Refactor BigchainDB Class to remove inheritance from Bigchain. * Fixed flake8 complaint about too many blank lines * Attempting to fix Sphinx docs. This may result in some redundant commits, as I don't know what I'm doing, and I can't experiment without running the CI... Sorry in advance! * Attempting to fix Sphinx docs. This may result in some redundant commits, as I don't know what I'm doing, and I can't experiment without running the CI... Sorry in advance! * Updating from master changed BigchainDB.process_post_response to a private method, so I had to align with that. * Fixed a couple stale references to bigchaindb.Bigchain in docstrings * Missed a reference to `Bigchain` in a patch call... * Problem: BigchainDB class should be part of project root Solution: Removed the /tendermint directory and moved its contents to project root * Problem: Flake8 complained that imports were not at the top of the file Solution: Had to play around with the order of imports to avoid cyclic dependencies, but its working and style compliant now * Problem: Stale reference to /tendermint directory in the index Solution: Removed the references to /tendermint * Problem: Flake8 complaining of unused import in __init__.py Solution: The import is there so I can import App directly from bigchaindb, rather than from bigchaindb.core (which I think improves code readability. I added a # noqa to silence Flake8. * Problem: Stale references to `bigchaindb.tendermint.BigchainDB` in the rst files cause Sphinx to fail Solution: Updated the autodoc files to use `bigchaindb.BigchainDB` instead * Problem: Stale reference to the `tendermint` directory in an @patch in a disabled test Solution: Updated the @patch for completeness * Problem: BigchainDB class should be part of project root Solution: Removed the /tendermint directory and moved its contents to project root * Problem: Flake8 complained that imports were not at the top of the file Solution: Had to play around with the order of imports to avoid cyclic dependencies, but its working and style compliant now * Problem: Stale reference to /tendermint directory in the index Solution: Removed the references to /tendermint * Problem: Flake8 complaining of unused import in __init__.py Solution: The import is there so I can import App directly from bigchaindb, rather than from bigchaindb.core (which I think improves code readability. I added a # noqa to silence Flake8. * Problem: Stale references to `bigchaindb.tendermint.BigchainDB` in the rst files cause Sphinx to fail Solution: Updated the autodoc files to use `bigchaindb.BigchainDB` instead * Problem: Stale reference to the `tendermint` directory in an @patch in a disabled test Solution: Updated the @patch for completeness
2018-07-25 16:59:25 +02:00
with patch('bigchaindb.BigchainDB.get_transactions_filtered',
lambda *_, **__: should_not_be_called()):
# Test asset id validated
2017-02-22 12:33:10 +01:00
url = TX_ENDPOINT + '?asset_id=' + '1' * 63
assert client.get(url).status_code == 400
# Test operation validated
2017-02-22 12:33:10 +01:00
url = TX_ENDPOINT + '?asset_id=' + '1' * 64 + '&operation=CEATE'
assert client.get(url).status_code == 400
# Test asset ID required
2017-02-22 12:33:10 +01:00
url = TX_ENDPOINT + '?operation=CREATE'
assert client.get(url).status_code == 400
@patch('requests.post')
@pytest.mark.parametrize('mode', [
('', 'broadcast_tx_async'),
('?mode=async', 'broadcast_tx_async'),
('?mode=sync', 'broadcast_tx_sync'),
('?mode=commit', 'broadcast_tx_commit'),
])
def test_post_transaction_valid_modes(mock_post, client, mode):
from bigchaindb.models import Transaction
from bigchaindb.common.crypto import generate_key_pair
def _mock_post(*args, **kwargs):
return Mock(json=Mock(return_value={'result': {'code': 0}}))
mock_post.side_effect = _mock_post
alice = generate_key_pair()
tx = Transaction.create([alice.public_key],
[([alice.public_key], 1)],
asset=None) \
.sign([alice.private_key])
mode_endpoint = TX_ENDPOINT + mode[0]
client.post(mode_endpoint, data=json.dumps(tx.to_dict()))
args, kwargs = mock_post.call_args
assert mode[1] == kwargs['json']['method']
@pytest.mark.abci
def test_post_transaction_invalid_mode(client):
from bigchaindb.models import Transaction
from bigchaindb.common.crypto import generate_key_pair
alice = generate_key_pair()
tx = Transaction.create([alice.public_key],
[([alice.public_key], 1)],
asset=None) \
.sign([alice.private_key])
mode_endpoint = TX_ENDPOINT + '?mode=nope'
response = client.post(mode_endpoint, data=json.dumps(tx.to_dict()))
assert '400 BAD REQUEST' in response.status
2018-01-12 11:06:27 +01:00
assert 'Mode must be "async", "sync" or "commit"' ==\
json.loads(response.data.decode('utf8'))['message']['mode']