本文实例讲述了python中django简单测试的用法。分享给大家供大家参考。具体如下:
这里以facebook台湾的测试版为例。
仅仅测试用户登录,主要说明测试的使用和django环境的设置。
代码如下:
import os
import sys
import unittest
import hashlib
test_member_id = 11
sns_id = 100002309745702
test_session_key = ‘125737724171219|2.aqcp7ctcyxjh4oow.3600.1310022000.1-100002309745702|qj4000whhkwgtapoi0icepzsyz8’ # need to get from sns platform
signed_request = ‘hoihyhot7rlooaxljwdogyiv6-qzizl3q9mbvjkjqja.eyjhbgdvcml0ag0ioijitufdlvniqti1niisimv4cglyzxmiojezmtawmjiwmdasimlzc3vlzf9hdci6mtmxmdaxnzg5mcwib2f1dghfdg9rzw4ioiixmju3mzc3mjqxnzeymtl8mi5buunwn2n0q1lysmg0b29xljm2mdaumtmxmdaymjawmc4xltewmdawmjmwotc0ntcwmnxxajqwmdbxaghlv0d0qxbpstbpy0vweln5wjgilcj1c2vyijp7imnvdw50cnkioij1cyisimxvy2fszsi6imvux1vtiiwiywdlijp7im1pbii6mjf9fswidxnlcl9pzci6ijewmdawmjmwotc0ntcwmij9’
class logintestcase(unittest.testcase):
def setup(self):
# set up django environment
pathname = os.path.dirname(sys.argv[0])
sys.path.append(os.path.abspath(pathname))
sys.path.append(os.path.normpath(os.path.join(os.path.abspath(pathname), ‘../’)))
os.environ[‘django_settings_module’] = ‘settings’
from django.http import httprequest
self.request = httprequest()
from django.contrib.sessions.backends.cache import sessionstore
self.request.session = sessionstore()
self.request.session[hashlib.md5(test_session_key).hexdigest()] = test_member_id
self.request.session.save()
self.request.post = {‘signed_request’:signed_request}
def teardown(self):
pass
def testloginfromweb(self):
# login without session key
from django.conf import settings
from platforms.login.login_facebook_tw import login_from_web
res = login_from_web(self.request)
self.assertequal(res.status_code, 200)
self.assertequal(res.items(), [(‘content-type’, ‘text/html; charset=utf-8’)])
self.asserttrue(settings.sns_url in res.content)
self.asserttrue(settings.media_url in res.content)
# check member
from apps.members.models import member
from apps.members.helper import login_sns_user
member = login_sns_user(self.request, test_session_key)
member_db = member.objects.get(id=test_member_id)
self.assertequal(member, member_db)
if __name__ == ‘__main__’:
unittest.main()
其他可以类推。
希望本文所述对大家的python程序设计有所帮助。