Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add error if no Infura key is found #1294

Merged
merged 1 commit into from
Mar 25, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions conftest.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import os
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this cruft from some local changes? I don't see how it's used.

Edit: oops, this was sitting in a pending review, unpublished. Super minor, anyway

import pytest
import time
import warnings
Expand Down
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@
"eth-hash[pycryptodome]>=0.2.0,<1.0.0",
"eth-typing>=2.0.0,<3.0.0",
"eth-utils>=1.3.0,<2.0.0",
"ethpm>=0.1.4a12,<1.0.0",
"ethpm>=0.1.4a13,<1.0.0",
"hexbytes>=0.1.0,<1.0.0",
"lru-dict>=1.1.6,<2.0.0",
"requests>=2.16.0,<3.0.0",
Expand Down
79 changes: 39 additions & 40 deletions tests/core/providers/test_auto_provider.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
import importlib
import logging
import os
import pytest

from web3.auto import (
infura,
from eth_utils import (
ValidationError,
)

from web3.exceptions import (
InfuraKeyNotFound,
)
from web3.providers import (
HTTPProvider,
Expand All @@ -14,6 +18,18 @@
load_provider_from_environment,
)

# Ugly hack to import infura now that API KEY is required
os.environ['WEB3_INFURA_API_KEY'] = 'test'
from web3.auto import ( # noqa E402 isort:skip
infura,
)


@pytest.fixture(autouse=True)
def delete_infura_key(monkeypatch):
monkeypatch.delenv('INFURA_API_KEY', raising=False)
monkeypatch.delenv('WEB3_INFURA_API_KEY', raising=False)


@pytest.mark.parametrize(
'uri, expected_type, expected_attrs',
Expand All @@ -38,75 +54,49 @@ def test_web3_auto_infura_empty_key(monkeypatch, caplog, environ_name):
monkeypatch.setenv('WEB3_INFURA_SCHEME', 'https')
monkeypatch.setenv(environ_name, '')

importlib.reload(infura)
assert len(caplog.record_tuples) == 1
logger, level, msg = caplog.record_tuples[0]
assert 'WEB3_INFURA_PROJECT_ID' in msg
assert level == logging.WARNING

w3 = infura.w3
assert isinstance(w3.provider, HTTPProvider)
assert getattr(w3.provider, 'endpoint_uri') == 'https://mainnet.infura.io/'
with pytest.raises(InfuraKeyNotFound):
importlib.reload(infura)


@pytest.mark.parametrize('environ_name', ['WEB3_INFURA_API_KEY', 'WEB3_INFURA_PROJECT_ID'])
def test_web3_auto_infura_deleted_key(monkeypatch, caplog, environ_name):
monkeypatch.setenv('WEB3_INFURA_SCHEME', 'https')

monkeypatch.delenv(environ_name, raising=False)

importlib.reload(infura)
assert len(caplog.record_tuples) == 1
logger, level, msg = caplog.record_tuples[0]
assert 'WEB3_INFURA_PROJECT_ID' in msg
assert level == logging.WARNING

w3 = infura.w3
assert isinstance(w3.provider, HTTPProvider)
assert getattr(w3.provider, 'endpoint_uri') == 'https://mainnet.infura.io/'
with pytest.raises(InfuraKeyNotFound):
importlib.reload(infura)


@pytest.mark.parametrize('environ_name', ['WEB3_INFURA_API_KEY', 'WEB3_INFURA_PROJECT_ID'])
def test_web3_auto_infura_websocket_empty_key(monkeypatch, caplog, environ_name):
monkeypatch.setenv(environ_name, '')

importlib.reload(infura)
assert len(caplog.record_tuples) == 1
logger, level, msg = caplog.record_tuples[0]
assert 'WEB3_INFURA_PROJECT_ID' in msg
assert level == logging.WARNING

w3 = infura.w3
assert isinstance(w3.provider, WebsocketProvider)
assert getattr(w3.provider, 'endpoint_uri') == 'wss://mainnet.infura.io/ws/'
with pytest.raises(InfuraKeyNotFound):
importlib.reload(infura)


@pytest.mark.parametrize('environ_name', ['WEB3_INFURA_API_KEY', 'WEB3_INFURA_PROJECT_ID'])
def test_web3_auto_infura_websocket_deleted_key(monkeypatch, caplog, environ_name):
monkeypatch.delenv(environ_name, raising=False)

importlib.reload(infura)
assert len(caplog.record_tuples) == 1
logger, level, msg = caplog.record_tuples[0]
assert 'WEB3_INFURA_PROJECT_ID' in msg
assert level == logging.WARNING

w3 = infura.w3
assert isinstance(w3.provider, WebsocketProvider)
assert getattr(w3.provider, 'endpoint_uri') == 'wss://mainnet.infura.io/ws/'
with pytest.raises(InfuraKeyNotFound):
importlib.reload(infura)


@pytest.mark.parametrize('environ_name', ['WEB3_INFURA_API_KEY', 'WEB3_INFURA_PROJECT_ID'])
def test_web3_auto_infura(monkeypatch, caplog, environ_name):
monkeypatch.setenv('WEB3_INFURA_SCHEME', 'https')
API_KEY = 'aoeuhtns'

monkeypatch.setenv(environ_name, API_KEY)
expected_url = 'https://%s/v3/%s' % (infura.INFURA_MAINNET_DOMAIN, API_KEY)

importlib.reload(infura)
assert len(caplog.record_tuples) == 0

w3 = infura.w3
assert isinstance(w3.provider, HTTPProvider)
expected_url = 'https://%s/v3/%s' % (infura.INFURA_MAINNET_DOMAIN, API_KEY)
assert getattr(w3.provider, 'endpoint_uri') == expected_url


Expand All @@ -123,3 +113,12 @@ def test_web3_auto_infura_websocket_default(monkeypatch, caplog, environ_name):
w3 = infura.w3
assert isinstance(w3.provider, WebsocketProvider)
assert getattr(w3.provider, 'endpoint_uri') == expected_url


def test_web3_auto_infura_raises_error_with_nonexistent_scheme(monkeypatch):
monkeypatch.setenv('WEB3_INFURA_API_KEY', 'test')
monkeypatch.setenv('WEB3_INFURA_SCHEME', 'not-a-scheme')

error_msg = "Cannot connect to Infura with scheme 'not-a-scheme'"
with pytest.raises(ValidationError, match=error_msg):
importlib.reload(infura)
20 changes: 9 additions & 11 deletions web3/auto/infura/endpoints.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
import logging
import os

from eth_utils import (
ValidationError,
)

from web3.exceptions import (
InfuraKeyNotFound,
)

INFURA_MAINNET_DOMAIN = 'mainnet.infura.io'
INFURA_ROPSTEN_DOMAIN = 'ropsten.infura.io'
INFURA_RINKEBY_DOMAIN = 'rinkeby.infura.io'
Expand All @@ -19,10 +22,9 @@ def load_api_key():
key = os.environ.get('WEB3_INFURA_PROJECT_ID',
os.environ.get('WEB3_INFURA_API_KEY', ''))
if key == '':
logging.getLogger('web3.auto.infura').warning(
"No Infura Project ID found. Add environment variable WEB3_INFURA_PROJECT_ID to "
"ensure continued API access after March 27th. "
"New keys are available at https://infura.io/register"
raise InfuraKeyNotFound(
"No Infura Project ID found. Please ensure "
"that the environment variable WEB3_INFURA_PROJECT_ID is set."
)
return key

Expand All @@ -31,13 +33,9 @@ def build_infura_url(domain):
scheme = os.environ.get('WEB3_INFURA_SCHEME', WEBSOCKET_SCHEME)
key = load_api_key()

if key and scheme == WEBSOCKET_SCHEME:
if scheme == WEBSOCKET_SCHEME:
return "%s://%s/ws/v3/%s" % (scheme, domain, key)
elif key and scheme == HTTP_SCHEME:
return "%s://%s/v3/%s" % (scheme, domain, key)
elif scheme == WEBSOCKET_SCHEME:
return "%s://%s/ws/" % (scheme, domain)
elif scheme == HTTP_SCHEME:
return "%s://%s/%s" % (scheme, domain, key)
return "%s://%s/v3/%s" % (scheme, domain, key)
else:
raise ValidationError("Cannot connect to Infura with scheme %r" % scheme)
7 changes: 7 additions & 0 deletions web3/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -142,3 +142,10 @@ class BlockNotFound(Exception):
Raised when the block id used to lookup a block in a jsonrpc call cannot be found.
"""
pass


class InfuraKeyNotFound(Exception):
"""
Raised when there is no Infura Project Id set.
"""
pass