尝试使用json文件将数据作为参数传递时出现键错误

时间:2017-12-05 15:41:09

标签: python json file io

代码如下 进口时间 进口单位测试 将日志记录导入日志 来自loggenerator import set_log_params,move_latest_log_to_persistent_file 从parse_test_json导入get_test_params 从报废导入SC

    class ScrapeTest(unittest.TestCase):
        def setup(self):
            self.start_time=time.time()
        def teardown(self):
            self.end_time=time.time()
        def test_SC_scrape(self):
            try:
                test_name="test scrape"
                set_log_params(log_file=test_name,level=log.INFO)
                log.info("step1:set all test params")
                test_params = get_test_params(self.__class__.__name__, test_name=test_name)
                log.info("step 2:set")
                ik=SC()
                log.info("step3:calling scrapper for")
                log.debug(ik.parseURL(party_name=test_params["party_name"],start_date=test_params["start_date"],end_date=test_params["end_date"]))

            except Exception as e:
                raise e
            move_latest_log_to_persistent_file(log_file=test_name)

####

    import json, os
    from builtins import *
    def get_test_params(test_class_name = None, test_name = None):
        dir_path = os.path.dirname(os.path.realpath(__file__))
        file_path = "/test_param_jsons/" + test_class_name + "params.json"
        json_file = dir_path + file_path
        with open(json_file) as test_data:
            test_json = json.load(test_data)
            return test_json[test_class_name][test_name]

此函数引发错误key error

1 个答案:

答案 0 :(得分:0)

只要您在<SCRIPT_PATH>/test_param_jsons/MyClass_params.json

处有一个json文件,这就可以正常工作

另外,为了避免KeyError,您需要确保输入的json文件包含key:value,test_class_name : test_name

import json, os
from builtins import *

class MyClass:
        def get_test_params (self, test_class_name = None, test_name = None):
              with open(os.path.join(os.path.dirname(__file__),"test_param_jsons\\params.json"), 'r') as test_data:
                        test_json = json.load (test_data)
                        try:
                                return test_json[test_class_name][test_name]
                        except KeyError as e:
                                print ('KeyError: {}'.format (e))


        def mymain(self, test_name):
                ''' mymain is defined to accomodate your requirement to use __class__ as a parameter '''
                test_params = self.get_test_params (self.__class__.__name__, test_name = test_name)
                return test_params


if __name__ == '__main__':
        test_name = 'sth' 
        myclass = MyClass ()
        result = myclass.mymain (test_name)
        print (result)