【问题标题】:How to keep database data when run py.test?运行py.test时如何保留数据库数据?
【发布时间】:2016-01-29 02:13:31
【问题描述】:

我想测试我的查询数据库功能。

import pytest
from account_system.action import my_action
from account_system.models import MyUser

@pytest.mark.django_db
def test_ok_profile():
    req = FakeRequest()
    email = 'tester@example.com'
    MyUser.objects.create_user(
        email=email,
        password="example",
    )
    # query MyUser table and return result
    result = my_action.get_profile(email)
    assert result == 'success'

但它失败了。

>       assert result == 'success'
E       assert None == 'success'

函数没有从 DB 中得到任何结果。

我检查了数据库数据,没有看到任何记录。 (例如,用户 tester@example.com

如何重写我的测试代码?

或者如何将数据保存在数据库中?

谢谢,

【问题讨论】:

    标签: python pytest pytest-django


    【解决方案1】:

    这就是数据库测试的工作方式.. 当您设置 django_db 时,pytest 将在使用后回滚您的数据。 但是如果你想在多个测试中使用相同的数据,你应该看看 pytest.fixtures 和 factory_boy 之类的:

    import factory
    
    class UserFactory(factory.DjangoModelFactory):
        class Meta:
            model = User
    
    @pytest.fixture
    def user():
      return UserFactory(email = "bla@bla.com", password = "blabla")
    

    现在你将这个引用应用到你的测试代码上:

    test_test_ok_profile(user):
      assert user.email = "bla@bla.com"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-11-12
      • 1970-01-01
      • 2011-06-04
      • 2014-02-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多