def test_post(client, auth, app): # test without login with app.app_context(): db, cursor = get_db() cursor.execute('SELECT * FROM post;') vals = cursor.fetchone() keys = ['id', 'author_id', 'created', 'title', 'body'] if vals: post = {keys[i]: vals[i] for i in xrange(len(keys))} response = client.get('/' + str(post['id']) + '/post') assert response.status_code == 200 assert post['title'] in response.data # test with login auth.login() with app.app_context(): db, cursor = get_db() cursor.execute('SELECT * FROM post;') vals = cursor.fetchone() keys = ['id', 'author_id', 'created', 'title', 'body'] if vals: post = {keys[i]: vals[i] for i in xrange(len(keys))} response = client.get('/' + str(post['id']) + '/post') assert response.status_code == 200 assert post['title'] in response.data assert post['body'].replace(str(hash("more")), "") in response.data assert str(hash("more")) not in response.data
def test_get_close_db(app): with app.app_context(): db, cursor = get_db() assert db, cursor is get_db() with pytest.raises(psycopg2.InterfaceError) as e: cursor.execute('SELECT 1') assert 'closed' in str(e)
def index(): db, cursor = get_db() cursor.execute('SELECT p.id, title, body, created, author_id, username' ' FROM post p JOIN users u ON p.author_id = u.id' ' ORDER BY created DESC') # ISSUE: (coming from sqlite -> psql migration) # sqlite was returning dictionaries fetched['key'] = 'value' # but psql returns just a list of values, there could some better ways # to fix this but this below is just an ugly work around to fix it keys = ['id', 'title', 'body', 'created', 'author_id', 'username'] posts_values = cursor.fetchall() # this is the list of list of values # here I create the list of dicts manually posts = [] for post_values in posts_values: post = {keys[i]: post_values[i] for i in range(len(keys))} # I am inserting in the body of the article the numeric value # of hash('more') to signal the stop of the preview and put # the readmore button more_index = post['body'].find(str(-8321014616845971137)) if more_index != -1: post['body'] = post['body'][:more_index] posts.append(post) # the dictionary is needed for jinja2 to render template return render_template('blog/index.html', posts=posts)
def login(): if request.method == 'POST': username = request.form['username'] password = request.form['password'] db, cursor = get_db() error = None cursor.execute( "SELECT * FROM users WHERE username = '******'".format(username)) # same issue as described in blog.py in line 20 cols = ['id', 'username', 'password'] vals = cursor.fetchone() if vals: user = {cols[i]: vals[i] for i in range(len(cols))} else: user = None if user is None: error = 'Incorrect username.' elif not check_password_hash(user['password'], password): error = 'Incorrect password.' if error is None: session.clear() session['user_id'] = user['id'] return redirect(url_for('index')) flash(error) return render_template('auth/login.html')
def register(): if request.method == 'POST': username = request.form['username'] password = request.form['password'] db, cursor = get_db() error = None if not username: error = 'Username is required.' elif not password: error = 'Password is required.' else: cursor.execute( "SELECT id FROM users WHERE username = '******';".format(username)) if cursor.fetchone() is not None: error = 'User {} is already registered.'.format(username) if error is None: cursor.execute( "INSERT INTO users (username, password) VALUES ('{}', '{}');". format(username, generate_password_hash(password))) db.commit() return redirect(url_for('auth.login')) flash(error) return render_template('auth/register.html')
def test_create_special_char(client, auth, app): auth.login() assert client.get('/create').status_code == 200 with app.app_context(): db, cursor = get_db() cursor.execute('SELECT COUNT(id) FROM post') before_count = cursor.fetchone()[0] client.post('/create', data={ 'title': 'special_char1', 'body': 'standard chars' }) client.post('/create', data={ 'title': 'special_char1', 'body': 'standard chars ) ( + / x % < >' }) client.post('/create', data={ 'title': 'special_char1', 'body': "standard chars ' " }) cursor.execute('SELECT COUNT(id) FROM post') count = cursor.fetchone()[0] assert count - before_count == 3
def test_delete(client, auth, app): auth.login() response = client.post('/1/delete') assert response.headers['Location'] == 'http://localhost/' with app.app_context(): db, cursor = get_db() cursor.execute('SELECT * FROM post WHERE id = 1') post = cursor.fetchone() assert post is None
def load_logged_in_user(): user_id = session.get('user_id') if user_id is None: g.user = None else: db, cursor = get_db() cursor.execute("SELECT * FROM users WHERE id = '{}'".format(user_id)) cols = ['id', 'username', 'password'] vals = cursor.fetchone() if vals: g.user = {cols[i]: vals[i] for i in range(len(cols))} else: g.user = None
def test_author_required(app, client, auth): # change the post author to another user with app.app_context(): db, cursor = get_db() cursor.execute('UPDATE post SET author_id = 2 WHERE id = 1') db.commit() auth.login() # current user can't modify other user's post assert client.post('/1/update').status_code == 403 assert client.post('/1/delete').status_code == 403 assert b'href="/1/update"' not in client.get('/').data
def test_create(client, auth, app): auth.login() assert client.get('/create').status_code == 200 with app.app_context(): db, cursor = get_db() cursor.execute('SELECT COUNT(id) FROM post') before_count = cursor.fetchone()[0] client.post('/create', data={'title': 'created', 'body': ''}) cursor.execute('SELECT COUNT(id) FROM post') count = cursor.fetchone()[0] assert count - before_count == 1
def test_update(client, auth, app): auth.login() assert client.get('/1/update').status_code == 200 client.post('/1/update', data={'title': 'updated', 'body': ''}) with app.app_context(): db, cursor = get_db() cursor.execute('SELECT * FROM post WHERE id = 1') vals = cursor.fetchone() keys = ['id', 'author_id', 'created', 'title', 'body'] assert len(vals) == len(keys) if vals: post = {keys[i]: vals[i] for i in xrange(len(keys))} else: post = None assert post['title'] == 'updated'
def app(): db_fd, db_path = tempfile.mkstemp() app = create_app({ 'TESTING': True, 'DATABASE': db_path, }) with app.app_context(): init_db() db, cursor = get_db() cursor.execute(_data_sql) db.commit() yield app os.close(db_fd) os.unlink(db_path)
def get_post(id, check_author=True): db, cursor = get_db() cursor.execute("SELECT p.id, title, body, created, author_id, username" " FROM post p JOIN users u ON p.author_id = u.id" " WHERE p.id = '{}'".format(id)) # this is a copy paste from line 20, should add code reusability vals = cursor.fetchone() keys = ['id', 'title', 'body', 'created', 'author_id', 'username'] if vals: post = {keys[i]: vals[i] for i in range(len(keys))} else: post = None if post is None: abort(404, "Post id {0} doesn't exist.".format(id)) if check_author and post['author_id'] != g.user['id']: abort(403) return post
def create(): if request.method == 'POST': title = request.form['title'] body = request.form['body'] error = None if not title: error = 'Title is required.' if error is not None: flash(error) else: db, cursor = get_db() cursor.execute( "INSERT INTO post (title, body, created, author_id)" " VALUES (%s, %s, %s, %s)", (title, body, ctime(), g.user['id'])) db.commit() return redirect(url_for('blog.index')) return render_template('blog/create.html')
def update(id): post = get_post(id) if request.method == 'POST': title = request.form['title'] body = request.form['body'] error = None if not title: error = 'Title is required.' if error is not None: flash(error) else: db, cursor = get_db() cursor.execute( "UPDATE post SET title = %s, body = %s" " WHERE id = %s", (title, body, id)) db.commit() return redirect(url_for('blog.index')) return render_template('blog/update.html', post=post)
def delete(id): get_post(id) db, cursor = get_db() cursor.execute("DELETE FROM post WHERE id = '{}' ".format(id)) db.commit() return redirect(url_for('blog.index'))