import unittest
import time
import json
from funkload.FunkLoadTestCase import FunkLoadTestCase
from func import utiltool


class authTest(FunkLoadTestCase):
    def setUp(self):
        self.url = self.conf_get('main', 'url')

    def test_authQuery(self):
        # init params
        testcase=self.conf_get('test_authQuery','tc_name')
        interface_url = self.url + '/auth/query'
        params_list=utiltool.get_request_params_list("authTest_data.xlsx",testcase)
        self.assertGreater(params_list.__len__(), 0, 'No testcase found!!!')

        for params in params_list:
            appId_value = str(params['appId'])
            nonce_value = utiltool.random_str(8)
            openId_value = str(params['openId'])
            timestamp_value = time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))
            token = str(params['token'])

            # generate signature
            tmp_str = 'appId=' + appId_value + '&nonce=' + nonce_value + '&openId=' + openId_value + '&timestamp=' \
                      + timestamp_value
            signature_value = utiltool.create_signature(token, tmp_str)

            # generate post params
            params = [['appId', appId_value], ['nonce', nonce_value],
                      ['signature', signature_value], ['timestamp', timestamp_value], ['openId', openId_value]]

            # post requet to server and verify the response
            self.post(interface_url, params=params, description='Restful auth.query')
            ret = self.getBody()
            ret_json = json.loads(ret)
            data = ret_json["data"]
            print ret
            self.assert_('"code":"0"' in ret, msg='code expect: 0 actuel: ' + ret_json['code'])
            self.assertEqual(data["token"], token, msg="token expect: " + token + " actuel: " + data["token"])
            self.assertEqual(data["openId"], openId_value,
                             msg="openId expect: " + openId_value + " actuel: " + data["openId"])

    def tearDown(self):
        pass


if __name__ in ('main', '__main__'):
    unittest.main()
