【问题标题】:Testing django with mongoengine使用 mongoengine 测试 django
【发布时间】:2018-02-22 01:48:10
【问题描述】:

我有一个 django 项目,默认在 Django 上测试只适用于 sql 数据库,但我需要在 mongodb 和 mongoengine 上工作。 我使用 Django 1.9,mongoengine 0.9 因为它支持 django。 我在这里关注文档https://mongoengine.readthedocs.io/en/v0.9.0/django.html 和用于测试的 django 文档https://docs.djangoproject.com/en/1.8/topics/testing/tools/ 问题是我如何配置测试文件来告诉它我想使用 mongodb 数据库。没有任何设置,测试文件如下所示:

import unittest
from django.test import Client
from .models import User

class UserTests(unittest.TestCase):

    def setUp(self):
        self.client = Client()

    def test_create_user(self):
        self.client.post('/users/', {'first_name': 'aaa', 'last_name': 'bbb',
                         'username': 'xxx', 'email': 'abc@gmail.com'})
        ...

运行python manage.py test时的错误是:

raise ImproperlyConfigured("settings.DATABASES is improperly configured. "
ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details.

settings.py:

from mongoengine import connect

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.dummy',
    },
}

connect(
    host='mongodb://localhost/book'
)

【问题讨论】:

  • github.com/MongoEngine/mongoengine/issues/950 MongoDB 是 Django 数据库的糟糕选择
  • 我也更喜欢sql,但是团队一开始是和mongo合作的,后来我加入了,所以别无选择。更改版本似乎可行,但引发另一个错误,我将编辑问题

标签: python django mongodb mongoengine


【解决方案1】:

1。为 NoSQLTests 定义自定义 DiscoverRunner

例如yourapp/tests.py

from django.test.runner import DiscoverRunner

class NoSQLTestRunner(DiscoverRunner):
    def setup_databases(self, **kwargs):
        pass
    def teardown_databases(self, old_config, **kwargs):
        pass

2。为 NoSQLTests 定义自定义 TestCase 类。

例如yourapp/tests.py

from django.test import TestCase

class NoSQLTestCase(TestCase):
    def _fixture_setup(self):
        pass
    def _fixture_teardown(self):
        pass

3。在你的 settings.py 中更改默认的 TEST_RUNNER

TEST_RUNNER = 'yourapp.tests.NoSQLTestRunner'

4。编写测试

不需要数据库的测试:

class YourTest(NoSQLTestCase):

    def test_foo(self):
        to_compare = 'foo'
        assumed = 'foo'
        self.assertEqual(to_compare, assumed)

需要数据库的测试,使用模拟:

https://docs.mongoengine.org/guide/mongomock.html

一步一步

  1. 安装 mongomock pip install mongomock
  2. 写测试:
from mongoengine import connect, disconnect, Document, StringField

class Foo(Document):
    content = StringField()

class TestFoo(NoSQLTestCase):

    @classmethod
    def setUpClass(cls):
        connect('mongoenginetest', host='mongomock://localhost', alias='testdb')

    @classmethod
    def tearDownClass(cls):
       disconnect(alias='testdb)

    def test_thing(self):
        foo = Foo(content='bar')
        foo.save()

        fresh_foo = Foo.objects().first()
        assert fresh_foo.content ==  'bar'

【讨论】:

  • 我在测试中使用了 mocking,它工作正常,所有断言都正确!!
【解决方案2】:

在使用 mongodb 时测试 django 可以通过创建自定义测试用例来完成,其中 setUp 函数使用 mongoengine 连接到 mongodb,而 tearDown 将删除测试数据库并断开连接。

from django.test import TestCase
import mongoengine

class MongoTestCase(TestCase):
    def setUp(self):
        mongoengine.connection.disconnect()
        mongoengine.connect(
            host=settings.MONGO['host'],
            port=settings.MONGO['port'],
            db=settings.MONGO['db'],
            username=settings.MONGO['username'],
            password=settings.MONGO['password']
           )
        super().setUpClass()

    def tearDown(self):
        from mongoengine.connection import get_connection, disconnect
        connection = get_connection()
        connection.drop_database(settings.MONGO['db'])
        disconnect()
        super().tearDownClass()

然后你可以在你的测试中使用这个测试用例。例如,假设我们有一个名为“App”的模型

from models import App

class AppCreationTest(MongoTestCase):
  def test(self):
    app = App(name="first_app")
    app.save()
    assert App.objects.first().name == app.name

您可以通过python manage.py test 运行这些测试

Here 是一个小要点,供您参考

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-10-19
    • 2013-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-29
    • 2018-12-14
    相关资源
    最近更新 更多