django中的view測試和models測試樣例
阿新 • • 發佈:2018-12-05
感覺用model_mommy比factory_boy要好些。
如果Models.py如下:
from django.db import models from django.contrib.auth.models import User # Create your models here. class Board(models.Model): name = models.CharField(max_length=30, unique=True) description = models.CharField(max_length=100)def __str__(self): return self.name class Topic(models.Model): subject = models.CharField(max_length=255) last_updated = models.DateTimeField(auto_now_add=True) board = models.ForeignKey(Board, related_name='topics', on_delete=models.CASCADE) started = models.ForeignKey(User, related_name='topics', on_delete=models.CASCADE) def __str__(self): return self.subject class Post(models.Model): message = models.TextField(max_length=4000) topic = models.ForeignKey(Topic, related_name='posts', on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) updated_at= models.DateTimeField(null=True) created_by = models.ForeignKey(User, related_name='posts', on_delete=models.CASCADE) updated_by = models.ForeignKey(User, null=True, related_name='+', on_delete=models.CASCADE) def __str__(self): return self.message
則單元測試如下:
from django.test import TestCase from django.urls import resolve, reverse from boards.views import home from model_mommy import mommy from boards.models import Board, Topic, Post # Create your tests here. class HomeTests(TestCase): def test_home_view_status_code(self): url = reverse('home') response = self.client.get(url) self.assertEqual(response.status_code, 200) def test_home_url_resolves_home_view(self): view = resolve('/') self.assertEqual(view.func, home) class BoardTestMommy(TestCase): def test_board_creation_mommy(self): board = mommy.make(Board) self.assertTrue(isinstance(board, Board)) self.assertEqual(board.__str__(), board.name) class TopicTestMommy(TestCase): def test_topic_creation_mommy(self): new_toipic = mommy.make('boards.Topic') self.assertTrue(isinstance(new_toipic, Topic)) self.assertEqual(new_toipic.__str__(), new_toipic.subject) class PostTestMommy(TestCase): def test_topic_creation_mommy(self): new_post = mommy.make('boards.Post') self.assertTrue(isinstance(new_post, Post)) self.assertEqual(new_post.__str__(), new_post.message)