skipif中condition字段无法获取到变量的解决办法

目的

1.需要将A.py中接口返回的某字段作为下一个B.py中是否跳过用例的判断

 

步骤

1.先将A.py中的接口返回的值存储到Map中

2.在B.py中利用map读取出变量

 

首先,先在util下创建GlobalMap.py

import json,logging


class GlobalMap:
    map = {}

    def set_map(self, key, value):
        if(isinstance(value,dict)):
            value = json.dumps(value)
        self.map[key] = value

    def set(self, **keys):
        try:
            for key_, value_ in keys.items():
                self.map[key_] = str(value_)
                logging.debug(key_+":"+str(value_))
        except BaseException as msg:
            logging.error(msg)
            raise msg

    def del_map(self, key):
        try:
            del self.map[key]
            return self.map
        except KeyError:
            logging.error("key:'" + str(key) + "'  不存在")

    def get(self, *args):
        try:
            dic = {}
            for key in args:
                if len(args)==1:
                    dic = self.map[key]
                    logging.debug(key+":"+str(dic))
                elif len(args)==1 and args[0]=='all':
                    dic = self.map
                else:
                    dic[key]=self.map[key]
            return dic
        except KeyError:
            logging.warning("key:'" + str(key) + "'  不存在")
            return 'Null_'

然后a.py中将返回的值存储到map

"""
@File: test_01_KeywordRetrieval.py
@Desc: 
@Time: 2020/11/9 10:54
@Author: Mo shaodong
"""
import json
import sys
import unittest
import datetime
from utils import GlobalMap
from utils.log import log_info, log_error
from utils.HttpRequest import req_post_json

class KeywordRetrieval(unittest.TestCase): def setUp(self): # 获取当前时间并开始记录info日志 self.log_time = datetime.datetime.now().strftime('%Y-%m-%d %H_%M_%S') log_info.info('begin') # 准备请求报文 self.header = {'Content-Type': 'application/json'} self.url = req_url def test_01_getRequestSuccess(self): """验证:XXX接口返回成功,且数据正常""" self.map_data = GlobalMap() body = {} res = req_post_json(self.url, header=self.header, body=json.dumps(body)) try:if res[0]['code'] == 0: # 存储id,供其他接口使用 self.map_data.set_map(key='samsungscreen_articleId', value=res[0]['data']['cards'][0]['articleId']) log_info.info("[{}] success".format(sys._getframe().f_code.co_name)) except AssertionError as e: log_info.error("[{}] error {}".format(sys._getframe().f_code.co_name, e)) log_error.error("[{}] error {}".format(sys._getframe().f_code.co_name, e)) def tearDown(self): log_info.info("end") if __name__ == '__main__': # 执行所有用例 unittest.main()

最后在B.py中引用参数

"""
@File: test_02_getNewdetail.py
@Desc: 
@Time: 2020/11/9 15:25
@Author: Mo shaodong
"""
import sys
import unittest
import datetime
import pytest
from utils import GlobalMap
from utils.log import log_info, log_error
from utils.HttpRequest import req_get

class GetNewDetail(unittest.TestCase): def setUp(self): # 获取当前时间并开始记录info日志 self.log_time = datetime.datetime.now().strftime('%Y-%m-%d %H_%M_%S') log_info.info('begin') # 准备请求报文 self.header = {'Content-Type': 'application/json'} self.map_data = GlobalMap() print(self.map_data.get('samsungscreen_articleId')) @pytest.mark.skipIf(condition='GlobalMap().get(\'samsungscreen_articleId\') == "Null_"', reason='未获取到ID则跳过此用例') # @unittest.skipIf(condition='GlobalMap().get(\'samsungscreen_articleId\') == "Null_"', reason='未获取到ID则跳过此用例') def test_01_getRequestSuccess(self): """验证:XXX接口返回成功,且数据正常""" url = req_url+"article/detail/{}/webCard".format(self.map_data.get('samsungscreen_articleId')) # url = req_url + "article/detail/e38fc269c695409f/webCard" res = req_get(url) try: self.assertEqual(res[2], 200, '状态码返回错误:' + str(res[2])) log_info.info("[{}] success".format(sys._getframe().f_code.co_name)) except AssertionError as e: log_info.error("[{}] error {}".format(sys._getframe().f_code.co_name, e)) log_error.error("[{}] error {}".format(sys._getframe().f_code.co_name, e)) def tearDown(self): log_info.info("end") if __name__ == '__main__': # 执行所有用例 unittest.main()

 

备注:

测试过程中发现,unittest.skipIf无法获取到参数,换成了pytest.mark.skipIf就可以了,原因暂时还不知道~

posted @ 2020-11-11 11:02  亿逍遥  阅读(201)  评论(0编辑  收藏  举报