SoFunction
Updated on 2024-10-29

Flask framework unit testing principles and usage examples of analysis

This article example tells the principle and usage of flask framework unit testing. Shared for your reference, as follows:

Why test?

The Web program development process generally consists of the following phases: [Requirements Analysis, Design Phase, Implementation Phase, Testing Phase]. In the testing phase, the functionality of a system is tested by running it manually or automatically. The purpose is to check whether it meets the requirements and produce specific results to achieve the ultimate goal of clarifying the difference between the expected results and the actual results.

Classification of tests:

Testing can be categorized from the software development process into: unit testing, integration testing, system testing and so on. Among the many tests, the one that is closest to the program developers is unit testing, because unit testing is carried out by the developers, while all other tests are done by professional testers. So we mainly learn unit testing.

What is unit testing?

During program development, code is written to fulfill a requirement. When our code passes compilation, it just means that its syntax is correct, whether the function can be realized is not guaranteed. Therefore, when some of our functional code is completed, in order to check whether it meets the needs of the program. You can write test code to simulate the process of running the program and check whether the functional code meets the expectations.

Unit testing is when a developer writes a small piece of code to verify that the target code functions as expected. Typically, unit testing is done for modules that have a single function.

An example: a cell phone has many components, in the formal assembly of a cell phone before the phone's internal components, CPU, memory, battery, camera, etc., should be tested, which is unit testing.

In the Web development process, unit testing is actually some "assert" (assert) code.

An assertion is a determination of whether the result produced by a function or a method of an object matches the one you expect. An assertion in python is a determination that a boolean value is true, and an exception is thrown if the expression is false. In unit testing, assert is generally used to assert the result.

Assertion method usage:

Assertion statements are similar:

if not expression:
  raise AssertionError

Commonly used assertion methods:

assertEqual pass if two values are equal
assertNotEqual pass if the two values are not equal
assertTrue Pass if the bool value is True.
assertFalse Pass if the bool value is False.
assertIsNone does not exist, then pass
assertIsNotNone exists, then pass

How is it tested?

Simple test cases: 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765.

def fibo(x):
  if x == 0:
    resp = 0
  elif x == 1:
    resp = 1
  else:
    return fibo(x-1) + fibo(x-2)
  return resp
assert fibo(5) == 5

Basic writing of unit tests:

First, define a class that inherits from

import unittest
class TestClass():
  pass

Next, in the test class, define two test methods

import unittest
class TestClass():
  # The method will be executed first, with a fixed write method name
  def setUp(self):
    pass
  # The method will be executed after the test code has finished executing, and the method name is written as fixed
  def tearDown(self):
    pass

Finally, in the test class, write the test code

import unittest
class TestClass():
  # The method will be executed first, which is equivalent to doing pre-testing work
  def setUp(self):
    pass
  # This method is executed after the test code is executed, which is equivalent to doing post-test cleanup work
  def tearDown(self):
    pass
  # Test code
  def test_app_exists(self):
    pass

Send an email to test:

#coding=utf-8
import unittest
from Flask_day04 import app
class TestCase():
  # Create test environments to be executed before test code is executed
  def setUp(self):
     = app
    # Activate the test flag
    ['TESTING'] = True
     = .test_client()
  # Execute after test code execution is complete
  def tearDown(self):
    pass
  # Test code
  def test_email(self):
    resp = ('/')
    print 
    (,'Sent Succeed')

Database testing:

#coding=utf-8
import unittest
from author_book import *
# Customize the test class, setUp method and tearDown method will be executed before and after the test respectively. Functions starting with test_ are the specific test code.
class DatabaseTest():
  def setUp(self):
    ['TESTING'] = True
    ['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:mysql@localhost/test0'
     = app
    db.create_all()
  def tearDown(self):
    ()
    db.drop_all()
  # Test code
  def test_append_data(self):
    au = Author(name='itcast')
    bk = Book(info='python')
    .add_all([au,bk])
    ()
    author = .filter_by(name='itcast').first()
    book = .filter_by(info='python').first()
    # Assert that data exists
    (author)
    (book)

I hope that the description of this article will be helpful for you to design Python programs based on flask framework.