---
title: "我怎么在Google App Engine上进行敏捷开发(GAE下的unit test较好实践)"
author: "woods"
date: "2008-12-21T16:42:05Z"
tags: []
categories: ["编程语言"]
slug: "google-app-engine-gae-unit-test"
draft: false
lastmod: "2008-12-21T19:52:54Z"
id: 298270
url: "https://woods.iteye.com/blog/298270"
---

GAE上面的Unittest总结: [http://ihere.appspot.com/post/2465](http://ihere.appspot.com/post/2465 "http://ihere.appspot.com/post/2465")  
我是个推崇敏捷开发 重构 TDD 小步迭代 快速交付的 开发者,本来一直都用java来开发 , 最近迷上了python, google app engine, django  
一开始我就想python上面的敏捷开发应该是怎么样的, 那阵还真不太了解 碰了不少壁:-( 经过一段时间的总结在 现在慢慢找到python gae上面开发的套路了, 觉得这个应该是GAE上开发以及unittest的较好实践了:P  特此发文分享:-)

参考:unit-tests-for-google-app-engine-apps, gaeunit, appengine helper

首先我想直接通过django的test 来测试gae上的app, 众所周知 appengine的mode层与django完全不同 这样其实直接运行test是不可取的 通过查阅这篇文章unit-tests-for-google-app-engine-apps得知 :其实appengine 的开发sdk本身已经提供了很多api stub 来帮助我们写unit test.  其实主要的地方是在test的setup方法里面注册这些stub 以及设置必要的环境变量, 以我发的demo 做个讲解

\# coding=UTF-8  
import unittest,os,urllib  
from django.test.client import Client  
#import the stubs, i.e. the fake datastore, user and mail service and urlfetch  
from google.appengine.api import apiproxy\_stub\_map  
from google.appengine.api import datastore\_file\_stub  
#from google.appengine.api import mail\_stub  
from google.appengine.api import urlfetch\_stub  
from google.appengine.api import user\_service\_stub  
from google.appengine.api.memcache import memcache\_stub

from django.utils.encoding import force\_unicode,smart\_str  
from google.appengine.api import users  
from django.test import TestCase

from google.appengine.ext.db.djangoforms import ModelForm  
import unittest  
from django.test.client import Client  
from google.appengine.api import users  
import logging  
from models import *

#How I do gae test:-)  
#1.  
#using gaeunit: http://code.google.com/p/gaeunit/  
#and need to fix a bug of Django : Ticket #5176  
#http://code.djangoproject.com/ticket/5176

#2.  
#using appengine\_django\_helper:  
#http://code.google.com/intl/zh-CN/appengine/articles/appengine\_helper\_for\_django.html  
#http://appengineguy.com/2008/06/proper-unit-testing-of-app-enginedjango.html \[GFW blocked]  
#run from cmd: manage.py test upload  
#Here i use the 2nd way:P  
#enjoy  
class FileTest(unittest.TestCase):  
    
    def setUp(self):        
        # Start with a fresh api proxy.  
        apiproxy\_stub\_map.apiproxy = apiproxy\_stub\_map.APIProxyStubMap()

        # Use a fresh stub datastore.  
        # From this point on in the tests, all calls to the Data Store, such as get and put,  
        # will be to the temporary, in-memory datastore stub.         
        stub = datastore\_file\_stub.DatastoreFileStub(u'myTemporaryDataStorage', '/dev/null', '/dev/null')  
        apiproxy\_stub\_map.apiproxy.RegisterStub('datastore\_v3', stub)

        # Use a fresh stub UserService.  
        apiproxy\_stub\_map.apiproxy.RegisterStub('user', user\_service\_stub.UserServiceStub())  
        os.environ\['AUTH\_DOMAIN'] = 'gmail.com'  
        os.environ\['USER\_EMAIL'] = 'myself@appengineguy.com' # set to '' for no logged in user  
        os.environ\['SERVER\_NAME'] = 'testserver'  
        os.environ\['SERVER\_PORT'] = '80'  
        os.environ\['USER\_IS\_ADMIN'] = '1' #admin user 0 | 1  
        os.environ\['APPLICATION\_ID'] = 'appId'  
        
        # Use a fresh urlfetch stub.  
        apiproxy\_stub\_map.apiproxy.RegisterStub('urlfetch', urlfetch\_stub.URLFetchServiceStub())

        #User a memcache stub  
        apiproxy\_stub\_map.apiproxy.RegisterStub('memcache', memcache\_stub.MemcacheServiceStub())

        # Use a fresh mail stub. mail stub have a conflit with the other api by now in the real gae environment. so comment it.  
#        apiproxy\_stub\_map.apiproxy.RegisterStub('mail', mail\_stub.MailServiceStub())

        # Every test needs a client. using django test client  
        self.client = Client()     

...

可以看到 蓝色部分是在注册gae的api stub (想深入研究 可以看看sdk 里面的dev\_appserver.py 那里有具体的使用方法)  
注意我使用了 Django的Test Client 来模拟Http请求  使用时候需要fix个bug 改django.zip里面的文件 如果使用我得demo 的话是已经改好的:-)

接下来是个简单的test:

    def test\_add\_file(self):  
        file=open('upload/testtxt.txt')  
        
        response = self.client.post('/album/', {'file': file})  
        file.close()  
        self.failUnlessEqual(response.status\_code, 302)  
        
        returnResponse = self.client.get('/album/')  
        self.assertTrue('testtxt.txt' in returnResponse.content)  
        userFile=UserFile.all().filter("name =","testtxt.txt").get()  
        self.assertTrue(userFile is not None)

向'/album/' 发起post请求  上传一个文件  并对response进行验证.

def tearDown(self):  
        #For that we are using a temporary datastore stub located in the memory,we don't have to clean up.  
        pass

tearDown不需要做任何动作  因为最开始setup的时候 只是在内存中建立了一个临时datastore

这就是一个完整的 unit test 例子:-)

上面这个例子 在本地控制台 直接 manage test upload 可以直接运行 不需要启动gae的dev\_appserver  
但是通过一段时间的开发发现本地的sdk环境与gae的实际环境不完全相同.本机调试ok ,上传之后 ,可能在实际环境中还会有意料之外的bug:-(  有没有一种方式可以在实际的环境中进行测试呢? 老外已经看到这个了 并且有了解决方案 就是 : gaeunit    它由http ajax驱动test的执行, 大家可以看我页面sidebar左下 lab 里面有个run test 就是这个出于安全原因当然只有admin才可以执行. 下面说下怎么将django 本身的test与gae unit结合,并且不留重复code:-)  
gaeunit 执行的时候会执行所有test文件夹下的test 我的demo 中test/test\_upload.py  
中只有一句话:  
from upload.tests import FileTest

简单吧:P 而FileTest就是我们之前写的django unit test .这样集成之后这两种方式可以混用而且没有重复test code :-)  
本地开发时候可以运行 manage test upload  
而在gae 实际环境中又可以 直接在浏览器:http://yourhost/test  
来执行gae unit test  
每次看到这个都很高兴:-)