python(Django flask)单元测试


目的:为了检验代码是否满足最终需求,是否能得出特定的结果;功能是否符合预期

在web开发中,单元测试实际就是一些断言assert代码

常用的断言方法

flask单元测试实例

unittest.main()会将当前文件中的所有测试行为都执行一遍

单元测试需要模拟所有场景行为

单元测试类中可以定义一个setup方法,用来进行初始化的操作,比如构造客户端等

django单元测试

from django.test import Client, TestCase

实际存在utils,删除项目根目录的__init__文件即可

An error occurred in the current transaction. You can't execute queries until the end of the 'atomic' block.

# 解决办法
from django.test importTransactionTestCase

涉及到多对多字段open_access都找不到数据,对应的查询也失败

book.open.add(company)

实例

from django.test import TestCase
from django.test import Client, TestCase,TransactionTestCase
from apps.books.models import BookModel,AuthorModel
from apps.user.models import UserModel

class TestBook(TransactionTestCase):
   
    def setUp(self):
        super(TestBook, self).setUp()
        self.client = Client()
        author = AuthorModel.objects.create(
            authorID="111",
            aname="python"
        )

        user = UserModel.objects.create(
            real_name="李四",
            username="李四",
            mobile="13411111111",
            department="研发",
            position="经理",
            role=3,
            is_delete=0,
            userID="111",
            companyId=company,
        )

        my_book = BookModel.objects.create(
            name="aaa",
            add_user=user,
            modified_user=user,
        )
        my_book.author.add(company)

    def test_post_book(self):
        '''添加书籍'''
        data = {
            "name": "111",
        }
        response = self.client.post("/api/books/", data=data,**self.header)
        response = response.json()

        self.assertIn("status",response)
        self.assertEqual(response["status"],"200")

        # 测试添加书籍名相同
        data_2 = {
            "name": "111",
        }
        response = self.client.post("/api/books/", data=data_2, **self.header)
        response = response.json()

        self.assertIn("status", response)
        self.assertEqual(response["status"], "106")

        # 测试参数错误
        data_3 = {
            "name": "333",
        }
        response = self.client.post("/api/books/", data=data_3, **self.header)
        response = response.json()

        self.assertIn("status", response)
        self.assertEqual(response["status"], "102")
        print("test post books ok!!!")

    def test_put_book(self):
        '''更新书籍'''
        data_4 = {
            "name": "111",
        }
        book_id = BookModel.objects.get(name="aaa").id
        response = self.client.put("/api/books/%d/"%book_id, **self.header, data=data_4, content_type='application/json')
        response = response.json()

        self.assertIn("status", response)
        self.assertEqual(response["status"], "200")

        # 书籍不存在
        response = self.client.put("/api/books/100/", **self.header, data=data_4,
                                   content_type='application/json')
        response = response.json()

        self.assertIn("status", response)
        self.assertEqual(response["status"], "104")
        print("put books test ok!!!")

    def test_get_book(self):
        '''查询书籍'''
        response = self.client.get("/api/books/", **self.header)
        response = response.json()

        self.assertIn("status", response)
        self.assertEqual(response["status"], "200")
        print("get all books test ok!!!")

    def test_get_book_id(self):
        '''书籍详情接口'''
        book_id = BookModel.objects.get(_name="aaa").id
        response = self.client.get("/api/books/%s/" % book_id, **self.header)
        response = response.json()

        self.assertIn("status", response)
        self.assertEqual(response["status"], "200")
        print("get book by id test ok!!!")

    def test_delete_book(self):
        '''删除书籍'''
        book_id = BookModel.objects.get(name="aaa").id
        response = self.client.delete("/api/books/%d/"%book_id, **self.header)
        response = response.json()

        self.assertIn("status", response)
        self.assertEqual(response["status"], "200")

        # 书籍不存在
        response = self.client.delete("/api/aqqzw/books/100/", **self.header)
        response = response.json()

        self.assertIn("status", response)
        self.assertEqual(response["status"], "104")
        print("delete book test ok!!!")

    def test_download_book(self):
        '''下载书籍'''
        book_id = BookModel.objects.get(name="aaa").id
        response = self.client.get("/api/download/book/%d/"%book_id, **self.header)
        response = response.json()

        self.assertIn("status", response)
        self.assertEqual(response["status"], "200")
        print("download book test ok!!!")

    def test_get_book_list(self):
        '''查询书籍下拉列表'''
        response = self.client.get("/api/book_parameter/", **self.header)
        response = response.json()

        self.assertIn("status", response)
        self.assertEqual(response["status"], "200")



执行

tests.py放在创建的app目录中

python manage.py test # 执行项目中所有以test开头的文件

python manage.py test app.tests.ClassName # 执行某个测试类

python manage.py test app.tests.ClassName.test_function # 执行单个测试