前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python unittest TestCase间共享数据(全局变量的使用)

python unittest TestCase间共享数据(全局变量的使用)

作者头像
用户7886150
修改2021-01-18 11:47:19
8900
修改2021-01-18 11:47:19
举报
文章被收录于专栏:bit哲学院bit哲学院

参考链接: 使用Unittest在Python中进行单元测试

使用unittest模块进行单元测试,涉及到以下场景 

例如对某个实体,测试方法有创建,更新,实体查询,删除 

使用unittest进行单元测试,可以在创建时候记录下返回的ID,在更新、删除等操作的时候就根据这个新创建的ID进行操作,这就涉及到不同的TestCase之间共享数据。 

最初我在class TestCase(unittest.TestCase):里增加变量,运行创建时候设置值,但是发现在运行其他方法时候值被清空了,说明这种方法不可行。 

最后只好定义全局变量,但是在局部用的时候需要使用globals()['newid'] 来操作全局变量。 

例如以下例子,创建时候获取ID,并设置,然后get的时候直接测刚才生成的ID,测delete时候就可以把这条数据删除掉了  

newid = None

class MonTemplateCase(unittest.TestCase):

    base = "http://localhost:8080/"

    def test_moncluster_temp_create(self):

        json = {"monitor_template":{"name":"testname1","desc":"desc2","dcid":"1","host_info":{"check_interval":"1","check_period":"5","max_check_attempts":"1","notification_interval":"1","notifications_enabled":"1","retry_interval":"1","contacts":"[1]"},"service_info":[{"id":"14","max_check_attempts":"1","notification_interval":"1","notifications_enabled":"1","retry_interval":"1","contacts":"[1]","check_period":"5","service_description":"CPU","check_command":"14!80 90","check_interval":"5"}]}}

        headers = {'content-type': 'application/json'}

        r = requests.post(self.base + "api/moncluster/template", data=simplejson.dumps(json),headers=headers)

        result = simplejson.loads(r.text)

        print "create result:", result

        if result['action'] is False:

            print result

        else:

            globals()['newid'] = result['data']

        self.assertEqual(True, result['action'])

    def test_comcluster_temp_get(self):

        global newid

        if newid is None:

            raise Exception('id is none cannot get')

        f = urllib2.urlopen(self.base + "api/moncluster/template/%s" % str(newid))

        result = simplejson.loads(f.read())

        print "get result:",result

        self.assertEqual(True, result['action'])

本文系转载,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文系转载前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档