title: Python Mocking a request for a bearer token?
body: <p>I'm trying to figure out how to mock my request for a bearer token in python.
  I have a class:</p>
  <pre><code>class grab_apitokens(object):
  
      def __init__(self, consumer_key, first_api_url, second_api_user, second_api_password, second_api_url):
          self.consumer_key = consumer_key
          self.second_api_user = second_api_user
          self.second_api_password = second_api_password
          self.first_api_url = first_api_url
          self.second_api_url = second_api_url
  
      def logintofirstsite(self):  
          b64val = base64.b64encode(self.consumer_key.encode()).decode()
          headers = {&quot;Authorization&quot;: &quot;Basic %s&quot; % b64val}
          data = {'grant_type': 'client_credentials', 'validity_period': '3600'}
          try:
              response = requests.post(self.first_api_url, headers=headers, data=data)
              decodedresponse = json.loads(response.content.decode())
              access_token = decodedresponse['access_token']
              return access_token
          except:
              return None
              
      def logintosecondsite(self):
          header = {&quot;accept&quot;: &quot;application/json&quot;, &quot;Content-Type&quot;: &quot;application/x-www-form-urlencoded&quot;}
          logindata = {'grant_type': 'password',
                       'username': &quot;&quot; + self.second_api_user + &quot;&quot;, 'password': &quot;&quot; + self.second_api_password + &quot;&quot;
                       }
          try:
              returnedfromsite = requests.post(self.second_api_url + '/api/V1/token', 
  headers=header, data=logindata)
              return returnedfromsite.json()['access_token']
          except:
              return None
  </code></pre>
  <p>What I can't figure out is how to mock that requests call and what it would look like in Python.</p>
  <p>My test currently looks like:</p>
  <pre><code>class MyTestCase(unittest.TestCase):
  
  
  
      def setUp(self) -&gt; None:       # PROBLEM BEGINS HERE
          self.grab_apitokens = grab_apitokens(actual_key, actual_site1, actual_user, actual_pass, actual_2nd_site)
  
      @patch('grab_apitokens.requests.get')
      def test_login(self, mock_get):
          mock_get.return_value.ok = True
          response = self.grab_apitokens.logintosite()
          assert_is_not_none(response)
          # self.assertEqual(True, False)
  
  
  
  if __name__ == '__main__':
      unittest.main()
  </code></pre>
  <p>How would I mock the requests.post functionality?</p>