python django TDD实现一个带简单注册的记事本例子
Posted bigsmart
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python django TDD实现一个带简单注册的记事本例子相关的知识,希望对你有一定的参考价值。
1.新建 django应用 NotPad
2.新建项目 note
3.新建功能测试
mkdir function_test
touch function_test/ __init__.py
在 /function_test下新建tests.py
功能测试 /function_test/tests.py代码
from selenium import webdriver from selenium.webdriver.common.keys import Keys import time from django.test import LiveServerTestCase from selenium.common.exceptions import WebDriverException class Myunittest(LiveServerTestCase): def setUp(self):#测试开始前运行 self.browser=webdriver.Firefox() def tearDown(self):#测试开始后运行 self.browser.quit() def test_correct_satrt_correct_return(self):#测试首页输入后跳转,增加事例,不同用户操作是否正常 #测试首页提交post后的提交是否正常 self.browser.get(self.live_server_url) self.assertIn("Notepad Rigister", self.browser.title) # 断言 header_text = self.browser.find_element_by_tag_name(‘h1‘).text self.assertIn(‘User Notepad‘, header_text) input = self.browser.find_element_by_id("id_input_name") self.assertEqual( input.get_attribute(‘placeholder‘), # 获取属性里的值 ‘Enter name‘ ) input.send_keys(‘cmy1‘) # 填入文本框 input.send_keys(Keys.ENTER) # 回车 time.sleep(10) self.wait_for_first_to_second(‘cmy1‘) women_lists_url = self.browser.current_url#测试重定向后的url self.assertRegex(women_lists_url, "/note/cmy1") #self.fail("Finish test1") # 提前结束测试,测试首页跳转成功 #测试存储事例是否成功 input = self.browser.find_element_by_id("id_input_item") self.assertEqual( input.get_attribute(‘placeholder‘), # 获取属性里的值 ‘Enter a new item‘ ) input.send_keys(‘women‘) # 填入文本框 input.send_keys(Keys.ENTER) # 回车 self.wait_for_row_in_list_table(‘1:women‘) #self.fail("Finish test2") # 提前结束测试,测试用户增加事例成功 #测试第二个用户访问有没有第一个用户留下的痕迹 self.browser.quit() self.browser = webdriver.Firefox() self.browser.get(self.live_server_url) input = self.browser.find_element_by_id("id_input_name") self.assertEqual( input.get_attribute(‘placeholder‘), # 获取属性里的值 ‘Enter name‘ ) input.send_keys(‘cmy2‘) # 填入文本框 input.send_keys(Keys.ENTER) # 回车 self.wait_for_first_to_second(‘cmy2‘) page_text = self.browser.find_element_by_tag_name(‘body‘).text self.assertNotIn(page_text, ‘women‘)#上一个用户的操作是否留下痕迹 women_lists_url = self.browser.current_url # 测试重定向后的url self.assertRegex(women_lists_url, "/note/cmy2") #self.fail("Finish test3") # 提前结束测试,测试不同用户操作不同显示成功 def wait_for_first_to_second(self, row_text):#等待首页跳转 start_time = time.time() max_wait = 5 while True: try: # 第一个出口测试成功 windows = self.browser.window_handles self.browser.switch_to.window(windows[-1]) # 获取窗口句柄 name = self.browser.find_element_by_tag_name(‘h1‘).text self.assertEqual(row_text,name) return except(AssertionError, WebDriverException) as e: if time.time() - start_time > max_wait: # 第二个出口测试失败,返回失败原因 raise e time.sleep(0.5) def wait_for_row_in_list_table(self, row_text):#等待添加事例 start_time = time.time() max_wait = 5 while True: try: # 第一个出口测试成功 table = self.browser.find_element_by_id(‘id_list_table‘) rows = table.find_elements_by_tag_name(‘tr‘) self.assertIn(row_text, [row.text for row in rows]) return except(AssertionError, WebDriverException) as e: if time.time() - start_time > max_wait: # 第二个出口测试失败,返回失败原因 raise e time.sleep(0.5)
单元测试 /note/tests.py代码
from django.test import TestCase from django.urls import resolve from note.views import home_page from note.models import Name,Item class liveViewTest(TestCase): def test_first_returns_correct_html(self):#测试首页模板 respose = self.client.get(‘/‘) self.assertTemplateUsed(respose, ‘home.html‘) # 检测响应是用哪个模板渲染的 def test_can_Skip_a_POST_request(self): # 测试首页post请求响应是否跳转到相应界面 response = self.client.post(‘/‘, data={‘name_text‘: ‘cmy‘}) self.assertRedirects(response, ‘/note/cmy‘) # 测试重定向 def test_can_saved_first_post(self):#测试首页填的数据是否正确填入数据库 response = self.client.post(‘/‘, data={‘name_text‘: ‘cmy‘}) new_name=Name.objects.first() self.assertEqual(new_name.name,‘cmy‘) response = self.client.post(‘/‘, data={‘name_text‘: ‘cmy‘})#测试输入同样的名字会不会保存到数据库 name_list=Name.objects.all() self.assertEqual(name_list.count(),1) def test_note_returns_correct_html(self):#测试note模板 Name.objects.create(name=‘cmy‘) respose = self.client.get(‘/note/cmy‘) self.assertTemplateUsed(respose, ‘node.html‘) # 检测响应是用哪个模板渲染的 def test_second_returns_correct_html(self): # 测试url参数是否传入视图模板,以及正确反应 Name.objects.create(name=‘cmy‘) respose = self.client.get(‘/note/cmy‘)#访问创建好名字的node模板 self.assertIn(‘cmy‘, respose.content.decode()) respose = self.client.get(‘/note/cmy1‘) # 访问没有创建好名字的node模板 self.assertNotIn(‘cmy1‘, respose.content.decode()) self.assertRedirects(respose, ‘/‘) def test_second_saved_post(self):#测试note页端的存储情况 Name.objects.create(name=‘cmy‘) response = self.client.post(‘/note/cmy‘, data={‘list_text‘: ‘test1‘}) self.assertEqual(Item.objects.count(), 1) # 测试在前端填写的有没有正确的填入数据库 new_item = Item.objects.first() self.assertEqual(‘test1‘, new_item.text) def test_Item_display_correct(self):#测试访问item是否正常显示 Name.objects.create(name=‘cmy‘) respose = self.client.get(‘/note/cmy‘)#没有存储事例前访问 self.assertNotIn(‘1:test1‘, respose.content.decode()) response = self.client.post(‘/note/cmy‘, data={‘list_text‘: ‘test1‘}) self.assertIn(‘1:test1‘, response.content.decode())#存储完,POST请求 respose = self.client.get(‘/note/cmy‘)#存储完 GET请求 self.assertIn(‘1:test1‘, respose.content.decode()) class TestModel(TestCase): # 测试数据库 def test_saving_and_retrieving_items(self): # 测试数据库是否正常存储 input_name=‘cmy‘ saved_Name = Name.objects.create(name=input_name) Item.objects.create(name=saved_Name,text=‘test1‘) Item.objects.create(name=saved_Name, text=‘test2‘) item=saved_Name.item_set.all first_saved=item[0] second_saved=item[2] self.assertEqual(first_saved.text, ‘test1‘) # 测试Item保存数据是否成功 self.assertEqual(second_saved.text, ‘test2‘) saved_Name_list = Name.objects.first()#测试Name表第一个保存的数据是否成功 self.assertEqual(saved_Name, saved_Name_list) # Create your tests here.
数据库模型代码 /note/models.py:
from django.db import models class Name(models.Model): name = models.TextField(default=‘‘) class Item(models.Model): text = models.TextField(default=‘‘) name = models.ForeignKey(Name,on_delete=models.CASCADE,default=None) # Create your models here.
数据库迁移 python manage.py makemigrations
生成数据库 python manage.py migrate
前端模型代码:
1. /templates/home.html (注册页面):
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Notepad Rigister</title> </head> <body> <h1>User Notepad</h1> <form method="post" > <input name="name_text" id="id_input_name" placeholder="Enter name"/> {% csrf_token %} </form> </body> </html>
2./templates/note.html(记事本页面)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>items</title> </head> <body> <h1>{{name}}</h1> <form method="post" action="/note/{{list.name}}"> <input name="list_text" id="id_input_item" placeholder="Enter a new item"/> {% csrf_token %} </form> <table id ="id_list_table"> {% for item in list.item_set.all %} <tr> <td>{{ forloop.counter}}:{{ item.text }}</td> </tr> {% endfor %} </table> </body> </html>
/note/view.py视图代码:
from django.http import HttpResponse from django.shortcuts import render,redirect from note.models import Item,Name def home_page(request): if request.POST: name_input = request.POST[‘name_text‘] saved_Name_list=Name.objects.all() f=1 for Name_list in saved_Name_list: if name_input==Name_list.name: f=-1 break if f==1: Name.objects.create(name=name_input) return redirect(‘/note/‘+name_input) return render(request, ‘home.html‘) def first_skip(request,list_name): #视图接受url参数 data={} saved_Name_list = Name.objects.all() for _Name in saved_Name_list: if _Name.name==list_name: data["name"] = list_name break if len(data)==0: return redirect(‘/‘) else: saved_Name = Name.objects.get(name=data[‘name‘]) data[‘list‘]=saved_Name if request.POST: item_input=request.POST[‘list_text‘] Item.objects.create(name=saved_Name,text=item_input) return render(request, ‘node.html‘, data) return render(request, ‘node.html‘,data) # Create your views here.
/NotePad/urls.py
from django.conf.urls import url from note import views urlpatterns=[ url(r‘^$‘,views.home_page,name=‘home‘), url(r‘^note/(.+)‘,views.first_skip,name=‘first_skip‘) ]
总体实现访问首页输入名字注册,回车进入记事本页面,下次访问输入名字即可,访问没有注册名字的页面跳转到注册页面,url由注册名字构成
项目下载:https://github.com/smartfish007/githubtest
以上是关于python django TDD实现一个带简单注册的记事本例子的主要内容,如果未能解决你的问题,请参考以下文章
Python之路第十八篇Django小项目简单BBS论坛部分内容知识点
Python之路第十八篇Django小项目简单BBS论坛部分内容知识点