Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing Flask web app with unittest POST Error 500

This is my test.py file:

import unittest, views, json

class FlaskTestCase(unittest.TestCase):

def setUp(self):
    self.app = views.app.test_client()

def test_index(self):
    rv = self.app.get('/')
    assert 'Hamptons Bank' in rv.data

def test_credit(self):
    response = self.app.post('/credit', data=json.dumps({
            'amount': '20',
            'account': '1'
        }), content_type='application/json')

    print response.data
    assert 'Deposit of 20 to account 1' in response.data


if __name__ == '__main__':
     unittest.main()

The test_index method works fine, but the self.app.post keeps returning (in print response.data):

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>500 Internal Server Error</title>
<h1>Internal Server Error</h1>
<p>The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.</p>

The method in my views.py is the following:

@app.route('/credit', methods=['POST'])
def credit_account():
  bank = Bank()

  amount = int(request.json["amount"])
  depositCommand = DepositCommand(find_account(request.json["account"]), amount)
  bank.execute(depositCommand)

  message = "Deposit of " + str(request.json["amount"]) + " to account "+str(request.json["account"])
  return message

What am I doing wrong?

This is my first time testing a Flask web app, so I am still a bit confused!

Thank you :-)

like image 384
Larissa Leite Avatar asked Jun 02 '15 18:06

Larissa Leite


People also ask

How do I run a Unittest test?

If you're using the PyCharm IDE, you can run unittest or pytest by following these steps: In the Project tool window, select the tests directory. On the context menu, choose the run command for unittest . For example, choose Run 'Unittests in my Tests…'.

What is Internal Server Error in flask?

Either the server is overloaded or there is an error in the application. This is the 500 Internal Server Error, which is a server error response that indicates that the server encountered an internal error in the application code.

How does Python handle internal server error?

Make sure debug mode is off, then try again. Here is a comment directly from the code itself: Default exception handling that kicks in when an exception occurs that is not caught. In debug mode the exception will be re-raised immediately, otherwise it is logged and the handler for a 500 internal server error is used.


1 Answers

(From my comment above): when testing, you should set app.config['DEBUG'] = True and app.config['TESTING'] = True.

like image 198
jonafato Avatar answered Oct 14 '22 14:10

jonafato