Reputation: 721
I am trying to emulate a http server on localhost for faster testing.
ex:
import my_module
class RequestsTestCase(unittest.TestCase):
def setUp(self):
# ...
html = 'hello, world'
my_server = MyServer(html, 8888)
my_server.run()
...
def test_my_module_request_phrase(self):
response = my_module.get_phrase('http://localhost:8888/')
self.assertEqual(response, 'hello, world')
Is something like this possible using python 3?
Upvotes: 3
Views: 5679
Reputation: 42405
I just wanted to test the response of a request without the need of internet (...)
No problem. You can run your test http server on the same host you run your tests. If you run it in the same process your tests are being run in (which is the case when using unittest and running test server from within setUp()
method) then the server has to be run in a separate thread so that it doesn't block your tests. You can take a look how it's done in urllib3 here.
Upvotes: 3
Reputation: 364
First, consider the following aspects:
If you are still looking for a tool to easily unit test the remaining web I/O, please consider using the libraries httpretty or responses. With these tools, it is easily possible to specify fake responses including header fields, return codes, and more. The resulting test code will be much cleaner and shorter than what you would write with Python mock alone (or a custom real web server you run concurrently in some other thread).
Upvotes: 2