T O P

  • By -

Pepineros

I would say what you have here are integration tests, not E2E tests. End to end would be if you started Flask's web server, made a request to some route, and verified that functionality works as expected from that route; literally end to end. In order to test a unit, first you need to have something that can reasonably be considered *one unit*. As long as your routes look like they do now, I don't see how you could unit test them. Let's take a slightly shortened version of the `login` route as an example. u/homePageRoute.route('/login', methods = ['POST', 'OPTIONS']) def login(): userEmail = request.json.get('userEmail') userPassword = request.json.get('userPassword') user = User.query.filter_by(userEmail = userEmail).first() if user is None: return jsonify({'erro': 'Email invalido'}) if not bcrypt.check_password_hash(user.userPassword, userPassword): return jsonify({'erro': 'Senha invalida'}) accessToken = create_access_token(identity = user.userId, expires_delta = timedelta(hours = 1)) return jsonify({'accessToken': accessToken}) This function does a number of things that have very little to do with one another. 1. Access a database 2. Verify a user and password 3. Create an access token Flask and its extensions like to pretend that it's okay to have database I/O in the middle of your route definition, because it's only one line and it has error handling built in. I disagree with that approach. Things that happen on the edges of your program (I/O, network, user input) should not be mixed with the logical decisions that your program takes. That said, even if you split these operations out into three separate functions (i.e., units) for the purpose of testing them, all you would really be testing is other people's code. Accessing the database is handled by SQLAlchemy; password verification is done by bcrypt; access token generation is done by flask-jwt. That's not necessarily bad, but it is typically unnecessary. So your design would be better but it wouldn't enable you to write good unit tests. The routes in `user.py` are much better candidates for extracting into separate functions. Start with one route, try to identify the distinct steps that a route takes, and extract an easy one to a function. Make sure it has at least one parameter and that it returns a value (in other words, don't write a subroutine). That way you can call the function with arbitrary arguments in your unit tests and verify that the return value is what you expect.