您的位置:首页 > 编程语言 > Python开发

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

2014-04-01 15:14 761 查看
使用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'])
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: