You don't have access to this class

Keep learning! Join and start boosting your career

Aprovecha el precio especial y haz tu profesi贸n a prueba de IA

Antes: $249

Currency
$209
Suscr铆bete

Termina en:

0 D铆as
5 Hrs
17 Min
18 Seg
Curso de Flask

Curso de Flask

Luis Mart铆nez

Luis Mart铆nez

Pruebas unitarias en Flask

17/18
Resources

Unit tests are fundamental in modern software development, especially when working with frameworks such as Flask. These tests allow us to verify that our code works correctly and maintains its integrity over time, even when we make modifications. Mastering this technique not only improves the quality of our applications, but also facilitates the implementation of methodologies such as continuous integration.

What are unit tests and why are they important?

Unit testing is an essential practice in software development that consists of validating that each individual component of our code works as we expect it to. This is particularly important when our code includes complex business logic.

There are several key benefits to implementing unit tests:

  • Constant validation: They allow us to verify that the code does exactly what we expect.
  • Safety when making changes: We can modify our code with confidence that we are not breaking existing functionality.
  • Continuous Integration: Tests can run automatically in CI/CD (Continuous Integration/Continuous Deployment) processes.
  • Live documentation: Tests serve as executable documentation of how our code should behave.

In Flask, we have specific tools that make it easy for us to create tests to validate both our models and our views.

How to set up a test environment in Flask?

To implement unit tests in Flask, we need to properly configure our environment. This involves several important steps:

Creating a test-specific configuration.

The first thing we need to do is to create a specific configuration for our tests:

class TestConfig: SQLALCHEMY_DATABASE_URI = 'sqlite:///test_notes.db' SECRET_KEY = 'test_secret_key' TESTING = True .

This configuration is similar to the production configuration, but with some key differences:

  • We use a different database(test_notes.db) so as not to affect the production data.
  • We set TESTING = True so that Flask knows that we are in test mode.
  • We can define a specific secret key for testing.

Implementation of the Application Factory pattern

In order to be able to change the configuration during testing, we need to implement the Application Factory pattern:

def create_app(config_class=Config): app = Flask(__name__) app.config.from_object(config_class)    
 # Here goes the rest of the app configuration # ...    
 return app

This pattern allows us to create instances of our application with different configurations, which is essential for testing. Instead of initializing the application directly, we create a function that initializes and returns it.

How to create and run unit tests in Flask?

Once our environment is configured, we can start writing unit tests for our models and views.

Creating a test class

We create a test_models.py file with a class that inherits from unittest.TestCase:

import unittestfrom app import create_appfrom config import TestConfigfrom models import db, Note
class NoteModelTest(unittest.TestCase): def setUp(self): self.app = create_app(TestConfig) self.client = self.app.test_client()        
 with self.app.app.app_context(): db.create_all()    
 def test_create_note(self): with self.app.app.app_context(): note = Note(title="Title",  content="Content") db.session.add(note) db.session.commit()            
 saved_note = Note.query.first()            
 self.assertEqual(saved_note.title, "Title") self.assertEqual(saved_note.content, "Content")

In this example:

  • The setUp method is executed before each test and sets up the necessary environment.
  • We create an instance of our application with the test configuration.
  • We initialize a test client that will allow us to simulate HTTP requests.
  • We create the database structure within the application context.
  • In test_create_note, we test that we can create a note and that it is saved correctly in the database.

Using the application context

A crucial aspect of working with tests in Flask is the use of the application context. Many operations, such as database interactions, require this context:

with self.app.app_context(): # Code that requires the application context db.create_all() # ...

Without this context, we will receive errors when trying to access the database or other application resources.

Using assertions to validate results

Assertions are the heart of unit tests. They allow us to verify that the results are as expected:

self.assertEqual(saved_note.title, "Title").

There are many types of assertions available:

  • assertEqual: Verifies that two values are equal.
  • assertTrue/assertFalse: Verifies that a value is true or false
  • assertIn: Verifies that an element is in a collection
  • assertRaises: Verifies that a specific exception is thrown

Execution of the tests

To run our tests, we use Python's unittest module:

python -m unittest test_models.py

If the test is successful, we will see a point for each test that passes. If it fails, we will see a detailed error message that will help us identify the problem.

Unit tests are a powerful tool for ensuring the quality of our code in Flask applications. By implementing them correctly, we can develop with greater confidence and keep our applications more robust over time. Have you implemented unit tests in your projects? Share your experiences and doubts in the comments section.

Contributions 0

Questions 0

Sort by:

Want to see more contributions, questions and answers from the community?