Professional Documents
Culture Documents
/usr/bin/env python
'''
GAEUnit: Google App Engine Unit Test Framework
Usage:
1. Put gaeunit.py into your application directory. Modify 'app.yaml' by
adding the following mapping below the 'handlers:' section:
- url: /test.*
script: gaeunit.py
2. Write your own test cases by extending unittest.TestCase.
3. Launch the development web server. To run all tests, point your browser to:
http://localhost:8080/test (Modify the port if necessary.)
For plain text output add '?format=plain' to the above URL.
See README.TXT for information on how to run specific tests.
4. The results are displayed as the tests are run.
Visit http://code.google.com/p/gaeunit for more information and updates.
------------------------------------------------------------------------------
Copyright (c) 2008-2009, George Lei and Steven R. Farley. All rights reserved.
Distributed under the following BSD license:
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
------------------------------------------------------------------------------
'''
__author__ = "George Lei and Steven R. Farley"
__email__ = "George.Z.Lei@Gmail.com"
__version__ = "#Revision: 1.2.8 $"[11:-2]
__copyright__= "Copyright (c) 2008-2009, George Lei and Steven R. Farley"
__license__ = "BSD"
__url__ = "http://code.google.com/p/gaeunit"
import sys
import os
import unittest
import time
import logging
import cgi
import django.utils.simplejson
from google.appengine.ext import webapp
from google.appengine.api import apiproxy_stub_map
from google.appengine.api import datastore_file_stub
from google.appengine.ext.webapp.util import run_wsgi_app
_LOCAL_TEST_DIR = 'test' # location of files
_WEB_TEST_DIR = '/test' # how you want to refer to tests on your web server
# or:
# _WEB_TEST_DIR = '/u/test'
# then in app.yaml:
# - url: /u/test.*
# script: gaeunit.py
##############################################################################
# Main request handler
##############################################################################
class MainTestPageHandler(webapp.RequestHandler):
def get(self):
unknown_args = [arg for arg in self.request.arguments()
if arg not in ("format", "package", "name")]
if len(unknown_args) > 0:
errors = []
for arg in unknown_args:
errors.append(_log_error("The request parameter '%s' is not vali
d." % arg))
self.error(404)
self.response.out.write(" ".join(errors))
return
format = self.request.get("format", "html")
if format == "html":
self._render_html()
elif format == "plain":
self._render_plain()
else:
error = _log_error("The format '%s' is not valid." % cgi.escape(form
at))
self.error(404)
self.response.out.write(error)
def _render_html(self):
suite, error = _create_suite(self.request)
if not error:
self.response.out.write(_MAIN_PAGE_CONTENT % (_test_suite_to_json(su
ite), _WEB_TEST_DIR, __version__))
else:
self.error(404)
self.response.out.write(error)
def _render_plain(self):
self.response.headers["Content-Type"] = "text/plain"
runner = unittest.TextTestRunner(self.response.out)
suite, error = _create_suite(self.request)
if not error:
self.response.out.write("====================\n" \
"GAEUnit Test Results\n" \
"====================\n\n")
_run_test_suite(runner, suite)
else:
self.error(404)
self.response.out.write(error)
##############################################################################
# JSON test classes
##############################################################################
class JsonTestResult(unittest.TestResult):
def __init__(self):
unittest.TestResult.__init__(self)
self.testNumber = 0
def render_to(self, stream):
result = {
'runs': self.testsRun,
'total': self.testNumber,
'errors': self._list(self.errors),
'failures': self._list(self.failures),
}
stream.write(django.utils.simplejson.dumps(result).replace('},', '},\n')
)
def _list(self, list):
dict = []
for test, err in list:
d = {
'desc': test.shortDescription() or str(test),
'detail': err,
}
dict.append(d)
return dict
class JsonTestRunner:
def run(self, test):
self.result = JsonTestResult()
self.result.testNumber = test.countTestCases()
startTime = time.time()
test(self.result)
stopTime = time.time()
timeTaken = stopTime - startTime
return self.result
class JsonTestRunHandler(webapp.RequestHandler):
def get(self):
self.response.headers["Content-Type"] = "text/javascript"
test_name = self.request.get("name")
_load_default_test_modules()
suite = unittest.defaultTestLoader.loadTestsFromName(test_name)
runner = JsonTestRunner()
_run_test_suite(runner, suite)
runner.result.render_to(self.response.out)
# This is not used by the HTML page, but it may be useful for other client test
runners.
class JsonTestListHandler(webapp.RequestHandler):
def get(self):
self.response.headers["Content-Type"] = "text/javascript"
suite, error = _create_suite(self.request)
if not error:
self.response.out.write(_test_suite_to_json(suite))
else:
self.error(404)
self.response.out.write(error)
##############################################################################
# Module helper functions
##############################################################################
def _create_suite(request):
package_name = request.get("package")
test_name = request.get("name")
loader = unittest.defaultTestLoader
suite = unittest.TestSuite()
error = None
try:
if not package_name and not test_name:
modules = _load_default_test_modules()
for module in modules:
suite.addTest(loader.loadTestsFromModule(module))
elif test_name:
_load_default_test_modules()
suite.addTest(loader.loadTestsFromName(test_name))
elif package_name:
package = reload(__import__(package_name))
module_names = package.__all__
for module_name in module_names:
suite.addTest(loader.loadTestsFromName('%s.%s' % (package_na
me, module_name)))
if suite.countTestCases() == 0:
raise Exception("'%s' is not found or does not contain any tests." %
\
(test_name or package_name or 'local directory: \"%s
\"' % _LOCAL_TEST_DIR))
except Exception, e:
error = str(e)
_log_error(error)
return (suite, error)
def _load_default_test_modules():
if not _LOCAL_TEST_DIR in sys.path:
sys.path.append(_LOCAL_TEST_DIR)
module_names = [mf[0:-3] for mf in os.listdir(_LOCAL_TEST_DIR) if mf.endswit
h(".py")]
return [reload(__import__(name)) for name in module_names]
def _test_suite_to_json(suite):
tests = []
_get_tests_from_suite(suite, tests)
test_tuples = [(type(test).__module__, type(test).__name__, test._testMethod
Name) \
for test in tests]
test_dict = {}
for test_tuple in test_tuples:
module_name, class_name, method_name = test_tuple
if module_name not in test_dict:
mod_dict = {}
method_list = []
method_list.append(method_name)
mod_dict[class_name] = method_list
test_dict[module_name] = mod_dict
else:
mod_dict = test_dict[module_name]
if class_name not in mod_dict:
method_list = []
method_list.append(method_name)
mod_dict[class_name] = method_list
else:
method_list = mod_dict[class_name]
method_list.append(method_name)
return django.utils.simplejson.dumps(test_dict)
def _log_error(s):
logging.warn(s)
return s
################################################
# Browser HTML, CSS, and Javascript
################################################
##############################################################################
# Script setup and execution
##############################################################################