[关闭]
@magine 2015-02-05T08:14:02.000000Z 字数 1506 阅读 1206

实习日记 2015年1月16日(第一次写测试)

实习日记


今晚被lepture前辈带去看《博物馆奇妙夜3》了,
影院前排的观众好热情啊,全程吵闹喋喋不休也是醉了。

今天上午在Satoru前辈的指导下,修正了一个vagrant provision文件里的Bug。

  1. # 旧版
  2. - name: log files for tristram
  3. file: state=file path=/var/log/tristram/nginx/{{ item }} mode=0644
  4. with_items:
  5. - access.log
  6. - error.log
  7. # 新版
  8. - name: log files for tristram
  9. file: state=touch path=/var/log/tristram/nginx/{{ item }} mode=0644
  10. with_items:
  11. - access.log
  12. - error.log

下午在lepture前辈的指导下,参照pytest的文档flask的测试文档写了一个后台界面的登陆测试。

  1. # filename: test_admin.py
  2. import pytest
  3. from flask import url_for
  4. from tristram.models import AdminUser
  5. # 被fixture装饰的client函数会在本脚本中的测试函数执行前被调用,
  6. # 并返回一个flask自带的链接测试对象test_client给测试函数
  7. # 此处还有一个额外的处理,在访问前先新建了一个admin用户
  8. @pytest.fixture()
  9. def client(app):
  10. AdminUser.create_admin_user(
  11. 'namenamename',
  12. 'password'
  13. )
  14. return app.test_client()
  15. # pytest执行时会自动找到所有带‘test_’前缀的函数来执行
  16. def test_get_login(client):
  17. rv = client.get('/admin/login/')
  18. assert b'</form>' in rv.data
  19. def test_login_success(client):
  20. rv = client.post('/admin/login/', data=dict(
  21. username='namename',
  22. password='password'
  23. ))
  24. assert rv.status_code == 302
  25. assert rv.location == url_for('admin.index')

看起来很简单吧?当然,还要有对应的配置文件的支持。

  1. # filename: conftest.py
  2. import pytest
  3. from tristram.app import create_app
  4. from tristram.models import db
  5. # 写在此处的fixture会在所有的测试开始前依次被执行
  6. # 其优先级高于各个测试脚本中的fixture
  7. @pytest.fixture()
  8. def app(request):
  9. app = create_app({
  10. 'SERVER_NAME': 'localhost',
  11. 'SQLALCHEMY_DATABASE_URI': 'sqlite://',
  12. 'MEMCACHED': ['127.0.0.1:11211'],
  13. })
  14. context = app.app_context()
  15. context.push()
  16. db.init_app(app)
  17. db.create_all()
  18. @request.addfinalizer
  19. def fin():
  20. from tristram.libs.cache import mc
  21. mc.clear()
  22. db.drop_all()
  23. context.pop()
  24. return app
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注