我一直在尝试将单元测试添加到我的Flask应用程序中。我使用的是应用程序工厂模式。
我一直在使用https://github.com/cookiecutter-flask作为参考,我相信我已经在实现之后实现了测试。我在运行py.test
时遇到了一些错误,我不知道如何修复这些错误,如果有任何帮助,我将不胜感激
我已将我认为与我的代码相关的部分包括在下面:
测试/conftest.py
import pytest
from webtest import TestApp
from urlshort import create_app
from urlshort.models import Link
from urlshort.models import db as _db
@pytest.fixture
def app():
"""Create application for the tests."""
_app = create_app(testing=True)
ctx = _app.test_request_context()
ctx.push()
yield _app
ctx.pop()
@pytest.fixture
def testapp(app):
"""Create Webtest app."""
return TestApp(app)
@pytest.fixture
def db(app):
"""Create database for the tests."""
_db.app = app
with app.app_context():
_db.create_all()
yield _db
_db.session.close()
_db.drop_all()
@pytest.fixture
def link(db):
"""Create a link for the tests."""
link = Link(long='https://example.com/', short='3')
db.session.add(link)
return link
测试/测试表单.py
from urlshort.forms import URLForm, UnshortenForm
from urlshort.strings import Strings
class TestURLForm:
"""URLForm tests"""
def test_inject_strings(self, testapp):
"""Tests if the inject_strings() context processor works as expected"""
response = self.testapp.post('/', data=dict(
url='notaurl'
), follow_redirects = True)
assert Strings.strings['URLValidationError'].encode() in response.data
def test_invalid_link(self):
"""Invalid link"""
form = URLForm(url='notaurl')
assert form.validate() is False
以下是我的create_应用程序(如果有帮助):
urlshort/\uuuuu init\uuuuuu.py
from flask import Flask
from config import Config, TestConfig
from urlshort.models import db
def create_app(testing=False):
app = Flask(__name__)
if testing:
app.config.from_object(TestConfig)
else:
app.config.from_object(Config)
db.init_app(app)
from urlshort.routes import shortener
app.register_blueprint(shortener)
with app.app_context():
db.create_all()
app.shell_context_processor(shell_context)
return app
def shell_context():
"""Shell context objects."""
return {"db": db}
以下是pytest的相关输出:
============================================================================================ short test summary info ============================================================================================
FAILED tests/test_forms.py::TestURLForm::test_invalid_link - RuntimeError: Working outside of application context.
测试应使用测试请求上下文()运行。我不知道如何调试这个,所以任何建议都将不胜感激
我设法解决了这个问题,解决方案是通过应用程序测试无效链接:
所以它实际上得到了应用程序上下文
相关问题 更多 >
编程相关推荐