Best Python code snippet using yandex-tank
test_inputtransformer.py
Source:test_inputtransformer.py
1import tokenize2import nose.tools as nt3from IPython.testing import tools as tt4from IPython.utils import py3compat5from IPython.core import inputtransformer as ipt6def transform_and_reset(transformer):7 transformer = transformer()8 def transform(inp):9 try:10 return transformer.push(inp)11 finally:12 transformer.reset()13 14 return transform15# Transformer tests16def transform_checker(tests, transformer, **kwargs):17 """Utility to loop over test inputs"""18 transformer = transformer(**kwargs)19 try:20 for inp, tr in tests:21 if inp is None:22 out = transformer.reset()23 else:24 out = transformer.push(inp)25 nt.assert_equal(out, tr)26 finally:27 transformer.reset()28# Data for all the syntax tests in the form of lists of pairs of29# raw/transformed input. We store it here as a global dict so that we can use30# it both within single-function tests and also to validate the behavior of the31# larger objects32syntax = \33 dict(assign_system =34 [('a =! ls', "a = get_ipython().getoutput('ls')"),35 ('b = !ls', "b = get_ipython().getoutput('ls')"),36 ('c= !ls', "c = get_ipython().getoutput('ls')"),37 ('d == !ls', 'd == !ls'), # Invalid syntax, but we leave == alone.38 ('x=1', 'x=1'), # normal input is unmodified39 (' ',' '), # blank lines are kept intact40 # Tuple unpacking41 ("a, b = !echo 'a\\nb'", "a, b = get_ipython().getoutput(\"echo 'a\\\\nb'\")"),42 ("a,= !echo 'a'", "a, = get_ipython().getoutput(\"echo 'a'\")"),43 ("a, *bc = !echo 'a\\nb\\nc'", "a, *bc = get_ipython().getoutput(\"echo 'a\\\\nb\\\\nc'\")"),44 # Tuple unpacking with regular Python expressions, not our syntax.45 ("a, b = range(2)", "a, b = range(2)"),46 ("a, = range(1)", "a, = range(1)"),47 ("a, *bc = range(3)", "a, *bc = range(3)"),48 ],49 assign_magic =50 [('a =% who', "a = get_ipython().run_line_magic('who', '')"),51 ('b = %who', "b = get_ipython().run_line_magic('who', '')"),52 ('c= %ls', "c = get_ipython().run_line_magic('ls', '')"),53 ('d == %ls', 'd == %ls'), # Invalid syntax, but we leave == alone.54 ('x=1', 'x=1'), # normal input is unmodified55 (' ',' '), # blank lines are kept intact56 ("a, b = %foo", "a, b = get_ipython().run_line_magic('foo', '')"),57 ],58 classic_prompt =59 [('>>> x=1', 'x=1'),60 ('x=1', 'x=1'), # normal input is unmodified61 (' ', ' '), # blank lines are kept intact62 ],63 ipy_prompt =64 [('In [1]: x=1', 'x=1'),65 ('x=1', 'x=1'), # normal input is unmodified66 (' ',' '), # blank lines are kept intact67 ],68 # Tests for the escape transformer to leave normal code alone69 escaped_noesc =70 [ (' ', ' '),71 ('x=1', 'x=1'),72 ],73 # System calls74 escaped_shell =75 [ ('!ls', "get_ipython().system('ls')"),76 # Double-escape shell, this means to capture the output of the77 # subprocess and return it78 ('!!ls', "get_ipython().getoutput('ls')"),79 ],80 # Help/object info81 escaped_help =82 [ ('?', 'get_ipython().show_usage()'),83 ('?x1', "get_ipython().run_line_magic('pinfo', 'x1')"),84 ('??x2', "get_ipython().run_line_magic('pinfo2', 'x2')"),85 ('?a.*s', "get_ipython().run_line_magic('psearch', 'a.*s')"),86 ('?%hist1', "get_ipython().run_line_magic('pinfo', '%hist1')"),87 ('?%%hist2', "get_ipython().run_line_magic('pinfo', '%%hist2')"),88 ('?abc = qwe', "get_ipython().run_line_magic('pinfo', 'abc')"),89 ],90 end_help =91 [ ('x3?', "get_ipython().run_line_magic('pinfo', 'x3')"),92 ('x4??', "get_ipython().run_line_magic('pinfo2', 'x4')"),93 ('%hist1?', "get_ipython().run_line_magic('pinfo', '%hist1')"),94 ('%hist2??', "get_ipython().run_line_magic('pinfo2', '%hist2')"),95 ('%%hist3?', "get_ipython().run_line_magic('pinfo', '%%hist3')"),96 ('%%hist4??', "get_ipython().run_line_magic('pinfo2', '%%hist4')"),97 ('Ï.foo?', "get_ipython().run_line_magic('pinfo', 'Ï.foo')"),98 ('f*?', "get_ipython().run_line_magic('psearch', 'f*')"),99 ('ax.*aspe*?', "get_ipython().run_line_magic('psearch', 'ax.*aspe*')"),100 ('a = abc?', "get_ipython().set_next_input('a = abc');"101 "get_ipython().run_line_magic('pinfo', 'abc')"),102 ('a = abc.qe??', "get_ipython().set_next_input('a = abc.qe');"103 "get_ipython().run_line_magic('pinfo2', 'abc.qe')"),104 ('a = *.items?', "get_ipython().set_next_input('a = *.items');"105 "get_ipython().run_line_magic('psearch', '*.items')"),106 ('plot(a?', "get_ipython().set_next_input('plot(a');"107 "get_ipython().run_line_magic('pinfo', 'a')"),108 ('a*2 #comment?', 'a*2 #comment?'),109 ],110 # Explicit magic calls111 escaped_magic =112 [ ('%cd', "get_ipython().run_line_magic('cd', '')"),113 ('%cd /home', "get_ipython().run_line_magic('cd', '/home')"),114 # Backslashes need to be escaped.115 ('%cd C:\\User', "get_ipython().run_line_magic('cd', 'C:\\\\User')"),116 (' %magic', " get_ipython().run_line_magic('magic', '')"),117 ],118 # Quoting with separate arguments119 escaped_quote =120 [ (',f', 'f("")'),121 (',f x', 'f("x")'),122 (' ,f y', ' f("y")'),123 (',f a b', 'f("a", "b")'),124 ],125 # Quoting with single argument126 escaped_quote2 =127 [ (';f', 'f("")'),128 (';f x', 'f("x")'),129 (' ;f y', ' f("y")'),130 (';f a b', 'f("a b")'),131 ],132 # Simply apply parens133 escaped_paren =134 [ ('/f', 'f()'),135 ('/f x', 'f(x)'),136 (' /f y', ' f(y)'),137 ('/f a b', 'f(a, b)'),138 ],139 # Check that we transform prompts before other transforms140 mixed =141 [ ('In [1]: %lsmagic', "get_ipython().run_line_magic('lsmagic', '')"),142 ('>>> %lsmagic', "get_ipython().run_line_magic('lsmagic', '')"),143 ('In [2]: !ls', "get_ipython().system('ls')"),144 ('In [3]: abs?', "get_ipython().run_line_magic('pinfo', 'abs')"),145 ('In [4]: b = %who', "b = get_ipython().run_line_magic('who', '')"),146 ],147 )148# multiline syntax examples. Each of these should be a list of lists, with149# each entry itself having pairs of raw/transformed input. The union (with150# '\n'.join() of the transformed inputs is what the splitter should produce151# when fed the raw lines one at a time via push.152syntax_ml = \153 dict(classic_prompt =154 [ [('>>> for i in range(10):','for i in range(10):'),155 ('... print i',' print i'),156 ('... ', ''),157 ],158 [('>>> a="""','a="""'),159 ('... 123"""','123"""'),160 ],161 [('a="""','a="""'),162 ('... 123','123'),163 ('... 456"""','456"""'),164 ],165 [('a="""','a="""'),166 ('>>> 123','123'),167 ('... 456"""','456"""'),168 ],169 [('a="""','a="""'),170 ('123','123'),171 ('... 456"""','... 456"""'),172 ],173 [('....__class__','....__class__'),174 ],175 [('a=5', 'a=5'),176 ('...', ''),177 ],178 [('>>> def f(x):', 'def f(x):'),179 ('...', ''),180 ('... return x', ' return x'),181 ],182 [('board = """....', 'board = """....'),183 ('....', '....'),184 ('...."""', '...."""'),185 ],186 ],187 ipy_prompt =188 [ [('In [24]: for i in range(10):','for i in range(10):'),189 (' ....: print i',' print i'),190 (' ....: ', ''),191 ],192 [('In [24]: for i in range(10):','for i in range(10):'),193 # Qt console prompts expand with spaces, not dots194 (' ...: print i',' print i'),195 (' ...: ', ''),196 ],197 [('In [24]: for i in range(10):','for i in range(10):'),198 # Sometimes whitespace preceding '...' has been removed199 ('...: print i',' print i'),200 ('...: ', ''),201 ],202 [('In [24]: for i in range(10):','for i in range(10):'),203 # Space after last continuation prompt has been removed (issue #6674)204 ('...: print i',' print i'),205 ('...:', ''),206 ],207 [('In [2]: a="""','a="""'),208 (' ...: 123"""','123"""'),209 ],210 [('a="""','a="""'),211 (' ...: 123','123'),212 (' ...: 456"""','456"""'),213 ],214 [('a="""','a="""'),215 ('In [1]: 123','123'),216 (' ...: 456"""','456"""'),217 ],218 [('a="""','a="""'),219 ('123','123'),220 (' ...: 456"""',' ...: 456"""'),221 ],222 ],223 multiline_datastructure_prompt =224 [ [('>>> a = [1,','a = [1,'),225 ('... 2]','2]'),226 ],227 ],228 229 multiline_datastructure =230 [ [('b = ("%s"', None),231 ('# comment', None),232 ('%foo )', 'b = ("%s"\n# comment\n%foo )'),233 ],234 ],235 236 multiline_string =237 [ [("'''foo?", None),238 ("bar'''", "'''foo?\nbar'''"),239 ],240 ],241 242 leading_indent =243 [ [(' print "hi"','print "hi"'),244 ],245 [(' for a in range(5):','for a in range(5):'),246 (' a*2',' a*2'),247 ],248 [(' a="""','a="""'),249 (' 123"""','123"""'),250 ],251 [('a="""','a="""'),252 (' 123"""',' 123"""'),253 ],254 ],255 256 cellmagic =257 [ [('%%foo a', None),258 (None, "get_ipython().run_cell_magic('foo', 'a', '')"),259 ],260 [('%%bar 123', None),261 ('hello', None),262 (None , "get_ipython().run_cell_magic('bar', '123', 'hello')"),263 ],264 [('a=5', 'a=5'),265 ('%%cellmagic', '%%cellmagic'),266 ],267 ],268 269 escaped =270 [ [('%abc def \\', None),271 ('ghi', "get_ipython().run_line_magic('abc', 'def ghi')"),272 ],273 [('%abc def \\', None),274 ('ghi\\', None),275 (None, "get_ipython().run_line_magic('abc', 'def ghi')"),276 ],277 ],278 279 assign_magic =280 [ [('a = %bc de \\', None),281 ('fg', "a = get_ipython().run_line_magic('bc', 'de fg')"),282 ],283 [('a = %bc de \\', None),284 ('fg\\', None),285 (None, "a = get_ipython().run_line_magic('bc', 'de fg')"),286 ],287 ],288 289 assign_system =290 [ [('a = !bc de \\', None),291 ('fg', "a = get_ipython().getoutput('bc de fg')"),292 ],293 [('a = !bc de \\', None),294 ('fg\\', None),295 (None, "a = get_ipython().getoutput('bc de fg')"),296 ],297 ],298 )299def test_assign_system():300 tt.check_pairs(transform_and_reset(ipt.assign_from_system), syntax['assign_system'])301def test_assign_magic():302 tt.check_pairs(transform_and_reset(ipt.assign_from_magic), syntax['assign_magic'])303def test_classic_prompt():304 tt.check_pairs(transform_and_reset(ipt.classic_prompt), syntax['classic_prompt'])305 for example in syntax_ml['classic_prompt']:306 transform_checker(example, ipt.classic_prompt)307 for example in syntax_ml['multiline_datastructure_prompt']:308 transform_checker(example, ipt.classic_prompt)309 # Check that we don't transform the second line if the first is obviously310 # IPython syntax311 transform_checker([312 ('%foo', '%foo'),313 ('>>> bar', '>>> bar'),314 ], ipt.classic_prompt)315def test_ipy_prompt():316 tt.check_pairs(transform_and_reset(ipt.ipy_prompt), syntax['ipy_prompt'])317 for example in syntax_ml['ipy_prompt']:318 transform_checker(example, ipt.ipy_prompt)319 # Check that we don't transform the second line if we're inside a cell magic320 transform_checker([321 ('%%foo', '%%foo'),322 ('In [1]: bar', 'In [1]: bar'),323 ], ipt.ipy_prompt)324def test_assemble_logical_lines():325 tests = \326 [ [("a = \\", None),327 ("123", "a = 123"),328 ],329 [("a = \\", None), # Test resetting when within a multi-line string330 ("12 *\\", None),331 (None, "a = 12 *"),332 ],333 [("# foo\\", "# foo\\"), # Comments can't be continued like this334 ],335 ]336 for example in tests:337 transform_checker(example, ipt.assemble_logical_lines)338def test_assemble_python_lines():339 tests = \340 [ [("a = '''", None),341 ("abc'''", "a = '''\nabc'''"),342 ],343 [("a = '''", None), # Test resetting when within a multi-line string344 ("def", None),345 (None, "a = '''\ndef"),346 ],347 [("a = [1,", None),348 ("2]", "a = [1,\n2]"),349 ],350 [("a = [1,", None), # Test resetting when within a multi-line string351 ("2,", None),352 (None, "a = [1,\n2,"),353 ],354 [("a = '''", None), # Test line continuation within a multi-line string355 ("abc\\", None),356 ("def", None),357 ("'''", "a = '''\nabc\\\ndef\n'''"),358 ],359 ] + syntax_ml['multiline_datastructure']360 for example in tests:361 transform_checker(example, ipt.assemble_python_lines)362def test_help_end():363 tt.check_pairs(transform_and_reset(ipt.help_end), syntax['end_help'])364def test_escaped_noesc():365 tt.check_pairs(transform_and_reset(ipt.escaped_commands), syntax['escaped_noesc'])366def test_escaped_shell():367 tt.check_pairs(transform_and_reset(ipt.escaped_commands), syntax['escaped_shell'])368def test_escaped_help():369 tt.check_pairs(transform_and_reset(ipt.escaped_commands), syntax['escaped_help'])370def test_escaped_magic():371 tt.check_pairs(transform_and_reset(ipt.escaped_commands), syntax['escaped_magic'])372def test_escaped_quote():373 tt.check_pairs(transform_and_reset(ipt.escaped_commands), syntax['escaped_quote'])374def test_escaped_quote2():375 tt.check_pairs(transform_and_reset(ipt.escaped_commands), syntax['escaped_quote2'])376def test_escaped_paren():377 tt.check_pairs(transform_and_reset(ipt.escaped_commands), syntax['escaped_paren'])378def test_cellmagic():379 for example in syntax_ml['cellmagic']:380 transform_checker(example, ipt.cellmagic)381 382 line_example = [('%%bar 123', None),383 ('hello', None),384 ('' , "get_ipython().run_cell_magic('bar', '123', 'hello')"),385 ]386 transform_checker(line_example, ipt.cellmagic, end_on_blank_line=True)387def test_has_comment():388 tests = [('text', False),389 ('text #comment', True),390 ('text #comment\n', True),391 ('#comment', True),392 ('#comment\n', True),393 ('a = "#string"', False),394 ('a = "#string" # comment', True),395 ('a #comment not "string"', True),396 ]397 tt.check_pairs(ipt.has_comment, tests)398@ipt.TokenInputTransformer.wrap399def decistmt(tokens):400 """Substitute Decimals for floats in a string of statements.401 Based on an example from the tokenize module docs.402 """403 result = []404 for toknum, tokval, _, _, _ in tokens:405 if toknum == tokenize.NUMBER and '.' in tokval: # replace NUMBER tokens406 yield from [407 (tokenize.NAME, 'Decimal'),408 (tokenize.OP, '('),409 (tokenize.STRING, repr(tokval)),410 (tokenize.OP, ')')411 ]412 else:413 yield (toknum, tokval)414def test_token_input_transformer():415 tests = [('1.2', "Decimal ('1.2')"),416 ('"1.2"', '"1.2"'),417 ]418 tt.check_pairs(transform_and_reset(decistmt), tests)419 ml_tests = \420 [ [("a = 1.2; b = '''x", None),421 ("y'''", "a =Decimal ('1.2');b ='''x\ny'''"),422 ],423 [("a = [1.2,", None),424 ("3]", "a =[Decimal ('1.2'),\n3 ]"),425 ],426 [("a = '''foo", None), # Test resetting when within a multi-line string427 ("bar", None),428 (None, "a = '''foo\nbar"),429 ],430 ]431 for example in ml_tests:...
text.py
Source:text.py
1# This program is free software; you can redistribute it and/or modify2# it under the terms of the (LGPL) GNU Lesser General Public License as3# published by the Free Software Foundation; either version 3 of the 4# License, or (at your option) any later version.5#6# This program is distributed in the hope that it will be useful,7# but WITHOUT ANY WARRANTY; without even the implied warranty of8# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the9# GNU Library Lesser General Public License for more details at10# ( http://www.gnu.org/licenses/lgpl.html ).11#12# You should have received a copy of the GNU Lesser General Public License13# along with this program; if not, write to the Free Software14# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.15# written by: Jeff Ortel ( jortel@redhat.com )16"""17Contains XML text classes.18"""19from suds import *20from suds.sax import *21class Text(unicode):22 """23 An XML text object used to represent text content.24 @ivar lang: The (optional) language flag.25 @type lang: bool26 @ivar escaped: The (optional) XML special character escaped flag.27 @type escaped: bool28 """29 __slots__ = ('lang', 'escaped',)30 31 @classmethod32 def __valid(cls, *args):33 return ( len(args) and args[0] is not None )34 35 def __new__(cls, *args, **kwargs):36 if cls.__valid(*args):37 lang = kwargs.pop('lang', None)38 escaped = kwargs.pop('escaped', False)39 result = super(Text, cls).__new__(cls, *args, **kwargs)40 result.lang = lang41 result.escaped = escaped42 else:43 result = None44 return result45 46 def escape(self):47 """48 Encode (escape) special XML characters.49 @return: The text with XML special characters escaped.50 @rtype: L{Text}51 """52 if not self.escaped:53 post = sax.encoder.encode(self)54 escaped = ( post != self )55 return Text(post, lang=self.lang, escaped=escaped)56 return self57 58 def unescape(self):59 """60 Decode (unescape) special XML characters.61 @return: The text with escaped XML special characters decoded.62 @rtype: L{Text}63 """64 if self.escaped:65 post = sax.encoder.decode(self)66 return Text(post, lang=self.lang)67 return self68 69 def trim(self):70 post = self.strip()71 return Text(post, lang=self.lang, escaped=self.escaped)72 73 def __add__(self, other):74 joined = u''.join((self, other))75 result = Text(joined, lang=self.lang, escaped=self.escaped)76 if isinstance(other, Text):77 result.escaped = ( self.escaped or other.escaped )78 return result79 80 def __repr__(self):81 s = [self]82 if self.lang is not None:83 s.append(' [%s]' % self.lang)84 if self.escaped:85 s.append(' <escaped>')86 return ''.join(s)87 88 def __getstate__(self):89 state = {}90 for k in self.__slots__:91 state[k] = getattr(self, k)92 return state93 94 def __setstate__(self, state):95 for k in self.__slots__:96 setattr(self, k, state[k])97 98 99class Raw(Text):100 """101 Raw text which is not XML escaped.102 This may include I{string} XML.103 """104 def escape(self):105 return self106 107 def unescape(self):108 return self109 110 def __add__(self, other):111 joined = u''.join((self, other))...
string-length.py
Source:string-length.py
1import re2class StringLength:3 def decode(self, escaped_string: str):4 escaped_string = re.sub("^\"", "", escaped_string)5 escaped_string = re.sub("[\"]\n?$", "", escaped_string)6 escaped_string = re.sub("[\\\]x[0-9a-f]{2}", "a", escaped_string)7 escaped_string = re.sub("[\\\][\"]", "a", escaped_string)8 escaped_string = re.sub("[\\\][\\\]", "a", escaped_string)9 return escaped_string10 def encoded_length(self, escaped_string: str):11 escaped_string = re.sub("[\\\]", "aa", escaped_string)12 escaped_string = re.sub("[\"]", "aa", escaped_string)13 # len_by_replacement = len("a" + escaped_string + "a")14 # print(len_by_replacement)15 encode_len = len(re.findall("[\\\]", escaped_string)) + len(re.findall("[\"]", escaped_string)) + len(16 escaped_string) + 217 # print(len_by_regex)18 return encode_len19if __name__ == '__main__':20 string_length = StringLength()21 decode_diff = 022 encode_diff = 023 with open('inputs/string-length.txt', 'r') as file:24 all_lines = file.readlines()25 for line in all_lines:26 line = line.strip()27 decoded = string_length.decode(line)28 # print(line, "\n", decoded, "\n")29 decode_diff += len(decoded) - len(line)30 encoded = string_length.encoded_length(line)31 # print(line, "\n", encoded, "\n")32 encode_diff += encoded - len(line)33 print(decode_diff)...
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!!