Reputation: 79
My tools: Python 3.5.0, flask 1.0.2, mac osx
My problem: I have a very simple RESTful app with two endpoints that are working. I wrote two very simple unit tests, via unittest, and they are not proceeding for a reason that I'm not sure of right now. The tests succeed if I do the following:
The tests just hang if I run the tests with the setUp(self) definition below:
Serving Flask app "testing" (lazy loading)
Environment: production
WARNING: Do not use the development server in a production environment.
Use a production WSGI server instead.
Debug mode: off
Running on http://127.0.0.1:8015/ (Press CTRL+C to quit)
And here is the pertinent code
def setUp(self):
self.app = Flask("testing")
self.app.testing = True
self.client = self.app.test_client()
self.EmployeeId = 4
with self.app.app_context():
db_connect = create_engine('sqlite:///some.db')
self.api = Api(self.app)
self.api.add_resource(server.Car, '/car/<employee_id>') # Route_4
app.run(port=8015, debug=False)
def test_api_can_get_employee_by_id(self):
res = requests.get(url = 'http://127.0.0.1:8015/car/{}'.format(self.EmployeeId))
data = res.json()
self.assertEqual(res.status_code, 200)
self.assertIn('mazda', data["data"][0]['make_model'])
I've looked online and found no resource that really covers my question. The set up of the server works during the testing but the unit tests are not executed. How would you recommend troubleshooting this? I'm open to all suggestions including changing the approach. Thank you!
Upvotes: 2
Views: 1819
Reputation: 509
For those of you stumbling here after Googling "Unit tests stuck on Running on with Flask":
It's possible that your code always starts the Flask server, regardless of how your module was loaded. If that's the case, even the unit tests will start the server, which will indefinitively listens for connections as expected.
Eg, this will get stuck:
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello():
return "Hello World!"
app.run()
Instead, you'll need to start the Flask server only if your module is the main program:
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello():
return "Hello World!"
if __name__ == '__main__':
app.run()
More info on the "name == 'main'" block here.
Regarding the original question, this answer does not solves it. To do something like that you would need to start the Flask server, but in a non-blocking way such as another thread or process. There's many ways to do this and without any additional info, the question is just too vague to answer as is.
Upvotes: 3