我有一个非常原始的Flask应用程序,它正如我所料,但我没有为它编写单元测试。该应用程序的代码如下(我省略了无关紧要的部分):
app.py
from flask import *
import random
import string
app = Flask(__name__)
keys = []
app.testing = True
@app.route('/keygen/api/keys', methods=['POST'])
def create():
symbol = string.ascii_letters + string.digits
key = ''.join(random.choice(symbol) for _ in range(4))
key_instance = {'key': key, 'is_used': False}
keys.append(key_instance)
return jsonify({'keys': keys}), 201
测试是:
tests.py
import unittest
from flask import *
import app
class TestCase(unittest.TestCase):
def test_number_one(self):
test_app = Flask(app)
with test_app.test_client() as client:
rv = client.post('/keygen/api/keys')
...something...
if __name__ == '__main__':
unittest.main()
追溯:
ERROR: test_number_one (__main__.TestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
File "tests.py", line 12, in test_number_one
test_app = Flask(app)
File "/Users/bulrathi/Yandex.Disk.localized/Virtualenvs/ailove/lib/python3.5/site-packages/flask/app.py", line 346, in __init__
root_path=root_path)
File "/Users/bulrathi/Yandex.Disk.localized/Virtualenvs/ailove/lib/python3.5/site-packages/flask/helpers.py", line 807, in __init__
root_path = get_root_path(self.import_name)
File "/Users/bulrathi/Yandex.Disk.localized/Virtualenvs/ailove/lib/python3.5/site-packages/flask/helpers.py", line 668, in get_root_path
filepath = loader.get_filename(import_name)
File "<frozen importlib._bootstrap_external>", line 384, in _check_name_wrapper
ImportError: loader for app cannot handle <module 'app' from '/Users/bulrathi/Yandex.Disk.localized/Обучение/Code/Django practice/ailove/keygen/app.py'>
----------------------------------------------------------------------
Ran 1 test in 0.003s
FAILED (errors=1)
感谢您的时间。
答案 0 :(得分:2)
发布的代码存在一些问题(除了缩进):
首先,在tests.py
import app
app
并使用它,但app
是模块,而不是app.py
中的app
对象。您应该使用
from app import app
对象
app
其次,您正在使用该Flask()
对象(假设我们修复导入)作为另一个app = Flask(Flask(app))
构造函数的参数 - 实质上是这样说:
app
由于我们已从app.py
导入app = Flask(app)
,因此我们可以直接使用它,因此我们删除了import
行(以及相关的import unittest
from app import app
class TestCase(unittest.TestCase):
def test_number_one(self):
with app.test_client() as client:
rv = client.post('/keygen/api/keys')
...something...
if __name__ == '__main__':
unittest.main()
声明不再需要它了,你的测试文件就变成了:
from flask import *
您还应该注意,不建议使用from flask import Flask, jsonify
表单来导入模块的特定部分,所以
app.py
在您的postgres -D "C:\Program Files\PostgreSQL\data\"
中会更好。