2

尝试通过 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.inimanage.pywsgi.pysettings.py Simple 测试进行测试assert 200==200可以正常工作。问题出在哪里?

4

2 回答 2

2

使用request.build_absolute_uri()

 resp = requests.get(request.build_absolute_uri(reverse('admin:index')))
于 2018-02-07T19:34:26.427 回答
0

正如错误所暗示的,requests需要一个带有架构(http、https、ftp 等)的 url。

问题是它reverse返回一个相对路径(例如/admin/index),但requests需要一个包含架构(例如http://localhost/admin/index)的完整 url。

如果您坚持在reverse('admin:index')测试中使用而不是硬编码完整的 url,则需要在返回http://localhost:<port>/的任何内容之前添加(或在您的情况下是正确的主机)reverse('admin:index')

于 2018-02-07T12:08:04.080 回答