Get IP Address when testing flask application through nosetests

前端 未结 3 1670
醉话见心
醉话见心 2020-12-31 03:01

My application depends on request.remote_addr which is None when i run tests through nosetests which uses app.test_client().post(\'/users/log

3条回答
  •  佛祖请我去吃肉
    2020-12-31 03:19

    You can also pass a header param to the test_request_context if you prefer.

    Example:

    from flask import Flask, request
    import unittest
    
    app = Flask(__name__)
    app.debug = True
    app.testing = True
    
    @app.route('/')
    def index():
        return str(request.remote_addr)
    
    class TestApp(unittest.TestCase):
    
        def test_headers(self):
            user_agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:52.0) Gecko/20100101 Firefox/52.0"
            ip_address = 127.0.0.1
            headers = {
                'Remote_Addr': ip_address,
                'User_Agent': user_agent
            }
    
            with self.test_request_context(headers=headers):
                # Do something
                pass
    

    This is useful when you need to perform several unit tests using the request object in other modules.

    See the test_request_context documentation.

提交回复
热议问题