Skip to content

Commit

Permalink
Demo app fixes after #981 refactor (#983)
Browse files Browse the repository at this point in the history
Also added end-to-end testing with tox
  • Loading branch information
mpaolini authored and asvetlov committed Jul 23, 2016
1 parent a5b75e0 commit 328bb36
Show file tree
Hide file tree
Showing 9 changed files with 96 additions and 15 deletions.
6 changes: 6 additions & 0 deletions demos/polls/README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,12 @@ Open browser::
:align: center


Run integration tests::

pip install tox
tox


Requirements
============
* aiohttp_
Expand Down
15 changes: 6 additions & 9 deletions demos/polls/aiohttpdemo_polls/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,10 @@

from aiohttpdemo_polls.middlewares import setup_middlewares
from aiohttpdemo_polls.routes import setup_routes
from aiohttpdemo_polls.utils import init_postgres, load_config
from aiohttpdemo_polls.views import SiteHandler
from aiohttpdemo_polls.utils import load_config
from aiohttpdemo_polls.db import init_postgres


PROJ_ROOT = pathlib.Path(__file__).parent.parent
PROJ_ROOT = pathlib.Path(__file__).parent


async def close_pg(app):
Expand All @@ -25,18 +24,16 @@ async def init(loop):
app = web.Application(loop=loop)
aiohttp_jinja2.setup(
app, loader=jinja2.PackageLoader('aiohttpdemo_polls', 'templates'))
# load config from yaml file
conf = load_config(str(PROJ_ROOT / 'config' / 'polls.yaml'))
# load config from yaml file in current dir
conf = load_config(str(pathlib.Path('.') / 'config' / 'polls.yaml'))

# create connection to the database
db = await init_postgres(conf['postgres'], loop)
app['db'] = db

app.on_cleanup.append(close_pg)

# setup views and routes
handler = SiteHandler(db)
setup_routes(app, handler, PROJ_ROOT)
setup_routes(app, PROJ_ROOT)
setup_middlewares(app)

host, port = conf['host'], conf['port']
Expand Down
File renamed without changes.
9 changes: 4 additions & 5 deletions demos/polls/aiohttpdemo_polls/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,17 +5,16 @@

@aiohttp_jinja2.template('index.html')
async def index(request):
async with request['db'].acquire() as conn:
async with request.app['db'].acquire() as conn:
cursor = await conn.execute(db.question.select())
records = await cursor.fetchall()

questions = [dict(q) for q in records]
return {'questions': questions}


@aiohttp_jinja2.template('detail.html')
async def poll(request):
async with request['db'].acquire() as conn:
async with request.app['db'].acquire() as conn:
question_id = request.match_info['question_id']
try:
question, choices = await db.get_question(conn,
Expand All @@ -30,7 +29,7 @@ async def poll(request):

@aiohttp_jinja2.template('results.html')
async def results(request):
async with request['db'].acquire() as conn:
async with request.app['db'].acquire() as conn:
question_id = request.match_info['question_id']

try:
Expand All @@ -46,7 +45,7 @@ async def results(request):


async def vote(request):
async with request['db'].acquire() as conn:
async with request.app['db'].acquire() as conn:
question_id = int(request.match_info['question_id'])
data = await request.post()
try:
Expand Down
3 changes: 3 additions & 0 deletions demos/polls/setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,9 @@ def read_version():
description='Polls project example from aiohttp',
platforms=['POSIX'],
packages=find_packages(),
package_data={
'': ['templates/*.html', 'static/*.*']
},
include_package_data=True,
install_requires=install_requires,
zip_safe=False)
2 changes: 1 addition & 1 deletion demos/polls/sql/install.sh
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
sudo -u postgres psql -c "DROP DATABASE IF EXISTS aiohttpdemo_polls"
sudo -u postgres psql -c "DROP ROLE IF EXISTS aiohttpdemo_user"
sudo -u postgres psql -c "CREATE USER aiohttpdemo_user WITH PASSWORD 'aiohttpdemo_user';"
sudo -u postgres psql -c "DROP DATABASE IF EXISTS aiohttpdemo_polls"
sudo -u postgres psql -c "CREATE DATABASE aiohttpdemo_polls ENCODING 'UTF8';"
sudo -u postgres psql -c "GRANT ALL PRIVILEGES ON DATABASE aiohttpdemo_polls TO aiohttpdemo_user;"

Expand Down
43 changes: 43 additions & 0 deletions demos/polls/tests/conftest.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import pathlib
import subprocess

import aiohttp
import pytest


@pytest.yield_fixture
def create_app(event_loop, unused_tcp_port):
app = handler = srv = client_session = None

async def create():
nonlocal app, handler, srv, client_session
import aiohttpdemo_polls.main
app, host, port = await aiohttpdemo_polls.main.init(event_loop)
handler = app.make_handler(debug=True, keep_alive_on=False)
srv = await event_loop.create_server(handler, '127.0.0.1', port)
url = "http://127.0.0.1:{}".format(port)
client_session = aiohttp.ClientSession()
return app, url, client_session

yield create

async def finish():
await handler.finish_connections()
await app.finish()
await client_session.close()
srv.close()
await srv.wait_closed()

event_loop.run_until_complete(finish())


BASE_DIR = pathlib.Path(__file__).parent.parent


@pytest.fixture
def app_db():
subprocess.call(
[(BASE_DIR / 'sql' / 'install.sh').as_posix()],
shell=True,
cwd=BASE_DIR.as_posix()
)
24 changes: 24 additions & 0 deletions demos/polls/tests/test_integration.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
"""
Integration tests. They need a running database.
Beware, they destroy your db using sudo.
"""

async def _test_index(create_app):
app, url, client_session = await create_app()
async with client_session.get('{}/'.format(url)) as response:
assert response.status == 200, await response.text()


def test_index(create_app, event_loop, app_db):
event_loop.run_until_complete(_test_index(create_app))


async def _test_results(create_app):
app, url, client_session = await create_app()
async with client_session.get('{}/results'.format(url)) as response:
assert response.status == 200, await response.text()


def test_results(create_app, event_loop, app_db):
event_loop.run_until_complete(_test_results(create_app))
9 changes: 9 additions & 0 deletions demos/polls/tox.ini
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
[tox]
envlist = py35

[testenv]
deps =
pytest
pytest-asyncio==0.3.0
usedevelop = True
commands=py.test tests -s

0 comments on commit 328bb36

Please sign in to comment.