def test_multichoice_filter(self): head("# 准备测试multichoice filter") head1("## 过滤CharField") models.TestFilter.objects.create(_type="类型1") fenlei1 = models.BasicModel.objects.create(text="分类1") fenlei2 = models.BasicModel.objects.create(text="分类2") fenlei3 = models.BasicModel.objects.create(text="分类3") instance1 = models.TestFilter.objects.create(_type="类型1") instance2 = models.TestFilter.objects.create(_type="类型2") instance3 = models.TestFilter.objects.create(_type="类型3") instance1.basic_model.add(fenlei1) instance2.basic_model.add(fenlei2) instance3.basic_model.add(fenlei3) client = Client() info("找到类型1和类型2的") response = client.get("/testapp/testfilter/?_type=类型1&_type=类型2", headers={"accept": "application/json"}) info(response.data) head1("## 过滤ManyToManyField") response = client.get( "/testapp/testfilter/?basic_model=1&basic_model=2", headers={"accept": "application/json"}) info(response.data) response = client.get( "/testapp/testfilter/?basic_model=1&basic_model=3", headers={"accept": "application/json"}) info(response.data)
def test_limit_nested_serializer(self): head("# 准备测试nest的字段,能否限制数量") # python3 manage.py test # testapp.testserializer.MySerializerTestCase.test_limit_nested_serializer text1 = BasicModel.objects.create(text="text1") text2 = BasicModel.objects.create(text="text2") text3 = BasicModel.objects.create(text="text3") filt1 = ManyModel.objects.create() filt1.texts.add(text1) filt1.texts.add(text2) filt1.texts.add(text3) info(serializers.TestLimitSerializer(filt1).data) info("实现不了, 直接用SerializerMethodField吧")
def test_viewset_post(self): head("# 准备测试ViewSet的post请求") head1("## 看看post调用的是create还是post") info("如果是post请求,调用的是create函数") response = client.post( "/testapp/testfilter/?format=json", headers={"accept": "application/json"}, json={ "_type": "类型1" } ) info(f"服务器返回的状态码: {response.status_code}") info(f"服务器返回的状态码: {response.content.decode('UTF-8')}")
def test_id(self): head("准备测试id这个field") list1("* 测试create的时候带id") data = {"id": 2, "text": "文字"} info("data: {}".format(data)) serializer = serializers.TestIdSerializer(data=data) serializer.is_valid(raise_exception=True) serializer.save() info("serializer.data: {}".format(serializer.data)) info("如果create的时候带了id参数, validated_data会是不存在id, 并且save的时候id会自动修改") list1("* 测试patch的时候带id") instance = serializer.instance data2 = {"id": 4, "text": "文字2"} info("data: {}".format(data)) serializer = serializers.TestIdSerializer(instance, data=data) serializer.is_valid(raise_exception=True) info("serializer.validated_data: {}".format(serializer.validated_data)) serializer.save() info("serializer.data: {}".format(serializer.data)) info("如果put的时候带了id参数, validated_data也会过滤掉这个id")
def test_source(self): head("准备测试source这个参数") list1("* 测试如果外键为None, 这个field必须设置default, 不然会报错") basicmodel = BasicModel.objects.create(text='text') fkm = ForeignKeyModel2.objects.create() info("数据创建成功") info(serializers.TestSourceSerializer(fkm).data) info("可以看到显示的是None") list1("* 测试如果save, 会发生什么, 他的数据竟然是 {'text': 'text'}, 不是简单的text") list2(" 1. 如果instance的外键为None") testsource_ser = serializers.TestSourceSerializer( instance=fkm, data={"text": "text"}) testsource_ser.is_valid(raise_exception=True) testsource_ser.save() list2(" 2. 如果instance的外键不是None, 仍然是 {'text': 'text'}") fkm.text = basicmodel fkm.save() testsource_ser = serializers.TestSourceSerializer( instance=fkm, data={"text": "text"}) testsource_ser.is_valid(raise_exception=True) testsource_ser.save()
# Xiang Wang @ 2018-09-19 11:27:49 from __future__ import unicode_literals import json import sys from django.test import TestCase from django.core.management.base import OutputWrapper from django.core.management.color import color_style from testapp.models import * from testapp.serializers import * from testapp import head, head1, list1, list2, success, info head("# 准备测试models") class ModelTest(TestCase): def test_unique(self): info("准备测试unique") # TestUniqueModel.objects.create(text1='') # TestUniqueModel.objects.create(text1='') # 报错,重复 print(TestUniqueModel.objects.create( text1='', text2='', ).text3) print(TestUniqueModel.objects.create(text1='er', text2='text2').text4) # 报错,重复 def test_decimal(self):
import json import time import sys from django.core.management.base import OutputWrapper from django.core.management.color import color_style from django.test import TestCase from django.utils import timezone from testapp import head, head1, list1, list2, info, success from .models import * from . import serializers out = OutputWrapper(sys.stdout) style = color_style() head("# 测试rest-framework的Serializer") class MySerializerTestCase(TestCase): def setUp(self): pass def test_local(self): return # 别测了. 有bug. 如果你设置user_tz=False, 你就别用timezone参数啊 head1("\n## 测试使用local是的timezone") data = {'time': '2020-06-10T03:45:13.026Z'} # 当作本地时间的 serializer = serializers.LocalModelSerializer(data=data) import ipdb ipdb.set_trace() serializer.is_valid(raise_exception=True)
#!/usr/bin/env python3 # -*- coding: UTF-8 -*- # Xiang Wang @ 2019-07-26 16:23:06 from django.test import Client from django.test import TestCase from rest_framework.test import APIClient from testapp import head, head1, list1, list2, info from testapp import models head("# 准备测试paginator") client = Client() apiclient = APIClient() class PaginatorTest(TestCase): def test_paginator(self): head1("## 准备测试paginator的函数") res = apiclient.get("/testapp/paginator/", format="json")
#!/usr/bin/env python3 # -*- coding: UTF-8 -*- # Xiang Wang @ 2019-10-10 15:57:49 from django.test import TestCase, Client from django.contrib.auth import get_user_model from rest_framework.test import APIClient from rest_framework.authtoken.models import Token from testapp import head, head1, list1, list2, info head("# 准备测试用户认证模块2") User = get_user_model() class AuthTestCase(TestCase): def setUp(self): self.user1 = User.objects.create_user(username="******", password="******") self.user2 = User.objects.create_user(username="******", password="******") def test_auth_views(self): head1("## 准备测试使用auth的view进行登录") client = APIClient() response = client.post( "/account/login/", data={ "username": "******", "password": "******" }, format="json", )
#!/usr/bin/env python3 # -*- coding: UTF-8 -*- # Xiang Wang @ 2019-03-28 16:48:33 from django.test import Client from django.test import TestCase from rest_framework.test import APIClient from testapp import head, head1, list1, list2, info from testapp import models head("# 准备测试viewset") client = Client() apiclient = APIClient() class ViewSetFilter(TestCase): def test_viewset_post(self): head("# 准备测试ViewSet的post请求") head1("## 看看post调用的是create还是post") info("如果是post请求,调用的是create函数") response = client.post( "/testapp/testfilter/?format=json", headers={"accept": "application/json"}, json={ "_type": "类型1" }
from django.utils import timezone out = OutputWrapper(sys.stdout) style = color_style() class ColorfulLog(object): def info(self, text): out.write(style.HTTP_INFO(text)) def log(self, text): out.write(style.HTTP_SUCCESS(text)) log = ColorfulLog() head("# 准备测试queryset") class DateTimeTestCase(TestCase): def setUp(self): head1("## 准备测试时间的过滤和排序") self.test_date_list = [ "2018-05-20T23:59:59+08:00", # 2018-05-20T15:59:59+00:00" "2018-05-21T00:00:00+08:00", # 2018-05-20T16:00:00+00:00" "2018-05-21T23:59:59+08:00", # 2018-05-21T15:59:59+00:00 "2018-05-22T00:00:00+08:00", # 2018-05-21T16:00:00+00:00 "2018-05-22T00:00:00+00:00", # 2018-05-22T00:00:00+00:00 "2018-05-22T23:00:00+08:00", # 2018-05-22T15:00:00+00:00 ] for date in self.test_date_list: datetime_obj = DateTimeModel.objects.create(time=date)
def setUp(self): head("# 准备测试缓存") pass
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Xiang Wang @ 2018-12-20 17:17:18 import time from django.test import TestCase, Client from testapp import head, head1, list1, list2, info from testapp import service head("# 准备测试缓存") class CacheTestCase(TestCase): def setUp(self): head("# 准备测试缓存") pass def test_cache_control(self): head1("## 准备测试cache_control") info("不可以使用cache_control来缓存函数") start = time.time() service.slow_function(3) end = time.time() info("第一次执行`slow_function`的时间: {}".format(end - start)) start = time.time() service.slow_function(3) end = time.time() info("第二次执行`slow_function`的时间: {}".format(end - start))
#!/usr/bin/env python3 # -*- coding: UTF-8 -*- # Xiang Wang @ 2019-04-10 11:57:08 from django.test import Client from django.test import TestCase from testapp import head, head1, list1, list2, info head("# 准备测试和urls有关的接口") class ViewSetFilter(TestCase): def test_path(self): head1("\n## 测试使用path") list1("* 测试如果是int的converter遇到") client = Client() info("使用负数传入就不支持了") response = client.get("/testapp/testint/1/") self.assertEqual(response.resolver_match.kwargs, {"pk": 1}) response = client.get("/testapp/testint/-1/") self.assertEqual(response.status_code, 200)
from datetime import timedelta import pytz from django.core.management.base import OutputWrapper from django.core.management.color import color_style from django.test import TestCase from testapp import models from testapp.models import DateTimeModel, Student, Teacher from testapp import models, head, head1, list1, list2, info from django.utils import timezone out = OutputWrapper(sys.stdout) style = color_style() head("# 准备测试Field") class FieldTestCase(TestCase): def setUp(self): pass def test_onetoone_field(self): head1("\n## 测试OneToOneField") text = models.BasicModel.objects.create(text="text") onetoone = models.TestOneToOneField.objects.create(text=text) text.delete() # CASCADE null=False|True, 此时可以用text.testonetoonefield 但是调用 text.testonetoonefield.refresh_from_db 就会报错 out.write(style.HTTP_INFO("text已经删除")) out.write(style.HTTP_INFO(models.TestOneToOneField.objects.all()))
def test_viewset_permission(self): head("# 准备测试ViewSet的permission") head1("## 看看detail的请求时候,permission里面有没有action") obj = models.BasicModel.objects.create(text="类型1") res = apiclient.get( "/testapp/modelviewset/{}/".format(obj.id), format="json")
#!/usr/bin/env python3 # -*- coding: UTF-8 -*- # Xiang Wang @ 2019-04-08 10:59:59 from django.test import TestCase, Client from django.contrib.auth import get_user_model from testapp import head, head1, list1, list2, info head("# 准备测试用户认证模块1") User = get_user_model() class AuthTestCase(TestCase): def setUp(self): self.user = User.objects.create_user(username='******', password='******') def test_user_modal(self): head1("## 准备测试用户model") list1("* 测试model的fields username") user = User.objects.create() info("直接创建用户成功") info("用户的username为空字符串") self.assertEqual(user.username, "") def test_auth_views(self): head1("## 准备测试使用auth的view进行登录") client = Client() response = client.post( "/api-auth/login/",
#!/usr/bin/env python3 # -*- coding: UTF-8 -*- # Xiang Wang @ 2019-03-15 15:23:12 import ipdb from django.test import TestCase, Client from testapp import head, head1, list1, list2, info head("# 准备测试template") class TemplateTestCase(TestCase): def test_template(self): head1("\n## 测试模板") list1("* 测试不同的url,的参数的传递") client = Client() info("通过request.resolver_match.kwargs可以获取到url里面额外的参数") response = client.get("/testapp/url/") self.assertEqual(response.template_name, ["testapp/测试模板.html"]) info("根据这个参数来判断要使用admin的template还是普通的template") response2 = client.get("/testapp/url2/") self.assertEqual(response2.template_name, ["testapp/测试模板_admin.html"])