Skip to content

Commit

Permalink
Merge pull request #79 from Crunch-io/py2-support-connect-bug
Browse files Browse the repository at this point in the history
Support python2 and a site_url to connect to
  • Loading branch information
jjdelc authored Mar 17, 2022
2 parents 01e43ec + 5e9d65d commit 45f9551
Show file tree
Hide file tree
Showing 4 changed files with 53 additions and 12 deletions.
2 changes: 1 addition & 1 deletion src/pycrunch/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -251,7 +251,7 @@ def connect(user="", pw="", site_url="https://app.crunch.io/api/",
)

sess = session_class(
user, pw, progress_tracking=progress_tracking
user, pw, progress_tracking=progress_tracking, site_url=site_url
)
else:
raise RuntimeError("You must provide either a user and pw or an api_key")
Expand Down
15 changes: 12 additions & 3 deletions src/pycrunch/elements.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,8 @@ class Foo(Element):

try:
# Python 2
from urllib import urlencode, quote, urlparse
from urllib import urlencode, quote
from urlparse import urlparse
except ImportError:
# Python 3
from urllib.parse import urlencode, quote, urlparse
Expand Down Expand Up @@ -315,22 +316,30 @@ class ElementSession(lemonpy.Session):
def __init__(
self, email=None, password=None, token=None, site_url=None, progress_tracking=None
):
if not site_url and token:
raise ValueError("Must include a `site_url` host to connect to")
self.__email = email
self.__password = password
self.token = token
self.site_url = site_url
self.domain = urlparse(site_url).netloc
self.domain = urlparse(site_url).netloc if site_url else None
self.progress_tracking = progress_tracking or DefaultProgressTracking()
super(ElementSession, self).__init__()

@property
def root(self):
if not self.site_url:
raise ValueError("Session must be initialized with `site_url`")
return self.get(self.site_url).payload

@property
def email(self):
warnings.warn(
"`session.email` is being deprecated. Read from `conn.user.body.email`.",
PendingDeprecationWarning,
)
if self.__email is None:
self.__email = self.get(self.site_url).payload.user["body"]["email"]
self.__email = self.root.user["body"]["email"]
return self.__email

@property
Expand Down
38 changes: 33 additions & 5 deletions tests/test_elements.py
Original file line number Diff line number Diff line change
Expand Up @@ -239,11 +239,13 @@ def test_delete(self):
session_mock.delete.assert_called_once_with('some uri')


class TestElementSession:
class TestElementSession(TestCase):
site_url = "https://www.example.com/api"

def test_email_login(self):
email = "[email protected]"
password = "1234"
session = elements.ElementSession(email=email, password=password)
session = elements.ElementSession(email=email, password=password, site_url=self.site_url)
with warnings.catch_warnings(record=True) as w:
assert session.email == email
assert session.password == password
Expand All @@ -259,8 +261,7 @@ def test_domain(self):

def test_token_login(self):
email = "[email protected]"
site_url = "https://www.example.com/api"
session = elements.ElementSession(token="abc", site_url=site_url)
session = elements.ElementSession(token="abc", site_url=self.site_url)
root_mock = mock.MagicMock()
root_mock.user = {"body": {"email": email}}
with mock.patch.object(session, "get") as get:
Expand All @@ -269,8 +270,35 @@ def test_token_login(self):

def test_response_handler_token_session(self):
token = "abc"
session = elements.ElementSession(token=token)
session = elements.ElementSession(token=token, site_url=self.site_url)
handler = elements.ElementResponseHandler(session)
response = mock.MagicMock()
# Since this is a token session. Do not attempt to re-login
assert handler.status_401(response) is response

def test_root(self):
session = elements.ElementSession(token="abc", site_url=self.site_url)
api_root = {"site": "root"}
with mock.patch.object(session, "get") as get:
get.return_value = mock.MagicMock(payload=api_root)
root = session.root
assert root == api_root

def test_root_no_site_url(self):
email = "[email protected]"
session = elements.ElementSession(email=email, password="abx")
with self.assertRaises(ValueError) as err:
_ = session.root
assert str(err.exception) == "Session must be initialized with `site_url`"

def test_require_host_with_token(self):
with self.assertRaises(ValueError) as err:
elements.ElementSession(token="abc")
assert str(err.exception) == "Must include a `site_url` host to connect to"

def test_host_not_required_on_email(self):
email = "[email protected]"
session = elements.ElementSession(email=email, password="abx")
assert session.site_url is None
assert session.email is email

10 changes: 7 additions & 3 deletions tests/test_http.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ class TestHTTPRequests(TestCase):

@classmethod
def setUpClass(cls):
cls.s = Session("not an email", "not a password")
cls.s = Session("not an email", "not a password", site_url="https://app.crunch.io/api/")
cls.r = cls.s.get("http://httpbin.org/headers")

def test_request_sends_user_agent(self):
Expand Down Expand Up @@ -55,7 +55,7 @@ def _resp(adapter, request, *args, **kwargs):
patch = mock.patch('requests.adapters.HTTPAdapter.send', _resp)

patch.start()
s = Session("not an email", "not a password")
s = Session("not an email", "not a password", site_url="https://app.crunch.io/api/")
with self.assertRaises(ServerError) as exc_info:
s.get("http://httpbin.org/status/504")
patch.stop()
Expand All @@ -65,7 +65,7 @@ def _resp(adapter, request, *args, **kwargs):
self.assertEqual(response.status_code, 504)

def test_401_handle_calls_proxies(self):
sess = Session("not an email", "not a password")
sess = Session("not an email", "not a password", site_url="https://app.crunch.io/api/")
headers = {'Set-Cookie': 'abx'}
sess.post = lambda slf, *args, **kwargs: mock.MagicMock(headers=headers)
sess.send = mock.MagicMock()
Expand Down Expand Up @@ -106,6 +106,7 @@ def test_connect(mock_sess):
"[email protected]",
"yourpassword",
session_class=mock_sess,
site_url="https://app.crunch.io/api/",
)

warns = {(warn.category, warn.message.args[0]) for warn in warninfo}
Expand All @@ -119,6 +120,7 @@ def test_connect(mock_sess):
"[email protected]",
"yourpassword",
progress_tracking=None,
site_url="https://app.crunch.io/api/",
)


Expand All @@ -127,13 +129,15 @@ def test_connect_with_api_key(mock_sess):
"[email protected]",
"yourpassword",
session_class=mock_sess,
site_url="https://app.crunch.io/api/",
)

assert ret == "success"
mock_sess.assert_called_once_with(
"[email protected]",
"yourpassword",
progress_tracking=None,
site_url="https://app.crunch.io/api/",
)


Expand Down

0 comments on commit 45f9551

Please sign in to comment.