Skip to content

Commit 1040231

Browse files
Fix tests (#1557)
1 parent c0c845a commit 1040231

File tree

6 files changed

+60
-71
lines changed

6 files changed

+60
-71
lines changed

demos/polls/tests/test_integration.py

Lines changed: 13 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -5,22 +5,22 @@
55

66

77
async def test_index(cli, tables_and_data):
8-
response = await cli.get('/')
9-
assert response.status == 200
10-
# TODO: resolve question with html code "'" instead of apostrophe in
11-
# assert 'What\'s new?' in await response.text()
12-
assert 'Main' in await response.text()
8+
async with cli.get('/') as response:
9+
assert response.status == 200
10+
# TODO: resolve question with html code "'" instead of apostrophe in
11+
# assert 'What\'s new?' in await response.text()
12+
assert 'Main' in await response.text()
1313

1414

1515
async def test_results(cli, tables_and_data):
16-
response = await cli.get('/poll/1/results')
17-
assert response.status == 200
18-
assert 'Just hacking again' in await response.text()
16+
async with cli.get('/poll/1/results') as response:
17+
assert response.status == 200
18+
assert 'Just hacking again' in await response.text()
1919

2020

2121
async def test_404_status(cli, tables_and_data):
22-
response = await cli.get('/no-such-route')
23-
assert response.status == 404
22+
async with cli.get('/no-such-route') as response:
23+
assert response.status == 404
2424

2525

2626
async def test_vote(cli, tables_and_data):
@@ -38,11 +38,11 @@ async def test_vote(cli, tables_and_data):
3838
not_much_choice_id = not_much_choice.id
3939
votes_before = not_much_choice.votes
4040

41-
response = await cli.post(
41+
async with cli.post(
4242
f'/poll/{question_id}/vote',
4343
data={'choice': not_much_choice_id}
44-
)
45-
assert response.status == 200
44+
) as response:
45+
assert response.status == 200
4646

4747
async with cli.server.app[db_key].begin() as sess:
4848
result = await sess.scalars(

demos/shortify/shortify/main.py

Lines changed: 11 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,25 @@
11
import asyncio
22
import logging
33
import pathlib
4+
from collections.abc import AsyncIterator
45

56
import aiohttp_jinja2
67
import jinja2
78
from aiohttp import web
8-
from redis.asyncio import Redis
9+
from redis import asyncio as aioredis
910

1011
from shortify.routes import setup_routes
11-
from shortify.utils import init_redis, load_config
12-
from shortify.views import SiteHandler
13-
12+
from shortify.utils import CONF_KEY, REDIS_KEY, load_config
1413

1514
PROJ_ROOT = pathlib.Path(__file__).parent.parent
1615
TEMPLATES_ROOT = pathlib.Path(__file__).parent / 'templates'
1716

18-
# Define AppKey for Redis
19-
REDIS_KEY = web.AppKey("REDIS_KEY", Redis)
20-
2117

22-
async def setup_redis(app, conf):
23-
redis = await init_redis(conf["redis"])
24-
app[REDIS_KEY] = redis
25-
return redis
18+
async def redis_ctx(app: web.Application) -> AsyncIterator[None]:
19+
conf = app[CONF_KEY]["redis"]
20+
async with await aioredis.from_url(f"redis://{conf['host']}:{conf['port']}") as redis:
21+
app[REDIS_KEY] = redis
22+
yield
2623

2724

2825
def setup_jinja(app):
@@ -35,12 +32,11 @@ async def init():
3532
conf = load_config(PROJ_ROOT / "config" / "config.yml")
3633

3734
app = web.Application()
38-
redis = await setup_redis(app, conf)
35+
app[CONF_KEY] = conf
36+
app.cleanup_ctx.append(redis_ctx)
3937
setup_jinja(app)
4038

41-
handler = SiteHandler(redis, conf)
42-
43-
setup_routes(app, handler, PROJ_ROOT)
39+
setup_routes(app, PROJ_ROOT)
4440
host, port = conf['host'], conf['port']
4541
return app, host, port
4642

demos/shortify/shortify/routes.py

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,11 @@
1-
def setup_routes(app, handler, project_root):
1+
from shortify.views import index, redirect, shortify
2+
3+
4+
def setup_routes(app, project_root):
25
router = app.router
3-
h = handler
4-
router.add_get('/', h.index, name='index')
5-
router.add_get('/{short_id}', h.redirect, name='short')
6-
router.add_post('/shortify', h.shortify, name='shortify')
6+
router.add_get('/', index, name='index')
7+
router.add_get('/{short_id}', redirect, name='short')
8+
router.add_post('/shortify', shortify, name='shortify')
79
router.add_static(
810
'/static/', path=str(project_root / 'static'),
911
name='static')

demos/shortify/shortify/utils.py

Lines changed: 3 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,10 @@
1-
from redis import asyncio as aioredis
21
import trafaret as t
32
import yaml
43
from aiohttp import web
4+
from redis.asyncio import Redis
55

6-
6+
CONF_KEY = web.AppKey("CONF_KEY", dict[str, object])
7+
REDIS_KEY = web.AppKey("REDIS_KEY", Redis)
78
CONFIG_TRAFARET = t.Dict(
89
{
910
t.Key('redis'): t.Dict(
@@ -27,13 +28,6 @@ def load_config(fname):
2728
return CONFIG_TRAFARET.check(data)
2829

2930

30-
async def init_redis(conf):
31-
redis = await aioredis.from_url(
32-
f"redis://{conf['host']}:{conf['port']}",
33-
)
34-
return redis
35-
36-
3731
CHARS = "abcdefghijkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789"
3832

3933

demos/shortify/shortify/views.py

Lines changed: 25 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -1,39 +1,37 @@
11
import aiohttp_jinja2
22
from aiohttp import web
33

4-
from .utils import encode, fetch_url
4+
from .utils import CONF_KEY, REDIS_KEY, encode, fetch_url
55

66

7-
class SiteHandler:
7+
@aiohttp_jinja2.template('index.html')
8+
async def index(request):
9+
return {}
810

9-
def __init__(self, redis, conf):
10-
self._redis = redis
11-
self._conf = conf
1211

13-
@aiohttp_jinja2.template('index.html')
14-
async def index(self, request):
15-
return {}
12+
async def shortify(request):
13+
data = await request.json()
14+
long_url = fetch_url(data)
1615

17-
async def shortify(self, request):
18-
data = await request.json()
19-
long_url = fetch_url(data)
16+
conf = request.app[CONF_KEY]
17+
redis = request.app[REDIS_KEY]
18+
index = await redis.incr("shortify:count")
19+
path = encode(index - 1)
20+
key = "shortify:{}".format(path)
21+
await redis.set(key, long_url)
2022

21-
index = await self._redis.incr("shortify:count")
22-
path = encode(index - 1)
23-
key = "shortify:{}".format(path)
24-
await self._redis.set(key, long_url)
23+
url = "http://{host}:{port}/{path}".format(
24+
host=conf['host'],
25+
port=conf['port'],
26+
path=path)
2527

26-
url = "http://{host}:{port}/{path}".format(
27-
host=self._conf['host'],
28-
port=self._conf['port'],
29-
path=path)
28+
return web.json_response({"url": url})
3029

31-
return web.json_response({"url": url})
3230

33-
async def redirect(self, request):
34-
short_id = request.match_info['short_id']
35-
key = 'shortify:{}'.format(short_id)
36-
location = await self._redis.get(key)
37-
if not location:
38-
raise web.HTTPNotFound()
39-
raise web.HTTPFound(location=location.decode())
31+
async def redirect(request):
32+
short_id = request.match_info['short_id']
33+
key = 'shortify:{}'.format(short_id)
34+
location = await request.app[REDIS_KEY].get(key)
35+
if not location:
36+
raise web.HTTPNotFound()
37+
raise web.HTTPFound(location=location.decode())

demos/shortify/tests/test_shortify.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,9 @@ async def test_create_short_url(cli, clean_redis):
33
long_url = "https://example.com/very/long/url/that/needs/shortening"
44

55
async with cli.post("/shortify", json={"url": long_url}) as resp:
6-
await resp.read()
76
assert resp.status == 200
7+
data = await resp.json()
88

9-
data = await resp.json()
109
assert "url" in data
1110
assert data["url"] == "http://127.0.0.1:9001/a"
1211

0 commit comments

Comments
 (0)