1

I am trying to save response from an HTTP request in a global variable using globals() in python so that I can use that data later.

def request_agent(agent_name, urL):
    r = requests.get(urL) 
    data = r.json()
    globals()[agent_name] = data

But when I write my test case to verify if that value has been saved or not, I get an error saying that the variable is not defined. Below is my test case.

class TinyTest(unittest.TestCase):

    def test_request_agent(self):
        agent_name = 'location'
        url = 'http://free.ipwhois.io/json/'
        tt.request_agent(agent_name, url)
        self.assertEqual(eval(location['continent']), 'Europe')

What am I doing wrong here?

Sumit Kumar
  • 11
  • 1
  • 5
  • I think the globals in the function scope are different from the globals in the test scope. But regardless I think it's bad practice to access the global scope from a unittest since they should be isolated. If you really wanna do it you'll need to send the globals from the test as a parameter. There is also a thing called Mock, I haven't tried it myself but I saw a good video on it. It basically lets you simulate a http request and such: https://youtu.be/6tNS--WetLI?t=1800 – Mandera May 27 '20 at 15:49

0 Answers0