This is the 28th day of my participation in Gwen Challenge

preface

Previous articles briefly described how to encapsulate CRUD methods in Flask-SQLAlchemy

With the most basic functionality in place, testing becomes essential when we start writing business logic code

It’s sometimes even more important than the code itself

So, this article will focus on how to use PyTest to test Flask projects

plan

Use PyTest to test, there are some examples in the official documentation, you brothers can learn by yourself

The theory is very simple, we just need to follow the following steps before testing:

  1. Install pytest
  2. Write test environment related code
  3. Write test cases

Let’s implement an interface test case step by step

Install pytest

Open the console in the project root directory and run PIP Install Pytest

Then create the Tests folder

Write test environment related code

In the Tests folder, create a file named conftest.py

Conf-test, as the name suggests, is the configuration of the test

Fixture (scope=”session”) : @pytest.fixture(scope=”session”)

As with ConfTest, WHEN learning a new skill, I highly recommend that you first look up the meaning of an English word you don’t know

Its meaning is usually an accurate indication of its use

Fixure is a fixed device for each test, and you can understand why it has a scope

Scope represents the range or position in which this fixture is installed and has four values:

  • Method the function:
  • Class: class
  • A py file is a module
  • Session: indicates the test environment

Most projects use databases, so in a test environment, database resources are the most important

If the test function is relevant, we can use a simple SQLite database:

@pytest.fixture(scope="session")
def app() :
    app = Flask(__name__)
    db_fd, db_file_path = tempfile.mkstemp(".db".dir="")
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///%s' % db_file_path
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
    app.config["JWT_SECRET_KEY"] = "Houtaroy"
    app.config['TESTING'] = True
    try:
        with app.test_request_context():
            yield app
    finally:
        os.close(db_fd)
        os.unlink(db_file_path)
Copy the code

At the beginning of the test, create temporary database files and do flask-related configuration

Then we initialize the app, and now we have a small Flask app that links to SQLite

To be continued…