1

I am trying to mock an HTTP server in my python script, but it fails. Here is what I am doing:

import bottle
from restclient import GET
from threading import Thread

@bottle.route("/go")
def index():
    return "ok"


server = Thread(target = bottle.run)
server.setDaemon(True)
server.start()

print "Server started..."

response = GET("http://127.0.0.1:8080/go")

assert response.body == "ok"

print "Done..."

Basically I am trying to launch bottle.py http server with 1 test route in a separate thread & then mock responses from it.

But it just won't work. The server is not getting started in a separate thread, so I always get "errno 111 connection refused" when trying to request it.

So the question is: how can it be solved? Is there any other ways to mock http servers?

talonmies
  • 70,661
  • 34
  • 192
  • 269
geCoder
  • 217
  • 1
  • 4
  • 7

1 Answers1

7

You're not leaving enough time for the webserver to start up.

When you do:

server.start()
print "Server started..."
response = GET("http://127.0.0.1:8080/go")   

You try to access the server just after starting it,

Depending on which thread (the main one, or the server one) gets to run first (and for how long), you might end up in a situation when the server hasn't started yet when you try to access it, hence the Connection Refused error.

You could try doing the following :

server.start()
import time
time.sleep(...) # Something long enough
# Continue your stuff.

As you can see in time.sleep -- sleeps thread or process?, doing time.sleep will only sleep the currently running thread, so you could leave enough time to your server thread to start.

Now, all that is a bit hackish, so you might want to look into your server startup process to see if there is a way to assess whether it's up and running and wait on this condition before starting up.

Looking at the bottle source now, I can't figure out a solution to do that cleanly; you could always try to hit the server repeatdly until it finally responds, thus indicating the server is alive.

Community
  • 1
  • 1
Thomas Orozco
  • 53,284
  • 11
  • 113
  • 116