Pytest 测试类、方法、接口写法

1. 测试类

import pytest
from django.test import TestCase
from blog.models import BlogCategory

@pytest.mark.django_db
class TestBlogCategory(TestCase):

    def setUp(self):
        self.blogcategory = BlogCategory.objects.create(id=1,title="Test Category", href='/category/1')

    def test_BogCategoryModel(self):
        blog_category = BlogCategory.objects.get(id=self.blogcategory.id)
        self.assertEqual(blog_category.title, "Test Category")
        self.assertEqual(blog_category.href, '/category/1')

if __name__ == '__main__':
    pytest.main(["-s", "-v", "-p", "no:warnings", "--tb=short", "--html=report.html", "blog/tests.py"])

2. 函数

import pytest
from django.test import TestCase
from blog.models import BlogCategory

@pytest.mark.django_db
def test_blog_category_create():
    blogcategory = BlogCategory.objects.create(id=1,title="Test Category", href='/category/1')
    category_count = BlogCategory.objects.count()
    assert category_count > 0, "Blog category was not created category_count=0."
    assert blogcategory.id > 0, "Blog category was not created."
    assert blogcategory.title == "Test Category", "Blog category title is wrong."
    assert blogcategory.href == "/category/1", "Blog category href is wrong."


@pytest.mark.django_db
def test_blog_category_query():
    category_count = len(BlogCategory.objects.all())
    assert category_count >= 0, "Blog category query error."


if __name__ == '__main__':
    pytest.main(["-s", "-v", "-p", "no:warnings", "--tb=short", "--html=report.html", "blog/tests.py"])

3. 测试接口

import requests
import pytest

host = "http://localhost:8000"


class TestApi:
    def test_getcategory_list(self):
        url = f'{host}/api/category/'
        response = requests.get(url)
        assert response.status_code == 200, f'Expected status code 200 but got {response.status_code}'
        assert response.json() != None, f'Expected to get json response but got {response.text}'
        print(response.json())

    def test_getpost_list(self):
        url = f'{host}/api/post/list'
        response = requests.get(url)
        assert response.status_code == 200, f'Expected status code 200 but got {response.status_code}'
        assert response.json() != None, f'Expected to get json response but got {response.text}'


if __name__ == '__main__':
    pytest.main(["-s", "-v", "-p", "no:warnings", "--tb=short", "--html=report.html", "api/tests.py"])
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值