私は期待しているように機能する非常に基本的なFlaskアプリケーションを持っていますが、私はそのためのユニットテストを書いていません。アプリのコードは、(私は重要でない部分を省略)は、次のされています小さな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)
感謝。
'app'が既に' Flask'のインスタンスで '本質的に' test_app = Flask(Flask(app)) 'を実行しているときに' test_app'を 'Flask(app)'として初期化しています。この行を削除し、 'with'行を' app.test_client()as client: 'に置き換えてみてください。 – kfb
'AttributeError:module 'app'に属性 'test_client''がありません –
テストに' app [' TESTING '] = True'を追加する必要があります。 – kfb