测试将数据插入 mongodb 数据库的 POST 方法单元测试

Testing a POST method unit test which inserts data to mongodb database

我想知道我应该如何测试我的代码并查看它是否正常工作。我想确保它将接收到的数据存储到数据库中。你能告诉我我该怎么做吗?在搜索论坛时,我发现 this post 但我并不真正了解发生了什么。这是我要测试的代码。

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}) 部分时出现错误。还请告诉我如何检索保存的数据以确保它以预期的方式保存

这是我使用 NodeJS 所做的,在 python 中完全没有测试,但想法是一样的。

首先,找一个内存DB,有pymongo-inmemory or mongomock

之类的选项

然后在您的代码中,您必须根据您的环境进行连接 (production/development/whatever)

像这样:

env = os.environ.get("ENV")
if env == "TESTING":
  # connect to mock db
elif env == "DEVELOMPENT":
  # for example if you want to test against a real DB but not the production one
  # then do the connection here
else:
  # connect to production DB

我不知道这样做是否正确,但我找到了解决方案。创建测试客户端后 self.app = app.test_client() 数据库设置为 localhost:27017 所以我手动更改它如下并且它有效:

self.app = app.test_client()
client = MongoClient(os.environ.get("MONGODB_URI"))