Best Python code snippet using tavern
xml2yml.py
Source:xml2yml.py
1# -*- coding: utf-8 -*-2##############################################################################3#4# OpenERP, Open Source Management Solution5# Copyright (C) 2004-2010 OpenERP SA (<http://openerp.com>).6#7# This program is free software: you can redistribute it and/or modify8# it under the terms of the GNU Affero General Public License as9# published by the Free Software Foundation, either version 3 of the10# License, or (at your option) any later version.11#12# This program is distributed in the hope that it will be useful,13# but WITHOUT ANY WARRANTY; without even the implied warranty of14# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the15# GNU Affero General Public License for more details.16#17# You should have received a copy of the GNU Affero General Public License18# along with this program. If not, see <http://www.gnu.org/licenses/>.19#20##############################################################################21"""22Experimental script for conversion between OpenERP's XML serialization format23and the new YAML serialization format introduced in OpenERP 6.0.24Intended to be used as a quick preprocessor for converting data/test files, then25to be fine-tuned manually.26"""27import yaml28import logging29from lxml import etree30__VERSION__ = '0.0.2'31def toString(value):32 value='"' + value + '"'33 return value34class XmlTag(etree.ElementBase):35 def _to_yaml(self):36 child_tags = []37 for node in self:38 if hasattr(node, '_to_yaml'):39 child_tags.append(node._to_yaml())40 return self.tag(attrib=self.attrib, child_tags=child_tags)41class YamlTag(object):42 """43 Superclass for constructors of custom tags defined in yaml file.44 """45 def __init__(self, **kwargs):46 self.__dict__.update(kwargs)47 self.attrib = self.__dict__.get('attrib', {})48 self.child_tags = self.__dict__.get('child_tags', '')49 def __getitem__(self, key):50 return getattr(self, key)51 def __getattr__(self, attr):52 return None53 def __repr__(self):54 for k,v in self.attrib.iteritems():55 if str(v) and str(v)[0] in ['[', '{', '#', '*', '(']:56 self.attrib[k] = toString(self.attrib[k]).replace("'", '')57 st = self.yaml_tag + ' ' + str(self.attrib)58 return st59# attrib tags60class ref(YamlTag):61 yaml_tag = u'!ref'62 def __init__(self, expr="False"):63 self.expr = expr64 def __repr__(self):65 return "'%s'"%str(self.expr)66class Eval(YamlTag):67 yaml_tag = u'!eval'68 def __init__(self, expr="False"):69 self.expr = expr70 def __repr__(self):71 value=str(self.expr)72 if value.find("6,") != -1:73 value = eval(str(eval(value)))74 value=value[0][2]75 value = [[value]]76 else:77 try:78 value=int(value)79 except:80 if value and value[0] in ['[', '{', '#', '*', '(']:81 value = value.replace('"', r'\"')82 value = toString(value)83 else:84 try:85 value = eval(value)86 except Exception:87 pass88 return value89class Search(YamlTag):90 yaml_tag = u'!ref'91# test tag92class xml_test(XmlTag):93 def _to_yaml(self):94 expr = self.attrib.get('expr')95 text = self.text96 if text:97 expr = expr + ' == ' + '"%s"'%text98 return [[expr]]99class xml_data(etree.ElementBase):100 def _to_yaml(self):101 value = self.attrib.get('noupdate', "0")102 return data(value)103# field tag:104class xml_field(etree.ElementBase):105 def _to_yaml(self):106 field = ' ' + self.attrib.pop('name','unknown')107 if self.attrib.get('search', None):108 value = Search(attrib=self.attrib, child_tags='').__repr__()109 else:110 attr = (self.attrib.get('ref', None) and 'ref') or (self.attrib.get('eval', None) and 'eval') or 'None'111 value = Eval(self.attrib.get(attr, self.text)).__repr__() or ''112 return {field: value}113# value tag114class xml_value(etree.ElementBase):115 def _to_yaml(self):116 if self.attrib.get('eval', None):117 key, val = 'eval', '"'+self.attrib.get('eval')+'"'118 elif self.attrib.get('model', None):119 key, val = 'model', self.attrib.get('model')120 val=val.replace("'",'""')121 self.attrib.pop(key)122 d={}123 for k,v in self.attrib.iteritems():124 if k == 'search':125 v = '"' + v + '"'126 k='--' + k127 v=v.replace("'",'""')128 d[k] = v129 if d:130 ls=[[{key:val},dict(d)]]131 else:132 ls=[[{key:val}]]133 return ls134# data tag135class data(YamlTag):136 yaml_tag = u'!context'137 def __init__(self, noupdate="0"):138 self.child_tags = {' noupdate':noupdate}139 def __repr__(self):140 return "!!context"141# Record tag142class Record(YamlTag):143 yaml_tag = u'!record'144class xml_record(XmlTag):145 tag=Record146 def _to_yaml(self):147 child_tags = {}148 for node in self:149 if hasattr(node, '_to_yaml'):150 child_tags.update(node._to_yaml())151 return Record(attrib=self.attrib, child_tags=child_tags)152# ir_set tag153class Ir_Set(YamlTag):154 yaml_tag = u'!ir_set'155 def __repr__(self):156 st = self.yaml_tag157 return st158class xml_ir_set(XmlTag):159 tag=Ir_Set160 def _to_yaml(self):161 child_tags = {}162 for node in self:163 if hasattr(node, '_to_yaml'):164 child_tags.update(node._to_yaml())165 return Ir_Set(attrib=self.attrib, child_tags=child_tags)166# workflow tag167class Workflow(YamlTag):168 yaml_tag = u'!workflow'169class xml_workflow(XmlTag):170 tag=Workflow171# function tag172class Function(YamlTag):173 yaml_tag = u'!function'174class xml_function(XmlTag):175 tag=Function176# function tag177class Assert(YamlTag):178 yaml_tag = u'!assert'179class xml_assert(XmlTag):180 tag=Assert181# menuitem tagresult.append(yaml.safe_dump(obj, default_flow_style=False, allow_unicode=True).replace("'",''))182class MenuItem(YamlTag):183 yaml_tag = u'!menuitem'184class xml_menuitem(XmlTag):185 tag=MenuItem186# act_window tag187class ActWindow(YamlTag):188 yaml_tag = u'!act_window'189class xml_act_window(XmlTag):190 tag=ActWindow191# report tag192class Report(YamlTag):193 yaml_tag = u'!report'194class xml_report(XmlTag):195 tag=Report196# deletes tag197class Delete(YamlTag):198 yaml_tag = u'!delete'199class xml_delete(XmlTag):200 tag=Delete201# python tag202class Python(YamlTag):203 yaml_tag = u'!python'204class xml_python(XmlTag):205 tag=Python206# context tag207class Context(YamlTag):208 yaml_tag = u'!context'209class xml_context(XmlTag):210 tag=Context211# url tag212class Url(YamlTag):213 yaml_tag = u'!url'214class xml_url(XmlTag):215 tag=Url216# delete tag217class Delete(YamlTag):218 yaml_tag = u'!delete'219class xml_delete(XmlTag):220 tag=Delete221def represent_data(dumper, data):222 return dumper.represent_mapping(u'tag:yaml.org,2002:map', [('!'+str(data), data.child_tags)])223yaml.SafeDumper.add_representer(Record, represent_data)224yaml.SafeDumper.add_representer(data, represent_data)225yaml.SafeDumper.add_representer(Workflow, represent_data)226yaml.SafeDumper.add_representer(Function, represent_data)227yaml.SafeDumper.add_representer(Assert, represent_data)228yaml.SafeDumper.add_representer(MenuItem, represent_data)229yaml.SafeDumper.add_representer(Ir_Set, represent_data)230yaml.SafeDumper.add_representer(Python, represent_data)231yaml.SafeDumper.add_representer(Context, represent_data)232class MyLookup(etree.CustomElementClassLookup):233 def lookup(self, node_type, document, namespace, name):234 if node_type=='element':235 return {236 'data': xml_data,237 'record': xml_record,238 'field': xml_field,239 'workflow': xml_workflow,240 'function': xml_function,241 'value': xml_value,242 'assert': xml_assert,243 'test': xml_test,244 'menuitem': xml_menuitem,245 'act_window': xml_act_window,246 'report': xml_report,247 'delete': xml_delete,248 'python': xml_python,249 'context': xml_context,250 'url': xml_url,251 'ir_set': xml_ir_set,252 }.get(name, None)253 elif node_type=='comment':254 return None#xml_comment255 return None256class xml_parse(object):257 def __init__(self):258 self.context = {}259 def parse(self, fname):260 parser = etree.XMLParser()261 parser.setElementClassLookup(MyLookup())262 result = []263 self.root = etree.XML(file(fname).read(), parser)264 for data in self.root:265 if hasattr(data, '_to_yaml'):266 obj = data._to_yaml()267 if obj.yaml_tag == '!context':268 result.append(yaml.dump(str(obj)).replace("'",'').split('\n')[0])269 result.append(yaml.dump(obj.child_tags, default_flow_style=False).replace("'",''))270 else:271 result.append(yaml.safe_dump(obj, default_flow_style=False, allow_unicode=True).replace("'",''))272 self.context.update(data.attrib)273 for tag in data:274 if tag.tag == etree.Comment:275 result.append(tag)276 else:277 if hasattr(tag, '_to_yaml'):278 obj = tag._to_yaml()279 if not obj.child_tags:280 result.append(yaml.dump('!'+str(obj), default_flow_style=False, allow_unicode=True, width=999).replace("'",''))281 else:282 result.append(yaml.safe_dump(obj, default_flow_style=False, allow_unicode=True, width=999).replace('\n:', ':\n').replace("'",''))283 print "# Experimental OpenERP xml-to-yml conversion! (v%s)"%__VERSION__284 print "# Please use this as a first conversion/preprocessing step,"285 print "# not as a production-ready tool!"286 for record in result:287 if type(record) != type(''):288 record=str(record)289 l= record.split("\n")290 for line in l:291 print '#' + str(line)292 continue293 record=str(record)294 record = record.replace('- --',' ') #for value tag295 record = record.replace('!!', '- \n !') #for all parent tags296 record = record.replace('- - -', ' -') #for many2many fields297 record = record.replace('? ', '') #for long expressions298 record = record.replace('""', "'") #for string-value under value tag299 print record300if __name__=='__main__':301 import optparse302 import sys303 parser = optparse.OptionParser(304 usage = '%s file.xml' % sys.argv[0])305 (opt, args) = parser.parse_args()306 if len(args) != 1:307 parser.error("incorrect number of arguments")308 fname = sys.argv[1]309 p = xml_parse()310 p.parse(fname)...
yamlobjects.py
Source:yamlobjects.py
1import yaml2def repr_for_obj(obj):3 sl = ['%s(']4 vl = [obj.__class__.__name__]5 6 for k, v in obj.__dict__.items():7 sl.append(k + "=%r, ")8 vl.append(v)9 sl[-1] = sl[-1][:-2]10 sl.append(')')11 return_str = ''.join(sl) % tuple(vl)12 return return_str13class yaml_obj(yaml.YAMLObject):14 def __repr__(self):15 return repr_for_obj(self)16class Env(yaml_obj):17 yaml_tag = u"!Env"18 def __init__(19 self, width, height, player_x, player_y, background_image, 20 prim_color=(0,0,0,1), player_angle=0.0, player_config='normal'21 ):22 self.width = width23 self.height = height24 self.player_x = player_x25 self.player_y = player_y26 self.background_image = background_image27 self.prim_color = prim_color28 self.player_angle = player_angle29 self.player_config = player_config30 31 def get_offset(self):32 return self33class Line(yaml_obj):34 yaml_tag = u"!Line"35 def __init__(self, obj_id, x1, y1, x2, y2, visible, collides):36 self.obj_id = obj_id37 self.collides = collides38 self.x1 = x139 self.y1 = y140 self.x2 = x241 self.y2 = y242 self.visible = visible43 44 def get_yaml_copy(self):45 return Line(46 self.obj_id, self.x1, self.y1, self.x2, self.y2, self.visible,47 self.collides48 )49 50class Door(yaml_obj):51 yaml_tag = u"!Door"52 def __init__(self, obj_id, x1, y1, x2, y2, key, visible):53 self.obj_id = obj_id54 self.x1 = x155 self.y1 = y156 self.x2 = x257 self.y2 = y258 self.key = key59 self.visible = visible60 61 def get_yaml_copy(self):62 return Door(63 self.obj_id, self.x1, self.y1, self.x2, self.y2, 64 self.key, self.visible65 )66 67class ImageDoor(yaml_obj):68 yaml_tag = u"!ImageDoor"69 def __init__(self, obj_id, key, x, y, rotation):70 self.obj_id = obj_id71 self.key = key72 self.x = x73 self.y = y74 self.rotation = rotation75 76class Key(yaml_obj):77 yaml_tag = u"!Key"78 def __init__(self, obj_id, x, y, number):79 self.obj_id = obj_id80 self.x = x81 self.y = y82 self.number = number83 84 def get_yaml_copy(self):85 return Key(self.obj_id, self.x, self.y, self.number)86 87class FilledRect(yaml_obj):88 yaml_tag = u"!FilledRect"89 def __init__(self, obj_id, x1, y1, x2, y2, visible):90 self.obj_id = obj_id91 self.x1 = x192 self.y1 = y193 self.x2 = x294 self.y2 = y295 self.visible = visible96 97 def get_yaml_copy(self):98 return FilledRect(99 self.obj_id, self.x1, self.y1, self.x2, self.y2, self.visible100 )101 102class FilledTriangle(yaml_obj):103 yaml_tag = u"!FilledTriangle"104 def __init__(self, obj_id, x1, y1, x2, y2, x3, y3, visible):105 self.obj_id = obj_id106 self.x1 = x1107 self.y1 = y1108 self.x2 = x2109 self.y2 = y2110 self.x3 = x3111 self.y3 = y3112 self.visible = visible113 114 def get_yaml_copy(self):115 return FilledTriangle(116 self.obj_id, self.x1, self.y1, 117 self.x2, self.y2, self.x3, self.y3, 118 self.visible119 )120 121class Circle(yaml_obj):122 yaml_tag = u"!Circle"123 def __init__(self, obj_id, x, y, radius, visible, collides):124 self.obj_id = obj_id125 self.x = x126 self.y = y127 self.radius = radius128 self.visible = visible129 self.collides = collides130 131 def get_yaml_copy(self):132 return Circle(133 self.obj_id, self.x, self.y, self.radius, self.visible,134 self.collides135 )136 137class Rock(yaml_obj):138 yaml_tag = u"!Rock"139 def __init__(self, obj_id, x, y, rotation, rock_type):140 self.obj_id = obj_id141 self.x = x142 self.y = y143 self.rotation = rotation144 self.rock_type = rock_type145 146class Decal(yaml_obj):147 yaml_tag = u"!Decal"148 def __init__(self, obj_id, x, y, rotation, scale, img_name, overhead=False):149 self.obj_id = obj_id150 self.x = x151 self.y = y152 self.rotation = rotation153 self.img_name = img_name154 self.scale = scale155 self.overhead = overhead156 157class DestructibleWall(yaml_obj):158 yaml_tag = u"!DestructibleWall"159 def __init__(self, obj_id, x, y, rotation, img_name):160 self.obj_id = obj_id161 self.x = x162 self.y = y163 self.rotation = rotation164 self.img_name = img_name165 166class SimpleObject(yaml_obj):167 yaml_tag = u"!SimpleObject"168 def __init__(self, obj_id, x, y, rotation):169 self.obj_id = obj_id170 self.x = x171 self.y = y172 self.rotation = rotation173 174class Turret(yaml_obj):175 yaml_tag = u"!Turret"176 def __init__(self, obj_id, x, y, rotation, base_type="", base_rotation=0):177 super(Turret, self).__init__()178 self.obj_id = obj_id179 self.x = x180 self.y = y181 self.rotation = rotation182 self.base_type = base_type183 self.base_rotation = base_rotation184 185class Tank1(SimpleObject):186 yaml_tag = u"!Tank1"187class Tank2(SimpleObject):188 yaml_tag = u"!Tank2"189class PlasmaTurret1(Turret):190 yaml_tag = u"!PlasmaTurret1"191class PlasmaTurret2(Turret):192 yaml_tag = u"!PlasmaTurret2"193class PlasmaTurret3(Turret):194 yaml_tag = u"!PlasmaTurret3"195class RapidTurret1(Turret):196 yaml_tag = u"!RapidTurret1"197class RapidTurret2(Turret):198 yaml_tag = u"!RapidTurret2"199class CannonTurret1(Turret):200 yaml_tag = u"!CannonTurret1"201class CannonTurret2(Turret):202 yaml_tag = u"!CannonTurret2"203class FreeThruster(SimpleObject):204 yaml_tag = u"!FreeThruster"205class FreeDecoy(SimpleObject):206 yaml_tag = u"!FreeDecoy"207class FreeShield(SimpleObject):208 yaml_tag = u"!FreeShield"209class FreeRepair(SimpleObject):210 yaml_tag = u"!FreeRepair"211class FreeBeacon(SimpleObject):212 yaml_tag = u"!FreeBeacon"213class FreeToxin(SimpleObject):214 yaml_tag = u"!FreeToxin"215class FreeGworpBrain(SimpleObject):216 yaml_tag = u"!FreeGworpBrain"217class FreeBomb(SimpleObject):218 yaml_tag = u"!FreeBomb"219class FreeTurret(SimpleObject):220 yaml_tag = u"!FreeTurret"221class FreeCargo(SimpleObject):...
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!!