Best Python code snippet using tempest_python
adm.py
Source:adm.py
...23from publica.utils.json import encode24from publica.utils.decorators import serialize, dbconnectionapp,\25 Permission, logportal26from publica import settings27def _unquote(text):28 if type(text) in StringTypes:29 return unquote(text)30 return text31class Adm(object):32 """33 Metodos relativo ao crud da administração34 """35 @dbconnectionapp36 def _getTipo(self):37 """38 """39 return self.execSql("select_tipo_noticia")40 @dbconnectionapp41 def _listarAutores(self):42 """ Lista autores cadastrados43 """44 return self.execSql("select_autor")45 @dbconnectionapp46 def getAutores(self):47 """ Lista autores cadastrados48 """49 return encode([i for i in self.execSql("select_autor")])50 @dbconnectionapp51 @serialize52 @Permission("PERM APP")53 def addAutor(self, nome, email, grupo):54 """ Cadastra um novo autor55 """56 self.execSqlu("insert_autor",57 nome=nome,58 email=email,59 grupo=grupo)60 return "Autor adicionado com sucesso!"61 @dbconnectionapp62 @serialize63 @Permission("PERM APP")64 def delAutor(self, id_autores=[]):65 """ Deleta autores cadastrados66 """67 for i in id_autores:68 self.execSqlBatch("delete_autor",69 id_autor=int(i))70 self.execSqlCommit()71 return "Autor deletado com sucesso!"72 @dbconnectionapp73 @serialize74 @Permission("PERM APP")75 def getAutor(self, id_autor):76 """ Seleciona um autor77 """78 return self.execSql("select_autor_unico",79 id_autor=int(id_autor)).next()80 @dbconnectionapp81 @serialize82 @Permission("PERM APP")83 def editAutor(self, id_autor, nome, email, grupo):84 """ Edita as informacoes de um autor85 """86 self.execSqlu("update_autor",87 id_autor=int(id_autor),88 nome=nome,89 email=email,90 grupo=grupo)91 return "Autor editado com sucesso!"92 @dbconnectionapp93 @serialize94 @Permission("PERM APP")95 def addNoticia(self, id_site, id_treeapp, id_aplicativo, titulo_categoria,96 titulo, descricao, tipo, corpo, publicado_em,97 autor=None, videos=[], editor=None, expira_em=None,98 publicado=None, foto_id=[], foto_grande_id=[],99 foto_credito=[], foto_legenda=[], foto_link=[],100 foto_alinhamento=[], video=None, audio=None,101 galeria=None,102 titulo_destaque=None, descricao_destaque=None,103 imagem_destaque=None, peso_destaque=None,104 data_edicao=None, relacionamento=[], tags="",105 exportar=None, exportar_xml=None,106 exportar_json=None, permissao=None, **kargs):107 """ Adiciona uma nova noticia108 """109 if kargs["titulo_capa"] == "null":110 kargs["titulo_capa"] = None111 if kargs["titulo_galeria"] == "null":112 kargs["titulo_galeria"] = None113 portal = Portal(id_site=self.id_site,114 request=self.request)115 id_conteudo = self.execSql("select_nextval_noticia").next()["id"]116 publicado = True if publicado else False117 tags = tags if tags else None118 dt = publicado_em119 try:120 p = strptime(publicado_em, "%d/%m/%Y %H:%M")121 publicado_em = strftime("%Y-%m-%d %H:%M", p)122 except ValueError, e:123 raise UserError(("Ocorreu um erro: "124 "Data de publicaçåo "125 "inválida (%s)") % publicado_em)126 try:127 p = strptime(expira_em, "%d/%m/%Y %H:%M")128 expira_em = strftime("%Y-%m-%d %H:%M", p)129 except ValueError, e:130 expira_em = None131 try:132 p = strptime(data_edicao, "%d/%m/%Y")133 data_edicao = strftime("%Y-%m-%d", p)134 except ValueError, e:135 data_edicao = None136 editor = True if editor else False137 video = True if video else False138 audio = True if audio else False139 galeria = True if galeria else False140 # adicionar noticia141 self.execSqlBatch("insert_noticia", 142 id_conteudo=id_conteudo,143 video=video,144 audio=audio,145 galeria=galeria,146 titulo_categoria=_unquote(titulo_categoria),147 titulo=_unquote(titulo),148 autor=_unquote(autor),149 descricao=_unquote(descricao),150 id_tipo_noticia=int(tipo),151 corpo=_unquote(corpo),152 publicado_em=publicado_em,153 expira_em=expira_em,154 publicado=publicado,155 data_edicao=data_edicao,156 editor=editor,157 ordem=kargs['ordem'],158 pdf=kargs['pdf'],159 is_capa=kargs['is_capa'],160 titulo_capa=_unquote(kargs['titulo_capa']),161 titulo_galeria=_unquote(kargs['titulo_galeria']))162 # returns application's config data163 dados_app = portal._getApp(env_site=self.id_site,164 schema=self.schema)["dados"]165 # fotos166 dados_fotos = []167 for i in range(len(foto_id)):168 arquivo = foto_id[i]169 arquivo_grande = foto_grande_id[i]170 alinhamento = foto_alinhamento[i]171 credito = foto_credito[i]172 legenda = foto_legenda[i]173 link = foto_link[i]174 if arquivo_grande:175 fl = File(id_site=self.id_site, request=self.request)176 arquivo2 = fl._getFileTemp(arquivo_grande)177 arquivo2 = fl._writeTmpFile("res" + arquivo2[1], arquivo2[0])178 arquivon = portal.addArquivo(arquivo=arquivo2,179 id_conteudo=id_conteudo,180 schema=self.schema,181 dt=dt,182 originid=1,183 filename="resized",184 transform={"metodo":"normal_ratio",185 "dimenx":int(dados_app["dim_x"]),186 "dimeny":int(dados_app["dim_y"])})187 188 if arquivon:189 arquivo = arquivon190 if arquivo_grande:191 arquivogn = portal.addArquivo(arquivo=arquivo_grande,192 id_conteudo=id_conteudo,193 schema=self.schema,194 dt=dt)195 196 if arquivogn:197 arquivo_grande = arquivogn198 self.execSqlBatch("insert_foto_noticia", 199 id_conteudo=id_conteudo,200 arquivo=arquivo,201 arquivo_grande=arquivo_grande,202 alinhamento=alinhamento,203 credito=_unquote(credito),204 legenda=_unquote(legenda),205 link=link)206 dados_fotos.append({"arquivo":arquivo,207 "arquivo_grande":arquivo_grande,208 "alinhamento":alinhamento,209 "credito":credito,210 "legenda":legenda,211 "link":link})212 # videos213 dados_video = []214 for i in videos:215 self.execSqlBatch("insert_video",216 id_conteudo=id_conteudo,217 embed=i)218 dados_video.append({"embed":i})219 220 #videos iPad221 videos_ipad = {"thumbs":kargs["videos_ipad_thumbnail"],222 "areaudio":kargs["videos_ipad_audio"],223 "nomes":kargs["videos_ipad_nome"],224 "links":kargs["videos_ipad_link"]}225 for i in range(len(videos_ipad["thumbs"])):226 self.execSqlBatch("insert_video_ipad",227 id_conteudo=id_conteudo,228 nome=_unquote(videos_ipad["nomes"][i]),229 is_audio=videos_ipad["areaudio"][i],230 thumb=videos_ipad["thumbs"][i],231 link=videos_ipad["links"][i])232 233 #fotos iPad234 fotos_ipad = {"ids":kargs["foto_ipad_id"],235 "creditos":kargs["foto_ipad_credito"],236 "legendas":kargs["foto_ipad_legenda"]}237 for i in range(len(fotos_ipad["ids"])):238 imagem = portal.addArquivo(arquivo=fotos_ipad["ids"][i],239 id_conteudo=id_conteudo,240 schema=self.schema,241 dt=dt)242 self.execSqlBatch("insert_foto_ipad",243 id_conteudo=id_conteudo,244 foto=imagem,245 credito=_unquote(fotos_ipad["creditos"][i]),246 legenda=_unquote(fotos_ipad["legendas"][i]))247 # destaque248 try:249 peso_destaque = int(peso_destaque)250 except:251 peso_destaque = 0252 dados_destaque = []253 if titulo_destaque or imagem_destaque or descricao_destaque:254 imagem_destaque = portal.addArquivo(arquivo=imagem_destaque,255 id_conteudo=id_conteudo,256 schema=self.schema,257 dt=dt)258 if not imagem_destaque:259 imagem_destaque = None260 self.execSqlBatch("insert_destaque", 261 id_conteudo=id_conteudo,262 titulo=_unquote(titulo_destaque),263 descricao=_unquote(descricao_destaque),264 img=imagem_destaque,265 peso=peso_destaque)266 dados_destaque.append({"titulo":titulo_destaque,267 "descricao":descricao,268 "img":imagem_destaque,269 "peso":peso_destaque})270 self.execSqlCommit()271 272 dados = self._setDados(id_conteudo=id_conteudo)273 portal._addConteudo(env_site=self.id_site,274 id_pk=id_conteudo,275 schema=self.schema,276 meta_type=self.meta_type,277 id_aplicativo=id_aplicativo,278 id_treeapp=id_treeapp,279 peso=peso_destaque,280 titulo=_unquote(titulo),281 publicado=publicado,282 publicado_em=publicado_em,283 expira_em=expira_em,284 titulo_destaque=_unquote(titulo_destaque),285 descricao_destaque=_unquote(descricao_destaque),286 imagem_destaque=imagem_destaque,287 tags=tags,288 permissao=permissao,289 relacionamento=relacionamento,290 dados=dados)291 if exportar_xml or exportar_json or exportar:292 portal._insertLog(self.id_site,293 "Nova notícia cadastrada e publicada '%s'" % titulo)294 portal._exportarFormatosConteudo(id_aplicativo=id_aplicativo,295 id_conteudo=id_conteudo,296 schema=self.schema,297 id_treeapp=id_treeapp,298 html=exportar,299 xml=exportar_xml,300 json=exportar_json,301 dados=dados,302 subitems=None,303 add=1)304 return "Notícia cadastrada com sucesso! Publicação iniciada."305 306 portal._insertLog(self.id_site,307 "Nova notícia cadastrada '%s'" % titulo)308 return "Notícia cadastrada com sucesso."309 @dbconnectionapp310 def _getNoticia(self, id_conteudo):311 """312 """313 dic = {}314 noticia = self.execSql("select_noticia",315 id_conteudo=int(id_conteudo)).next()316 fotos = [i for i in self.execSql("select_noticia_fotos",317 id_conteudo=int(id_conteudo))]318 videos = [i for i in self.execSql("select_videos",319 id_conteudo=int(id_conteudo))]320 autores = []321 fotos_ipad = [i for i in self.execSql("select_fotos_ipad", 322 id_conteudo=id_conteudo)]323 videos_ipad = [i for i in self.execSql("select_videos_ipad",324 id_conteudo=id_conteudo)]325 if len(autores) == 1:326 autores.append(None)327 elif len(autores) == 0:328 autores = [None, None]329 return {"noticia":noticia,330 "fotos":fotos,331 "autores":autores,332 "videos":videos,333 "fotosipad":fotos_ipad,334 "videosipad":videos_ipad}335 @dbconnectionapp336 @serialize337 @Permission("PERM APP")338 def editNoticia(self, id_treeapp, id_aplicativo, id_conteudo, titulo_categoria,339 titulo, descricao, tipo, corpo, publicado_em,340 autor=None, videos=[], editor=None, expira_em=None,341 publicado=None, foto_id=[], foto_grande_id=[],342 foto_credito=[], foto_legenda=[], foto_link=[],343 foto_alinhamento=[], video=None, audio=None,344 galeria=None,345 titulo_destaque=None, descricao_destaque=None,346 imagem_destaque=None, peso_destaque=None,347 id_destaque=None,348 relacionamento=[], tags=None,349 data_edicao=None, exportar=None, exportar_json=None,350 exportar_xml=None, permissao=None, **kargs):351 """352 """353 if kargs["titulo_capa"] == "null":354 kargs["titulo_capa"] = None355 if kargs["titulo_galeria"] == "null":356 kargs["titulo_galeria"] = None357 portal = Portal(id_site=self.id_site, request=self.request)358 publicado = True if publicado else False359 tags = tags if tags else None360 dt = publicado_em361 try:362 publicado_em_t = strptime(publicado_em, "%d/%m/%Y %H:%M")363 publicado_em = strftime("%Y-%m-%d %H:%M", publicado_em_t)364 except ValueError, e:365 raise UserError(("Ocorreu um erro: "366 "Data de publicaçåo "367 "inválida (%s)") % publicado_em)368 try:369 p = strptime(expira_em, "%d/%m/%Y %H:%M")370 expira_em = strftime("%Y-%m-%d %H:%M", p)371 except ValueError, e:372 expira_em = None373 try:374 p = strptime(data_edicao, "%d/%m/%Y")375 data_edicao = strftime("%Y-%m-%d", p)376 except ValueError, e:377 data_edicao = None378 atualizado_em = strftime('%Y-%m-%d %H:%M')379 editor = True if editor else False380 video = True if video else False381 audio = True if audio else False382 galeria = True if galeria else False383 self.execSqlBatch("delete_dados_noticia",384 id_conteudo=int(id_conteudo))385 # adicionar noticia386 self.execSqlBatch("update_noticia",387 id_conteudo=int(id_conteudo),388 video=video,389 audio=audio,390 galeria=galeria,391 titulo_categoria=_unquote(titulo_categoria),392 titulo=_unquote(titulo),393 autor=_unquote(autor),394 descricao=_unquote(descricao),395 id_tipo_noticia=int(tipo),396 corpo=_unquote(corpo),397 publicado_em=publicado_em,398 expira_em=expira_em,399 publicado=publicado,400 atualizado_em=atualizado_em,401 data_edicao=data_edicao,402 editor=editor,403 ordem=kargs['ordem'],404 pdf=kargs['pdf'],405 is_capa=kargs['is_capa'],406 titulo_capa=_unquote(kargs['titulo_capa']),407 titulo_galeria=_unquote(kargs['titulo_galeria']))408 # returns application's config data409 dados_app = portal._getApp(env_site=self.id_site,410 schema=self.schema)["dados"]411 # fotos412 dados_fotos = []413 for i in range(len(foto_id)):414 arquivo = foto_id[i]415 arquivo_grande = foto_grande_id[i]416 alinhamento = foto_alinhamento[i]417 credito = foto_credito[i]418 legenda = foto_legenda[i]419 link = foto_link[i]420 if arquivo_grande:421 fl = File(id_site=self.id_site, request=self.request)422 arquivo2 = fl._getFileTemp(arquivo_grande)423 arquivo2 = fl._writeTmpFile("res" + arquivo2[1], arquivo2[0])424 arquivon = portal.addArquivo(arquivo=arquivo2,425 id_conteudo=id_conteudo,426 schema=self.schema,427 dt=dt,428 originid=1,429 filename="resized",430 transform={"metodo":"normal_ratio",431 "dimenx":int(dados_app["dim_x"]),432 "dimeny":int(dados_app["dim_y"])})433 434 if arquivon:435 arquivo = arquivon436 if arquivo_grande:437 arquivogn = portal.addArquivo(arquivo=arquivo_grande,438 id_conteudo=id_conteudo,439 schema=self.schema,440 dt=dt)441 442 if arquivogn:443 arquivo_grande = arquivogn444 self.execSqlBatch("insert_foto_noticia", 445 id_conteudo=int(id_conteudo), 446 arquivo_grande=arquivo_grande,447 arquivo=arquivo,448 alinhamento=alinhamento,449 credito=_unquote(credito),450 legenda=_unquote(legenda),451 link=link)452 dados_fotos.append({"arquivo":arquivo,453 "arquivo_grande":arquivo_grande,454 "alinhamento":alinhamento,455 "credito":credito,456 "legenda":legenda,457 "link":link})458 # videos459 dados_videos = []460 for i in videos:461 self.execSqlBatch("insert_video", 462 id_conteudo=int(id_conteudo),463 embed=i)464 dados_videos.append({"embed":i})465 #videos iPad466 videos_ipad = {"thumbs":kargs["videos_ipad_thumbnail"],467 "areaudio":kargs["videos_ipad_audio"],468 "nomes":kargs["videos_ipad_nome"],469 "links":kargs["videos_ipad_link"]}470 for i in range(len(videos_ipad["thumbs"])):471 self.execSqlBatch("insert_video_ipad",472 id_conteudo=id_conteudo,473 nome=_unquote(videos_ipad["nomes"][i]),474 is_audio=videos_ipad["areaudio"][i],475 thumb=videos_ipad["thumbs"][i],476 link=videos_ipad["links"][i])477 478 #fotos iPad479 fotos_ipad = {"ids":kargs["foto_ipad_id"],480 "creditos":kargs["foto_ipad_credito"],481 "legendas":kargs["foto_ipad_legenda"]}482 for i in range(len(fotos_ipad["ids"])):483 imagem = portal.addArquivo(arquivo=fotos_ipad["ids"][i],484 id_conteudo=id_conteudo,485 schema=self.schema,486 dt=dt)487 self.execSqlBatch("insert_foto_ipad",488 id_conteudo=id_conteudo,489 foto=imagem,490 credito=_unquote(fotos_ipad["creditos"][i]),491 legenda=_unquote(fotos_ipad["legendas"][i]))492 # destaque493 try:494 peso_destaque = int(peso_destaque)495 except:496 peso_destaque = 0497 dados_destaque = []498 if titulo_destaque or imagem_destaque or descricao_destaque:499 imagem_destaquen = portal.addArquivo(arquivo=imagem_destaque,500 id_conteudo=int(id_conteudo),501 schema=self.schema,502 dt=dt)503 504 if imagem_destaquen:505 imagem_destaque = imagem_destaquen506 elif not imagem_destaque:507 imagem_destaque = None508 if id_destaque:509 self.execSqlBatch("update_destaque", 510 id_conteudo=int(id_conteudo),511 id_destaque=int(id_destaque),512 titulo=titulo_destaque,513 descricao=descricao_destaque,514 img=imagem_destaque,515 peso=peso_destaque)516 else:517 self.execSqlBatch("insert_destaque", 518 id_conteudo=int(id_conteudo),519 titulo=titulo_destaque,520 descricao=descricao_destaque,521 img=imagem_destaque,522 peso=peso_destaque)523 elif id_destaque:524 self.execSqlBatch("delete_destaque",525 id_destaque=int(id_destaque))526 titulo_destaque = titulo_destaque527 descricao_destaque = descricao_destaque528 imagem_destaque = imagem_destaque529 dados_destaque.append({"titulo":titulo_destaque,530 "descricao":descricao_destaque,531 "img":imagem_destaque,532 "peso":peso_destaque})533 self.execSqlCommit()534 dados = self._setDados(id_conteudo=id_conteudo)535 portal._editConteudo(env_site=self.id_site,536 id_pk=id_conteudo,537 id_aplicativo=int(id_aplicativo),538 schema=self.schema,539 id_treeapp=id_treeapp,540 peso=peso_destaque,541 titulo=_unquote(titulo),542 publicado=publicado,543 publicado_em=publicado_em,544 expira_em=expira_em,545 titulo_destaque=_unquote(titulo_destaque),546 descricao_destaque=_unquote(descricao_destaque),547 imagem_destaque=imagem_destaque,548 permissao=permissao,549 tags=tags,550 relacionamento=relacionamento,551 dados=dados)552 if exportar_xml or exportar_json or exportar:553 portal._insertLog(self.id_site,554 "Notícia '%s' editada e publicada" % titulo)555 portal._exportarFormatosConteudo(id_aplicativo=id_aplicativo,556 id_conteudo=id_conteudo,557 schema=self.schema,558 id_treeapp=id_treeapp,559 html=exportar,560 xml=exportar_xml,...
syntax.py
Source:syntax.py
...3031@command(r'open {name} help page')32def _open_help(name, **kwargs):33 if hasattr(kwargs['course'], 'help'):34 name = _unquote(name)35 kwargs['course'].help('index.html' if name == 'main' else name)36 else:37 kwargs['parser'].add_warning('Ignored: open {0} help page'.format(name))3839@command(r'click {name} menu item')40def _click_menu_item(name, **kwargs):41 click_menu_item(_unquote(name))4243@command(r'set {alias} dir, asking {prompt}')44def _set_dir(alias, prompt, **kwargs):45 if not kwargs['course'].set_dir(_unquote(alias), tempfile.tempdir, _unquote(prompt)):46 raise Exception('A directory must be specified')4748@command(r'set {name} alias, asking {prompt}, with default {default}')49def _set_alias(name, default, prompt, **kwargs):50 if not kwargs['course'].set_alias(_unquote(name), _unquote(default), _unquote(prompt)):51 raise Exception('A directory must be specified')52 53@command(r'set {name} flag, asking {prompt}, with default {default}')54def _set_flag(name, default, prompt, **kwargs):55 defaultno = default.lower() in ['false', 'no']56 kwargs['course'].set_flag(_unquote(name), defaultno, _unquote(prompt))5758@command(r'install addin {id} ({name})')59def _install_addin(name, id, **kwargs):60 Addin(_unquote(name)).install(_unquote(id.strip()), kwargs['course'])6162@command(r'configure {name} addin')63def _configure_addin(name, **kwargs):64 Addin(_unquote(name)).configure(kwargs['datasource'], kwargs['course'])6566@command(r'configure {name} addin, setting key {key}')67def _configure_addin(name, key, **kwargs):68 Addin(_unquote(name)).configure(kwargs['datasource'], kwargs['course'], _split(key, sep='/'))6970# TODO. if a key contains a comma this method fails71# for now as a work around above syntax can be called multiple times72@command(r'configure {name} addin, setting keys {keys}')73def _configure_addin(name, keys, **kwargs):74 addin = Addin(_unquote(name))75 for key in _split(keys):76 addin.configure(kwargs['datasource'], kwargs['course'], _split(key, sep='/'))7778@command('copy all files from {source} to {destination}')79def _copy_files(source, destination, **kwargs):80 if kwargs['course'].get_flag(_unquote(source), default=False):81 destination = kwargs['course'].get_alias(_unquote(destination))82 kwargs['datasource'].copy_files(_unquote(source), destination)8384@command('copy files from {source} to {destination}, asking {prompt}')85def _copy_files_with_prompt(source, destination, prompt, **kwargs):86 if kwargs['course'].set_flag(_unquote(source), True, _unquote(prompt)):87 destination = kwargs['course'].get_alias(_unquote(destination))88 kwargs['datasource'].copy_files(_unquote(source), destination)8990@command('copy {name} from {source} to {destination}')91def _copy_file(name, source, destination, **kwargs):92 if _unquote(destination) == 'Anki media collection':93 kwargs['datasource'].install_media_file(_unquote(name))94 else:95 if kwargs['course'].get_flag(_unquote(source), default=False):96 destination = kwargs['course'].get_alias(_unquote(destination))97 kwargs['datasource'].copy_file(_unquote(name), _unquote(source), destination)9899@command(r'create decks {decks}')100def _add_decks(decks, **kwargs):101 for deck in _split_names(decks):102 _create_deck(deck, **kwargs)103104@command(r'create deck {deck}')105def _add_deck(deck, **kwargs):106 _create_deck(_unquote(deck), **kwargs)107108@command(r'set default deck to {deck} for {model} card type {template}')109def _set_default_deck(model, template, deck, **kwargs):110 deck = kwargs['course'].get_alias(_unquote(deck))111 notetype = kwargs['course'].get_alias(_unquote(model))112 if notetype and deck:113 setDefaultDeck(notetype, _unquote(template), deck)114115@command(r'set default deck to {deck} for {model} card types {templates}')116def _set_default_deck(model, templates, deck, **kwargs):117 deck = kwargs['course'].get_alias(_unquote(deck))118 if deck:119 for template in _split_names(templates):120 notetype = kwargs['course'].get_alias(_unquote(model))121 if notetype:122 setDefaultDeck(notetype, template, deck)123124@command(r'add {model} note, setting fields {fields}')125def _add_note_and_field_values(model, fields, **kwargs):126 deck = kwargs['course'].get_alias('default')127 notetype = kwargs['course'].get_alias(_unquote(model))128 if notetype and deck:129 fields = _split_key_value_pairs(fields)130 _ensure_media_files_installed(fields, **kwargs)131 createNote(deck, notetype, fields)132 133@command(r'for {model} {note} set fields {fields}')134def _set_field_values(model, fields, note, **kwargs):135 _set_field_values(_unquote(model), _unquote(note), _split_key_value_pairs(fields), **kwargs)136137@command(r'for {model} {note} set field {field} to {value}')138def _set_field_value(model, note, field, value, **kwargs):139 _set_field_values(_unquote(model), _unquote(note), {_unquote(field):_unquote(value)}, **kwargs)140141#... creating/changing note types142143@command(r'create {model} note type and {commands}')144def _create_model(model, commands, **kwargs):145 _process_model_data(ModelData.create, model, False, commands, **kwargs)146147@command(r'create {model} cloze type and {commands}')148def _create_cloze_model(model, commands, **kwargs):149 _process_model_data(ModelData.create, model, True, commands, **kwargs)150151@command(r'change {model} note type and {commands}')152def _edit_model(model, commands, **kwargs):153 _process_model_data(ModelData.edit, model, None, commands, **kwargs)154155#.... note type sub-commands156157@command(r'with {parameters}')158def _with_parameters(parameters, **kwargs):159 #with ONE in [a, b, c], TWO in [d, e, "f and g"] and THREE in [x, y, z]:160 # note param order is preserved161 regexp = r'\s*(?P<quote1>[\'"]|\b)(?P<key>.*?)(?P=quote1)\s*in\s*\[(?P<value>.*?)\]\s*(?:,|and|$)'162 for m in re.finditer(regexp, parameters):163 kwargs['context'].add_parameter(m.group('key'), _split(m.group('value')))164165@command(r'translate {name} to [{values}]')166def _add_translation(name, values, **kwargs):167 kwargs['context'].add_translation(_unquote(name), _split(values))168169@command(r'add field {field}')170def _add_field_to_context(field, **kwargs):171 kwargs['context'].add_fields([field])172173@command(r'add fields {fields}')174def _add_fields_to_context(fields, **kwargs):175 kwargs['context'].add_fields(_split_names(fields))176177@command(r'add card type {template}, setting default deck to {deck}')178def _add_card_to_context(template, deck, **kwargs):179 kwargs['context'].add_templates([_unquote(template)], _unquote(deck))180181@command(r'add card types {templates}, setting default deck to {deck}')182def _add_cards_to_context(templates, deck, **kwargs):183 kwargs['context'].add_templates(_split_names(templates), _unquote(deck))184185@command(r'change card type {template}')186def _add_card_change_to_context(template, **kwargs):187 kwargs['context'].add_templates([_unquote(template)])188189@command(r'change card types {templates}')190def _add_card_changes_to_context(templates, **kwargs):191 kwargs['context'].add_templates(_split_names(templates))192193def _process_model_data(action, model, cloze, commands, **kwargs):194 with ModelData(kwargs['course'], kwargs['datasource']) as data:195 data.set_note(action, model, cloze)196 for cmd in commands.split(';'):197 kwargs['parser'].parse_line(cmd.strip(), context=data)198199def _create_deck(deck, **kwargs):200 deck = kwargs['course'].get_alias(deck)201 if deck:202 try:203 createDeck(deck)204 except DuplicateException as x:205 # permit users to map multiple aliases to the same deck if they really want to206 if not askUser('Deck {0} already exists - continue?'.format(deck)):207 raise x208209def _set_field_values(model, note, fields, **kwargs):210 notetype = kwargs['course'].get_alias(model)211 if notetype:212 _ensure_media_files_installed(fields, **kwargs)213 setFields(notetype, note, fields)214215def _ensure_media_files_installed(fields, **kwargs):216 '''217 Checks if field values contain image (<img src="...">) or sound data ([sound:...]), 218 and if so installs media file(s)219 '''220 for name in fields.keys():221 _ensure_media_file_installed(fields, name, r'<img src="(?P<filename>.*?)">', **kwargs)222 _ensure_media_file_installed(fields, name, r'\[sound:(?P<filename>.*?)\]', **kwargs)223224def _ensure_media_file_installed(fields, name, pattern, **kwargs):225 for m in re.finditer(pattern, fields[name]):226 filename = m.group('filename')227 installed = kwargs['datasource'].install_media_file(filename)228 if not installed:229 kwargs['parser'].add_warning('{0} media file was not installed'.format(filename))230 elif installed != filename:231 # Anki renames files if a media file already exists with this name so must use that in field value232 fields[name] = fields[name].replace(filename, installed)233234def _unquote(s):235 return s[1:-1] if s[0] in '\'"' and s[0] == s[-1] else s236237def _split(s, sep=','):238 return [_unquote(value) for value in re.split(sep + r'\s*', s)] if s else []239240def _split_names(s):241 regexp = r'\s*(?P<quote2>[\'"]|\b)(?P<value>.*?)(?P=quote2)\s*(?:,|and|$)'242 return [m.group('value') for m in re.finditer(regexp, s) if m.group('value') != '']243244def _split_key_value_pairs(s):245 # list: a to 'b,x,y' , c to d and e to 'f and g'246 regexp = r'\s*(?P<quote1>[\'"]|\b)(?P<key>.*?)(?P=quote1)\s*to\s*(?P<quote2>[\'"]|\b)(?P<value>.*?)(?P=quote2)\s*(?:,|and|$)'247 return {m.group('key'):m.group('value') for m in re.finditer(regexp, s)}
...
test_unquote.py
Source:test_unquote.py
1from unittest import TestCase2from protego import _RuleSet3rs = _RuleSet(None)4def _unquote(url, ignore='', errors='replace'):5 global rs6 return rs._unquote(url, ignore, errors)7def hexescape(char):8 global rs9 return rs.hexescape(char)10class TestUnquote(TestCase):11 """Tests for unquote()"""12 def test_unquoting(self):13 # Make sure unquoting of all ASCII values works14 escape_list = []15 for num in range(128):16 given = hexescape(chr(num))17 expect = chr(num)18 result = _unquote(given)19 self.assertEqual(expect, result,20 "using unquote(): %r != %r" % (expect, result))21 escape_list.append(given)22 escape_string = ''.join(escape_list)23 del escape_list24 result = _unquote(escape_string)25 self.assertEqual(result.count('%'), 1,26 "using unquote(): not all characters escaped: "27 "%s" % result)28 def test_unquoting_badpercent(self):29 # Test unquoting on bad percent-escapes30 given = '%xab'31 expect = given32 result = _unquote(given)33 self.assertEqual(expect, result, "using unquote(): %r != %r"34 % (expect, result))35 given = '%x'36 expect = given37 result = _unquote(given)38 self.assertEqual(expect, result, "using unquote(): %r != %r"39 % (expect, result))40 given = '%'41 expect = given42 result = _unquote(given)43 self.assertEqual(expect, result, "using unquote(): %r != %r"44 % (expect, result))45 def test_unquoting_parts(self):46 # Make sure unquoting works when have non-quoted characters47 # interspersed48 given = 'ab%sd' % hexescape('c')49 expect = "abcd"50 result = _unquote(given)51 self.assertEqual(expect, result,52 "using quote(): %r != %r" % (expect, result))53 def test_unquoting_plus(self):54 # Test difference between unquote() and unquote_plus()55 given = "are+there+spaces..."56 expect = given57 result = _unquote(given)58 self.assertEqual(expect, result,59 "using unquote(): %r != %r" % (expect, result))60 def test_unquote_with_unicode(self):61 # Characters in the Latin-1 range, encoded with UTF-862 given = 'br%C3%BCckner_sapporo_20050930.doc'63 expect = u'br\u00fcckner_sapporo_20050930.doc'64 result = _unquote(given)65 self.assertEqual(expect, result,66 "using unquote(): %r != %r" % (expect, result))67 # Characters in the Latin-1 range, encoded with None (default)68 result = _unquote(given)69 self.assertEqual(expect, result,70 "using unquote(): %r != %r" % (expect, result))71 # Characters in BMP, encoded with UTF-872 given = "%E6%BC%A2%E5%AD%97"73 expect = u"\u6f22\u5b57" # "Kanji"74 result = _unquote(given)75 self.assertEqual(expect, result,76 "using unquote(): %r != %r" % (expect, result))77 # Decode with UTF-8, invalid sequence78 given = "%F3%B1"79 expect = u"\ufffd" # Replacement character80 result = _unquote(given)81 self.assertEqual(expect, result,82 "using unquote(): %r != %r" % (expect, result))83 # Decode with UTF-8, invalid sequence, replace errors84 result = _unquote(given, errors="replace")85 self.assertEqual(expect, result,86 "using unquote(): %r != %r" % (expect, result))87 # Decode with UTF-8, invalid sequence, ignoring errors88 given = "%F3%B1"89 expect = ""90 result = _unquote(given, errors="ignore")91 self.assertEqual(expect, result,92 "using unquote(): %r != %r" % (expect, result))93 # A mix of non-ASCII and percent-encoded characters, UTF-894 result = _unquote(u"\u6f22%C3%BC")95 expect = u'\u6f22\u00fc'96 self.assertEqual(expect, result,97 "using unquote(): %r != %r" % (expect, result))98 def test_escape_sequence_uppercase(self):99 result = _unquote('%2fabc%7exyz', ignore='/~')100 expect = "%2Fabc%7Exyz"101 self.assertEqual(expect, result,...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!