【发布时间】:2021-12-21 16:06:00
【问题描述】:
我想知道我应该如何测试我的代码并查看它是否正常工作。我想确保它将接收到的数据存储到数据库中。你能告诉我我该怎么做吗?在我搜索论坛时,我发现了this 的帖子,但我并不真正了解发生了什么。这是我要测试的代码。
client = MongoClient(os.environ.get("MONGODB_URI"))
app.db = client.securify
app.secret_key = str(os.environ.get("APP_SECRET"))
@app.route("/", methods=["GET", "POST"])
def home():
if request.method == "POST":
ip_address = request.remote_addr
entry_content = request.form.get("content")
formatted_date = datetime.datetime.today().strftime("%Y-%m-%d/%H:%M")
app.db.entries.insert({"content": entry_content, "date": formatted_date, "IP": ip_address})
return render_template("home.html")
这是我写的模拟测试:
import os
from unittest import TestCase
from app import app
class AppTest(TestCase):
# executed prior to each test
def setUp(self):
# you can change your application configuration
app.config['TESTING'] = True
# you can recover a "test cient" of your defined application
self.app = app.test_client()
# then in your test method you can use self.app.[get, post, etc.] to make the request
def test_home(self):
url_path = '/'
response = self.app.get(url_path)
self.assertEqual(response.status_code, 200)
def test_post(self):
url_path = '/'
response = self.app.post(url_path,data={"content": "this is a test"})
self.assertEqual(response.status_code, 200)
test_post 卡住,几秒钟后到达app.db.entries.insert({"content": entry_content, "date": formatted_date, "IP": ip_address}) 部分时会出错。请告诉我如何检索保存的数据以确保以预期的方式保存它
【问题讨论】:
标签: python mongodb unit-testing flask pymongo