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

preface

We’ve introduced pyTest concepts and manually initialized a small Flask App that links to an SQLite database

But those fixtures (remember it?) Obviously not enough

plan

Write test environment related code

When we test with a database, we inevitably preset some data

And the interfaces need to be written to the database when they are accessed

First, we create a method to generate the data:

def init_data() :. Initialize dataCopy the code

After that, we created our database fixture, which I used in this case flask-SQLalchemy:

from flask_sqlalchemy import SQLAlchemy

my_db = SQLAlchemy()

def init_data() :. Initialize data@pytest.fixture(scope="session")
def db() :
    init_data()
    try:
        yield my_db
    finally:
        my_db.close_all_sessions()
        my_db.drop_all()
Copy the code

Be careful to close all database connections and delete all data at the end of the test

Otherwise, temporary database files will not be cleared, which is very inelegant

After data initialization, we introduce the request client to write subsequent test cases:

@pytest.fixture(scope='session')
def client(app, db) :
    with app.test_client() as test_client:
        yield test_client
Copy the code

The app, db, is the fixture we created earlier, so make sure the names are the same to load correctly

Write test cases

In the Tests folder, create a file starting with test_, for example: test_API

Pytest executes test cases in character order

Test cases can be broadly categorized into two types: HTTP requests and non-HTTP requests

Remember the custom JSON encoder from the previous article? It converts all the time to a timestamp

For its tests to be non-HTTP requests, we don’t need to use fixtures, test_json_encoder.py:

from datetime import datetime

from .encoders import MyJSONEncoder

json_encoder = MyJSONEncoder()

def test_datetime() :
    now = datetime.now()
    result = json_encoder.default(now)
    assert result == str(round(now.timestamp()))
Copy the code

Assert is the essence of validation, but it should be used for more than just testing. See the Python documentation for more information on how to use it

The HTTP request is going to use the client that we just created, and when we introduce it, we’re going to introduce the APP, the DB

This is the entire Flask App environment constructed by test_user_api.py:

def test_list(client) :
    rv = client.get('/api/users')
    json_data = rv.get_json()
    assert json_data['code'] = =200
    assert 'data' in json_data
    assert 1= =len(json_data['data'] ['items'])
Copy the code

conclusion

Testing is a prerequisite for robust code

Keep in mind that writing accurate test cases first is twice the effort