【问题标题】:mocking - request and the response inside django rest fbvmocking - django rest fbv 中的请求和响应
【发布时间】:2017-11-03 05:54:27
【问题描述】:

我有 3 个玩家。
1. 客户端:任何移动设备
2.poink: Django 服务器
3.platform:另一台服务器

机械师是
1.client POST 到poink
2.poinkGETplatform
3.platform回复poink
4.poink回复client

views.py https://gist.github.com/elcolie/111fde80317e96523a34bb297e5ccf25
tests.py https://gist.github.com/elcolie/565b458716dbf5358d2ad7ba1ff2ee6b
output.txt https://gist.github.com/elcolie/9a93d5fc5237b403b4d1d2c8ee3c352e

目标:
我想在这个端点上运行集成测试,但我不想拍摄真正的端点

阅读:
python mock Requests and the response
Python mock, django and requests
mocking functions using python mock
http://engineroom.trackmaven.com/blog/real-life-mocking/

问题:
这不是mock 我的对象。它引发了您可以从output.txt 看到的错误

解决方法:
我不知道这个集成测试的最佳实践是什么。但我做了更多的简化。

  1. 让登录函数成为普通函数
  2. request是在测试环境中创建的
  3. patch函数requests.get

这是确认的代码。感谢 Andrew Backer

def test_mobile_send_wrong_session_key(db):
    from rest_framework.test import APIRequestFactory
    factory = APIRequestFactory()
    url = reverse('auth:login')
    data = {'session_key': 'Wrong value'}
    request = factory.post(url, data)
    from poinkbackend.apps.authentications.views import login
    with patch('requests.get') as mock_get:
        # `Platform` response with 400 to `Poink`
        mock_get.return_value.ok = False
        mock_get.return_value.status_code = 400
        mock_get.return_value.text = 'Bad Request El'
        res = login(request)
    assert 406 == res.status_code

参考:
https://realpython.com/blog/python/testing-third-party-apis-with-mocks/

【问题讨论】:

    标签: python django rest unit-testing


    【解决方案1】:

    您的端点模拟没问题,但是您正在运行的测试试图在数据库中设置一些东西。这提供了两种选择:

    • 要么你也模拟数据库
    • 或者您可以使用django TestCase 生成测试数据库,并在测试结束时将其删除

    【讨论】:

    • 感谢您提及数据库。我使用pytest。那么实际的数据库就不会动了。
    【解决方案2】:

    我不知道这个集成测试的最佳实践是什么。但我做了更多的简化。

    1. 让登录函数成为普通函数
    2. request是在测试环境中创建的
    3. patch函数requests.get

    参考:
    https://realpython.com/blog/python/testing-third-party-apis-with-mocks/

    def test_mobile_send_wrong_session_key(db):
        from rest_framework.test import APIRequestFactory
        factory = APIRequestFactory()
        url = reverse('auth:login')
        data = {'session_key': 'Wrong value'}
        request = factory.post(url, data)
        from poinkbackend.apps.authentications.views import login
        with patch('requests.get') as mock_get:
            # `Platform` response with 400 to `Poink`
            mock_get.return_value.ok = False
            mock_get.return_value.status_code = 400
            mock_get.return_value.text = 'Bad Request El'
            res = login(request)
        assert 406 == res.status_code
    

    【讨论】:

      猜你喜欢
      • 2020-11-09
      • 2011-06-18
      • 2015-12-17
      • 1970-01-01
      • 2016-11-13
      • 2013-02-20
      • 1970-01-01
      • 2016-12-29
      • 1970-01-01
      相关资源
      最近更新 更多