def test_configuration(): config_string = ':inFO,a:trace,a.b:debug' slogging.configure(config_string=config_string) log = slogging.get_logger() log_a = slogging.get_logger('a') log_a_b = slogging.get_logger('a.b') assert log.is_active('info') assert not log.is_active('debug') assert log_a.is_active('trace') assert log_a_b.is_active('debug') assert not log_a_b.is_active('trace')
def test_listeners(caplog): slogging.configure() log = slogging.get_logger() called = [] def log_cb(event_dict): called.append(event_dict) # activate listener slogging.log_listeners.append(log_cb) # Add handlers log.error('test listener', abc='thislistener') assert 'thislistener' in caplog.text r = called.pop() assert r == dict(event='test listener', abc='thislistener') # this handler for function log_cb does not work log.trace('trace is usually filtered', abc='thislistener') assert "trace is usually filtered" not in caplog.text # deactivate listener slogging.log_listeners.remove(log_cb) log.error('test listener', abc='nolistener') assert 'nolistener' in caplog.text assert not called
def test_basic(caplog, level_name): slogging.configure(":trace") log = slogging.get_logger() with caplog.at_level('TRACE'): getattr(log, level_name)(level_name) assert len(caplog.records) == 1 assert caplog.records[0].levelname == level_name.upper() assert level_name in caplog.records[0].msg
def test_jsonconfig(caplog): slogging.configure(log_json=True) log = slogging.get_logger('prefix') log.warn('abc', a=1) assert json.loads( caplog.records[0].msg) == dict( event='prefix.abc', a=1, level='WARNING')
def test_logger_filter(caplog, logger_name, filter, should_log): slogging.configure() log = slogging.get_logger(logger_name) if filter: log.addFilter(logging.Filter(filter)) log.info("testlogmessage", v=1) if should_log: assert "testlogmessage" in caplog.text else: assert "testlogmessage" not in caplog.text
def test_how_to_use_as_vm_logger(): """ don't log until there was an error """ slogging.configure(':DEBUG,bible.vm:INFO') log = slogging.get_logger('bible.vm') # record all logs def run_vm(raise_error=False): log.trace('op', pc=1) log.trace('op', pc=2) if raise_error: raise Exception recorder = slogging.LogRecorder() try: run_vm(raise_error=True) except BaseException: log = slogging.get_logger('bible.vm') for x in recorder.pop_records(): log.info(x.pop('event'), **x)
def test_tracebacks(caplog): slogging.configure() log = slogging.get_logger() def div(a, b): try: _ = a // b log.error('heres the stack', stack_info=True) except Exception as e: log.error( 'an Exception trace should preceed this msg', exc_info=True) div(1, 0) assert 'an Exception trace' in caplog.text assert 'Traceback' in caplog.text div(1, 1) assert 'the stack' in caplog.text
def test_recorder(caplog): slogging.configure(log_json=True) log = slogging.get_logger() # test info recorder = slogging.LogRecorder() assert len(slogging.log_listeners) == 1 log.info('a', v=1) assert "a" in caplog.text r = recorder.pop_records() assert r[0] == dict(event='a', v=1) assert len(slogging.log_listeners) == 0 # test trace log.setLevel(logging.TRACE) recorder = slogging.LogRecorder() assert len(slogging.log_listeners) == 1 log.trace('a', v=2) assert '"v": 2' in caplog.text r = recorder.pop_records() assert r[0] == dict(event='a', v=2) assert len(slogging.log_listeners) == 0
def test_lazy_log(): """ test lacy evaluation of json log data e.g. class LogState class LogMemory """ called_print = [] class Expensive(object): def __repr__(self): called_print.append(1) return 'expensive data preparation' slogging.configure(log_json=True) log = slogging.get_logger() log.trace('no', data=Expensive()) assert not called_print log.info('yes', data=Expensive()) # !!!!!!!!!!!!! assert called_print.pop()
from biblecoin.slogging import get_logger log = get_logger('bible.block_creation') from biblecoin.block import Block, BlockHeader from biblecoin.common import mk_block_from_prevstate, validate_header, \ verify_execution_results, validate_transaction_tree, \ set_execution_results, add_transactions, post_finalize from biblecoin.consensus_strategy import get_consensus_strategy from biblecoin.messages import apply_transaction from biblecoin.state import State from biblecoin.utils import sha3, encode_hex import rlp # Applies the block-level state transition function def apply_block(state, block): # Pre-processing and verification snapshot = state.snapshot() cs = get_consensus_strategy(state.config) try: # Start a new block context cs.initialize(state, block) # Basic validation assert validate_header(state, block.header) assert cs.check_seal(state, block.header) assert cs.validate_uncles(state, block) assert validate_transaction_tree(state, block) # Process transactions for tx in block.transactions: apply_transaction(state, tx) # Finalize (incl paying block rewards) cs.finalize(state, block)
from biblecoin import vm from biblecoin.specials import specials as default_specials from biblecoin.config import Env, default_config from biblecoin.db import BaseDB, EphemDB from biblecoin.exceptions import InvalidNonce, InsufficientStartGas, UnsignedTransaction, \ BlockGasLimitReached, InsufficientBalance, VerificationFailed, InvalidTransaction import sys if sys.version_info.major == 2: from repoze.lru import lru_cache else: from functools import lru_cache from biblecoin.slogging import get_logger null_address = b'\xff' * 20 log = get_logger('bible.block') log_tx = get_logger('bible.pb.tx') log_msg = get_logger('bible.pb.msg') log_state = get_logger('bible.pb.msg.state') # contract creating transactions send to an empty address CREATE_CONTRACT_ADDRESS = b'' # DEV OPTIONS SKIP_MEDSTATES = False def rp(tx, what, actual, target): return '%r: %r actual:%r target:%r' % (tx, what, actual, target)
import biblecoin.utils as utils import rlp import biblecoin.tools.testutils as testutils import biblecoin.config as config from biblecoin.state import State from biblecoin.common import calc_difficulty from biblecoin.block import Block, BlockHeader import sys import os import json from biblecoin.slogging import get_logger logger = get_logger() # customize VM log output to your needs # hint: use 'py.test' with the '-s' option to dump logs to the console # configure_logging(':trace') def test_difficulty(filename, testname, testdata): parent_timestamp = int(testdata["parentTimestamp"], 10 if testdata["parentTimestamp"].isdigit() else 16) parent_difficulty = int( testdata["parentDifficulty"], 10 if testdata["parentDifficulty"].isdigit() else 16) parent_blk_number = int( testdata["currentBlockNumber"], 10 if testdata["currentBlockNumber"].isdigit() else 16) - 1 cur_blk_timestamp = int( testdata["currentTimestamp"], 10 if testdata["currentTimestamp"].isdigit() else 16)
verify_stack_after_op = False # ###################################### import sys sys.setrecursionlimit(10000) from biblecoin import utils from biblecoin.abi import is_numeric import copy from biblecoin import opcodes import time from biblecoin.slogging import get_logger from rlp.utils import encode_hex, ascii_chr from biblecoin.utils import to_string, encode_int, zpad, bytearray_to_bytestr log_log = get_logger('bible.vm.log') log_msg = get_logger('bible.pb.msg') log_vm_exit = get_logger('bible.vm.exit') log_vm_op = get_logger('bible.vm.op') log_vm_op_stack = get_logger('bible.vm.op.stack') log_vm_op_memory = get_logger('bible.vm.op.memory') log_vm_op_storage = get_logger('bible.vm.op.storage') TT256 = 2**256 TT256M1 = 2**256 - 1 TT255 = 2**255 MAX_DEPTH = 1024 JUMPDEST = 0x5b # Hardcoded, change if needed
import copy from biblecoin.hybrid_casper import casper_utils, chain from biblecoin.pow.ethpow import Miner from biblecoin.tools import tester from biblecoin.meta import make_head_candidate from biblecoin import block, transactions from biblecoin.transaction_queue import TransactionQueue from biblecoin.messages import apply_transaction from biblecoin import abi, utils from biblecoin.slogging import get_logger log = get_logger('bible.validator') # config_string = ':info,bible.vm.log:trace,bible.vm.op:trace,bible.vm.stack:trace,bible.vm.exit:trace,bible.pb.msg:trace,bible.pb.tx:debug' # configure_logging(config_string=config_string) class Network(object): def __init__(self): self.nodes = [] self.time = 0 # TODO: Add the concept of time def broadcast(self, msg): for n in self.nodes: n.on_receive(msg) def join(self, node): self.nodes.append(node) class Validator(object): def __init__(self, key, genesis, network, valcode_addr=None, mining=False): self.key = key
from biblecoin.pow import ethash from biblecoin import utils import time import sys import warnings from collections import OrderedDict from biblecoin import utils from biblecoin.slogging import get_logger import rlp log = get_logger('bible.pow') if sys.version_info.major == 2: from repoze.lru import lru_cache else: from functools import lru_cache try: import pyethash ETHASH_LIB = 'pyethash' # the C++ based implementation except ImportError: ETHASH_LIB = 'ethash' warnings.warn('using pure python implementation', ImportWarning) if ETHASH_LIB == 'ethash': mkcache = ethash.mkcache EPOCH_LENGTH = 30000 hashimoto_light = ethash.hashimoto_light elif ETHASH_LIB == 'pyethash': mkcache = pyethash.mkcache_bytes EPOCH_LENGTH = 30000
from biblecoin import utils from biblecoin.slogging import get_logger from rlp.utils import str_to_bytes import sys if sys.version_info.major == 2: from repoze.lru import lru_cache else: from functools import lru_cache log = get_logger('db') databases = {} class BaseDB(object): pass class _EphemDB(BaseDB): def __init__(self): self.db = {} self.kv = self.db def get(self, key): return self.db[key] def put(self, key, value): self.db[key] = value def delete(self, key): del self.db[key]
import pytest from biblecoin.tools import tester from biblecoin.tests.utils import new_db from biblecoin.db import EphemDB from biblecoin.hybrid_casper import casper_utils from biblecoin.slogging import get_logger from biblecoin.tests.hybrid_casper.testing_lang import TestLangHybrid log = get_logger('test.chain') logger = get_logger() _db = new_db() # from biblecoin.slogging import configure_logging # config_string = ':info,bible.chain:debug,test.chain:info' # configure_logging(config_string=config_string) EPOCH_LENGTH = 25 SLASH_DELAY = 864 ALLOC = {a: {'balance': 500 * 10**19} for a in tester.accounts[:10]} k0, k1, k2, k3, k4, k5, k6, k7, k8, k9 = tester.keys[:10] a0, a1, a2, a3, a4, a5, a6, a7, a8, a9 = tester.accounts[:10] @pytest.fixture(scope='function') def db(): return EphemDB() alt_db = db
def test_howto_use_in_tests(): # select what you want to see. # e.g. TRACE from vm except for pre_state :DEBUG otherwise slogging.configure(':DEBUG,bible.vm:TRACE,vm.pre_state:INFO') log = slogging.get_logger('tests.logging') log.info('test starts')
def test_is_active(): slogging.configure() tester = slogging.get_logger('tester') assert tester.is_active(level_name='info') assert not tester.is_active(level_name='trace')
) from biblecoin.hybrid_casper import casper_utils from biblecoin.meta import apply_block from biblecoin.common import update_block_env_variables from biblecoin.tools import tester import rlp from rlp.utils import encode_hex from biblecoin.exceptions import InvalidTransaction, VerificationFailed from biblecoin.slogging import get_logger from biblecoin.config import Env from biblecoin.state import State, dict_to_prev_header from biblecoin.block import Block, BlockHeader, BLANK_UNCLES_HASH from biblecoin.pow.consensus import initialize from biblecoin.genesis_helpers import mk_basic_state, state_from_genesis_declaration, initialize_genesis_keys log = get_logger('bible.chain') config_string = ':info,bible.chain:debug' # from biblecoin.slogging import configure_logging # config_string = ':info,bible.vm.log:trace,bible.vm.op:trace,bible.vm.stack:trace,bible.vm.exit:trace,bible.pb.msg:trace,bible.pb.tx:debug' # configure_logging(config_string=config_string) class Chain(object): def __init__(self, genesis=None, env=None, coinbase=b'\x00' * 20, new_head_cb=None, reset_genesis=False, localtime=None, **kwargs):
def test_logger_names(): slogging.configure() names = {'a', 'b', 'c'} for n in names: slogging.get_logger(n) assert names.issubset(set(slogging.get_logger_names()))