Python Flask unittest can't set headers for GET requests

4.1k views Asked by At

I am trying to set a Token in my header request for unit test:

def setUp(self):
    #app = Flask(__name__)
    self.app = main.application.test_client()

def login(self):
    payload = {"user": "*******", "password": "******"}
    url ='/user/auth'
    headers = {'Content-Type': 'application/json'}
    response = self.app.post(url, data=json.dumps(payload), headers=headers) 
    result = json.loads(response.data)
    token = str(result["data"]["Token"])
    headers={'Content-Type': 'application/json','Token':token}
    return headers


def GetTool(self):
    headers= self.login()
    return self.app.get('/tool/all',headers=headers,follow_redirects=True)

But the headers are not set. I know that because I am printing it. See below:

@toolAPI.route('/tool/all/', methods=['GET'])
#@authService.authorized
def getAllTools():
   print '*request headers'
   print request.headers
   try:
      ......

This is what I get in the logs:

8:27:07 [MainThread  ] [INFO ]  ######HTTP MODE######
18:27:07 [MainThread  ] [INFO ]  *request headers
18:27:07 [MainThread  ] [INFO ]  Host: localhost
18:27:07 [MainThread  ] [INFO ]  Content-Length: 0
18:27:07 [MainThread  ] [INFO ]  Content-Type

Any suggestions what the issue is?

2

There are 2 answers

0
kenneho On

I found that I could set HTTP headers like this:

 client.environ_base['HTTP_ACCEPT'] = 'application/xml'
 response = client.get("/", follow_redirects=True)

The client seems to strip the "HTTP_" prefix before executing the request.

0
karlcow On

In your test file.

class TestYourthing(unittest.TestCase):
    def setUp(self):
        self.client = main.app.test_client()
        # get your token from somewhere
        self.headers = {'Content-Type': 'application/json', 'Token': token}

    def test_forbidden_get(self):
        """GET is forbidden for this route."""
        rv = self.client.get('/somewhere', headers=self.headers)
        self.assertEqual(rv.status_code, 404)

    # if you need to update locally the headers for a test

    def test_post_working(self):
        """testing POST for blah"""
        # Adding another header here
        self.headers.update({'X-Blah': 'ping'})
        rv = self.client.post('/somewhere', headers=self.headers)
        self.assertEqual(rv.status_code, 200)