How to use _tag_start method in avocado

Best Python code snippet using avocado_python

behaviour_parser.py

Source:behaviour_parser.py Github

copy

Full Screen

1from __future__ import unicode_literals2 3import re4import sys5from .ordered_xml import OrderedXMLElement6if sys.version_info[0] < 3:7 from io import open8class ParseError(Exception):9 """Represents an error encountered during parsing."""10 def __init__(self, msg, parsed_seq, trace=None):11 super(ParseError, self).__init__(msg, parsed_seq, trace)12 13 def __str__(self):14 return self.args[0]15 16_tag_start = re.compile(r'.*?\<([a-zA-Z0-9\-\_]+)\s*?(.*?)\s*?(\/?)\>', re.DOTALL)17_attribute = re.compile(r"([a-zA-Z0-9\-\_]+)(?:\s*\=\s*(\"(.*?)\"))?")18_comment = re.compile(r'\s*(?:\<\!\-\-(.*?)\-\-\>)?', re.DOTALL)19_decl_tag = re.compile(r'\<\?(.*?)\?\>', re.DOTALL) # ignored for now20base_tag_spec = {21 'opponent': {22 'version': None,23 'first': None,24 'last': None,25 'label': None,26 'gender': None,27 'poses': {28 'pose': {29 'sprite': None,30 'directive': { 'keyframe': None, 'animFrame': None }31 }32 },33 'size': None,34 'timer': None,35 'intelligence': None,36 'tags': { 'tag': None },37 'start': { 'state': None },38 'wardrobe': { 'clothing': None },39 'behaviour': {40 'stage': {41 'case': { 'priority': None, 'condition': None, 'test': None, 'state': None }42 }43 },44 'epilogue': {45 'title': None,46 'screen': {47 'start': None,48 'text': {49 'x': None,50 'y': None,51 'width': None,52 'arrow': None,53 'content': None,54 }55 }56 },57 'nicknames': { 'nickname': None }58 }59} 60meta_tag_spec = {61 'opponent': {62 'enabled': None,63 'first': None,64 'last': None,65 'label': None,66 'pic': None,67 'gender': None,68 'height': None,69 'from': None,70 'writer': None,71 'artist': None,72 'description': None,73 'has_ending': None,74 'layers': None,75 'tags': { 'tag': None },76 'costume': None77 }78}79listing_tag_spec = {80 'catalog': {81 'individuals': {82 'opponent': None83 },84 'groups': {85 'group': None86 }87 }88}89# skip whitespace and comments90def _skip_chars(seq, index):91 match = _comment.match(seq, index)92 while match is not None:93 if(len(match.group(0)) == 0):94 return index95 96 index += len(match.group(0))97 match = _comment.match(seq, index)98 99 return index100def _consume_char(seq, char, index, suppress_eof_error=False):101 index = _skip_chars(seq, index)102 103 if index >= len(seq)-1 and not suppress_eof_error:104 raise ParseError("Unexpected end of input", index)105 106 if seq.startswith(char, index):107 return True, index + len(char)108 else:109 return None, index110def _consume_re(seq, regex, index, suppress_eof_error=False):111 index = _skip_chars(seq, index)112 113 if index >= len(seq)-1 and not suppress_eof_error:114 raise ParseError("Unexpected end of input", index)115 116 match = regex.match(seq, index)117 if match is not None:118 index = match.end()119 120 return match, index121def parse_attribute_list(seq, elem):122 attr_match, index = _consume_re(seq, _attribute, 0, True)123 124 while attr_match is not None:125 try:126 elem.attributes[attr_match.group(1)] = attr_match.group(3)127 except IndexError:128 elem.attributes[attr_match.group(1)] = True129 130 attr_match, index = _consume_re(seq, _attribute, index, True)131 132 return index133def parse_tag(seq, index, tag_spec, progress_cb=None):134 if progress_cb is not None:135 progress_cb(index)136 137 _start_index = index138 139 match, index = _consume_re(seq, _tag_start, index)140 if match is None:141 raise ParseError("Expected opening tag", index)142 143 _tag_start_index = index - len(match.group(0))144 145 tag_type = match.group(1)146 if tag_type not in tag_spec:147 raise ParseError("Unexpected tag type '{}'".format(tag_type), index)148 149 elem = OrderedXMLElement(tag_type)150 if len(match.group(2)) > 0:151 parse_attribute_list(match.group(2), elem)152 simple_tag_match = (len(match.group(3)) > 0)153 154 try:155 # For simple tags (for example: <br />) just return the empty element156 if not simple_tag_match:157 # This tag contains either child text or child elements.158 child_tag_spec = tag_spec[tag_type]159 if child_tag_spec is None:160 # For text-only nodes, just grab everything up to the closing tag as the node's contents.161 tag_close_regex = re.compile(r'(.*?)\<\s*?\/{}\s*?\>'.format(re.escape(tag_type)), re.DOTALL)162 163 match, index = _consume_re(seq, tag_close_regex, index)164 if match is None:165 raise ParseError("Could not find closing tag for <{:s}> element".format(tag_type), index)166 167 elem.text = match.group(1)168 else:169 # Otherwise, parse this node's child elements.170 # The tag-close regex here is slightly different from the one above.171 # we only want to know if the start of the string has a tag close.172 tag_close_regex = re.compile(r'\<\s*?\/{}\s*?\>'.format(re.escape(tag_type)))173 174 closing_tag_match, index = _consume_re(seq, tag_close_regex, index)175 while closing_tag_match is None:176 child, index = parse_tag(seq, index, child_tag_spec, progress_cb)177 elem.children.append(child)178 closing_tag_match, index = _consume_re(seq, tag_close_regex, index)179 except ParseError as e:180 context = seq[_tag_start_index:_tag_start_index+50].strip()181 trace = "\n in {:s} (pos. {:d}): {:s} ...".format(tag_type, _tag_start_index, context)182 if e.args[2] is not None:183 trace = e.args[2] + trace184 185 raise ParseError(e.args[0], e.args[1], trace)186 187 return elem, index188def parse(seq, tag_spec=base_tag_spec, progress_cb=None):189 _, index = _consume_re(seq, _decl_tag, 0)190 191 try:192 base_elem, _ = parse_tag(seq, index, tag_spec, progress_cb)193 return base_elem194 except ParseError as e:195 error_index = e.args[1]196 197 # find line number and position of error:198 error_line = 0199 error_pos = 0200 201 cur_idx = 0202 for i, line in enumerate(seq.split('\n')):203 if error_index < cur_idx + len(line) + 1:204 error_line = i205 error_pos = error_index - cur_idx206 break207 cur_idx += len(line)+1208 209 raise ParseError("{:s} at line {:d}, position {:d} (abs. position {:d})".format(e.args[0], error_line, error_pos, error_index), None)210def parse_file(fname, progress_cb=None):211 with open(fname, encoding='utf-8') as infile:212 if progress_cb is not None:213 seq = infile.read()214 215 def wrapped_progress_cb(cur_index):216 return progress_cb(len(seq), cur_index)217 218 return parse(seq, base_tag_spec, wrapped_progress_cb)219 else:220 return parse(infile.read())221def parse_meta(fname, progress_cb=None):222 with open(fname, encoding='utf-8') as infile:223 if progress_cb is not None:224 seq = infile.read()225 226 def wrapped_progress_cb(cur_index):227 return progress_cb(len(seq), cur_index)228 229 return parse(seq, meta_tag_spec, wrapped_progress_cb)230 else:231 return parse(infile.read(), meta_tag_spec)232 233def parse_listing(fname, progress_cb=None):234 with open(fname, encoding='utf-8') as infile:235 if progress_cb is not None:236 seq = infile.read()237 238 def wrapped_progress_cb(cur_index):239 return progress_cb(len(seq), cur_index)240 241 return parse(seq, listing_tag_spec, wrapped_progress_cb)242 else:...

Full Screen

Full Screen

common_tags.py

Source:common_tags.py Github

copy

Full Screen

1# -*- coding: utf-8 -*-2import os, locale3from django.conf import settings4from django import forms5from django.forms.util import ErrorDict, ErrorList6from django.utils import simplejson7from django.utils.safestring import mark_safe8from django.template import Variable, Library, Node, NodeList, Template, Context, TemplateDoesNotExist9from django.template.defaultfilters import timesince10from django.utils.encoding import StrAndUnicode, force_unicode11from django.template.loader_tags import IncludeNode12from django_modules.http import get_host as get_host_http, get_current_url as get_current_url_http13register = Library()14@register.filter15def json_loads (s, ) :16 try :17 return simplejson.loads(s)18 except :19 return None20@register.filter21def json_dumps (s, ) :22 try :23 return simplejson.dumps(s)24 except :25 return None26@register.filter27def split (s, d=" ") :28 return s.split(d, )29@register.filter()30def currency(value):31 return locale.currency(value, grouping=True)32INCLUDE_MEDIA_TYPES = (33 (34 ".css",35 "<style type=\"text/css\">",36 "</style>",37 ),38 (39 ".js",40 "<script type=\"text/javascript\">",41 "</script>",42 ),43)44class IncludeMediaNode (Node, ) :45 def __init__(self, source, ) :46 super(IncludeMediaNode, self).__init__()47 self._source = source48 def __repr__ (self, ) :49 return "<IncludeMediaNode>"50 def _get_template_path (self, ) :51 _abs = os.path.abspath52 for i in settings.TEMPLATE_DIRS :53 if _abs(self._source).startswith(_abs(i)) :54 return os.path.relpath(_abs(self._source), _abs(i), )55 def render (self, context, ) :56 _source = self._get_template_path()57 (_fprefix, _ext_orig, ) = os.path.splitext(_source, )58 if not _fprefix :59 return60 _media = list()61 for _ext, _tag_start, _tag_end in INCLUDE_MEDIA_TYPES :62 try :63 _o = IncludeNode(Variable("\"%s%s\"" % (_fprefix, _ext, ), ), ).render(context, )64 except TemplateDoesNotExist :65 pass66 else :67 if not _o :68 continue69 _media.append(u"\n<!-- include_media: %s -->" % _fprefix, )70 _media.append(_tag_start, )71 _media.append(_o, )72 _media.append(_tag_end, )73 _media.append(u"\n", )74 return u"\n".join(_media)75@register.tag76def include_media (parser, token, ) :77 try :78 _source = token.source[0].name79 except :80 return u""81 return IncludeMediaNode(_source, )82@register.filter83def getitem (d, k, ) :84 return d.get(k)85@register.filter86def normalize_error (e, ) :87 if isinstance(e, ErrorDict, ) :88 return [u"%s%s" % (89 k != "__all__" and ("%s: " % k) or u"",90 v.as_text()[2:],91 ) for k, v in e.items()]92 elif isinstance(e, ErrorList, ) :93 return [v for v in e]94 elif isinstance(e, forms.Form, ) :95 return normalize_error(e.errors, )96 return [e, ]97@register.filter98def get_range (n, ) :99 return range(n)100@register.filter101def subtract (a, b, ) :102 return a - b103@register.filter104def timeago (t, ) :105 return mark_safe(106 """<span class="datetime"107 data-datetime="%(datetime)s"108 data-since="%(since)s ago"109 ><span class="value">%(since)s ago</span></span>""" % dict(110 since=timesince(t, ),111 datetime=t,112 ),113 )114class MessageNode (Node, ) :115 def __init__ (self, msg, mtype=None, ) :116 self._msg = msg117 self._mtype = mtype118 def render (self, context, ) :119 _msgs = self._msg.resolve(context)120 _mtype = "info"121 if self._mtype :122 _mtype = self._mtype.resolve(context)123 if isinstance(_msgs, (ErrorDict, ErrorList, forms.Form, ), ) :124 _mtype = "error"125 if _mtype == "error" :126 _msgs = normalize_error(_msgs, )127 if not _msgs :128 return u""129 if type(_msgs) not in (list, tuple, ) :130 _msgs = (_msgs, )131 return mark_safe(132 u"""<div class="msgs">%s</div>""" % u"".join(133 (self._render_msg(i, _mtype, ) for i in _msgs)134 ),135 )136 def _render_msg (self, i, mtype, ) :137 return u"""138<span class="msg"><span class="%(mtype)s">%(msg)s</span></span>139 """ % dict(140 mtype=mtype,141 msg=i,142 )143@register.tag144def print_message (parser, token, ) :145 _bits = list(token.split_contents())146 _msg = parser.compile_filter(_bits[1])147 _mtype = None148 if len(_bits) > 2 :149 _mtype = parser.compile_filter(_bits[2])150 151 return MessageNode(_msg, _mtype, )152@register.filter153def get_host (request, ) :...

Full Screen

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run avocado automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful