我认为 Flask 希望我在 tests.py 文件中实例化该应用程序,但我不知道该怎么做



我认为 Flask 希望我实例化应用程序,但我不知道如何,收到错误AttributeError: 'NoneType' object has no attribute 'app'

回溯

C:UsersMlambaEnvsvirScriptspython.exe D:/code/web-projects/Bucketlist-Python-Flask-project/tests.py
E
======================================================================
ERROR: test_index_view (__main__.ViewTests)
----------------------------------------------------------------------
Traceback (most recent call last):
File "D:/code/web-projects/Bucketlist-Python-Flask-project/tests.py", line 11, in test_index_view
response = make_response(render_template("index.html"))
File "C:UsersMlambaEnvsvirlibsite-packagesflasktemplating.py", line 132, in render_template
ctx.app.update_template_context(context)
AttributeError: 'NoneType' object has no attribute 'app'
----------------------------------------------------------------------
Ran 1 test in 0.001s
FAILED (errors=1)

Run.py文件:

from app import app
if __name__ == '__main__':
app.run()

初始化.py文件:

from flask import Flask
# Load the views
from app import views
# Initialize the app
app = Flask(__name__, instance_relative_config=True)
# Load the config file
app.config.from_object('config')

测试文件

import unittest
from flask import render_template, make_response

class ViewTests(unittest.TestCase):
def test_index_view(self):
"""
Test that index page is accessible without login
"""
response = make_response(render_template("index.html"))
self.assertEquals(response.status_code, 200)

if __name__ == '__main__':
unittest.main()

目录结构:

|-- README.md
|-- __pycache__
|   `-- config.cpython-36.pyc
|-- app
|   |-- __init__.py
|   |-- __pycache__
|   |   |-- __init__.cpython-36.pyc
|   |   `-- views.cpython-36.pyc
|   |-- models.py
|   |-- static
|   |-- templates
|   |   |-- index.html
|   |   `-- layout.html
|   `-- views.py
|-- config.py
|-- requirements.txt
|-- run.py
`-- tests.py

您从未导入过app因此无法对其进行测试。 查看有关如何导入应用以及如何测试它的文档。

下面是基本flask测试的示例:

main.py:

from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return "Hello world!" 
if __name__ = '__main__':
app.run()

test_app.py:

import unittest
from main import app
class FlaskTestCase(unittest.TestCase):
def setUp(self):
self.app = app.test_client()
self.app.testing = True
pass
def test_num1(self):
rv = self.app.get('/')
assert b'Hello world' in rv.data

if __name__ == '__main__':
unittest.main()

您可以使用以下命令运行测试:python test_app.py

虽然我不确定。我猜你忘了将你的应用程序模块导入 run.py。也请发布您的 run.py 和初始化的内容.py只是为了更加确定。

在您的 run.py 中,您必须import app并运行该功能app.run()两者都是必需的,并且应该是在您的应用程序中执行的第一步,之后只需执行一个python run.py,服务器将从端口号5000启动我相信。

编辑: 如果你看到你已导入from app import viewsinit.py 这是错误的,因为从 init.py 上下文来看,你已经在应用中,无需再次从应用键入,因为导入将尝试在当前层次结构中查找名为 app 的文件夹或包。 将其更改为import views,您应该在路上。同样正如 Kemis指出的那样,将你的应用程序导入到你的单元测试文件中。

相关内容

最新更新