0
我有一個非常原始的瓶應用程序,它可以像我期待的那樣工作,但我沒有爲它編寫單元測試。該應用程序的代碼如下(我省略微不足道的一部分):單元測試問題的小瓶應用程序
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(app)',實質上是'test_app = Flask(Flask(app))'。嘗試刪除這一行,並用app.test_client()作爲客戶端替換'with'行。'。 – kfb
我得到了'AttributeError:模塊'app'沒有'test_client'屬性 –
你也需要在你的測試中添加'app ['TESTING'] = True'。 – kfb