标签: pytest-django

django-pytest setup_method数据库问题

我在Ubuntu 14.04上进行了以下设置:

  • python 2.7.6
  • django 1.7 [虽然我也用django 1.9再现了同样的行为]
  • pytest-django 2.8.0 [也用2.9.1测试]
  • pytest 2.7.2 [也用2.8.3测试]

以下测试代码:

import pytest
from django.db import connection

import settings
from pollsapp.models import Question

original_db_name = settings.DATABASES["default"]["NAME"]

@pytest.mark.django_db
class TestExperiment(object):

    def setup_method(self, method):
        # it's not using the "test_" + DATABASE_NAME !
        assert connection.settings_dict["NAME"] == \ 
        settings.DATABASES["default"]["NAME"]
        Question.objects.create(question_text="How are you?")
        # this data remains in the main database
Run Code Online (Sandbox Code Playgroud)
  1. 虽然该类被标记为使用django数据库,但构造函数中创建的数据到达主(生产)数据库(名称取自settings.py)

  2. django_db装饰器放在上面setup_method并没有任何区别

  3. 在setup_method创建该数据保留在主数据库,不回滚如果数据创建调用是在做他们应该和他们是test_case方法

  4. 当测试单独运行时会发生此行为.在测试套件中运行时,setup_method db调用失败,并显示:Failed:不允许数据库访问,使用django_db标记启用虽然装饰器显然在那里(这意味着此错误消息不是100%可信的btw).

pytest是一个很棒的框架,如果数据库调用是从django_db标记的测试用例方法发生的,那么django-pytest很有用.

它看起来像没有数据库交互应该永远存在于特殊的pytest方法,如setup_method, …

python django unit-testing pytest pytest-django

6
推荐指数
1
解决办法
2846
查看次数

Pytest 和 Django 设置运行时更改

我有一个接收器需要知道是否DEBUG设置为Truesettings.py

from django.conf import settings
...
@receiver(post_save, sender=User)
def create_fake_firebaseUID(sender, instance, created=False, **kwargs):
    # Fake firebaseUID if in DEBUG mode for development purposes
    if created and settings.DEBUG:
        try:
            instance.userprofile
        except ObjectDoesNotExist:
            UserProfile.objects.create(user=instance, firebaseUID=str(uuid.uuid4()))
Run Code Online (Sandbox Code Playgroud)

问题是,当我使用manage.py shell一切正常创建用户时。但是,如果我运行通过我的测试中py.test,价值settings.DEBUG的变化False。如果我签conftest.pypytest_configureDEBUG则设置为True。它稍后在某个地方发生变化,我不知道在哪里。

什么会导致这种情况?我确信我不会在代码中的任何地方更改它。

编辑。

conftest.py

import uuid

import pytest
import tempfile
from django.conf import settings
from django.contrib.auth.models import User


@pytest.fixture(scope='session', autouse=True)
def set_media_temp_folder():
    with tempfile.TemporaryDirectory() …
Run Code Online (Sandbox Code Playgroud)

python django pytest pytest-django

6
推荐指数
2
解决办法
3701
查看次数

如何使用带数据的数据库在django中运行测试?

我想使用postgres localhost数据库中的数据(已经加载的数据)测试我的视图.我正在使用pyx和pytest-django.

我的问题:如何设置/连接到本地数据库以获取所有数据模型架构和数据本身?或者也许最好使用factory_boy?或者从.sql脚本加载整个数据(如果是,如何)?

我的测试示例:

def test_foo_view(custom_client_login):
    response = custom_client_login.get('/foo/bar/123/')

    assert response.status_code == 200
    assert 'Transaction no. 123' in response.content
Run Code Online (Sandbox Code Playgroud)

但是不是获取状态代码200,而是获得404,这表明测试数据库中没有数据.但是当我午餐runserver并进入该视图时,('localhost:8000/foo/bar/123/')我将获得状态200和html网页以及一些数据.

请帮忙!


我正在使用:

  • Django的== 1.7.11
  • pytest == 3.0.6
  • pytest-Django的== 3.1.2
  • TOX == 2.6.0

python django postgresql pytest pytest-django

6
推荐指数
1
解决办法
1038
查看次数

如何断言django在pytest中使用某些模板

unittest样式中,我可以通过调用来测试页面是否使用特定模板assertTemplateUsed.这很有用,例如,当Django通过模板插入值时,我不能只测试字符串相等性.

我应该如何在pytest中编写等效语句?

我一直在寻找pytest-django,但不知道该怎么做.

python django pytest pytest-django

6
推荐指数
2
解决办法
1082
查看次数

尝试运行pytest-django时显示“应用尚未加载”

Django教程中的(部分)民意调查应用为例,我试图让pytest-django运行。

使用命令django-admin startproject mysite2,我创建了一个具有以下结构的项目目录:

.
??? db.sqlite3
??? manage.py
??? mysite2
?   ??? __init__.py
?   ??? settings.py
?   ??? urls.py
?   ??? wsgi.py
??? polls
?   ??? __init__.py
?   ??? admin.py
?   ??? apps.py
?   ??? migrations
?   ?   ??? 0001_initial.py
?   ?   ??? __init__.py
?   ??? models.py
?   ??? tests.py
?   ??? urls.py
?   ??? views.py
??? pytest.ini
Run Code Online (Sandbox Code Playgroud)

我的pytest.ini样子

[pytest]
DJANGO_SETTINGS_MODULE = mysite2.settings
python_files = tests.py test_*.py *_tests.py
Run Code Online (Sandbox Code Playgroud)

按照该教程,polls/models.py我已经创建 …

python django pytest pytest-django

6
推荐指数
3
解决办法
4013
查看次数

强制Django测试将模型写入数据库

我正在建立一个非常简单的Django项目,并且测试非常简单:

def test_name(self):
    t = Thing.objects.create(name='a')
    print(t.id)
    import time
    time.sleep(30)
    self.assertEqual('a', t.name)
Run Code Online (Sandbox Code Playgroud)

当然测试通过,但是数据库(TEST数据库)没有填充我的Thing模型信息,即使我可以看到它,id因为你可以看到我的脚本.

当我连接到数据库时,Thing表总是空的(我在文档中也看到了一些关于它的评论).

现在,我如何告诉Django实际填充数据?我正在使用mysql,并检查完整的日志,我看到Django正在创建一个SAVEPOINT填充前的数据(未提交),一旦测试通过,它就会回到之前的状态SAVEPOINT.

我在用:

Django==2.0.1
mysqlclient==1.3.12
pytest==3.3.2
pytest-django==3.1.2
Run Code Online (Sandbox Code Playgroud)

我希望Django实际填充TEST数据库,使用我的测试中的信息,最后删除该数据库,这就是为什么我假设Django正在为测试创建一个全新的数据库.

python mysql django pytest pytest-django

6
推荐指数
1
解决办法
440
查看次数

即使有标记,pytest-django 也不允许访问数据库

我很难弄清楚我的设置有什么问题。我正在尝试测试登录视图,无论我尝试什么,我都会收到:

Database access not allowed, use the "django_db" mark, or the "db" or "transactional_db" fixtures to enable it.

我的测试:

import pytest

from ..models import User


@pytest.mark.django_db
def test_login(client):
    # If an anonymous user accesses the login page:
    response = client.get('/users/login/')
    # Then the server should respond with a successful status code:
    assert response.status_code == 200

    # Given an existing user:
    user = User.objects.get(username='user')
    # If we attempt to log into the login page:
    response = client.post('/users/login/', {'username': user.username, 'password': 'somepass'}) …
Run Code Online (Sandbox Code Playgroud)

django pytest pytest-django

6
推荐指数
2
解决办法
3881
查看次数

Pytest:查找每个测试的开始和结束时间

我有一个复杂的 Django-Pytest 测试套件,其中有许多在并行进程中运行的测试。我想查看每个测试开始和结束的确切时间点。我怎样才能从 Pytest 中获取这些信息?

python testing pytest pytest-django

6
推荐指数
1
解决办法
352
查看次数

如何从 python manage.py test 调用 pytest-django?

我已经制作了名为 pytest_wrp 的自定义管理命令

所以当我打电话时

python manage.py test
Run Code Online (Sandbox Code Playgroud)

这段代码称为:

class Command(test.Command):

    def handle(self, *args, **options):
        super(Command, self).handle(*args, **options) # this calls the python manage.py test
        self.stdout.write("My code starts from here.")
        management.call_command(pytest_wrp.Command(), '--pact-files="{argument}"'.format(argument=path_to_file), '--pact-provider-name="MyService"', verbosity=0)

Run Code Online (Sandbox Code Playgroud)

基本上pytest_wrp有这样的代码:

class Command(BaseCommand):
    help = "Runs tests with Pytest"

    def add_arguments(self, parser):
        parser.add_argument("args", nargs=argparse.REMAINDER)

    def handle(self, *args, **options):
        pytest.main(list(args)) # This doesn't accept the pact args, even if you specify a "--" separator

Run Code Online (Sandbox Code Playgroud)

但这pytest并不pytest-django 意味着我传递的额外参数不会被识别,并且 pytest 无法启动测试套件。

我想传递一些测试用例的额外参数。如果有某种方法可以直接调用 pytest-django 并在代码中传递额外的参数,那将是最佳的。

django django-admin pytest pytest-django django-management-command

6
推荐指数
1
解决办法
2226
查看次数

如何使用 pytest-django 在每个会话中仅创建一次用户对象?

首先,我厌倦了这个:

\n
@pytest.mark.django_db\n@pytest.fixture(scope='session')\ndef created_user(django_db_blocker):\n    with django_db_blocker.unblock():\n        return CustomUser.objects.create_user("User", "UserPassword")\n\ndef test_api_create(created_user):\n    user = created_user()\n    assert user is not None\n
Run Code Online (Sandbox Code Playgroud)\n

但我得到了一个UndefinedTable错误。因此,以某种方式标记我的装置并@pytest.mark.django_db没有\xe2\x80\x99t 实际上注册了我的 Django DB。接下来我尝试将 db 对象直接传递给固定装置:

\n
@pytest.fixture(scope='session')\ndef created_user(db, django_db_blocker):\n    with django_db_blocker.unblock():\n        return CustomUser.objects.create_user("User", "UserPassword")\n\ndef test_api_create(created_user):\n    user = created_user()\n    assert user is not None\n
Run Code Online (Sandbox Code Playgroud)\n

但后来我得到了一个错误

\n
ScopeMismatch: You tried to access the 'function' scoped fixture 'db' with a 'session' scoped request object, involved factories\n
Run Code Online (Sandbox Code Playgroud)\n

最后,为了确认一切正常,我尝试了:

\n
@pytest.fixture\ndef created_user(db, django_db_blocker):\n    with django_db_blocker.unblock():\n        return CustomUser.objects.create_user("User", "UserPassword")\n\ndef test_api_create(created_user):\n …
Run Code Online (Sandbox Code Playgroud)

python fixtures pytest django-fixtures pytest-django

6
推荐指数
1
解决办法
1626
查看次数