尝试通过python-requests
制作简单的测试管理页面import requests
from django.urls import reverse
def test_admin():
resp = requests.get(reverse('admin:index'))
assert resp.status_code == 200
但出现意外错误
def test_admin():
> resp = requests.get(reverse('admin:index'))
src/users/tests/test_user_admin.py:6:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
venv1/lib/python3.5/site-packages/requests/api.py:72: in get
return request('get', url, params=params, **kwargs)
venv1/lib/python3.5/site-packages/requests/api.py:58: in request
return session.request(method=method, url=url, **kwargs)
venv1/lib/python3.5/site-packages/requests/sessions.py:494: in request
prep = self.prepare_request(req)
venv1/lib/python3.5/site-packages/requests/sessions.py:437: in prepare_request
hooks=merge_hooks(request.hooks, self.hooks),
venv1/lib/python3.5/site-packages/requests/models.py:305: in prepare
self.prepare_url(url, params)
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
> raise MissingSchema(error)
E requests.exceptions.MissingSchema: Invalid URL '/admin/': No schema supplied. Perhaps you meant http:///admin/?
venv1/lib/python3.5/site-packages/requests/models.py:379: MissingSchema
已安装软件包列表
pytest==3.3.2
requests==2.18.4
pytest-django==3.1.2
django==1.10.2
阅读了很多文档和手册但找不到解决方案。
使用不同的pytest.ini
,manage.py
,wsgi.py
和settings.py
进行测试
简单测试assert 200==200
正常运行。
问题在哪里?
答案 0 :(得分:2)
使用request.build_absolute_uri()
:
resp = requests.get(request.build_absolute_uri(reverse('admin:index')))
答案 1 :(得分:0)
正如错误所示,requests
需要一个带架构的URL(http,https,ftp等)。
问题在于reverse
会返回相对路径(例如/admin/index
),但requests
需要包含架构的完整网址(例如http://localhost/admin/index
)。
如果您坚持使用reverse('admin:index')
而不是在测试中对完整网址进行硬编码,则需要在http://localhost:<port>/
之前添加reverse('admin:index')
(或者在您的情况下为正确的主机) }返回。