-1

I'm using the Python package requesocks instead of requests since it has support for using a SOCKS proxy.

I'm trying to mock the get() method of the session object using Python's built in mock library, but I'm unable to mock the status code:

import mock 
import requesocks

class WebScraper:
    def get_content(self, url, proxy):
        session = requesocks.session()
        session.proxies = proxy
        response = session.get(url)
        return response.status_code 

def main():
    session = requesocks.session()
    session.get = mock.MagicMock(return_value={'status_code': 400})

    scraper = WebScraper()
    proxy = {'http': 'socks5://localhost:1080'}
    status_code = scraper.get_content('http://www.purple.com', proxy)
    print "Status Code: ", status_code 

if __name__ == "__main__":
    main()

Running this contrived example results in the following output:

$ python test_mock.py 
Status Code:  200

What is the correct way to mock this so that I get a status code of 400?

Also, is there a similar mocking lib like requests-mock for requesocks?

Dirty Penguin
  • 4,212
  • 9
  • 45
  • 69

1 Answers1

0

I got it working by adapting the solution in this answer. Hoping this may help others, here is my updated code:

import mock 
import requesocks

class WebScraper:
    def get_content(self, url, proxy):
        session = requesocks.session()
        session.proxies = proxy
        response = session.get(url)
        return response.status_code 

@mock.patch('requesocks.session')
def main(mock_class):
    instance = mock_class.return_value 
    type(instance.get.return_value).status_code = mock.PropertyMock(return_value=400)

    scraper = WebScraper()
    proxy = {'http': 'socks5://localhost:1080'}
    status_code = scraper.get_content('http://www.purple.com', proxy)
    print "Status Code: ", status_code 

if __name__ == "__main__":
    main()

This produces the desired output:

$ python test_mock.py 
Status Code:  400
Community
  • 1
  • 1
Dirty Penguin
  • 4,212
  • 9
  • 45
  • 69