Question

I have a REST API made with Flask that I want to accept POST requests, but only those made from the same machine as is running the API itself.

I attempted to write a test to this effect. After browsing Flask and Werkzeug docs for a bit, this is what I came up with:

def test_external_post_fails(self):

    my_data = {
        ...
    }

    result = self.client.post('/my_uri', 
                    data=my_data
                    environ_overrides={'remote_addr': '127.0.0.2'})
    assert result.status_code == 401

However, after writing some corresponding code in my Flask view function, I don't think I am achieving what I hoped with the test. Here's that code:

if request.environ.get('REMOTE_ADDR', '127.0.0.1') != '127.0.0.1':
    abort(401)
post_data = request.form
DPC.store(post_data)
return jsonify(post_data), 201

When I run my test, it gets the normal 201 Created response. So I don't think I am testing for this in the right way. In short, I need to modify the request environment. What I tried to do, using the environ_overrides keyword argument, was really just a guess I made after browsing the API for Flask's client.

Does anyone know the canonical way to do this? Thanks in advance.

Était-ce utile?

La solution

As discovered in comments above, the environ_overrides dictionary is case-sensitive. remote_addr needs to be capitalized, like so:

environ_overrides={'REMOTE_ADDR': '127.0.0.2'})
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top