【问题标题】:How can I fake request.POST and GET params for unit testing in Flask?如何在 Flask 中伪造 request.POST 和 GET 参数以进行单元测试?
【发布时间】:2011-11-17 16:37:20
【问题描述】:

我想伪造请求参数以进行单元测试。如何在 Flask 中实现这一点?

【问题讨论】:

    标签: python unit-testing flask


    【解决方案1】:

    如果您更喜欢使用test_request_context

    import unittest
    from myapp import extract_query_params
    
    testapp = flask.Flask(__name__)
    
    class TestFoo(unittest.TestCase):
        def test_happy(self):
            with testapp.test_request_context('?limit=1&offset=2'):
                limit, offset = extract_query_params(['limit', 'offset'])
                self.assertEquals(limit, 1)
                self.assertEquals(offset, 2)
    

    【讨论】:

    • with testapp.test_request_context(headers=h): 可用于传递 headers 而无需提及任何 url,这将使用 default-url 模拟请求我>
    【解决方案2】:

    我需要一个简单的单元测试请求,这是一个简单的解决方案:

    from flask import Request
    r = Request({})
    

    【讨论】:

      【解决方案3】:

      你读过Flask docs about testing吗?

      您可以使用以下内容:

      self.app.post('/path-to-request', data=dict(var1='data1', var2='data2', ...))
      self.app.get('/path-to-request', query_string=dict(arg1='data1', arg2='data2', ...))
      

      Flask 的当前开发版本还包括对testing JSON APIs 的支持:

      from flask import request, jsonify
      
      @app.route('/jsonapi')
      def auth():
          json_data = request.get_json()
          attribute = json_data['attr']
          return jsonify(resp=generate_response(attribute))
      
      with app.test_client() as c:
          rv = c.post('/jsonapi', json={
              'attr': 'value', 'other': 'data'
          })
          json_data = rv.get_json()
          assert generate_response(email, json_data['resp'])
      

      【讨论】:

      • 所以,.get 只是希望您在查询末尾添加参数,就像这样 -- ?param1=value&param2=value2 -- 或者它也可以接收字典?
      • 我都试过了,只有第一个选项有效。为什么要问?
      • @ssilver 你可以使用 dict 但它不像 .post 那样被称为数据:self.app.get('/endpoint', query_string=params)
      • 感谢@jskulski 的建设性回答——它也帮助了我。尝试一些东西会告诉你什么是行不通的,但它不会告诉你是否有不同的方法行得通。
      • 如何将 json 作为输入传递?
      【解决方案4】:

      这是一个完整的单元测试代码示例

      testapp = app.test_client()
      
      class Test_test(unittest.TestCase):
          def test_user_registration_bad_password_short(self):
              response = self.register(name='pat',
                                       email='me@mail.com', 
                                       password='Flask', 
                                       password2='Flask')
              self.assertEqual(response.status_code, 200)
              self.assertIn(b'password should be 8 or more characters long', 
                            response.data)
      
          def register(self, name, email, password, password2):
              return testapp.post(
                  '/register',
                  data=dict(username=name, 
                            email=email, 
                            password=password, 
                            password2=password2),
                  follow_redirects=True
              )
      

      【讨论】:

        【解决方案5】:

        在测试用于登录的帖子表单数据时,我仍然遇到此问题。

        def login(self, username, password):
            return self.app.post('/', data='Client_id=' + username +'&Password=' + password,
                                 follow_redirects=True,content_type='application/x-www-form-urlencoded')
        

        我发现这是这样的。

        铬: 开发者模式 --> 文档 --> 请求的 HTML 文档 --> 标题选项卡 --> 表单数据 --> 查看源代码

        【讨论】:

        • py3 中的 urllib.urlencode(form_data_dict)urllib.parse.encode 对于从字典中创建 data 很有用。
        【解决方案6】:

        发布:

        self.app.post('/endpoint', data=params)
        

        获取:

        self.app.get('/endpoint', query_string=params)
        

        【讨论】:

        • self._add_file_from_data(key, value) 文件“/usr/local/lib/python3.5/dist-packages/werkzeug/test.py”,第 355 行,在 _add_file_from_data self.files.add_file (key, **value) TypeError: add_file() got an unexpected keyword argument 'birthDate'
        猜你喜欢
        • 1970-01-01
        • 2021-09-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-07-23
        • 2011-12-20
        相关资源
        最近更新 更多