简体   繁体   English

使用 MongoEngine 在 Flask 中测试套件

[英]Test Suite in Flask with MongoEngine

I have a small app in Flask which I want to accompany with tests.我在 Flask 中有一个小应用程序,我想与测试一起使用。 I have used Django tests before, and I'm just getting to grips with the lower level functionality in Flask.我之前使用过 Django 测试,我刚刚开始掌握 Flask 中较低级别的功能。

My tests currently look like this:我的测试目前看起来像这样:

import unittest
from config import app
from mongoengine import connect
from my_app.models import User

class TestCase(unittest.TestCase):

    def setUp(self):
        app.config['TESTING'] = True
        app.config["MONGODB_DB"] = 'xxx'
        connect(
            'xxx',
            username='heroku',
            password='xxx',
            host='xxx',
            port=xxx
        )
        self.app = app.test_client()

    def tearDown(self):
        pass

    def test_create_user(self):
        u = User(username='john', email='john@example.com')
        u.save()

I know that this is wrong, because the test passes but I have added an entry into the database.我知道这是错误的,因为测试通过了,但我在数据库中添加了一个条目。 How should I test the creation of a User without polluting the database?如何在不污染数据库的情况下测试用户的创建? I had assumed that app.config['TESTING'] had some significance here.我曾假设app.config['TESTING']在这里有一些意义。

There are two approaches I know of:我知道有两种方法:

1. Separate Test Database 1. 单独的测试数据库

This is something that Django does automatically for unittesting.这是 Django 自动为单元测试所做的事情。 It simply uses a separate database for testing that it clears before and after every test run.它只是使用单独的数据库进行测试,每次测试运行前后都会清除该数据库。 You could implement something like this manually.你可以手动实现这样的东西。

2. Use Mocking to avoid actually using the database 2. 使用 Mocking 避免实际使用数据库

This is the more preferred method for most situations.对于大多数情况,这是更优选的方法。 You use mocking to simulate various functions so that the tests don't actually create/edit/delete information in a real database.您使用模拟来模拟各种功能,以便测试实际上不会在真实数据库中创建/编辑/删除信息。 This is better for multiple reasons, most notably for performance/speed of your unit tests.由于多种原因,这更好,最显着的是单元测试的性能/速度。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM