我只是运行py.test我的代码并得到以下输出:
================== 6 passed, 2 pytest-warnings in 40.79 seconds =======================
Run Code Online (Sandbox Code Playgroud)
但是,我看不出有什么py.test想提醒我的.如何打开警告输出到控制台?
py.test --help给我--strict一面旗帜:
- 严格模式下运行pytest,警告成为错误.
但是我只是想看看输出,而不是让我的测试失败.
我检查了pytest.org和这个问题,但他们只关心在python中声明警告,而不是在命令行上显示警告.
我正在使用 django 构建我的网站,并使用 django-pytest 来测试我的应用程序,但我收到此错误 注意我正在使用 python 3.9
================================================================== warnings summary
===================================================================
..\venv\lib\site-packages\_pytest\config\__init__.py:1233
c:\users\eng_diaa_shalaby\desktop\unittest\venv\lib\site-packages\_pytest\config\__init__.py:1233: PytestConfigWarning: Unknown config option: DJANGO_
SETTINGS_MODULE
self._warn_or_fail_if_strict(f"Unknown config option: {key}\n")
-- Docs: https://docs.pytest.org/en/stable/warnings.html
Run Code Online (Sandbox Code Playgroud)
这是我的 pytest.ini 文件内容
# -- FILE: pytest.ini (or tox.ini)
[pytest]
DJANGO_SETTINGS_MODULE = testing_settings
# -- recommended but optional:
python_files = tests.py test_*.py *_tests.py
Run Code Online (Sandbox Code Playgroud)
我运行这个命令
pytest
Run Code Online (Sandbox Code Playgroud)
这是我的 venv 包
Package Version
------------- -------
asgiref 3.3.4
atomicwrites 1.4.0
attrs 21.2.0
colorama 0.4.4
coverage 5.5
Django 3.2.4
django-pytest 0.2.0
iniconfig 1.1.1
packaging 20.9
pip 21.1.2
pluggy …Run Code Online (Sandbox Code Playgroud) 在从 shell调用pytest期间,我得到以下输出,因为我的测试存储在apps.business.metrics.tools.tests.py 中,并且在模块导入期间
apps/business/metrics/widgets/employees/utilization.py
在模块调用期间实时调用 SQL。这是由
get_metric_columns('EmployeeUtilization', shapers=SHAPERS)
和 pytest 投诉:
? pytest
=========================================================================== test session starts ===========================================================================
platform linux -- Python 3.6.8, pytest-4.0.0, py-1.7.0, pluggy-0.8.0
Django settings: config.settings.local (from ini file)
rootdir: /home/dmitry/Projects/analytics/backend, inifile: pytest.ini
plugins: django-3.4.7, pylama-7.6.6, django-test-plus-1.1.1, celery-4.2.1
collected 60 items / 1 errors
================================================================================= ERRORS ==================================================================================
__________________________________________________________ ERROR collecting apps/business/metrics/tools.tests.py __________________________________________________________
../../../.pyenv/versions/3.6.8/envs/cam/lib/python3.6/site-packages/py/_path/local.py:668: in pyimport
__import__(modname)
apps/business/metrics/__init__.py:3: in <module>
from .widgets import * # noqa
apps/business/metrics/widgets/__init__.py:1: in <module>
from . import help # …Run Code Online (Sandbox Code Playgroud) 是否可以autouse=True仅使用特定标记来阻止"功能范围"灯具的执行?
我将以下fixture设置为autouse,以便自动模拟所有传出请求:
@pytest.fixture(autouse=True)
def no_requests(monkeypatch):
monkeypatch.setattr("requests.sessions.Session.request", MagicMock())
Run Code Online (Sandbox Code Playgroud)
但我有一个标记叫做endtoend我用来定义一系列测试,允许外部请求进行更强大的端到端测试.我想注入no_requests所有测试(绝大多数),但不是在以下测试中:
@pytest.mark.endtoend
def test_api_returns_ok():
assert make_request().status_code == 200
Run Code Online (Sandbox Code Playgroud)
这可能吗?
我有一个用 pytest 和诗歌管理的 django 项目。
我想将 pytest 配置放入pyproject.toml文件中,所以我添加了:
[tool.pytest]
filterwarnings = ["ignore::django.utils.deprecation.RemovedInDjango40Warning", "ignore::django.utils.deprecation.RemovedInDjango41Warning"]
Run Code Online (Sandbox Code Playgroud)
然而,这没有什么区别——警告没有被过滤。
如果我添加包含以下内容的 pytest.ini 文件...
[pytest]
filterwarnings =
ignore::django.utils.deprecation.RemovedInDjango40Warning
ignore::django.utils.deprecation.RemovedInDjango41Warning
Run Code Online (Sandbox Code Playgroud)
...效果很好。
我的或我的 pytest 配置有什么问题pyproject.toml,它没有被拾取?
我是新来的Django unittest和pytest.但是,我开始觉得pytest测试用例更紧凑,更清晰.
这是我的测试用例:
class OrderEndpointTest(TestCase):
def setUp(self):
user = User.objects.create_superuser(username='admin', password='password', email='pencil@gmail.com')
mommy.make(CarData, _quantity=1)
mommy.make(UserProfile, _quantity=1, user=user)
def test_get_order(self):
mommy.make(Shop, _quantity=1)
mommy.make(Staff, _quantity=1, shop=Shop.objects.first())
mommy.make(Order, _quantity=1, car_info={"color": "Black"}, customer={"name": "Lord Elcolie"},
staff=Staff.objects.first(), shop=Shop.objects.first())
factory = APIRequestFactory()
user = User.objects.get(username='admin')
view = OrderViewSet.as_view({'get': 'list'})
request = factory.get('/api/orders/')
force_authenticate(request, user=user)
response = view(request)
assert 200 == response.status_code
assert 1 == len(response.data.get('results'))
Run Code Online (Sandbox Code Playgroud)
这是pytest版本
def test_get_order(car_data, admin_user, orders):
factory = APIRequestFactory()
user = User.objects.get(username='admin')
view = OrderViewSet.as_view({'get': …Run Code Online (Sandbox Code Playgroud) 对于以下代码:
@pytest.fixture(scope="module")
def dummy_article(request, db):
return mixer.blend("core.article", title="this one price", internal_id=3000)
def test_article_str_method(dummy_article):
assert (
str(dummy_article)
== f"article with ID {dummy_article.internal_id} and title: {dummy_article.title}"
)
Run Code Online (Sandbox Code Playgroud)
我收到以下错误:
ScopeMismatch: You tried to access the 'function' scoped fixture 'db' with a 'module' scoped request object, involved factories
core/tests/test_article_model.py:13: def dummy_article(request, db)
Run Code Online (Sandbox Code Playgroud)
如果我将夹具更改为 use scope="function",错误就会消失,但这违背了将其用于其他测试而不必为每个测试“设置”的目的。
我怎样才能拥有可db访问范围大于 的装置function?
我正在使用django REST框架构建API.
为了测试这个API,我使用pytest和测试客户端,如下所示:
def test_doesnt_find(self, client):
resp = client.post(self.url, data={'name': '123'})
assert resp.status_code == 404
Run Code Online (Sandbox Code Playgroud)
要么
def test_doesnt_find(self, client):
resp = client.get(self.url, data={'name': '123'})
assert resp.status_code == 404
Run Code Online (Sandbox Code Playgroud)
在使用REST框架的常规GET,POST和DELETE类时(例如DestroyAPIView,RetrieveUpdateAPIView或仅APIView使用get和post函数)都可以工作
我遇到问题的地方是使用PATCH和PUT视图.如RetrieveUpdateAPIView.在这里,我突然不得不使用:
resp = client.patch(self.url, data="name=123", content_type='application/x-www-form-urlencoded')
Run Code Online (Sandbox Code Playgroud)
要么
resp = client.patch(self.url, data=json.dumps({'name': '123'}), content_type='application/json')
Run Code Online (Sandbox Code Playgroud)
如果我只是尝试像我习惯的那样使用测试客户端,我会收到错误:
rest_framework.exceptions.UnsupportedMediaType: Unsupported media type "application/octet-stream" in request.
Run Code Online (Sandbox Code Playgroud)
当我在client.patch()调用中指定'application/json'时:
rest_framework.exceptions.ParseError: JSON parse error - Expecting property name enclosed in double quotes: line 1 column 2 (char 1)`
Run Code Online (Sandbox Code Playgroud)
任何人都可以向我解释这种行为吗?特别难以捕捉,因为卷曲只是用得很好-X PATCH …
我开始使用pytest.我已经配置了pytest,无论如何我都找不到使用pytest进行Django特定测试的资源.如何测试模型pytest_django?
我已经问了一个关于单元测试的问题,
我想知道如何使用py.test编写相同的测试?
在模型下面添加以及在unittest中编写的测试.
被测模型是,
class User(AbstractBaseUser, PermissionsMixin):
username = models.CharField(max_length=25, unique=True, error_messages={
'unique': 'The username is taken'
})
first_name = models.CharField(max_length=60, blank=True, null=True)
last_name = models.CharField(max_length=60, blank=True, null=True)
email = models.EmailField(unique=True, db_index=True, error_messages={
'unique': 'This email id is already registered!'
})
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
date_joined = models.DateTimeField(auto_now_add=True)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username',]
objects = UserManager()
def get_full_name(self):
return ' '.join([self.first_name, self.last_name])
def get_short_name(self):
return self.email
def __unicode__(self):
return self.username
Run Code Online (Sandbox Code Playgroud)
和unittest书面的, …
结论:在使用pytest-django测试期间,我的Django连接对象没有看到第二个数据库的表关系.
概述: 我有一个问题,我的Django连接对象似乎得到错误的数据库信息.我偶然发现了这个问题,当我在"客户" DB查询在桌子上,Django的告诉我的关系不存在.使用settings.py数据库部分设置如下:
DATABASES = {
'default': {
'NAME': 'user_data',
'ENGINE': 'django.db.backends.postgres',
'USER': 'postgres_1',
'PASSWORD': 'superS3cret'
},
'customers': {
'NAME': 'customer_data',
'ENGINE': 'django.db.backends.postgres',
'USER': 'postgres_1',
'PASSWORD': 'superS3cret'
}
}
Run Code Online (Sandbox Code Playgroud)
当我在目录上运行'pytest'时,下面的两个游标都从'default'数据库中获取信息:
sql = """SELECT table_name FROM information_schema.tables WHERE table_nameschema='public'"""
default = connections["default"].cursor()
default.execute(sql)
raw_data = default.fetchall()
sql_columns = [col[0] for col in default.description]
df1 = pd.DataFrame(raw_data, columns=sql_columns)
customers = connections["customers"].cursor()
customers.execute(sql)
raw_data = customers.fetchall()
sql_columns = [col[0] for col in customers.description]
df2 = pd.DataFrame(raw_data, columns=sql_columns)
Run Code Online (Sandbox Code Playgroud)
df1和df2的结果完全相同:只有'default'数据库中的表名.
使用pytest-django并使用第二个Postgres数据库会发生这种情况,但有时只会发生. …