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

使用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'])


  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

day walker

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值