Skip to content
This repository has been archived by the owner on Jun 8, 2022. It is now read-only.

Commit

Permalink
Add aiohttp & requests tests
Browse files Browse the repository at this point in the history
  • Loading branch information
ovv committed Jan 7, 2018
1 parent 71e3fcf commit b7b08fc
Show file tree
Hide file tree
Showing 4 changed files with 161 additions and 6 deletions.
1 change: 1 addition & 0 deletions examples/curio/query.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@

asks.init('curio')


async def query(client):

data = await client.query(slack.methods.AUTH_TEST)
Expand Down
30 changes: 25 additions & 5 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,14 @@
import json
import copy
import pytest
import requests
import asynctest
import functools

from unittest.mock import Mock

from slack.io.abc import SlackAPI
from slack.io.requests import SlackAPI as SlackAPIRequest
from slack.events import Event, EventRouter, MessageRouter
from slack.actions import Action, Router as ActionRouter
from slack.commands import Command, Router as CommandRouter
Expand All @@ -25,9 +30,17 @@ async def _rtm(self, url):
pass


@pytest.fixture(params=(FakeIO, ))
def io_client(request):

if request.param is SlackAPIRequest:
return functools.partial(request.param, session=requests.session())
return request.param


@pytest.fixture(params=({'retry_when_rate_limit': True, 'token': TOKEN},
{'retry_when_rate_limit': False, 'token': TOKEN}))
def client(request):
def client(request, io_client):
default_request = {'status': 200, 'body': {'ok': True},
'headers': {'content-type': 'application/json; charset=utf-8'}}

Expand All @@ -42,20 +55,27 @@ def client(request):
if 'token' not in request.param:
request.param['token'] = TOKEN

slackclient = FakeIO(**{k: v for k, v in request.param.items() if not k.startswith('_')})
slackclient = io_client(**{k: v for k, v in request.param.items() if not k.startswith('_')})

if isinstance(request.param['_request'], dict):
slackclient._request = asynctest.CoroutineMock(return_value=(
return_value = (
request.param['_request']['status'],
json.dumps(request.param['_request']['body']).encode(),
request.param['_request']['headers']
))
)
if isinstance(slackclient, SlackAPIRequest):
slackclient._request = Mock(return_value=return_value)
else:
slackclient._request = asynctest.CoroutineMock(return_value=return_value)
else:
responses = [
(response['status'], json.dumps(response['body']).encode(), response['headers'])
for response in request.param['_request']
]
slackclient._request = asynctest.CoroutineMock(side_effect=responses)
if isinstance(slackclient, SlackAPIRequest):
slackclient._request = Mock(side_effect=responses)
else:
slackclient._request = asynctest.CoroutineMock(side_effect=responses)

return slackclient

Expand Down
134 changes: 134 additions & 0 deletions tests/test_io.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,14 @@
import json
import pytest
import aiohttp
import datetime
import asynctest

from slack import methods, exceptions

from slack.io.aiohttp import SlackAPI as SlackAPIAiohttp
from slack.io.requests import SlackAPI as SlackAPIRequest


@pytest.mark.asyncio
class TestABC:
Expand Down Expand Up @@ -153,3 +158,132 @@ async def test_iter_not_supported(self, client):
with pytest.raises(ValueError):
async for _ in client.iter('https://slack.com/api/channels.list'): # noQa: F841
pass


@pytest.mark.parametrize('io_client', (SlackAPIRequest, ), indirect=True)
class TestRequest:

def test_sleep(self, client):
delay = 1
start = datetime.datetime.now()
client.sleep(delay)
stop = datetime.datetime.now()
assert (stop - start) > datetime.timedelta(seconds=delay)

def test_query(self, client):
rep = client.query(methods.AUTH_TEST)
client._request.assert_called_once()
assert client._request.call_args[0][0] == 'POST'
assert client._request.call_args[0][1] == 'https://slack.com/api/auth.test'
assert client._request.call_args[0][2] == {}
assert client._request.call_args[0][3] == {'token': 'abcdefg'}

assert rep == {'ok': True}

def test_query_data(self, client, token):
data = {'hello': 'world'}

called_with = data.copy()
called_with['token'] = token

client.query(methods.AUTH_TEST, data)
assert client._request.call_args[0][3] == called_with

def test_query_headers(self, client):
custom_headers = {'hello': 'world'}
called_headers = custom_headers.copy()

client.query('https://hooks.slack.com/abcdef', headers=custom_headers)
assert client._request.call_args[0][2] == called_headers

@pytest.mark.parametrize('client', ({'retry_when_rate_limit': True,
'_request': [
{'status': 429, 'body': {"ok": False}, 'headers': {'Retry-After': 1}},
{},
]},), indirect=True)
def test_retry_rate_limited(self, client):
client.sleep = asynctest.CoroutineMock(side_effect=client.sleep)
rep = client.query(methods.AUTH_TEST)
assert client._request.call_count == 2
client.sleep.assert_called_once_with(1)
assert client._request.call_args_list[0] == client._request.call_args_list[1]
args, kwargs = client._request.call_args_list[0]
assert args == ('POST', 'https://slack.com/api/auth.test', {}, {'token': 'abcdefg'})
assert kwargs == {}
assert rep == {'ok': True}

@pytest.mark.parametrize('client', ({'retry_when_rate_limit': True,
'_request': [
{'status': 429, 'body': {"ok": False}, 'headers': {'Retry-After': 1}},
{},
]},), indirect=True)
def test_retry_rate_limited_with_body(self, client):
client.sleep = asynctest.CoroutineMock(side_effect=client.sleep)
client.query(methods.AUTH_TEST, data={'foo': 'bar'})
assert client._request.call_count == 2
client.sleep.assert_called_once_with(1)
assert client._request.call_args_list[0] == client._request.call_args_list[1]
args, kwargs = client._request.call_args_list[0]
assert args == ('POST', 'https://slack.com/api/auth.test', {}, {'foo': 'bar', 'token': 'abcdefg'})
assert kwargs == {}

@pytest.mark.parametrize('client', ({'retry_when_rate_limit': True,
'_request': [
{'status': 429, 'body': {"ok": False}, 'headers': {'Retry-After': 1}},
{},
]},), indirect=True)
def test_retry_rate_limited_with_headers(self, client):
client.sleep = asynctest.CoroutineMock(side_effect=client.sleep)
client.query(methods.AUTH_TEST, headers={'foo': 'bar'})
assert client._request.call_count == 2
client.sleep.assert_called_once_with(1)
assert client._request.call_args_list[0] == client._request.call_args_list[1]
args, kwargs = client._request.call_args_list[0]
assert args == ('POST', 'https://slack.com/api/auth.test', {'foo': 'bar'}, {'token': 'abcdefg'})
assert kwargs == {}

@pytest.mark.parametrize('client', ({'retry_when_rate_limit': False,
'_request':
{'status': 429, 'body': {"ok": False}, 'headers': {'Retry-After': 2}}
},), indirect=True)
def test_raise_rate_limited(self, client):
with pytest.raises(exceptions.RateLimited):
client.query(methods.AUTH_TEST)

@pytest.mark.parametrize('client', ({'retry_when_rate_limit': False,
'_request': [
{'body': 'channels_iter'},
{'body': 'channels'}
]}, ), indirect=True)
def test_iter(self, client, token, itercursor):
channels = 0
for _ in client.iter(methods.CHANNELS_LIST): # noQa: F841
channels += 1

assert channels == 4
assert client._request.call_count == 2
client._request.assert_called_with(
'POST', 'https://slack.com/api/channels.list', {}, {'limit': 200, 'token': token, 'cursor': itercursor}
)


class TestAiohttp:

@pytest.mark.asyncio
async def test_sleep(self, token):
delay = 1
start = datetime.datetime.now()
async with aiohttp.ClientSession() as session:
client = SlackAPIAiohttp(session=session, token=token)
await client.sleep(delay)
stop = datetime.datetime.now()
assert (stop - start) > datetime.timedelta(seconds=delay)

@pytest.mark.asyncio
async def test__request(self, token):
async with aiohttp.ClientSession() as session:
client = SlackAPIAiohttp(session=session, token=token)
response = await client._request('POST', 'https://slack.com/api//api.test', {}, {'token': token})

assert response[0] == 200
assert response[1] == b'{"ok":false,"error":"invalid_auth"}'
2 changes: 1 addition & 1 deletion tox.ini
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,6 @@ commands =

[testenv]
extras =
tests
dev
commands =
python setup.py test

0 comments on commit b7b08fc

Please sign in to comment.