Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LiveServerTestCase hangs at python-requests post call in django view

I'm writing a Django app that uses a REST api I created. The purpose is to prove api use cases using the web app. In my view, I therefore call the api using the python-requests library like so:

def my_view_method(request):
    if request.method == 'POST':
    form = MyForm(request.POST)
    if form.is_valid():
        data = form.cleaned_data
        data_to_post = {
            'fieldA': data.get('fieldA_in_form'),
            'fieldB': data.get('fieldB_in_form'),
        }
        post_url = "http://%s/%s/" % (request.get_host(), 'entries')
        logger.info("request api url: "+ post_url)
        r = requests.post(post_url, data=data_to_post)
        return HttpResponseRedirect('/')
    else:
        form = MyForm()

    return render(request, 'myview.html', { 'form': form })

I have verified using Unit Tests that POSTing to /entries/ with valid data results in the correct database updates.

url = '/entries/'
#verify initial db state
data = { 'fieldA': value1, 'fieldB': value2 }
response = self.client.post(url, data, format='json')
# verify db was updated

In my Functional Tests, I use LiveServerTestCase and interact with the Form. When the test submits the form, the browser tab shows "Connecting..." in the title and the test case hangs. It wasn't so when I was directly interacting with the database instead of calling the api using requests, so that must be the source of the delay.

Is there something about how LiveServerTestCase works that I'm not understanding here?

like image 922
theraju Avatar asked Feb 11 '14 00:02

theraju


1 Answers

Could it be that the LiveServerTestCase server can only handle a single request at a time? So it hangs because it can't deal with a request-from-within-a-request?

The source says it will "handle one request at a time", but then again it says "without blocking", so that's ambiguous...

I think you're going to be best off dropping LiveServerTestCase and just rolling your own test runner. You can use setUp to spin up runserver in a separate process, and tearDown to reset the database (manage.py flush?). If you want to use a test database, you could use a different settings.py, or just move the "real" database out of the way for the duration of the test...

like image 125
hwjp Avatar answered Oct 22 '22 11:10

hwjp