def test_delete(self): '''delete的同时要删除相关数据''' category_model = self.model model_model = Model() new_category_id = category_model.insert(test_helper.storage({'title':'cat1'})) new_model_id = model_model.insert(test_helper.storage({'Categoryid':new_category_id})) inserted_model = getDBHelper().fetchOne('select * from '+model_model.table_name+' where '+model_model.primary_key+'=%s',new_model_id) self.assertTrue(inserted_model is not None) category_model.delete(new_category_id) inserted_model = getDBHelper().fetchOne('select * from '+model_model.table_name+' where '+model_model.primary_key+'=%s',new_model_id) self.assertTrue(inserted_model is None)
def test_insert(self): '''插入的数据, 如果type表中没有相关数据, 要先插入type''' content_model = self.model data = test_helper.storage({'page':'brand-list', 'content':'brandshow', 'model_name':'Brand', 'model_id':1, }) exists_content = getDBHelper().fetchOne("select * from PageContentType where page='brand-list' and content='brandshow' ") self.assertEqual(exists_content, None) new_id = content_model.insert(data) exists_content = getDBHelper().fetchOne("select * from PageContentType where page='brand-list' and content='brandshow' ") self.assertEqual(exists_content.model_name, 'Brand')
def test_update(self): '''Image的update函数只能更新数据库表的值,而不创建、删除或修改图片文件。 ''' image_model = self.image_model data = test_helper.storage({'imagefile':{'value':'image_file_content','filename':'c://my files/sdjl.png'},'itemtype':'AImage','itemid':1017,'alt':' image alt ',}) new_image_id = image_model.insert(data) update_data = test_helper.storage({'imagefile':{'value':'image_file_content2','filename':'c://my files/sdjl2.png'},'itemtype':'AImage2','itemid':10172,'alt':' image alt2 ',}) image_model.update(new_image_id,update_data) updated_image = site_helper.getDBHelper().fetchOne('select uri,itemtype,itemid,alt from '+image_model.table_name+' where '+image_model.primary_key+'=%s',new_image_id) self.assertEqual(updated_image.itemtype,'AImage2') self.assertEqual(updated_image.itemid,10172) self.assertEqual(updated_image.alt,' image alt2 ') # don't strip self.assertEqual(updated_image.uri,'%s%d.png' % (site_helper.config.UPLOAD_IMAGE_URL, new_image_id)) # has the old image uri self.assertTrue(not os.path.exists(site_helper.config.UPLOAD_IMAGE_PATH+'/%d.png' % (new_image_id+1))) # don't create new image file new_image2 = site_helper.getDBHelper().fetchOne('select uri,itemtype,itemid,alt from '+image_model.table_name+' where '+image_model.primary_key+'=%s',new_image_id+1) self.assertTrue(new_image2 is None) # don't insert new image data
def __getTotal(self, select): db = sh.getDBHelper() if " group by " in select.lower(): return len(db.fetchSomeFirst(select)) else: form_key = " from " if " from " in select else " FROM " return db.fetchFirst("select count(*) from " + select.partition(form_key)[2])
def test_getInstance(self): '''ModelFactory可以根据class名和新表名动态生成新model,此新model类似继承了class,但使用了新的table_name, 因此它会链接另外一个数据表,而和原class的数据互不影响。''' test_helper.dropTable('your_table') new_image = ModelFactory.getInstance('Image','your_table') self.assertTrue(isinstance(new_image, model.Image)) self.assertTrue(not site_helper.getDBHelper().isTableExists('your_table')) self.assertEqual(new_image.table_name, 'your_table')
def rebulidTestDataBase(): from tool import init_database assert sh.config.DB_DATABASE.endswith('_test'), u'你使用正式数据库来测试?' db = sh.getDBHelper() for table_name in db.fetchSomeFirst('show tables', ignore_assert=True): db.executeQuery('DROP TABLE %s' % table_name) init_database.initTables()
def __getTotal(self, select): db = sh.getDBHelper() if ' group by ' in select.lower(): return len(db.fetchSomeFirst(select)) else: form_key = ' from ' if ' from ' in select else ' FROM ' return db.fetchFirst('select count(*) from ' + select.partition(form_key)[2])
def POST(self): i = web.input() subject = i.get('subject', '').encode('utf-8','ignore').replace('"','') from_addr = i.get('from_addr', '').encode('utf-8','ignore').replace('"','') to = i.get('to', '').encode('utf-8','ignore') content = i.get('content', '').encode('utf-8','ignore') now = time.localtime() #content_file_name = os.path.join(CONTENT_DIR, '%d_%d_%d_%d_%d_%d' % (now.tm_year, now.tm_mon, now.tm_mday, now.tm_hour, now.tm_min, now.tm_sec) ) #f = open(content_file_name,'w') #f.write(content) #f.close() if i.get('to_all','') == 'on': db = site_helper.getDBHelper() receivers = [i.email for i in db.fetchSome('select email from User')] else: receivers = [i.strip().replace('"','') for i in to.split('\n')] #sends = [] for receiver in receivers: if receiver: #sends.append('mail -r "%s" -s "%s" "%s" < %s' % (from_addr, subject, receiver, content_file_name)) try: self.send_html_email(from_addr, receiver, subject, content) except SMTPRecipientsRefused: pass #os.system('\n'.join(sends)) return page_helper.refresh()
def test_getImageid(self): imglink_model = self.model image_model = Image() data = test_helper.storage({'imagefile':{'value':'imagefile_content', 'filename':'c://sdjl/lyh.png'}}) new_imglink_id = imglink_model.insert(data) # insert imglink new_image_id = getDBHelper().fetchFirst('select max('+image_model.primary_key+') from '+image_model.table_name) self.assertEqual(imglink_model.getImageid(new_imglink_id), new_image_id)
def test_setItemID(self): image_model = self.image_model data = test_helper.storage({'imagefile':{'value':'image_file_content','filename':'c://my files/sdjl.png'},'itemtype':'AImage','itemid':1017,'alt':' image alt ',}) new_image_id = image_model.insert(data) image_model.setItemID(new_image_id,801) new_image = site_helper.getDBHelper().fetchOne('select uri,itemtype,itemid,alt from '+image_model.table_name+' where '+image_model.primary_key+'=%s',new_image_id) self.assertEqual(new_image.itemid, 801)
def test_delete(self): '''删除的时候要级联删除MakeupHasAttribute''' makeup_model = self.model data = test_helper.storage({'name':'面膜', 'enname':'mianmo', 'brand':'sdjlbrand', 'category':'good', 'score':'5.5', 'attributeids':[10,1,1017], 'release_time':'2011-10-17', 'intro':'haobao','cover_url':'/img/makeupreserve/cover/1.jpg' }) new_makeup_id = makeup_model.insert(data) makeup_model.delete(new_makeup_id) db_helper = getDBHelper() self.assertEqual(db_helper.fetchSome('select * from MakeupHasAttribute where Makeupid=%s', new_makeup_id), [])
def test_getAll(self): '''getAll函数返回的数据要包含uri属性,表示图片的uri''' imglink_model = self.model image_model = Image() data = test_helper.storage({'imagefile':{'value':'imagefile_content', 'filename':'c://sdjl/lyh.png'}}) new_imglink_id = imglink_model.insert(data) # insert imglink new_imglinks = imglink_model.getAll() new_image_id = getDBHelper().fetchFirst('select max('+image_model.primary_key+') from '+image_model.table_name) self.assertEqual(new_imglinks[0].uri, site_helper.config.UPLOAD_IMAGE_URL+'%d.png' % new_image_id)
def test_update(self): '''update时如果有imagefile,则新建图片数据与文件给imglink,且不删除老数据与文件''' imglink_model = self.model image_model = Image() data = test_helper.storage({'imagefile':{'value':'imagefile_content', 'filename':'c://sdjl/lyh.png'}}) new_imglink_id = imglink_model.insert(data) # insert imglink first_image_id = getDBHelper().fetchFirst('select max('+image_model.primary_key+') from '+image_model.table_name) imglink_model.update(new_imglink_id, data) # update imglink second_image = getDBHelper().fetchOne('select * from '+image_model.table_name+' where '+image_model.primary_key+'=%s', first_image_id+1) self.assertTrue(second_image is not None) self.assertTrue(os.path.exists(site_helper.config.UPLOAD_IMAGE_PATH+'/%d.png' % (second_image.get(image_model.primary_key)))) first_image = getDBHelper().fetchOne('select * from '+image_model.table_name+' where '+image_model.primary_key+'=%s', first_image_id) self.assertTrue(first_image is not None) self.assertTrue(os.path.exists(site_helper.config.UPLOAD_IMAGE_PATH+'/%d.png' % (first_image.get(image_model.primary_key))))
def test_update_saveimage(self): '''更新的时候要替换原来的图片文件''' makeup_model = self.model db_helper = getDBHelper() data = test_helper.storage({'name':'面膜', 'cover_url':'/img/makeupreserve/cover/1.jpg' }) data.imagefile = site_helper.storage({'filename':'c://sdjl.jpg', 'value':'liuyonghui'}) new_makeup_id = makeup_model.insert(data) data.imagefile = site_helper.storage({'filename':'c://wx.jpg', 'value':'wangxuan'}) makeup_model.update(new_makeup_id, data) self.assertEqual(open('%s%d.jpg' % (site_helper.config.MAKEUP_COVER_PATH, new_makeup_id)).read().strip(), 'wangxuan')
def test_getModelidsByTypeid(self): content_model = self.model data = test_helper.storage({'page':'brand-list', 'content':'brandshow', 'model_name':'Brand', 'model_id':1, }) new_id = content_model.insert(data) type_id = getDBHelper().fetchFirst("select PageContentTypeid from PageContentType") contents = content_model.getModelidsByTypeid(type_id) self.assertEqual(len(contents), 1) self.assertEqual(contents[0], 1)
def test_insert_saveimage(self): '''插入makeup时, 如果有imagefile,就把文件保存在config.MAKEUP_COVER_PATH中, 并且以Makeupid命名, 修改cover_url指向图片文件''' makeup_model = self.model db_helper = getDBHelper() data = test_helper.storage({'name':'面膜', 'cover_url':'/img/makeupreserve/cover/1.jpg' }) data.imagefile = site_helper.storage({'filename':'c://sdjl.jpg', 'value':'liuyonghui'}) new_makeup_id = makeup_model.insert(data) self.assertTrue(os.path.exists('%s%d.jpg' % (site_helper.config.MAKEUP_COVER_PATH, new_makeup_id))) self.assertEqual(db_helper.fetchFirst('select cover_url from Makeup where Makeupid=%s', new_makeup_id), site_helper.config.MAKEUP_COVER_URL+str(new_makeup_id)+'.jpg') self.assertEqual(open('%s%d.jpg' % (site_helper.config.MAKEUP_COVER_PATH, new_makeup_id)).read().strip(), 'liuyonghui')
def test_insert(self): '''保存图片, 验证加密方式, 生日格式''' user_model = self.model data = test_helper.storage({'username':'******', 'email':'*****@*****.**', 'password':'******', 'birthday':'1985-10-17'}) data.imagefile = site_helper.storage({'filename':'sdjl.jpg', 'value':'shuai!shuai!shuai!shuai!shuai!shuai!shuai!shuai!shuai!shuai!shuai!'}) new_id = user_model.insert(data) new_user = getDBHelper().fetchOne('select * from '+user_model.table_name+' where '+user_model.primary_key+'=%s',new_id) self.assertEqual(new_user.password, 'dab61a7c59b7d5f2e9fd22c85f6aa03c') # 不允许改变加密方式 self.assertEqual(new_user.cover_url, '%s%d.jpg' % (site_helper.config.USER_COVER_URL, new_id)) # 保存图片 self.assertEqual(open('%s%d.jpg' % (site_helper.config.USER_COVER_PATH, new_id)).read().strip(), 'shuai!shuai!shuai!shuai!shuai!shuai!shuai!shuai!shuai!shuai!shuai!') self.assertEqual(new_user.birthday, date(1985,10,17) )
def test_insert(self): '''当插入的数据有imagefile时,ImgLink会自动插入一个Image数据,并与之关联''' imglink_model = self.model image_model = Image() max_image_id = getDBHelper().fetchFirst('select max('+image_model.primary_key+') from '+image_model.table_name) data = test_helper.storage({'imagefile':{'value':'imagefile_content', 'filename':'c://sdjl/lyh.png'}}) self.assertTrue(not os.path.exists(site_helper.config.UPLOAD_IMAGE_PATH+'/%d.png' % (max_image_id+1))) inserted_image = getDBHelper().fetchOne('select * from '+image_model.table_name+' where '+image_model.primary_key+'=%s', max_image_id+1) self.assertTrue(inserted_image is None) new_imglink_id = imglink_model.insert(data) # insert imglink self.assertTrue(os.path.exists(site_helper.config.UPLOAD_IMAGE_PATH+'/%d.png' % (max_image_id+1))) inserted_image = getDBHelper().fetchOne('select * from '+image_model.table_name+' where '+image_model.primary_key+'=%s', max_image_id+1) self.assertTrue(inserted_image is not None) self.assertEqual(inserted_image.itemtype, imglink_model.table_name) self.assertEqual(inserted_image.itemid, new_imglink_id) inserted_imglink = getDBHelper().fetchOne('select * from '+imglink_model.table_name+' where '+imglink_model.primary_key+'=%s', new_imglink_id) self.assertEqual(inserted_imglink.Imageid, max_image_id+1)
def test_delete(self): '''Image的delete函数仅删除表数据,而不删除图片文件''' image_model = self.image_model data = test_helper.storage({'imagefile':{'value':'image_file_content','filename':'c://my files/sdjl.png'},'itemtype':'AImage','itemid':1017,'alt':' image alt ',}) new_image_id = image_model.insert(data) image_model.delete(new_image_id) # delete data new_image = site_helper.getDBHelper().fetchOne('select uri,itemtype,itemid,alt from '+image_model.table_name+' where '+image_model.primary_key+'=%s',new_image_id) self.assertEqual(new_image,None) # don't delete image file self.assertTrue(os.path.exists(site_helper.config.UPLOAD_IMAGE_PATH+'/%d.png' % new_image_id)) self.assertEqual(open(site_helper.config.UPLOAD_IMAGE_PATH+'/%d.png' % new_image_id).read().strip(),'image_file_content')
def test_insert(self): image_model = self.image_model data = test_helper.storage({'imagefile':{'value':'image_file_content','filename':'c://my files/sdjl.png'},'itemtype':'AImage','itemid':1017,'alt':' image alt ',}) new_image_id = image_model.insert(data) # save image file success self.assertTrue(os.path.exists(site_helper.config.UPLOAD_IMAGE_PATH+'/%d.png' % new_image_id)) # file content self.assertEqual(open(site_helper.config.UPLOAD_IMAGE_PATH+'/%d.png' % new_image_id).read().strip(),'image_file_content') # data value new_image = site_helper.getDBHelper().fetchOne('select uri,itemtype,itemid,alt from '+image_model.table_name+' where '+image_model.primary_key+'=%s',new_image_id) self.assertEqual(new_image.uri,'%s%d.png' % (site_helper.config.UPLOAD_IMAGE_URL, new_image_id)) self.assertEqual(new_image.itemtype,'AImage') self.assertEqual(new_image.itemid,1017) self.assertEqual(type(new_image.itemid),long) self.assertEqual(new_image.alt,' image alt ') # don't strip
def test_equal(self): getDBHelper().insert('insert into Category (Categoryid, title) values (1017, %s)', 'sdjl') getDBHelper().insert('insert into Category (Categoryid, title) values (801, %s)', 'wx') decorator = [('MatchData',{'matchs':[{'table_name':'Category','match_key':'datatitle','type':'equal','match_column':'title','add':'Categoryid','functions':'insert update'}]}), ] model = site_helper.getModel('Model', decorator ) data = test_helper.storage({'datatitle':'sdjl'}) new_id = model.insert(data) self.assertEqual(getDBHelper().fetchOne('select * from Model where Modelid=%s',new_id).Categoryid, 1017) data = test_helper.storage({'datatitle':'wx'}) model.update(new_id, data) self.assertEqual(getDBHelper().fetchOne('select * from Model where Modelid=%s',new_id).Categoryid, 801)
def increaseCreateTable(self): '''根据table_template在原有表上添加新字段, 但不添加新的索引.''' assert(len(self.table_name)>0) assert(len(self.table_template)>0) assert(DBHelper().isTableExists(self.table_name)) def getColumnsFromSQL(sql): sql = sql.partition('(')[2].rpartition(')')[0].replace('\n', ' ').replace('\r', ' ') columns = [] column = [] bracket_count = 0 for c in sql+',': if c == '(': bracket_count += 1 column.append(c) elif c == ')': bracket_count -= 1 column.append(c) elif bracket_count == 0 and c==',': column = ''.join(column) if column.strip().split()[0].lower() not in ['key', 'primary','unique'] and column.strip().split('(')[0].lower() not in ['key', 'primary','unique']: columns.append((column.strip().split()[0], column)) column = [] else: column.append(c) if bracket_count < 0: raise Exception('table template is invalid. model name is: ' + self.table_name) return columns try: exists_columns = site_helper.getDBHelper().getTableColumns(self.table_name) formated_creat_query = self._getCreateTableQuery() columns = getColumnsFromSQL(formated_creat_query) db = site_helper.getDB() for column_name, query in columns: if column_name.lower() not in map(str.lower, exists_columns): try: db.cursor().execute('alter table %s add %s' % (self.table_name, query)) except: print 'alter query is:' print 'alter table %s add %s' % (self.table_name, query) raise db.commit() except: print 'formated creat query is:' print formated_creat_query raise
def GET(self, path): mc = sh.ctrl("Editor").getMenuConfig() # 禁止访问未公开的路径 if not mc: return sh.redirectTo404() inputs = sh.inputs() select = mc.get("select", "").replace("%", "%%") # 因为MySQLdb会转义% db = sh.getDBHelper() if mc.get("paging", ""): if " limit " in select.lower(): return sh.alert("使用paging选项时select中不能使用limit, 请检查后台配置", stay=10) # 如果使用了paging, select中就不允许出现limit if int(mc.get("paging")) <= 0: return sh.alert("paging配置参数应为正整数", stay=10) if " distinct " in select.lower(): return sh.alert("抱歉, 暂不支持paging与distinct一起使用", stay=10) # 查询count(*) form_key = " from " if " from " in select else " FROM " total = self.__getTotal(select) # 设置limit获得数据 select = select + " limit %d, %d" % self.__getLimit(inputs.get("page_num", 1), int(mc.paging)) items = db.fetchSome(select) # 获得分页 pagination_html = ( '<div fx="paging[style=zarkpy;pageCount=%d;totalCount=%d;displayPages=10;firstText=第一页;lastText=末页;]"></div>' % (int(mc.paging), total) ) else: items = db.fetchSome(select) pagination_html = "" keys = self.__getSortedKeys(select) if len(keys) == 0 and len(items) > 0: keys = items[0].keys() return sh.editor.ReportForms(items, pagination_html, keys, mc)
def GET(self, path): mc = sh.ctrl('Editor').getMenuConfig() # 禁止访问未公开的路径 if not mc: return sh.redirectTo404() inputs = sh.inputs() select = mc.get('select', '').replace('%', '%%') # 因为MySQLdb会转义% db = sh.getDBHelper() if mc.get('paging', ''): if ' limit ' in select.lower(): return sh.alert('使用paging选项时select中不能使用limit, 请检查后台配置', stay=10) # 如果使用了paging, select中就不允许出现limit if int(mc.get('paging')) <= 0: return sh.alert('paging配置参数应为正整数', stay=10) if ' distinct ' in select.lower(): return sh.alert('抱歉, 暂不支持paging与distinct一起使用', stay=10) # 查询count(*) form_key = ' from ' if ' from ' in select else ' FROM ' total = self.__getTotal(select) # 设置limit获得数据 select = select + ' limit %d, %d' % \ self.__getLimit(inputs.get('page_num', 1), int(mc.paging)) items = db.fetchSome(select) # 获得分页 pagination_html = '<div fx="paging[style=zarkpy;pageCount=%d;totalCount=%d;displayPages=10;firstText=第一页;lastText=末页;]"></div>' % (int(mc.paging), total) else: items = db.fetchSome(select) pagination_html = '' keys = self.__getSortedKeys(select) if len(keys) == 0 and len(items) > 0: keys = items[0].keys() return sh.editor.ReportForms(items, pagination_html, keys, mc)
#!coding=utf-8 import unittest import site_helper as sh db = sh.getDBHelper() class TestStringProcess(unittest.TestCase): def setUp(self): model = sh.model("SiteConfig") db.executeQuery("delete from %s" % model.table_name) def test_insert_update(self): decorator = [("StringProcess", dict(strip=["name", "value"], lower=["value"]))] model = sh.model("SiteConfig", decorator) new_id = model.insert(dict(name=" speed ", value="FAST ")) item = model.get(new_id) # 用strip删除了两边的空格, 用lower把value改为小写 self.assertEqual(item.name, "speed") self.assertEqual(item.value, "fast") # update同样起作用 model.update(new_id, dict(value=" SLOW ")) item = model.get(new_id) self.assertEqual(item.value, "slow")
#!coding=utf-8 import site_helper as sh from .. import AppTest db = sh.getDBHelper() test_model = 'ForTestPrivate' class TestPrivate(AppTest.AppTest): def appTestSetUp(self): db.executeQuery('delete from %s' % sh.model(test_model).table_name) db.executeQuery('delete from %s' % sh.model('Private').table_name) def appTestTearDown(self): self.logout() def test_insert(self): self.register() my_id = self.getUserid() model = sh.model(test_model) pri_model = sh.model('Private') # 插入一个数据 pri_1 = pri_model.getNextPrivateid(test_model, my_id) new_id = self.insert(test_model, dict(title='test')) # 新数据的id等于刚才得到的next private id self.assertEqual(pri_1, new_id) # Private表中的next private id增1 pri_2 = pri_model.getNextPrivateid(test_model, my_id) self.assertEqual(pri_1 + 1, pri_2) # 插入数据会自动记录private id item = self.getItem(test_model, new_id)
def initDatas(): query = open(site_helper.config.APP_ROOT_PATH + 'web/cgi/tool/init_datas.sql').read().strip() assert('insert' not in query.lower()) # 请用replace, 否则会导致重复插入数据 site_helper.getDBHelper().executeQuery(query)
def test_validatePassword(self): user_model = self.model data = test_helper.storage({'username':'******', 'email':'*****@*****.**', 'password':'******', 'birthday':'1985-10-17'}) new_id = user_model.insert(data) new_user = getDBHelper().fetchOne('select * from '+user_model.table_name+' where '+user_model.primary_key+'=%s',new_id) self.assertTrue(user_model.validatePassword(new_id, 'sdjllyh'))
#!/usr/bin/env python #coding=utf-8 import sys, os filePath = os.path.split(os.path.realpath(__file__))[0] sys.path.append(filePath+'/..') USAGE = 'python excute_sql.py file_name1.sql file_name2.sql ..' import site_helper if __name__=='__main__': if len(sys.argv) <= 1: print USAGE exit(0) for file_name in sys.argv[1:]: if not os.path.exists(file_name): print USAGE exit(0) db = site_helper.getDBHelper() for file_name in sys.argv[1:]: sql = open(file_name).read() db.executeQuery(sql)
def existsDomain(self, self_domain, user_id): item = site_helper.getDBHelper().fetchFirst('select Userid from User where LOWER(self_domain)=%s and Userid<>%s', [self_domain.lower(), user_id]) return item is not None
def existsUsername(self, user_name, user_id): item = site_helper.getDBHelper().fetchFirst('select Userid from User where LOWER(username)=%s and Userid<>%s', [user_name.lower(), user_id]) return item is not None
def initDatas(): query = open(site_helper.config.APP_ROOT_PATH + 'web/cgi/tool/init_datas.sql').read().strip() site_helper.getDBHelper().executeQuery(query)
def _getExistsTables(): return site_helper.getDBHelper().fetchSomeFirst('show tables', ignore_assert=True)