Django基于模拟浏览器的测试用例编写、python-slugify、django-taggit

《Django高级实战-开发企业及问答网站》学习笔记6:使用django.test.Client编写模拟浏览器访问的测试用例,实用库python-slugify(url别名)、django-taggit(标签管理)​学习。
227阅读 · 2020-7-24 23:10发布

模拟浏览器调用的测试用例

  • 视图代码的测试用例,除了前面讲过的django.test.RequestFactory,也可以使用dajngo.test.Client模拟浏览器的请求方式走整个django响应流程。
  • django.test中的Client类,用于模仿浏览器http请求。示例代码:
    from django.test import Client
      # 创建客户端
      self.client = Clist()
    
  • 代码示例:

    from django.test import client
      from django.urls import reverse
      from test_plus.test import TestCase
    
      from .models import News
    
      class NewsViewsTest(TestCase):
    
          def setUp(self):
              self.other_client = Client()
              # 用户登录
              self.client.login(username="user01",password="password")
              self.other_client.login(username="user02",password="password")
              self.first_news = News.objects.create(
                  user=self.user,
                  content="第一条记录"
              )
              self.second_news = News.objects.create(
                  user=self.user,
                  content="第二条记录"
              )
              self.third_news = News.objects.create(
                  user=self.other_user,
                  content="第二条记录",
                  reply=True,
                  parent=self.first_news
              )
    
          def test_news_list(self):
              """测试列表页功能"""
              response self.client.get(reverse("news:list"))
              assert response.status_code == 200
              assert self.first_news in response.context["news_list"]
              assert self.second_news in response.context["news_list"]
              assert self.thrid_news not in response.context["news_list"]
    
          def test_delete_news(self):
              """删除动态"""
              initial_count = News.objects.count()
              response = self.client.post(reverse("news:delete_news",kwargs={"pk":self.second_news.pk} ))
              assert response.status_code = 302
              assert News.objects.count() == initial_count - 1
    
          def test_post_new(self):
              initial_count = News.objects.count()
              response = self.client.post(
                  reverse("news:post_news"),{"post":"内容文字"},
                  HTTP_X_REQUESTED_WITH="XMLHttpRequest" # 表示发送ajax请求
              )
              assert response.status_code == 200
              assert News.objects.count() == initial_count + 1
    
          def test_like_news(self):
              response = self.client.post(
                  reverse("news:like_post"),{"news":self.first_news.pk},
                  HTTP_X_REQUESTED_WITH="XMLHttpRequest"
              )
              assert response.status_code == 200
              assert self.first_news_count_likers() == 1
              assert self.user in self.first_news.get_likers()
              assert response.json()["likes"] == 1  # 从ajax请求的返回值中取值
    

django第三方实用库

python-slugify生成url别名

  • slugify是指可以根据一段标题,生成一个符合标题内容的拼音字符串(通常被称为url的别名)。
  • uuslug,用于生成一串uuid的url别名。
  • slugify的使用:
    from slugify import slugify
      text = "这里是标题内容"
      print(slugify(text))
      # 输出zhe-li-shi-biao-ti-nei-rong
    
  • 在models.py中集成slugify:

    # models.py
      # 重写模型中save方法即可
    
      class Article(models.Model):
          ...省略...
    
          def save(self, force_insert=False, force_update=False, using=None, update_fields=None):
              self.slug = slugify(self.title)
              super().save()
    

django-taggit标签tag管理

  • django-taggit用于管理标签。
  • 在models.py中集成django-taggit:

    from taggit.managers import TaggableManager
    
      class Article(models.Model):
          ...省略...
          tags = TaggableManager(help_text="多个标签使用英文逗号隔开",verbose_name="标签")
    
    # setting.py中添加taggit应用
      THIRD_PARTY_APPS = [
          ...省略...
          'taggit',
      ]