论坛首页 综合技术版 python

一个django测试的例子----验证登录时id不存在的情况

浏览 2879 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
最后更新时间:2007-07-24 关键字: django,test,python,测试,form

        今天盯着代码看了一下午,通过django官方的测试源代码,解决了一个难我一天的问题。哈哈,生怕忘记,赶紧志之。

情形描述:

    我已经有了登录的代码:

def login(request):
    if request.method=='POST':
        form = LoginForm(request.POST)
        if form.is_valid():
            try:
                m = User.objects.get(id=request.POST['id'])
            except ObjectDoesNotExist:
                return HttpResponse("There is no the id")
            if m.password == request.POST['password']:
                request.session['id'] = m.id
                return HttpResponseRedirect('/accounts/loginok')
            else:
                return HttpResponse("Your username and password didn't match.")
           
    else:
        form = LoginForm()
    return render_to_response('accounts/login.html',{'form':form})

现在我想测试当我的id不存在时会否显示  'There is no the id'

那么我的思路是:先client().post到这个登录地址,然后传入错误的字典数据迫使它返回There is no the id,在然后用self.assertContains去判断放回的response是否包含"There is no the id".

而让我为难的问题就是如何迫使网页返回There is no the id!

我起初先写了如下代码:

class testLogin(TestCase):
    def setUp(self):
        self.client = Client()
        User.objects.create(id='test1',password='testtest',email='test1@test.com')
        User.objects.create(id='test2',password='testtest',email='test2@test.com')
    def testNoID(self):
        user = {'id':'test','password':'test'}
        form = LoginForm(user)   
        response = self.client.post('/accounts/',{'form':form})

        .......................
     def tearDown(self):
        pass

.......................代表要添加代码的地方,而不是俺写了代码在此省略;)

上面代码的testNoID函数中模拟了错误的id并发送请求到了登录页面。如果你此时print response ,就会发现response里是你的<form></form>代码。那如何继续让程序提交这些数据进而得到包含“There is no the id” 的response呢?

我刚开始以为这个form或response有手动提交数据的函数,可找了半天,form有--isvalid。可我form提交过并没有返回我想要的东西(当然,也可能因为俺英文次,官方文档的一些东西没看明白----事实上,这种情况时有发生)。

然后就开始漫长的试图在官方文档和django自带的源码中寻找蛛丝马迹的旅程。当我快要放弃的时候,一段代码引起了我的注意(当然,这段代码我已经看了好多遍了,只是之前没有引起足够的重视而起):

def test_valid_form_with_hints(self):
        "GET a form, providing hints in the GET data"
        hints = {
            'text': 'Hello World',
            'multi': ('b','c','e')
        }
        response = self.client.get('/test_client/form_view/', data=hints)
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, "Form GET Template")
        # Check that the multi-value data has been rolled out ok
        self.assertContains(response, 'Select a valid choice.', 0)

这段代码位于"D:\django\tests\modeltests\test_client\models.py"中:然后我就有了如下代码----顺利达到目的:

class testLogin(TestCase):
    def setUp(self):
        self.client = Client()
        User.objects.create(id='test1',password='testtest',email='test1@test.com')
        User.objects.create(id='test2',password='testtest',email='test2@test.com')
    def testNoID(self):
        user = {'id':'test','password':'test'}
        response = self.client.post('/accounts/',user)
        print response
        self.assertContains(response, 'There is no the id')
    def tearDown(self):
        pass

注意加红部分!看来缺乏对django深入的认识真的让人进度缓慢啊

   
最后更新时间:2007-08-02
呵呵,前两天发现Django有自己的登录方法,所以哪位小哥看了上面文章千万别按照上面测试的思路去写登录代码。用Django的方法写非常简单的。
   
0 请登录后投票
最后更新时间:2007-08-02
还有,tearDown()是起清除作用,我用pass纯粹省事,实际中,你如果不写tearDown的具体实现,Django很可能会通知你一些错误----比如 告诉你 类似于数据字段应该是唯一的之类的咚咚...
   
0 请登录后投票
最后更新时间:2007-11-06
如何让Password显示为password而不是text呢
   
0 请登录后投票
最后更新时间:2007-11-16
password = forms.CharField(widget=forms.PasswordInput(), min_length=6, max_length=12, label='Password*')
   
0 请登录后投票
最后更新时间:2007-12-17
请问如何在测试时模拟session
   
0 请登录后投票
最后更新时间:2008-01-04
我不太明白你的意思...
如果你是指给session写入登录的user这种情况的话,你只需要
c = Client()
c.login(username='fred', password='secret')

(摘自Django 文档)
Django已经帮你写入了相关信息...

或者你在view中写入session,然后post/get到这个url,就达到session的目的了...
   
0 请登录后投票
论坛首页 综合技术版 python

跳转论坛:
JavaEye推荐