コード例 #1
0
def test_get_402_info(monkeypatch):
    # Patch requests from making actual http requests
    monkeypatch.setattr(requests, 'get', mockrequest)

    # Test that OnChainRequests 402 info returns a dict of headers
    bit_req = OnChainRequests(wallet)
    headers = bit_req.get_402_info('fakeurl')
    assert type(headers) == dict
    assert headers['price'] == 1337
    assert headers['bitcoin-address'] == '1THISISANADDRESS'

    # Test that BitTransferRequests 402 info returns a dict of headers
    def mock_bittransfer_request(*args, **kwargs):
        mock_req = mockrequest(*args, **kwargs)
        mock_req.headers['username'] = '******'
        mock_req.headers['bitcoin-address'] = '3NEWADDRESS'
        return mock_req

    monkeypatch.setattr(requests, 'get', mock_bittransfer_request)
    bit_req = BitTransferRequests(wallet, config.username)
    headers = bit_req.get_402_info('fakeurl')
    assert type(headers) == dict
    assert headers['price'] == 1337
    assert headers['bitcoin-address'] == '3NEWADDRESS'
    assert headers['username'] == 'long john silver'
コード例 #2
0
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)

    # Test that we can make a successful 402 payment
    onchain_pmt = bit_req.make_402_payment(mock_request, test_max_price)
    assert type(onchain_pmt) == dict
    assert onchain_pmt['Bitcoin-Transaction'] == MockWallet.TXN.to_hex()
    assert onchain_pmt['Return-Wallet-Address'] == MockWallet.ADDR

    # Test that an error is raised if the server doesn't support onchain
    with pytest.raises(BitRequestsError):
        headers = {'price': price}
        setattr(mock_request, 'headers', headers)
        bit_req.make_402_payment(mock_request, test_max_price)
コード例 #3
0
ファイル: test_bitrequests.py プロジェクト: 0xDeX/two1-python
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)

    # Test that we can make a successful 402 payment
    onchain_pmt = bit_req.make_402_payment(mock_request, test_max_price)
    assert type(onchain_pmt) == dict
    assert onchain_pmt['Bitcoin-Transaction'] == MockWallet.TXN.to_hex()
    assert onchain_pmt['Return-Wallet-Address'] == MockWallet.ADDR

    # Test that an error is raised if the server doesn't support onchain
    with pytest.raises(BitRequestsError):
        headers = {'price': price}
        setattr(mock_request, 'headers', headers)
        bit_req.make_402_payment(mock_request, test_max_price)
コード例 #4
0
ファイル: test_bitrequests.py プロジェクト: 0xDeX/two1-python
def test_get_402_info(monkeypatch):
    # Patch requests from making actual http requests
    monkeypatch.setattr(requests, 'get', mockrequest)

    # Test that OnChainRequests 402 info returns a dict of headers
    bit_req = OnChainRequests(wallet)
    headers = bit_req.get_402_info('fakeurl')
    assert type(headers) == dict
    assert headers['price'] == 1337
    assert headers['bitcoin-address'] == '1THISISANADDRESS'

    # Test that BitTransferRequests 402 info returns a dict of headers
    def mock_bittransfer_request(*args, **kwargs):
        mock_req = mockrequest(*args, **kwargs)
        mock_req.headers['username'] = '******'
        mock_req.headers['bitcoin-address'] = '3NEWADDRESS'
        return mock_req
    monkeypatch.setattr(requests, 'get', mock_bittransfer_request)
    bit_req = BitTransferRequests(wallet, config.username)
    headers = bit_req.get_402_info('fakeurl')
    assert type(headers) == dict
    assert headers['price'] == 1337
    assert headers['bitcoin-address'] == '3NEWADDRESS'
    assert headers['username'] == 'long john silver'
コード例 #5
0
    def buy(config, resource, data, method, data_file, output_file,
            payment_method, max_price, info_only):
        """Buy from any machine payable endpoint

           Note: The two1lib _buy function does not support simply returning an object,
                 until then, include a local copy here
        """
        # If resource is a URL string, then bypass seller search
        if URL_REGEXP.match(resource):
            target_url = resource
            seller = target_url
        elif resource in DEMOS:
            target_url = TWO1_WWW_HOST + DEMOS[resource]["path"]
            data = json.dumps(data)
        else:
            raise NotImplementedError('Endpoint search is not implemented!')

        # Change default HTTP method from "GET" to "POST", if we have data
        if method == "GET" and (data or data_file):
            method = "POST"

        # Set default headers for making bitrequests with JSON-like data
        headers = {'Content-Type': 'application/json'}

        try:
            # Find the correct payment method
            if payment_method == 'offchain':
                bit_req = BitTransferRequests(config.machine_auth,
                                              config.username)
            elif payment_method == 'onchain':
                bit_req = OnChainRequests(config.wallet)

            else:
                raise Exception('Payment method does not exist.')

            # Make the request
            if info_only:
                res = bit_req.get_402_info(target_url)
            else:
                res = bit_req.request(method.lower(),
                                      target_url,
                                      max_price=max_price,
                                      data=data or data_file,
                                      headers=headers)
        except ResourcePriceGreaterThanMaxPriceError as e:
            config.log(
                uxstring.Error.resource_price_greater_than_max_price.format(e))
            return
        except Exception as e:
            if 'Insufficient funds.' in str(e):
                config.log(
                    uxstring.Error.insufficient_funds_mine_more.format(
                        DEFAULT_ONCHAIN_BUY_FEE))
            else:
                config.log(str(e), fg="red")
            return

        # Output results to user
        if output_file:
            # Write response output file
            output_file.write(res.content)
        elif info_only:
            # Print headers that are related to 402 payment required
            for key, val in res.items():
                config.log('{}: {}'.format(key, val))
        elif resource in DEMOS:
            config.log(DEMOS[resource]["formatter"](res))
        else:
            response = res.json()
            # Clean up names
            for index, elem in enumerate(response):
                if elem['name'] is None:
                    response[index]['name'] = 'Please name me'
                elif len(elem['name']) == 0:
                    response[index]['name'] = 'Please name me'
                else:
                    response[index]['name'] = response[index]['name'].title()
                print(elem['description'])
                if elem['description'] is None:
                    try:
                        response[index]['description'] = elem['owner'].title(
                        ) + ' is a bad endpoint operator and forgot to place a description'
                    except:
                        response[index][
                            'description'] = 'Anonymous is a bad endpoint operator and forgot to place a description'
                # Any description greater than 66 characters causes the text to overflow, this enforces a limit
                elif len(elem['description']) > 63:
                    response[index]['description'] = response[index][
                        'description'][:63] + '...'

            # Write response to console
            return response

        # Write the amount paid out if something was truly paid
        if not info_only and hasattr(res, 'amount_paid'):
            client = rest_client.TwentyOneRestClient(TWO1_HOST,
                                                     config.machine_auth,
                                                     config.username)
            user_balances = _get_balances(config, client)
            if payment_method == 'offchain':
                balance_amount = user_balances.twentyone
                balance_type = '21.co'
            elif payment_method == 'onchain':
                balance_amount = user_balances.onchain
                balance_type = 'blockchain'

        # Record the transaction if it was a payable request
        if hasattr(res, 'paid_amount'):
            config.log_purchase(s=seller,
                                r=resource,
                                p=res.paid_amount,
                                d=str(datetime.datetime.today()))