I am writing a unit test for a function. The function works perfectly on it self, but when I tried to test this function throught a unit test, it gives me a unbondlocalerror. I have rev_get_event define as a global variable
#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
and my unit test is:
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")
and it gives me:
UnboundLocalError: local variable 'rev_get_event' referenced before assignment
You are returning a variable that is only declared if you go in to the flow of:
except requests.exceptions.RequestException:
I guess that when you used it not in the unit testing, you always got in to this flow, but at the unit testing you dont, and this is exactly why unit testing is for, to find these kind of bugs!
The issue here seems to be the variable scope.
In the function the variable rev_get_event is local to the scope of the function. If you mean the global variable the function should explicitly declare it, for example as follows:
global rev_get_event
def Get_event(username, password, eventID):
global rev_get_event
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
Pay attention to the first line of the function:
global rev_get_event
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.