【问题标题】:MissingSchema error while test Django via Pytest and Requests通过 Pytest 和 Requests 测试 Django 时出现 MissingSchema 错误
【发布时间】:2018-02-07 12:03:59
【问题描述】:

尝试通过 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 进行测试 简单的测试assert 200==200 工作正常。 问题出在哪里?

【问题讨论】:

    标签: python-3.x python-requests pytest pytest-django


    【解决方案1】:

    使用request.build_absolute_uri():

     resp = requests.get(request.build_absolute_uri(reverse('admin:index')))
    

    【讨论】:

      【解决方案2】:

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

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

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

      【讨论】:

        猜你喜欢
        • 2023-03-15
        • 1970-01-01
        • 1970-01-01
        • 2018-10-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-11-30
        • 1970-01-01
        相关资源
        最近更新 更多