嘲笑 - 请求和django中的响应rest fbv

时间:2017-11-03 05:54:28

标签: python django rest unit-testing

我有3名球员 1.客户:任何移动设备
2. poink:Django服务器
3. platform:另一台服务器

机械师是 1. client张贴到poink
2. poink GETplatform
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
  4. 这是确认的代码。感谢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/

2 个答案:

答案 0 :(得分:0)

我不知道这次集成测试的最佳做法是什么。但我对它做了更多的简化。

  1. 让登录功能为普通功能
  2. request在测试环境中创建
  3. patch函数requests.get
  4. <强>参考:
    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
    

答案 1 :(得分:0)

您的端点模拟没问题,但您正在运行的测试是尝试在数据库中设置某些内容。这有两个选择:

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