我正在尝试使用Flask-Testing Flask-SQLAlchemy模型进行测试。更准确地说,这个模型的静态方法使用first_or_404()
我找不到让我的测试工作的方法。
这是一个突出问题的自包含示例:
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask.ext.testing import TestCase
db = SQLAlchemy()
class ModelToTest(db.Model):
__tablename__ = 'model_to_test'
identifier = db.Column(db.String(80), unique=True, nullable=False, primary_key=True)
@staticmethod
def get_by_identifier(identifier):
return ModelToTest.query.filter_by(identifier=identifier).first_or_404()
class Config:
DEBUG = True
TESTING = True
SQLALCHEMY_DATABASE_URI = 'sqlite:///'
SQLALCHEMY_TRACK_MODIFICATIONS = False
class TestGetByIdentifier(TestCase):
def create_app(self):
app = Flask('test')
app.config.from_object(Config())
db.init_app(app)
return app
def setUp(self):
db.create_all()
def tearDown(self):
db.session.remove()
db.drop_all()
def test_get_by_identifier(self):
self.assert404(ModelToTest.get_by_identifier('identifier'))
我得到了错误:
(my_env) PS C:\Dev\Test\Python\test_flask> nosetests-3.4.exe
E
======================================================================
ERROR: test_get_by_identifier (test_flask.TestGetByIdentifier)
----------------------------------------------------------------------
Traceback (most recent call last):
File "C:\Dev\Test\Python\test_flask\test_flask.py", line 37, in test_get_by_identifier
self.assert404(ModelToTest.get_by_identifier('identifier'))
File "C:\Dev\Test\Python\test_flask\test_flask.py", line 13, in get_by_identifier
return ModelToTest.query.filter_by(identifier=identifier).first_or_404()
File "c:\\my_env\lib\site-packages\flask_sqlalchemy\__init__.py", line 431, in first_or_404
abort(404)
File "c:\\my_env\lib\site-packages\werkzeug\exceptions.py", line 646, in __call__
raise self.mapping[code](*args, **kwargs)
werkzeug.exceptions.NotFound: 404: Not Found
----------------------------------------------------------------------
Ran 1 test in 0.913s
所以该行self.assert404(ModelToTest.get_by_identifier('identifier'))
确实在调用中产生了一个异常,first_or_404()
这个异常是 a werkzeug.exceptions.NotFound
,它似乎不是self.assert404()
.
运行此测试的要求是:
- 烧瓶
- 烧瓶-sqlalchemy
- 烧瓶测试
值得注意的是,当我在应用程序中使用该函数时,它的行为符合预期。
提前致谢。