配件網(wǎng)站模板網(wǎng)站優(yōu)化什么意思
Django測試
一、今日學(xué)習(xí)內(nèi)容概述
學(xué)習(xí)模塊 | 重要程度 | 主要內(nèi)容 |
---|---|---|
測試基礎(chǔ) | ????? | TestCase、斷言方法 |
模型測試 | ????? | 模型方法、數(shù)據(jù)驗(yàn)證 |
視圖測試 | ???? | 請(qǐng)求處理、響應(yīng)驗(yàn)證 |
表單測試 | ???? | 表單驗(yàn)證、數(shù)據(jù)處理 |
覆蓋率測試 | ???? | coverage配置、報(bào)告生成 |
二、測試基礎(chǔ)示例
2.1 基本測試類
# tests/test_base.py
from django.test import TestCase
from django.contrib.auth.models import User
from .models import Articleclass ArticleTestCase(TestCase):def setUp(self):"""測試前準(zhǔn)備工作"""# 創(chuàng)建測試用戶self.user = User.objects.create_user(username='testuser',email='test@example.com',password='testpass123')# 創(chuàng)建測試文章self.article = Article.objects.create(title='Test Article',content='Test Content',author=self.user)def tearDown(self):"""測試后清理工作"""self.user.delete()self.article.delete()def test_article_creation(self):"""測試文章創(chuàng)建"""self.assertEqual(self.article.title, 'Test Article')self.assertEqual(self.article.author, self.user)def test_article_str_representation(self):"""測試文章字符串表示"""self.assertEqual(str(self.article), 'Test Article')
2.2 測試工具類
# tests/test_utils.py
import unittest
from django.test import TestCase
from .utils import calculate_reading_time, generate_slugclass UtilsTestCase(TestCase):def test_reading_time_calculation(self):"""測試閱讀時(shí)間計(jì)算"""# 準(zhǔn)備測試數(shù)據(jù)content = ' '.join(['word'] * 500) # 500個(gè)單詞# 調(diào)用測試函數(shù)reading_time = calculate_reading_time(content)# 驗(yàn)證結(jié)果(假設(shè)每分鐘閱讀200個(gè)單詞)self.assertEqual(reading_time, 2.5)def test_slug_generation(self):"""測試slug生成"""test_cases = [('Hello World', 'hello-world'),('測試文章', 'ce-shi-wen-zhang'),('Python & Django', 'python-django'),]for title, expected_slug in test_cases:with self.subTest(title=title):self.assertEqual(generate_slug(title), expected_slug)
三、模型測試示例
# tests/test_models.py
from django.test import TestCase
from django.core.exceptions import ValidationError
from django.utils import timezone
from .models import Article, Categoryclass ArticleModelTest(TestCase):@classmethoddef setUpTestData(cls):"""創(chuàng)建測試數(shù)據(jù)"""cls.category = Category.objects.create(name='Test Category')cls.article = Article.objects.create(title='Test Article',content='Test Content',category=cls.category,status='draft')def test_title_max_length(self):"""測試標(biāo)題長度限制"""article = Article.objects.get(id=self.article.id)max_length = article._meta.get_field('title').max_lengthself.assertEqual(max_length, 200)def test_article_label(self):"""測試字段標(biāo)簽"""article = Article.objects.get(id=self.article.id)title_label = article._meta.get_field('title').verbose_nameself.assertEqual(title_label, '標(biāo)題')def test_publish_article(self):"""測試文章發(fā)布功能"""article = Article.objects.get(id=self.article.id)article.publish()self.assertEqual(article.status, 'published')self.assertIsNotNone(article.published_at)def test_article_ordering(self):"""測試文章排序"""Article.objects.create(title='Second Article',content='Content',category=self.category,status='published')articles = Article.objects.all()self.assertEqual(articles[0].title, 'Second Article')
四、視圖測試示例
# tests/test_views.py
from django.test import TestCase, Client
from django.urls import reverse
from django.contrib.auth.models import User
from .models import Articleclass ArticleViewsTest(TestCase):def setUp(self):self.client = Client()self.user = User.objects.create_user(username='testuser',password='testpass123')self.article = Article.objects.create(title='Test Article',content='Test Content',author=self.user)def test_article_list_view(self):"""測試文章列表視圖"""response = self.client.get(reverse('article_list'))self.assertEqual(response.status_code, 200)self.assertTemplateUsed(response, 'articles/article_list.html')self.assertContains(response, 'Test Article')def test_article_detail_view(self):"""測試文章詳情視圖"""response = self.client.get(reverse('article_detail', args=[self.article.id]))self.assertEqual(response.status_code, 200)self.assertTemplateUsed(response, 'articles/article_detail.html')self.assertEqual(response.context['article'], self.article)def test_create_article_view(self):"""測試創(chuàng)建文章視圖"""self.client.login(username='testuser', password='testpass123')response = self.client.post(reverse('article_create'), {'title': 'New Article','content': 'New Content',})self.assertEqual(response.status_code, 302) # 重定向self.assertTrue(Article.objects.filter(title='New Article').exists())
五、表單測試示例
# tests/test_forms.py
from django.test import TestCase
from .forms import ArticleForm, CommentFormclass ArticleFormTest(TestCase):def test_article_form_valid_data(self):"""測試表單有效數(shù)據(jù)"""form = ArticleForm(data={'title': 'Test Article','content': 'Test Content','category': 1,'status': 'draft'})self.assertTrue(form.is_valid())def test_article_form_invalid_data(self):"""測試表單無效數(shù)據(jù)"""form = ArticleForm(data={})self.assertFalse(form.is_valid())self.assertEqual(len(form.errors), 3) # title, content, category 必填def test_article_form_title_max_length(self):"""測試標(biāo)題長度限制"""form = ArticleForm(data={'title': 'x' * 201, # 超過最大長度'content': 'Test Content','category': 1})self.assertFalse(form.is_valid())self.assertIn('title', form.errors)
六、覆蓋率測試配置
6.1 安裝配置
# 安裝coverage
pip install coverage# 運(yùn)行測試并收集覆蓋率數(shù)據(jù)
coverage run manage.py test# 生成覆蓋率報(bào)告
coverage report
coverage html
6.2 配置文件
# .coveragerc
[run]
source = .
omit =*/migrations/**/tests/**/venv/*manage.py[report]
exclude_lines =pragma: no coverdef __repr__raise NotImplementedErrorif settings.DEBUGpass
七、測試流程圖
八、高級(jí)測試技巧
8.1 異步測試
from django.test import TestCase
import asyncioclass AsyncTests(TestCase):async def test_async_view(self):"""測試異步視圖"""response = await self.async_client.get('/async-view/')self.assertEqual(response.status_code, 200)async def test_async_task(self):"""測試異步任務(wù)"""result = await async_task()self.assertTrue(result)
8.2 測試fixtures
# tests/fixtures/test_data.json
[{"model": "app.category","pk": 1,"fields": {"name": "Test Category","description": "Test Description"}}
]# tests/test_with_fixtures.py
class CategoryTestCase(TestCase):fixtures = ['test_data.json']def test_category_exists(self):"""測試fixture數(shù)據(jù)加載"""category = Category.objects.get(pk=1)self.assertEqual(category.name, 'Test Category')
九、測試最佳實(shí)踐
-
測試命名規(guī)范
- 文件名以test_開頭
- 測試類以Test結(jié)尾
- 測試方法以test_開頭
-
測試組織結(jié)構(gòu)
- 按功能模塊分組
- 保持測試獨(dú)立性
- 避免測試間依賴
-
測試用例設(shè)計(jì)
- 包含邊界條件
- 考慮異常情況
- 驗(yàn)證業(yè)務(wù)規(guī)則
-
性能優(yōu)化
- 使用setUpTestData
- 合理使用事務(wù)
- 避免不必要的數(shù)據(jù)庫操作
怎么樣今天的內(nèi)容還滿意嗎?再次感謝朋友們的觀看,關(guān)注GZH:凡人的AI工具箱,回復(fù)666,送您價(jià)值199的AI大禮包。最后,祝您早日實(shí)現(xiàn)財(cái)務(wù)自由,還請(qǐng)給個(gè)贊,謝謝!