"""
@autor:Yue
@date::15:14
@file:execcase.py
@project:autoInterface

"""
import os,unittest
from blueprints.settings import testConfig
from unittest import TestCase,TestSuite
from blueprints.tools.dealScene import dealScene

def wcases(config,scences):
    f=os.path.join(config.projectdir,"blueprints","testcases.py")
    scences=dealScene(config,scences)
    with open(f,"w+",encoding="utf8") as f:
        f.write("import unittest\n")
        f.write("from blueprints.settings import testConfig\n")
        f.write("from blueprints.requestResult import requestResult\n")
        f.write("from blueprints.tools.asertcase import asertcase\n")
        f.write("from blueprints.tools.dealCasefile import readCaseFile\n")
        f.write("class maintest(unittest.TestCase):\n")
        f.write("   def __init__(self, methodName='runTest', config=None):\n")
        f.write("       super(maintest, self).__init__(methodName)\n")
        f.write("       self.config = config\n")



        f.write("   @staticmethod\n")
        f.write("   def parametrize(testcase_klass, config=None):\n")
        f.write("       testloader = unittest.TestLoader()\n")
        f.write("       testnames = testloader.getTestCaseNames(testcase_klass) \n")

        f.write("       suite = unittest.TestSuite()\n")
        f.write("       for name in testnames:\n")
        f.write("           print('name====',name)\n")
        f.write("           suite.addTest(testcase_klass(name, config=config))\n")
        f.write("       return suite\n\n")

        for index,scence in enumerate(scences):

            for project,case in scence.items():
                f.write("class {0}(maintest):\n".format(project+str(index)))
                #print(scence)
                for index,kk in enumerate(case):
                    ###index从100开始算起，不然字符串中2>12，会导致执行顺序出错
                    ak=kk.split(os.sep)[-1].split(".")[0]
                    print("kk=",kk,case,type(case))
                    index+=100
                    f.write("   def test_{0}(self):\n".format(str(index)))
                    f.write("       res1=requestResult(self.config,'{0}')\n".format(kk))

                    f.write("       res,finalresult=res1.requestJson()\n")


                    f.write("       t=readCaseFile('{0}').get('result')\n".format(kk))
                    #f.write("       try:\n")
                    f.write("       r=0 if 0 in finalresult and len(finalresult)>0 else 1\n".format(kk))
                    #f.write("       except:\n")

                    f.write("       if r:\n")
                    f.write("           self.detail=res1.keyoption()+('Success',)\n")
                    f.write("       else:\n")
                    f.write("           if isinstance(res,dict):\n")
                    f.write("               self.detail=res1.keyoption()+(res.__str__(),)\n")
                    f.write("           elif len(res.text)>5000 :\n")
                    f.write("               self.detail=res1.keyoption()+('响应数据过长',)\n")
                    f.write("           else:\n")
                    f.write("               self.detail=res1.keyoption()+(res.text,)\n")
                    f.write("       if r==0:\n")
                    f.write("           msg='断言失败，预期结果：'+str(t)+',实际结果查看响应数据'\n")
                    f.write("           self.assertEqual(1, 0,msg=msg)\n")
                    f.write("       else :\n")
                    f.write("           msg='断言成功，预期结果：'+str(t)+',实际结果查看响应数据'\n")
                    f.write("           self.assertEqual(0, 0,msg=msg)\n")
            f.write("\n")

# suite.addTest(execcase("test_cases"))

def getcases(config,suite,scences):
    from blueprints import testcases
    for index,scence in enumerate(scences):

        for project, case in scence.items():
            #print(project,index)
            #print("testcases.maintest.parametrize(testcases.{0},config=config)".format(project))
            suite.addTest(eval("testcases.maintest.parametrize(testcases.{0},config=config)".format(project+str(index))))

            # for kk in case:
            #     #print("testcases.{0}('test_{1}')".format(project,kk.split(".")[0]))
            #     suite.addTest(eval("testcases.{0}('test_{1}')".format(project,kk.split(".")[0])))





if __name__ == '__main__':
    #tt=[ {"t1": ["2522.json"]}]

    cases_number = [323, 382, 383, 384, 385, 361]
    # cases_number=[323,361]
    t = '.json,'.join([str(i) for i in cases_number]) + ".json"
    casefile = [{'passportapi': ['323.json', '382.json', '383.json', '384.json', '385.json']}, {'payment': ['565.json', '566.json', '607.json', '608.json', '609.json', '610.json', '611.json', '652.json', '688.json']}]
    wcases(testConfig,casefile)
    # suite=TestSuite()
    # getcases(testConfig,suite,casefile)
