【问题标题】:Testing a POST method unit test which inserts data to mongodb database测试将数据插入 mongodb 数据库的 POST 方法单元测试
【发布时间】: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


    【解决方案1】:

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

    首先,找到一个内存数据库,有pymongo-inmemorymongomock之类的选项

    然后在您的代码中,您必须根据您的环境(生产/开发/其他)进行连接

    类似这样的:

    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
    

    【讨论】:

    • 对于 test_post 我收到此错误。这是为什么?你能告诉我为什么会这样吗?
    • Traceback(最近一次调用最后一次):失败:builtins.tuple:(, ServerSelectionTimeoutError("localhost:27017: [WinError 10061] 无法建立连接因为目标机器主动拒绝了,Timeout: 30s, Topology Description: ]>"), )
    【解决方案2】:

    我不知道这是否是正确的方法,但我找到了解决方案。创建测试客户端self.app = app.test_client() 后,db 被设置为localhost:27017,所以我手动更改它,如下所示:

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

    【讨论】:

      猜你喜欢
      • 2019-07-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多