因目前业务还跑在Pylons上,因此就拿Pylons来做这个例子吧。其他Python环境应该也是大同小异的。
CI系统环境:
OS: Ubuntu
CI 工具: Hudson 1.396
单元测试工具: nosetests
Hudson 本身的安装使用就不细写了,网上现在已经有很多了。直接下载war包,用java -jar运行即可。
启动之后,在管理界面中安装 Hudson Cobertura plugin、Python Plugin、Hudson Violations plugin、Subversion Plugin等插件即可。
一、建立虚拟环境
为了使Hudson同时支持多个python项目的持续集成,建议为每一个项目建立独立的虚拟环境,以便更清楚与项目相关联的包的情况,方便今后的部署。
下面几个步骤即可建立一个基本的虚拟环境。
1. 找到virtualenv包,取出其中的virtualenv.py
2. 运行python virtualenv.py --no-site-packages pylons-0.9.7 建立一个名字叫pylons-0.9.7的虚拟环境。这里 --no-site-packages参数是为了排除linux系统自带的python包对项目的影响,加了这个参数即可建立比较干净的Python虚拟环境。
3. 启动刚才建立的虚拟环境 source pylons-0.9.7/bin/activate
4. 运行easy_install nose 安装nosetests单元测试工具
5. 运行easy_install fudge 安装fudge Mock工具
6. 运行easy_install nosexcover 安装覆盖率生成工具,这个工具可以生成hudson中需要的xml格式的报表。仅仅安装coverage包不能生成类似报表。
二、建立项目运行环境
现在一个基本的环境已经基本建立完成了。下面在安装一些该项目特定的包
1. 安装mysql python包、sqlalchemy包
sudo apt-get install libmysqlclient-dev (MySQL-python编译安装需要mysql client开发环境)
easy_install MySQL-python
easy_install "sqlalchemy==0.5.8"
2. 安装pylons
easy_install -Z "pylons==0.9.7"
在pylons-0.9.7/lib/python26/site-packages/WebOb-1.1beta1-py2.6.egg/webob/__init__.py中加入一行from webob.multidict import UnicodeMultiDict
(pylons下载了最新的webob,里面有些改动,pylons 0.9.7不支持,需要改下)
3. 再按装写杂七杂八的项目用到的包
easy_install pycrypto
easy_install recaptcha_client
easy_install python-memcached
好了,一个pylons虚拟环境基本完成了,可以先直接下载项目代码运行nosetests看看有没有什么问题,如果运行都正常,即可进行以下步骤
三、建立Hudsong项目
1. 在Hudson中新建一个任务,选择“构建一个自由风格的软件项目“
2. 输入代码地址(SVN/CVS...)
3. 按照crontab规则建立build规律
4. 选择shell脚本作为build命令,在里面输入如下内容:
. /home/mm/pylons-0.9.7/bin/activate
cd ${WORKSPACE}
nosetests --cover-package=包名 --cover-tests --with-xcoverage --with-xunit --verbose
注:这里报名替换成需要测试覆盖率的包名
5. 设置输出报表
Publish JUnit test result report
xml文件直接输入 nosetests.xml
Publish Cobertura Coverage Report
xml文件直接输入 coverage.xml
Showing posts with label pylons. Show all posts
Showing posts with label pylons. Show all posts
Wednesday, August 10, 2011
Friday, April 1, 2011
other thread pool options used in pylons configuration
[server:main]
use = egg:Paste#http
host = 127.0.0.1:8081
# These options make it easier to trigger the thread pool catches
# (i.e., threads are hung fast, killed fast, spawn fast, and the
# whole process dies quickly due to zombies)
threadpool_workers = 3
threadpool_hung_thread_limit = 10
threadpool_kill_thread_limit = 20
threadpool_spawn_if_under = 2
threadpool_max_zombie_threads_before_die = 2
threadpool_hung_check_period = 1
threadpool_dying_limit = 10
use = egg:Paste#http
host = 127.0.0.1:8081
# These options make it easier to trigger the thread pool catches
# (i.e., threads are hung fast, killed fast, spawn fast, and the
# whole process dies quickly due to zombies)
threadpool_workers = 3
threadpool_hung_thread_limit = 10
threadpool_kill_thread_limit = 20
threadpool_spawn_if_under = 2
threadpool_max_zombie_threads_before_die = 2
threadpool_hung_check_period = 1
threadpool_dying_limit = 10
extend default thread pool workers of paster in pylons
add a option named threadpool_workers in server:main section in development.ini as below:
[server:main]
use = egg:Paste#http
host = 127.0.0.1
port = 5000
threadpool_workers = 20
then you will get this message from log:
11:09:33,678 INFO [paste.httpserver.ThreadPool] kill_hung_threads status: 20 threads (0 working, 20 idle, 0 starting) ave time N/A, max time 0.00sec, killed 0 workers
[server:main]
use = egg:Paste#http
host = 127.0.0.1
port = 5000
threadpool_workers = 20
then you will get this message from log:
11:09:33,678 INFO [paste.httpserver.ThreadPool] kill_hung_threads status: 20 threads (0 working, 20 idle, 0 starting) ave time N/A, max time 0.00sec, killed 0 workers
Monday, March 28, 2011
Saturday, March 12, 2011
mock a rollback in pylons unit testing
@fudge.patch('samples.model.meta.Session') def test_add_user_commit_exception(FakeSession): FakeSession.provides('query').returns(1).provides("filter").returns_fake().\ provides("all").returns_fake() FakeSession.provides('commit').raises(ValueError("Commit excepion!")) FakeSession.expects("rollback").returns_fake() try: user.add_user("name") except Exception, ex: pass
Friday, March 11, 2011
fake ip in pylons unit testing
controller code:
--------------------------------------------------------------------------
unit testing code:
--------------------------------------------------------------------------
--------------------------------------------------------------------------
import logging from pylons import request, response, session, tmpl_context as c from pylons.controllers.util import abort, redirect_to from samplebundle.lib.base import BaseController, render log = logging.getLogger(__name__) class WebenvironsController(BaseController): def get_ip(self): # Return a rendered template #return render('/webenvirons.mako') # or, return a response ip = request.environ["REMOTE_ADDR"] return ip
unit testing code:
--------------------------------------------------------------------------
from samplebundle.tests import * class TestWebenvironsController(TestController): def test_get_ip(self): my_extra_environ = {"REMOTE_ADDR":"127.0.0.1"} response = self.app.get(url(controller='webenvirons', action='get_ip'), extra_environ = my_extra_environ) assert '127.0.0.1' in response
file upload unit testing in pylons
controller code:
--------------------------------------------------------------------------
unit testing code:
--------------------------------------------------------------------------
--------------------------------------------------------------------------
import logging from pylons import request, response, session, tmpl_context as c from pylons.controllers.util import abort, redirect_to from samplebundle.lib.base import BaseController, render log = logging.getLogger(__name__) class WebflowcontrolsController(BaseController): def upload(self): myfile = request.POST['myfile'] return 'Successfully uploaded: %s, size: %i' % \ (myfile.filename, len(myfile.value))
unit testing code:
--------------------------------------------------------------------------
from samplebundle.tests import * class TestWebflowcontrolsController(TestController): def test_upload(self): my_upload_files = [("myfile","myfilename","myfilecontent")] # field, filename, content response = self.app.post(url(controller='webflowcontrols', action='upload'), upload_files=my_upload_files) assert 'size: 13' in response
response status unit testing in pylons
controller code:
--------------------------------------------------------------------------
unit testing code:
--------------------------------------------------------------------------
--------------------------------------------------------------------------
import logging from pylons import request, response, session, tmpl_context as c from pylons.controllers.util import abort, redirect_to from samplebundle.lib.base import BaseController, render log = logging.getLogger(__name__) class WebflowcontrolsController(BaseController): def redirect_to_action(self): # Return a rendered template #return render('/webredirects.mako') # or, return a response redirect_to(controller='webflowcontrols', action='redirect_target') def redirect_target(self): # Return a rendered template #return render('/webredirects.mako') # or, return a response return 'redirect target' def abort_action(self, id): # Return a rendered template #return render('/webredirects.mako') # or, return a response if id == '404': abort(status_code=404) elif id == '400': abort(status_code=400) else: return "not abort"
unit testing code:
--------------------------------------------------------------------------
from samplebundle.tests import * class TestWebflowcontrolsController(TestController): def test_redirect_to_action(self): response = self.app.get(url(controller='webflowcontrols', action='redirect_to_action')) assert not 'redirect target' in response assert '/webflowcontrols/redirect_target' in response.location assert 302 == response.status_int # Test response... def test_abort_action(self): #'status' is the integer status code you expect. #If you expect a 404 response, for instance, #you must give status=404 or it will be an error. response = self.app.get(url(controller='webflowcontrols', action='abort_action', id="404"), status=404 ) assert response.status_int == 404 response = self.app.get(url(controller='webflowcontrols', action='abort_action', id="400"), status='*' ) assert response.status_int == 400
cookies unit testing in pylons
Controller code:
unit testing code:
import logging from pylons import request, response, session, tmpl_context as c from pylons.controllers.util import abort, redirect_to from samplebundle.lib.base import BaseController, render log = logging.getLogger(__name__) class CookiesController(BaseController): def get_cookie(self): my_cookie = request.cookies.get("my_cookie_name") if my_cookie == "my_cookie_value": return 'Found a cookie named my_cookie_name' else: return 'Nothing found' def set_cookie(self): response.set_cookie('my_cookie_name', 'my_cookie_value', max_age=360) return 'Done' def delete_cookie(self): response.delete_cookie('my_cookie_name') return 'Done'
unit testing code:
from samplebundle.tests import * class TestCookiesController(TestController): def test_get_cookie(self): myheaders = {} myheaders['Cookie'] = 'my_cookie_name=my_cookie_value' response = self.app.get(url(controller='cookies', action='get_cookie'), headers = myheaders) assert "Found a cookie" in response def test_set_cookie(self): response = self.app.get(url(controller='cookies', action='set_cookie')) assert 'my_cookie_name=my_cookie_value' in response.headers['Set-Cookie'] assert 'Max-Age=360' in response.headers['Set-Cookie'] """Cookie storage format in headers['Set-Cookie'] 'key=value; Domain=example.org; expires="Mon, 28-Feb-2011 07:48:56 GMT"; Max-Age=360; Path=/; secure' """ def test_delete_cookie(self): myheaders = {} myheaders['Cookie'] = 'my_cookie_name=my_cookie_value' response = self.app.get(url(controller='cookies', action='delete_cookie'), headers = myheaders) assert 'my_cookie_name=' in response.headers['Set-Cookie']
Wednesday, May 19, 2010
pylons middleware to strip HTML comments
import re from webob import Request class StripHtmlCommentsMiddleware: """ Strips all html comments from response content. """ def __init__(self, app): self.app = app self.htmlcomments = re.compile( '\<![ \r\n\t]*(--([^\-]|[\r\n]|-[^\-])*--[ \r\n\t]*)\>') def __call__(self, environ, start_response): req = Request(environ) rsp = req.get_response(self.app) if "text/html" == rsp.content_type: new_content = self.htmlcomments.sub('', rsp.unicode_body) rsp.unicode_body = new_content return rsp(environ, start_response)
Subscribe to:
Posts (Atom)