Пример #1
0
def test_no_config_file_exists():
    """Test that a new `two1.json` file is created if it doesn't exist."""
    mock_config = mock.mock_open()
    mock_config.side_effect = [FileNotFoundError(), mock.DEFAULT]
    with mock.patch('two1.commands.util.config.Config.save',
                    return_value=None):
        with mock.patch('two1.commands.util.config.open',
                        mock_config,
                        create=True):
            config.Config('config_file')

    assert mock_config.call_count == 2
    dc = json.loads(mock_config.return_value.write.call_args[0][0])
    mock_config.assert_called_with('config_file', mode='w')

    assert dc['username'] is None
    assert dc['sellprice'] == 10000
    assert dc['contact'] == "*****@*****.**"
    assert dc['stdout'] == ".two1/two1.stdout"
    assert dc['stderr'] == ".two1/two1.stderr"
    assert dc['sortby'] == "price"
    assert dc['maxspend'] == 20000
    assert dc['verbose'] is False
    assert dc['mining_auth_pubkey'] is None
    assert dc['auto_update'] is False
    assert dc['wallet_path'] == wallet.Two1Wallet.DEFAULT_WALLET_PATH
    assert dc['collect_analytics'] is True
Пример #2
0
 def __init__(self, wallet):
     """Initialize the on-chain request with a wallet."""
     super().__init__()
     self.wallet = wallet
     try:
         self.username = config.Config().username
     except exceptions.FileDecodeError:
         self.username = None
Пример #3
0
 def __init__(self):
     """
     Constructor for the Rev class.
     """
     self.config = two1_config.Config(two1.TWO1_CONFIG_FILE, None)
     self.wallet = wallet_utils.get_or_create_wallet(self.config.wallet_path)
     self.machine_auth = machine_auth_wallet.MachineAuthWallet(self.wallet)
     self.client = rest_client.TwentyOneRestClient(two1.TWO1_HOST, self.machine_auth, self.config.username)
Пример #4
0
def create_default_rest_client():
    """Return a rest client using default parameters."""
    import two1
    from two1 import wallet
    from two1.commands.util import config
    from two1.server import machine_auth_wallet, rest_client
    auth = machine_auth_wallet.MachineAuthWallet(wallet.Wallet())
    return rest_client.TwentyOneRestClient(two1.TWO1_HOST, auth,
                                           config.Config().username)
Пример #5
0
def test_invalid_config_file():
    """Test that an invalid `two1.json` file cannot be imported."""
    mock_config = mock.mock_open(mock=mock.Mock(side_effect=ValueError))
    with mock.patch('two1.commands.util.config.open', mock_config,
                    create=True), pytest.raises(
                        exceptions.FileDecodeError):  # nopep8
        config.Config('config_file')

    mock_config.assert_called_with('config_file', mode='r')
Пример #6
0
 def __init__(self, wallet, deposit_amount=DEFAULT_DEPOSIT_AMOUNT, duration=DEFAULT_DURATION):
     """Initialize the channel requests with a payment channel client."""
     super().__init__()
     self._channelclient = ChannelRequests.channels.PaymentChannelClient(wallet)
     self._deposit_amount = deposit_amount
     self._duration = duration
     try:
         self.username = config.Config().username
     except exceptions.FileDecodeError:
         self.username = None
Пример #7
0
def test_needs_old_last_update_check_with_new_version():
    """Test for a last_update_check more than 3600 seconds ago, but version is new
    and that it does not suggest an update"""
    mock_config = mock.mock_open(read_data=CONFIG_DATA)
    with mock.patch('two1.commands.util.config.open', mock_config,
                    create=True):
        c = config.Config('config_file')
        c.set('last_update_check', 000000.000, should_save=True)

    with capture_stdout(config.Config, 'config_file') as output:
        assert len(output.strip()) == 0
Пример #8
0
def parse_config(
    config_file=two1.TWO1_CONFIG_FILE,
    config_dict=None,
    need_wallet_and_account=True,
    check_update=False,
    debug=False,
):
    """Get configuration information that is used to drive all 21 commands.

    This function is very useful for testing as it builds up several
    key variables (like the client, wallet, username, and the like)
    that are used in many commands. The way it does this is by taking
    in the config_file (typically .two1/two1.json) and the config_dict
    (a list of key-value pairs to override the config_file, typically
    an empty dictionary), and then running the logic below.

    It returns obj which is a dictionary that has Config, Wallet,
    MachineAuth, and TwentyOneRestClient instances underneath it, as
    well as a string with the username. The obj is passed down by
    click to various other commands.

    You can use this function in any test to instantiate the user's
    wallet, username, and other variables.
    """
    try:
        config = two1_config.Config(config_file,
                                    config_dict,
                                    check_update=check_update)
    except exceptions.FileDecodeError as e:
        raise click.ClickException(
            uxstring.UxString.Error.file_decode.format((str(e))))

    wallet, machine_auth, username, client = None, None, None, None
    if need_wallet_and_account:
        try:
            wallet = wallet_utils.get_or_create_wallet(config.wallet_path)
        except blockchain_exceptions.DataProviderError as err:
            raise exceptions.Two1Error(
                'You have experienced a data provider error: %s ' % err.args)
        machine_auth = machine_auth_wallet.MachineAuthWallet(wallet)
        username = account_utils.get_or_create_username(config, machine_auth)
        client = rest_client.TwentyOneRestClient(two1.TWO1_HOST, machine_auth,
                                                 config.username)
        config.username = username

    obj = dict(
        config=config,
        wallet=wallet,
        machine_auth=machine_auth,
        username=username,
        client=client,
        debug=debug,
    )
    return obj
Пример #9
0
 def __init__(self, wallet, username=None):
     """Initialize the bittransfer with wallet and username."""
     from two1.server.machine_auth_wallet import MachineAuthWallet
     super().__init__()
     if isinstance(wallet, MachineAuthWallet):
         self.wallet = wallet
     else:
         self.wallet = MachineAuthWallet(wallet)
     if username is None:
         self.username = config.Config().username
     else:
         self.username = username
Пример #10
0
def test_last_update_check_set():
    """Asert last_update_check is set in a config with none."""
    mock_config = mock.mock_open(read_data=CONFIG_DATA)
    assert 'last_update_check' not in CONFIG_DATA
    with mock.patch('two1.commands.util.config.open', mock_config,
                    create=True):
        conf = config.Config('config_file')
        # last_update_check should now be set after
        # initalizing the config object.
        assert hasattr(conf, 'last_update_check')
        assert 'last_update_check' in json.loads(
            mock_config.return_value.write.call_args[0][0])
Пример #11
0
def test_needs_update_legacy_last_update_check():
    """Test for a legacy two1.json with an older last_update_check, and that
    it does not throw an error"""
    mock_config = mock.mock_open(read_data=CONFIG_DATA)
    with mock.patch('two1.commands.util.config.open', mock_config,
                    create=True):
        c = config.Config('config_file')
        c.set('last_update_check', "", should_save=True)
    try:
        c.check_update()
    except ValueError:
        pytest.fail("Error dealing with legacy timestamp")
Пример #12
0
def test_default_config():
    """Test Config object loads defualt settings when file is incomplete."""
    c = config.Config('config_file')

    assert c.username is None
    assert c.sellprice == 10000
    assert c.contact == "*****@*****.**"
    assert c.stdout == ".two1/two1.stdout"
    assert c.stderr == ".two1/two1.stderr"
    assert c.sortby == "price"
    assert c.maxspend == 20000
    assert c.verbose is False
    assert c.mining_auth_pubkey is None
    assert c.auto_update is False
    assert c.wallet_path == wallet.Two1Wallet.DEFAULT_WALLET_PATH
    assert c.collect_analytics is True
Пример #13
0
def test_basic_config():
    """Test Config object can load a file and access its settings."""
    c = config.Config('config_file')

    assert c.username == 'satoshi'
    assert c.sellprice == 11000
    assert c.contact == '*****@*****.**'
    assert c.stdout == '.two1/two1.stdout'
    assert c.stderr == '.two1/two1.stderr'
    assert c.sortby == 'price'
    assert c.maxspend == 25000
    assert c.verbose is False
    assert c.mining_auth_pubkey == 'i_haz_key'
    assert c.auto_update is False
    assert c.wallet_path == wallet.Two1Wallet.DEFAULT_WALLET_PATH
    assert c.collect_analytics is True
Пример #14
0
def test_config_repr():
    """Test Config object can be displayed nicely in `print` statements."""
    c = config.Config('config_file')
    printed = c.__repr__()

    assert 'satoshi' in printed
    assert '11000' in printed
    assert '*****@*****.**' in printed
    assert '.two1/two1.stdout' in printed
    assert '.two1/two1.stderr' in printed
    assert 'price' in printed
    assert '25000' in printed
    assert 'False' in printed
    assert 'i_haz_key' in printed
    assert 'False' in printed
    assert wallet.Two1Wallet.DEFAULT_WALLET_PATH in printed
    assert 'True' in printed
Пример #15
0
 def __init__(self, wallet, username=None, client=None):
     """Initialize the bittransfer with wallet and username."""
     from two1.server.machine_auth_wallet import MachineAuthWallet
     from two1.server import rest_client
     super().__init__()
     if isinstance(wallet, MachineAuthWallet):
         self.wallet = wallet
     else:
         self.wallet = MachineAuthWallet(wallet)
     if username is None:
         self.username = config.Config().username
     else:
         self.username = username
     if client is None:
         self.client = rest_client.TwentyOneRestClient(
             two1.TWO1_HOST, self.wallet, self.username)
     else:
         self.client = client
Пример #16
0
def test_save_config():
    """Test Config object can save to update a file."""
    mock_config = mock.mock_open(read_data=CONFIG_DATA)
    with mock.patch('two1.commands.util.config.open', mock_config,
                    create=True):
        c = config.Config('config_file')

    num_config_keys = len(c.state.keys())

    # Update an existing key and add a new one
    with mock.patch('two1.commands.util.config.open', mock_config,
                    create=True):
        c.set('username', 'TEST_USERNAME', should_save=True)
        c.set('some_list_key', [123, 456, 789], should_save=True)

    # Import the newly saved configuration file
    new_config = json.loads(mock_config.return_value.write.call_args[0][0])

    mock_config.assert_called_with('config_file', mode='w')
    assert c.username == 'TEST_USERNAME'
    assert c.some_list_key == [123, 456, 789]
    assert new_config['username'] == 'TEST_USERNAME'
    assert new_config['some_list_key'] == [123, 456, 789]
    assert len(new_config.keys()) == num_config_keys + 1
Пример #17
0
import logging
import os
from transcodeE16 import TranscodeE16

from two1.commands.util import config
from two1.wallet import Wallet
from two1.bitrequests import BitTransferRequests
requests = BitTransferRequests(Wallet(), config.Config().username)

log = logging.getLogger('werkzeug')
log.setLevel(logging.INFO)


def testDuration():
    """
    Tests getting the duration for a sample video.
    """
    try:
        log.warning("In testDuration()")
        dataDir = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'data')

        # Create the speed testing client
        transcoder = TranscodeE16(dataDir)
        duration = transcoder.getDuration('http://www.esixteen.co/video/sample.mp4')

        log.info("Success!")
        log.info("Duration test completed with duration: {}", duration)

    except Exception as err:
        log.warning('Client test failed')
Пример #18
0
        return {'Bitcoin-Transaction': 'paid'}


def mockrequest(*args, **kwargs):
    mock_request = MockRequest()
    mock_headers = {'price': '1337', 'bitcoin-address': '1THISISANADDRESS'}
    setattr(mock_request, 'status_code', 402)
    setattr(mock_request, 'headers', mock_headers)
    setattr(mock_request, 'response_method', args[0])
    return mock_request


##############################################################################

# Set up Two1 command line config
config = config.Config()
# Inject the mock wallet into config as a test dependency
wallet = MockWallet()
# Mock two1 rest client
client = MockTwentyOneRestClient()


def test_onchain_request():
    """Test that it handles on-chain requests."""
    bit_req = OnChainRequests(wallet)
    test_max_price = 10000
    price = 1000
    address = 'test_bitserv_host_address'
    mock_request = MockRequest()
    headers = {'price': price, 'bitcoin-address': address}
    setattr(mock_request, 'headers', headers)
Пример #19
0
            data = {"public_key": public_key}

        data_json = json.dumps(data)
        path = "/pool/account/{}/wallets/primary/".format(self.username)
        resp = self._request(sign_username=self.username,
                             method="POST",
                             path=path,
                             data=data_json)
        return resp.json()

    def list_wallets(self):
        path = "/pool/account/{}/wallets/".format(self.username)
        resp = self._request(sign_username=self.username,
                             method="GET",
                             path=path)
        return resp.json()


if __name__ == "__main__":
    # host = "http://127.0.0.1:8000"
    from two1.commands.util import config

    conf = config.Config()
    host = two1.TWO1_HOST
    for n in range(2):
        m = TwentyOneRestClient(host, conf.machine_auth, conf.username)
        try:
            earn = m.get_mined_satoshis()
        except requests.exceptions.ConnectionError:
            print("Error: cannot connect to ", host)
Пример #20
0
def main(ctx, wallet_path, passphrase, blockchain_data_provider, insight_url,
         insight_api_path, debug):
    """ Command-line Interface for the Two1 Wallet
    """
    if wallet_path is None:
        try:
            config = two1_config.Config(config_file)
            wallet_path = config.wallet_path
        except two1exceptions.FileDecodeError as e:
            raise click.ClickException(
                uxstring.UxString.Error.file_decode.format((str(e))))

    wp = Path(wallet_path)

    # Initialize some logging handlers
    ch = logging.StreamHandler()
    ch_formatter = logging.Formatter('%(levelname)s: %(message)s')
    ch.setFormatter(ch_formatter)

    if not os.path.exists(wp.dirname()):
        os.makedirs(wp.dirname())
    fh = logging.handlers.TimedRotatingFileHandler(
        wp.dirname().joinpath("wallet_cli.log"),
        when='midnight',
        backupCount=5)
    fh_formatter = logging.Formatter('%(asctime)s %(levelname)s: %(message)s')
    fh.setFormatter(fh_formatter)

    logger.addHandler(ch)
    logger.addHandler(fh)

    fh.setLevel(logging.DEBUG if debug else logging.INFO)
    ch.setLevel(logging.DEBUG if debug else logging.WARNING)
    logger.setLevel(logging.DEBUG if debug else logging.INFO)

    logger.info("Wallet client started.")

    if ctx.obj is None:
        ctx.obj = {}

    ctx.obj['wallet_path'] = wallet_path
    ctx.obj['passphrase'] = passphrase

    if ctx.invoked_subcommand not in ['create', 'restore']:
        # Check that the wallet path exists
        if not Two1Wallet.check_wallet_file(ctx.obj['wallet_path']):
            click.echo("ERROR: Wallet file does not exist or is corrupt.")
            ctx.exit(code=7)

        p = get_passphrase() if passphrase else ''

        try:
            logger.info("Loading wallet %s ..." % (wp))
            ctx.obj['wallet'] = Wallet(wallet_path=wallet_path,
                                       data_provider=ctx.obj['data_provider'],
                                       passphrase=p)
            logger.info("... loading complete.")
        except exceptions.PassphraseError as e:
            click.echo(str(e))
            ctx.exit(code=1)
        except (TypeError, ValueError) as e:
            logger.error("Internal wallet error. Please report this as a bug.")
            logger.debug("".join(traceback.format_tb(e.__traceback__)))
            ctx.exit(code=2)

        def _on_close():
            try:
                ctx.obj['wallet'].sync_wallet_file()
            except:
                pass

        ctx.call_on_close(_on_close)