-4
我正在爲函數編寫單元測試。 該函數完全適用於它自己,但是當我試圖通過單元測試來測試這個函數時,它給了我一個unbondlocalerror。 我已經rev_get_event定義爲一個全局變量python - UnboundLocalError:在賦值之前引用的局部變量
#return value for get event
global rev_get_event
def Get_event(username, password, eventID):
try:
payload = {'username': username, 'password': password}
s = requests.Session()
r = s.get("https://www.regonline.com/api/default.asmx/Login", params=payload)
login_info = minidom.parseString(r.text)
except requests.exceptions.RequestException:
logger.exception("Requests error")
api = login_info.getElementsByTagName('APIToken')
for api_token in api:
api_token = api_token.firstChild.nodeValue
payload2 = {'eventID' : eventID, "apiToken" : api_token }
rev_get_event = requests.get('https://www.regonline.com/api/default.asmx/GetEvent', params=payload2)
except requests.exceptions.RequestException:
logger.exception("Requests error")
return rev_get_event
和我的單元測試是:
def test_get_event_good(self):
result = rg.Get_event("eddietest", "eddietest", 18283)
get_event = minidom.parseString(result)
print result
success = get_event.getElementsByTagName('Success')
for answer in success:
answer = answer.firstChild.nodeValue
self.assertEqual(answer, "true", "connetion failed")
,這讓我:
UnboundLocalError: local variable 'rev_get_event' referenced before assignment
'rev_get_event'只在'except'塊中定義,如果'try'成功,則該變量永遠不會被定義。 – CoryKramer 2014-11-21 19:30:12
我把它定義爲一個全局變量「global rev_get_event」 – jifferent 2014-11-21 19:34:51