Flask-Testing and Flask-SQLAlchemy: first_or_404()



我正在尝试使用 Flask-Testing a 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:DevTestPythontest_flask> nosetests-3.4.exe
E
======================================================================
ERROR: test_get_by_identifier (test_flask.TestGetByIdentifier)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:DevTestPythontest_flasktest_flask.py", line 37, in test_get_by_identifier
    self.assert404(ModelToTest.get_by_identifier('identifier'))
  File "C:DevTestPythontest_flasktest_flask.py", line 13, in get_by_identifier
    return ModelToTest.query.filter_by(identifier=identifier).first_or_404()
  File "c:\my_envlibsite-packagesflask_sqlalchemy__init__.py", line 431, in first_or_404
    abort(404)
  File "c:\my_envlibsite-packageswerkzeugexceptions.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()调用中生成了一个异常,这个异常是一个werkzeug.exceptions.NotFound,它似乎不是self.assert404()所期望的。

运行此测试的要求是:

  • 烧瓶-SQL炼金术
  • 烧瓶测试

值得注意的是,当我在应用程序中使用该函数时,它的行为符合预期。

提前谢谢。

我引用了我在GitHub上收到的答案:

https://github.com/jarus/flask-testing/issues/89

我认为这是对驾驶测试方式的误解。 first_or_404函数确实会引发NotFound异常。什么时候 在请求的上下文中,异常将冒泡,即 处理,并变成 404 HTTP 响应,这就是 烧瓶测试正在寻找。

但是,在这种情况下,您不在请求的上下文中,因为 您直接调用该方法,它只是导致 例外。您可以这样做以使测试工作

from werkzeug.exceptions import NotFound
def test_get_by_identifier(self):
    with self.assertRaises(NotFound):
        ModelToTest.get_by_identifier('identifier')

或者,您可以将该函数放在路由后面并使用 self.client,它将正确为您提供404 http响应。 但是,测试例外(不使用烧瓶测试)可能会 在这种情况下,考虑到您正在测试的水平,更合适。

相关内容

最新更新