unittest批量组织依赖用例(组织依赖用例,结果前端展示,测试报告发送 )

在上一篇unittest批量组织依赖用例(一)我们讲了在拿到依赖case的情况下如何批量生成测试方法,那么如何组织依赖case呢,我们今天来试试~本次以Excel为例,做一个简单的依赖case读取与执行~实现代码与业务逻辑解耦(这篇只介绍如何设计,具体设计可以自行根据需求变化~)

  • 第一步,搭建几个依赖接口,流程如下:
  • 那么我们这次脚本的流程图设计如下~
  • 上次用flask,那我们这次还是用django写几个简单依赖接口吧~ views中伪代码如下(路由省略):
    def test_api_01(request):
        global A
        if request.method =='POST':
            username = request.POST['username']
            password = request.POST['password']
            if username=='root' and password=='123456':
                A=random.randint(111111,999999)
                resp = {
                    'number': A,
                }
                return HttpResponse(json.dumps(resp), status=520, content_type="application/json")
            else:
                resp = {
                    'status':'error',
                }
                return HttpResponse(json.dumps(resp), status=520, content_type="application/json")
        else:
            return  render(request,"api1.html")
    
    def test_api_02(request):
        global A
        if request.method == 'POST':
            username = request.POST['username']
            password = request.POST['password']
            number = request.POST['number']
            number2 =  request.POST['number2']
            if username == 'root' and password == '123456' and int(number)==int(A) and number2=="ASDYUASIDKLASD":
               resp = {
                        'code': '200',
                        'message': 'success',
                      }
               return HttpResponse(json.dumps(resp),status=520, content_type="application/json")
            else:
                resp = {
                    'code': '100',
                    'message': 'fail',
                }
                return HttpResponse(json.dumps(resp), status=444, content_type="application/json")
    
        else:
            return render(request, "api2.html")
    
    
    def test_api_03(request):
        global A
        if request.method == 'POST':
            username = request.POST['username']
            password = request.POST['password']
            if username == 'root' and password == '123456':
               resp = {
                        'code': '200',
                        'orderid': '78562564DASDJSK655656',
                      }
               return HttpResponse(json.dumps(resp),status=520, content_type="application/json")
            else:
                resp = {
                    'code': '100',
                    'message': 'fail',
                }
                return HttpResponse(json.dumps(resp), status=444, content_type="application/json")
    
        else:
            return render(request, "api2.html")
    
    def test_api_04(request):
        global A
        if request.method == 'POST':
            username = request.POST['username']
            password = request.POST['password']
            if username == 'root' and password == '123456':
               resp = {
                        'code': '200',
                        'number2': 'ASDYUASIDKLASD',
                      }
               return HttpResponse(json.dumps(resp),status=520, content_type="application/json")
    

     

  •  接下来我们新建一个excel,我们这次只看关于body中的依赖,其他字段设计暂时忽略。api_sum_list 为汇总表记录所有api,而api对应的具体测试用例分别在各自的sheet,url列可以自行填写不同环境的baseURL,当然也可以在配置文件中进行配置~
  • 咋们再来看看具体API中依赖表的设计(可点击查看大图),依赖数据存于dependenceCase 这一列,多个依赖为了方便看起来不费劲,我用‘===’当做分割符~ 而data中的占位符用%s表示~ 如果请求中有%怎么办呢~可以用%%来代替~这一列中的sheet:代表依赖case所在的sheet ,case 代表所在sheet中的位置,dependence 代表需要保存依赖case中的返回值~
  • 哈哈那么如何组织case的运行顺序呢,从流程图上不难看出 A依赖B,B依赖C,C依赖D 那么则他们的运行顺序则为 D=>C=>B=>A,也就是入栈的方式,先进后出~那么如何获得到最后一层依赖数据呢~那就要去递归啦~伪代码如下:
     if api_data['dependenceCase']:
                    if '===' in api_data['dependenceCase']: #多平行依赖
                        for i  in  (api_data['dependenceCase']).split('==='):
                            dependenceCase = exchange(i)
                            if run == 'y':
                                depencedata(dependenceCase)
                    else:
                        dependenceCase = exchange(api_data['dependenceCase'])
                        depencedata(dependenceCase)

    其中exchange 方法用来生成依赖字典,传入depencedata,更方便的是从chrome抓如的请求经常为 XX:XX  使用此方法可以转化成字典,自动使用formdata进行请求~

    def exchange(data):
        data_star = data.replace(':',' ').split()
        data = {data_star[x]: data_star[x + 1] for x in range(len(data_star) - 1) if x % 2 == 0}
        return data
  • 重点来了,递归函数如下~也就是传入依赖sheet ,case,dependence,将会递归到最后一层,然后依次请求。
    def depencedata(dependenceCase):# 依赖case 的递归提取传入的case
        if dependenceCase:
            depen_st = TestCases().api_detail(data_sum_list=None,
                                            assign=dependenceCase["sheet"],
                                            case=dependenceCase["case"])  # 取到Case 后继续取的依赖用例
            depen = depen_st[0]
            url_new = depen['url']
            header_new  = exchange(depen['header'])
            data_mode =depen['data_mode']
            if 'json' in data_mode:
                if not isinstance(depen['data'], str):
                    data_new = str(depen['data'])
                else:
                    data_new = str(depen['data'])
            else:
                data_new = exchange(depen['data'])  # 转化成字典 默认formdata
            dependence_new = depen['dependence']
            method = depen['method']
            dependencecase = exchange(depen['dependenceCase'])
            if  dependencecase:
                depencedata(dependencecase)
            if  dependence_new:
                data_end = eval(str(data_new) % (getattr(dependenceClass,dependence_new)))
            if  method == 'post':
                req = requests.post(url=url_new, data=data_end, headers=header_new, verify=False)
                depen_name = dependenceCase['dependence']
                if isinstance(req.text,str):
                    json_data = eval(req.text) #依赖dict
                depen_data = json_ex(param=depen_name, json_c=json_data)   #提取依赖
                setattr(dependenceClass,str(depen_name),depen_data)
            if method == 'get':
                req = requests.get(url=url_new, data=data_end, headers=header_new, verify=False)
                depen_name = dependenceCase['dependence']
                if isinstance(req.text,str):
                    json_data = eval(req.text)
                depen_data = json_ex(param=depen_name, json_c=json_data)   #提取依赖
                setattr(dependenceClass, str(depen_name), depen_data)

     

  • 其中 json_ex 这个方法,可以快去提取需要的key对应的value,如果json数据量大不需要再[][][]一层一层的去写啦~(使用yield 记住所在递归位置)
    def json_recursion(dic,rec=[]):
        if isinstance(dic, dict):
            for k,v in dic.items():
                if isinstance(v,dict):
                    for d in json_recursion(v, rec + [k]):
                        yield d
                elif isinstance(v,list):
                    for i in v:
                        for d in json_recursion(i, rec + [k]):
                            yield d
                else:
                    yield rec+[k,v] #output
        else:
            yield dic
    
    def json_ex(param,json_c,back=True):
        """
        :param param: 提取key值
        :param json_c: 提取json
        :param back:  是否return 第一次匹配值
        :return:
        """
        applist=[]
        for i in json_recursion(dic=json_c):
            # print(i)
            if param in str(i):
                applist.append(['.'.join(i[0:-1]),i[-1]])
        if len(applist)==1:
            return applist[0][1]
        elif len(applist)>1 and  back :
            return  applist[0][1]
        else:
            return applist

     

  • 这样大概的框架已经形成啦,再把咋们上次写的装饰器用上稍作补充~得到run_all文件,为啥这么写?哈哈哈 其实这么写很麻烦~但是我觉得看着很好看哈哈~
    @runTime
    @deco_setarrt
    @run(title="Api Test",description="API TEST RESULTS", tester="Ayo")
    def run():
        Log.info('======>测试已完成')

     

  • run一下瞧瞧~哈哈我们依赖的case 全在我们主case 运行之前全部跑完~
  • 我们再多run 几个case~并结合前端页面进行结果审查~(本次暂不详细介绍如何结合vue+element UI)
  • 最后看看咋们运行邮件报告~ 嘻嘻这样一个完整的 用例脚本就这么设计好啦~可以根据自己项目进行diy,主要思想就是递归取依赖~
26,526 次浏览

“unittest批量组织依赖用例(组织依赖用例,结果前端展示,测试报告发送 )”的1,975个回复

  1. Hello there! I simply want to give you a
    huge thumbs up for the excellent information you’ve
    got here on this post. I will be returning to your site for more soon.

  2. Everything said was actually very reasonable. But, what about this? what if you were to write a killer headline? I ain’t saying your information isn’t solid, but what if you added something that grabbed folk’s attention? I mean BLOG_TITLE is a little vanilla. You could peek at Yahoo’s home page and see how they create post headlines to grab viewers to click. You might add a video or a related picture or two to grab readers interested about everything’ve written. In my opinion, it would make your posts a little livelier.|

  3. Revolutional update of captcha regignizing software “XRumer 19.0 + XEvil”:
    captcha regignizing of Google (ReCaptcha-2 and ReCaptcha-3), Facebook, BitFinex, Bing, Hotmail, SolveMedia, Yandex,
    and more than 12000 another subtypes of captchas,
    with highest precision (80..100%) and highest speed (100 img per second).
    You can use XEvil 4.0 with any most popular SEO/SMM programms: iMacros, XRumer, GSA SER, ZennoPoster, Srapebox, Senuke, and more than 100 of other software.

    Interested? There are a lot of introducing videos about XEvil in YouTube.

    Free XEvil Demo available.

    See you later!

    http://XEvil.net

  4. Ваш онлайн кинотеатр. Постоянно обновляемая и дополняемая основание с фильмами.
    Последние новинки мирового проката. Лучшие из лучших кинофильмы российского и иностранного кинематографа.
    Kinositepro
    https://kinositepro.ru

  5. Hmm is anyone else experiencing problems with the pictures on this blog loading?

    I’m trying to figure out if its a problem on my
    end or if it’s the blog. Any feed-back would be greatly appreciated.

  6. An outstanding share! I have just forwarded this onto
    a co-worker who has been doing a little homework on this.
    And he in fact ordered me lunch due to the fact
    that I stumbled upon it for him… lol.
    So allow me to reword this…. Thank YOU for the meal!! But yeah, thanx for spending the time
    to discuss this matter here on your web site.

  7. I seriously love your blog.. Pleasant colors & theme.
    Did you create this site yourself? Please reply back as I’m trying to create my own website and would like
    to find out where you got this from or exactly what the theme is called.

    Kudos!

  8. First off I would like to say terrific blog! I had a quick
    question that I’d like to ask if you do not mind.
    I was interested to know how you center yourself and clear your mind prior to writing.
    I have had difficulty clearing my mind in getting my thoughts out.

    I do take pleasure in writing but it just seems like the first 10 to 15 minutes are lost simply just trying to figure out how to begin. Any recommendations or hints?

    Kudos!

  9. My brother recommended I would possibly like this blog. He was once totally right.
    This publish truly made my day. You can not consider simply how a lot time I had spent for
    this info! Thank you!

  10. It’s really very complex in this full of activity life to listen news on TV,
    thus I just use world wide web for that purpose, and take the hottest information.

  11. Hey! Would you mind if I share your blog with my myspace group?
    There’s a lot of people that I think would really enjoy your content.

    Please let me know. Thank you

  12. hey there and thank you for your information – I’ve definitely picked up something new from right here.
    I did however expertise some technical points using this site, since I experienced
    to reload the site many times previous to I could get it to load
    properly. I had been wondering if your web host is OK?

    Not that I am complaining, but sluggish loading instances times will sometimes affect your placement in google and can damage
    your high-quality score if advertising and marketing with Adwords.
    Well I’m adding this RSS to my email and could look out for
    much more of your respective intriguing content. Ensure that you update this again soon.

  13. whoah this weblog is great i like studying your articles.
    Stay up the good work! You understand, lots of people
    are searching around for this information, you can help them greatly.

  14. Hey fantastic website! Does running a blog such as this take a large amount of work?
    I’ve no knowledge of computer programming however I had been hoping to start my
    own blog in the near future. Anyway, if you have any ideas or tips for new
    blog owners please share. I understand this is off subject but I just needed to ask.
    Kudos!

  15. Wow, fantastic blog layout! How long have you been blogging for?
    you made blogging look easy. The overall look of your web site
    is wonderful, let alone the content!

  16. I do agree with all the ideas you’ve presented on your post.
    They’re really convincing and will definitely work.
    Nonetheless, the posts are very short for starters.
    May just you please lengthen them a bit from subsequent time?
    Thanks for the post.

  17. I’ve been browsing online more than three hours today,
    yet I by no means found any interesting article like yours.

    It is lovely worth enough for me. In my opinion, if all website
    owners and bloggers made just right content
    material as you did, the internet shall be much more
    useful than ever before.

  18. Today, I went to the beach with my kids. I found a sea shell and gave it to my 4 year old daughter and said “You can hear the ocean if you put this to your ear.” She placed
    the shell to her ear and screamed. There was a hermit crab inside and it pinched her ear.

    She never wants to go back! LoL I know this is completely
    off topic but I had to tell someone!

  19. I think this is among the so much important info for me.
    And i’m happy studying your article. But wanna remark on some common things, The website style is perfect, the articles
    is in reality nice : D. Just right activity, cheers

  20. I was very pleased to discover this great site.

    I wanted to thank you for ones time due to this wonderful read!!
    I definitely really liked every part of it and i also have you saved as a favorite to look at
    new information in your blog.

  21. Hi there, i read your blog occasionally and i own a similar one and i
    was just wondering if you get a lot of spam responses? If so
    how do you protect against it, any plugin or anything you
    can suggest? I get so much lately it’s driving me insane so any assistance is very much appreciated.

  22. Thanks , I have recently been looking for info about this subject for ages and yours is the greatest I
    have discovered till now. However, what concerning the bottom line?
    Are you certain about the source?

  23. Hi, i read your blog from time to time and i own a similar one and i was just
    curious if you get a lot of spam responses? If so how do you prevent
    it, any plugin or anything you can advise? I get so much lately it’s driving me
    insane so any assistance is very much appreciated.

  24. Thank you for the auspicious writeup. It in fact was a amusement account it.
    Look advanced to far added agreeable from you!

    By the way, how could we communicate?

  25. Hmm is anyone else experiencing problems with the images on this blog loading?
    I’m trying to determine if its a problem on my end or if it’s the blog.

    Any feed-back would be greatly appreciated.

  26. Heya are using WordPress for your blog platform? I’m new
    to the blog world but I’m trying to get started and create my own. Do you need any html coding expertise to make your own blog?

    Any help would be really appreciated!

  27. An impressive share! I have just forwarded this onto a coworker who has been doing a
    little research on this. And he actually bought me breakfast due to the fact that I discovered
    it for him… lol. So allow me to reword this….
    Thanks for the meal!! But yeah, thanx for spending the time to discuss this issue here on your internet site.

  28. you’re actually a just right webmaster. The web site loading velocity
    is amazing. It kind of feels that you are doing any distinctive trick.
    In addition, The contents are masterwork. you’ve done a magnificent activity on this
    subject!

  29. Thank you a bunch for sharing this with all people you
    really recognize what you’re talking approximately! Bookmarked.
    Kindly also talk over with my site =). We could have a hyperlink trade contract among us

  30. Howdy! I could have sworn I’ve been to this blog before but after reading through some
    of the post I realized it’s new to me. Anyways, I’m definitely glad I found it and
    I’ll be book-marking and checking back frequently!

  31. Wonderful items from you, man. I’ve understand your stuff prior to and you are
    simply extremely fantastic. I really like what you have
    acquired here, certainly like what you are saying and
    the best way wherein you assert it. You are making it enjoyable and you still care for to stay it sensible.
    I can not wait to read much more from you. This is really a great web
    site.

  32. We’re a group of volunteers and opening a new scheme in our community.
    Your site provided us with valuable info to work on. You’ve done a
    formidable job and our whole community will be grateful to you.

  33. certainly like your web-site however you need to take a look
    at the spelling on quite a few of your posts. A number of them are rife with spelling
    issues and I to find it very bothersome to tell the truth then again I
    will surely come again again.

  34. Pretty great post. I just stumbled upon your blog
    and wished to mention that I’ve truly loved browsing your weblog posts.

    After all I’ll be subscribing for your feed and I am hoping you write once more soon!