Best Python code snippet using pyatom_python
test_superconsole.py
Source:test_superconsole.py  
1#####################################################################################2#3#  Copyright (c) Microsoft Corporation. All rights reserved.4#5# This source code is subject to terms and conditions of the Apache License, Version 2.0. A6# copy of the license can be found in the License.html file at the root of this distribution. If7# you cannot locate the  Apache License, Version 2.0, please send an email to8# ironpy@microsoft.com. By using this source code in any fashion, you are agreeing to be bound9# by the terms of the Apache License, Version 2.0.10#11# You must not remove this notice, or any other, from this software.12#13#14#####################################################################################15from iptest.assert_util import *16skiptest("silverlight")17skiptest("win32")18from   time import sleep19import sys20import re21import clr22if is_netstandard:23    clr.AddReference("System.Diagnostics.Process")24    clr.AddReference("System.IO.FileSystem")25from   System.Diagnostics import Process, ProcessWindowStyle26from   System.IO import File27# test case disabled - requires MAUI to run28sys.exit(0)29#------------------------------------------------------------------------------30#--Globals31#if this is a debug build and the assemblies are being saved...peverify is run.32#for the test to pass, Maui assemblies must be in the AssembliesDir33if is_peverify_run:34    AddReferenceToDlrCore()35    clr.AddReference("Microsoft.Scripting")36    from Microsoft.Scripting.Runtime import ScriptDomainManager37    from System.IO import Path38    tempMauiDir = Path.GetTempPath()39    40    print "Copying Maui.Core.dll to %s for peverify..." % (tempMauiDir)41    if not File.Exists(tempMauiDir + '\\Maui.Core.dll'):42        File.Copy(testpath.rowan_root + '\\Util\\Internal\\Maui_old\\Maui.Core.dll',43                  tempMauiDir + '\\Maui.Core.dll')44#Cleanup the last run45for t_name in ['ip_session.log', 'ip_session_stderr.log']:46    if File.Exists(t_name):47        File.Delete(t_name)48    Assert(not File.Exists(t_name))49    50#------------------------------------------------------------------------------51#--Helper functions52def getTestOutput():53    '''54    Returns stdout and stderr output for a console test.55    '''56    #On some platforms 'ip_session.log' is not immediately created after57    #calling the 'close' method of the file object writing to 'ip_session.log'.58    #Give it a few seconds to catch up.59    sleep(1)60    for i in xrange(5):61        if "ip_session.log" in nt.listdir(nt.getcwd()):62            tfile = open('ip_session.log', 'r')63            break64        print "Waiting for ip_session.log to be created..."65        sleep(1)66    67    outlines = tfile.readlines()68    tfile.close()69    70    errlines = []71    if File.Exists('ip_session_stderr.log'):72        tfile = open('ip_session_stderr.log', 'r')73        errlines = tfile.readlines()74        tfile.close()75        76    return (outlines, errlines)77def removePrompts(lines):78    return [line for line in lines if not line.startswith(">>>") and not line.startswith("...")]79def verifyResults(lines, testRegex):80    '''81    Verifies that a set of lines match a regular expression.82    '''83    lines = removePrompts(lines)84    chopped = ''.join([line[:-1] for line in lines])85    Assert(re.match(testRegex, chopped),86           "Expected Regular Expression=" + testRegex + "\nActual Lines=" + chopped)87#------------------------------------------------------------------------------88#--Preliminary setup89sys.path.append(testpath.rowan_root + '\\Util\\Internal\\Maui_old')90try:91    clr.AddReference('Maui.Core.dll')92except:93    print "test_superconsole.py failed: cannot load Maui.Core assembly"94    sys.exit(int(is_snap))95from Maui.Core import App96proc = Process()97proc.StartInfo.FileName = sys.executable98proc.StartInfo.WorkingDirectory = testpath.rowan_root + '\\Languages\\IronPython\\Tests'99proc.StartInfo.Arguments = '-X:TabCompletion -X:AutoIndent -X:ColorfulConsole'100proc.StartInfo.UseShellExecute = True101proc.StartInfo.WindowStyle = ProcessWindowStyle.Normal102proc.StartInfo.CreateNoWindow = False103started = proc.Start()104try:105    superConsole = App(proc.Id)106except Exception as e:107    print "test_superconsole.py failed: cannot initialize App object (probably running as service, or in minimized remote window)"108    print "On VSLGO-MAUI machines close all remote desktop sessions using EXIT command on desktop!"109    proc.Kill()110    sys.exit(1) 111    112superConsole.SendKeys('from pretest import *{ENTER}')113#------------------------------------------------------------------------------114#--Tests115def test_newlines():116    '''117    Ensure empty lines do not break the console.118    '''119    #test120    superConsole.SendKeys('outputRedirectStart{(}{)}{ENTER}')121    superConsole.SendKeys('{ENTER}')122    superConsole.SendKeys('None{ENTER}')123    superConsole.SendKeys('{ENTER}{ENTER}{ENTER}')124    superConsole.SendKeys('outputRedirectStop{(}{)}{ENTER}')125    126    #verification127    for lines in getTestOutput():128        AreEqual(removePrompts(lines), [])129def test_cp12403():130    '''131    An exception thrown should appear in stderr.132    '''133    #setup134    superConsole.SendKeys('outputRedirectStart{(}{)}{ENTER}')135    136    superConsole.SendKeys('raise Exception{(}"Some string exception"{)}{ENTER}')137    expected = [138                "Traceback (most recent call last):",139                '  File "<stdin>", line 1, in <module>',140                "Exception: Some string exception",141                "",142                ]143    #verification144    superConsole.SendKeys('outputRedirectStop{(}{)}{ENTER}')145    #stdout should be empty146    AreEqual(removePrompts(getTestOutput()[0]),147             [])148    #stderr should contain the exception149    errlines = getTestOutput()[1]150    for i in xrange(len(errlines)):151        Assert(errlines[i].startswith(expected[i]), str(errlines) + " != " + str(expected))152    153def test_unique_prefix_completion():154    '''155    Ensure that an attribute with a prefix unique to the dictionary is156    properly completed.157    '''158    #setup159    superConsole.SendKeys('outputRedirectStart{(}{)}{ENTER}')160    testRegex = ""161    superConsole.SendKeys('print z{TAB}{ENTER}')162    testRegex += 'zoltar'163    superConsole.SendKeys('print yo{TAB}{ENTER}')164    testRegex += 'yorick'165    #verification166    superConsole.SendKeys('outputRedirectStop{(}{)}{ENTER}')167    verifyResults(getTestOutput()[0], testRegex)168    AreEqual(removePrompts(getTestOutput()[1]),169             [])170def test_nonunique_prefix_completion():171    '''172    Ensure that tabbing on a non-unique prefix cycles through the available173    options.174    '''175    #setup176    superConsole.SendKeys('outputRedirectStart{(}{)}{ENTER}')177    testRegex = ""178    179    superConsole.SendKeys('print y{TAB}{ENTER}')180    superConsole.SendKeys('print y{TAB}{TAB}{ENTER}')181    testRegex += '(yorickyak|yakyorick)'182    #verification183    superConsole.SendKeys('outputRedirectStop{(}{)}{ENTER}')184    verifyResults(getTestOutput()[0], testRegex)185    AreEqual(removePrompts(getTestOutput()[1]),186             [])187def test_builtin_completion():188    """189    verifies we can complete to builtins.  This tests min() is available190    """191    #setup192    superConsole.SendKeys('outputRedirectStart{(}{)}{ENTER}')193    testRegex = ""194    superConsole.SendKeys('print mi{TAB}{(}1,2,3{)}{ENTER}')195    testRegex += '1'196    #verification197    superConsole.SendKeys('outputRedirectStop{(}{)}{ENTER}')198    verifyResults(getTestOutput()[0], testRegex)199def test_member_completion():200    '''201    Ensure that tabbing after 'ident.' cycles through the available options.202    '''203    #setup204    superConsole.SendKeys('outputRedirectStart{(}True{)}{ENTER}')205    testRegex = ""206    # 3.1: identifier is valid, we can get dict207    superConsole.SendKeys('print c.{TAB}{ENTER}')208    # it is *either* __doc__ ('Cdoc') or __module__ ('pretest')209    testRegex += '(Cdoc|pretest)'210    # 3.2: identifier is not valid211    superConsole.SendKeys('try:{ENTER}')212    # autoindent213    superConsole.SendKeys('print f.{TAB}x{ENTER}')214    # backup from autoindent215    superConsole.SendKeys('{BACKSPACE}except:{ENTER}')216    superConsole.SendKeys('print "EXC"{ENTER}{ENTER}{ENTER}')217    testRegex += 'EXC'218    219    #verification220    superConsole.SendKeys('outputRedirectStop{(}{)}{ENTER}')221    verifyResults(getTestOutput()[0], testRegex)222    223def test_member_completion_com():224    superConsole.SendKeys('outputRedirectStart{(}True{)}{ENTER}')225    superConsole.SendKeys('import clr{ENTER}')226    superConsole.SendKeys('import System{ENTER}')227    superConsole.SendKeys('clr.AddReference{(}"Microsoft.Office.Interop.Word"{)}{ENTER}')228    superConsole.SendKeys('import Microsoft.Office.Interop.Word{ENTER}')229    superConsole.SendKeys('wordapp = Microsoft.Office.Interop.Word.ApplicationClass{(}{)}{ENTER}')230    sleep(10) #http://ironpython.codeplex.com/WorkItem/View.aspx?WorkItemId=24427231    superConsole.SendKeys('wordapp.Activ{TAB}{ENTER}')232    sleep(15) #http://ironpython.codeplex.com/WorkItem/View.aspx?WorkItemId=24427233    superConsole.SendKeys('outputRedirectStop{(}{)}{ENTER}')234    235    #Verification236    temp = getTestOutput()237    Assert(len(temp[0])==8, str(temp[0]))238    Assert(temp[0][6].startswith('<Microsoft.Scripting.ComInterop.DispCallable object at '), str(temp[0]))239def test_cp17797():240    #setup241    superConsole.SendKeys('outputRedirectStart{(}{)}{ENTER}')242    testRegex = ""243    superConsole.SendKeys('import clr{ENTER}')244    superConsole.SendKeys('print clr.Comp{TAB}{ENTER}')245    testRegex += '<built-in function CompileModules>'246    #verification247    superConsole.SendKeys('outputRedirectStop{(}{)}{ENTER}')248    verifyResults(getTestOutput()[0], testRegex)249@retry_on_failure250def test_autoindent():251    '''252    Auto-indent253    '''254    #setup255    superConsole.SendKeys('outputRedirectStart{(}True{)}{ENTER}')256    testRegex = ""257    258    superConsole.SendKeys("def f{(}{)}:{ENTER}print 'f!'{ENTER}{ENTER}")259    superConsole.SendKeys('f{(}{)}{ENTER}')260    testRegex += 'f!'261    #verification262    superConsole.SendKeys('outputRedirectStop{(}{)}{ENTER}')263    verifyResults(getTestOutput()[0], testRegex)264def test_backspace_and_delete():265    '''266    Backspace and delete267    '''268    #setup269    superConsole.SendKeys('outputRedirectStart{(}True{)}{ENTER}')270    testRegex = ""271    272    superConsole.SendKeys("print 'IQ{BACKSPACE}P'{ENTER}")273    testRegex += "IP"274    superConsole.SendKeys("print 'FW'{LEFT}{LEFT}{DELETE}X{ENTER}")275    testRegex += "FX"276    # 5.3: backspace over auto-indentation277    #   a: all white space278    #   b: some non-whitespace characters279    #verification280    superConsole.SendKeys('outputRedirectStop{(}{)}{ENTER}')281    verifyResults(getTestOutput()[0], testRegex)282def test_cursor_keys():283    '''284    Cursor keys285    '''286    #setup287    superConsole.SendKeys('outputRedirectStart{(}True{)}{ENTER}')288    testRegex = ""289    290    superConsole.SendKeys("print 'up'{ENTER}")291    testRegex += 'up'292    superConsole.SendKeys("print 'down'{ENTER}")293    testRegex += 'down'294    superConsole.SendKeys("{UP}{UP}{ENTER}")295    testRegex += 'up'296    superConsole.SendKeys("{DOWN}{ENTER}")297    testRegex += 'down'298    superConsole.SendKeys("print 'up'{ENTER}{UP}{ENTER}")299    testRegex += 'upup'300    superConsole.SendKeys("print 'awy{LEFT}{LEFT}{RIGHT}a{RIGHT}'{ENTER}")301    testRegex += 'away'302    superConsole.SendKeys("print 'bad'{ESC}print 'good'{ENTER}")303    testRegex += 'good'304    superConsole.SendKeys("rint 'hom'{HOME}p{END}{LEFT}e{ENTER}")305    testRegex += 'home'306    307    #verification308    superConsole.SendKeys('outputRedirectStop{(}{)}{ENTER}')309    verifyResults(getTestOutput()[0], testRegex)310def test_control_character_rendering():311    '''312    Control-character rendering313    '''314    #setup315    superConsole.SendKeys('outputRedirectStart{(}{)}{ENTER}')316    testRegex = ""317    # Ctrl-D318    superConsole.SendKeys('print "^(d)^(d){LEFT}{DELETE}"{ENTER}')319    testRegex += chr(4)320    # check that Ctrl-C breaks an infinite loop (the test is that subsequent things actually appear)321    superConsole.SendKeys('while True: pass{ENTER}{ENTER}')322    superConsole.SendKeys('^(c)')323    print "CodePlex Work Item 12401"324    errors = [325                "Traceback (most recent call last):", #CodePlex Work Item 12401326                "  File", #CodePlex Work Item 12401327                "  File", #CodePlex Work Item 12401328                "KeyboardInterrupt",329                "", #CodePlex Work Item 12401330            ]331    # check that Ctrl-C breaks an infinite loop (the test is that subsequent things actually appear)332    superConsole.SendKeys('def foo{(}{)}:{ENTER}try:{ENTER}while True:{ENTER}pass{ENTER}')333    superConsole.SendKeys('{BACKSPACE}{BACKSPACE}except KeyboardInterrupt:{ENTER}print "caught"{ENTER}{BACKSPACE}{ENTER}')334    superConsole.SendKeys('print "after"{ENTER}{BACKSPACE}{ENTER}foo{(}{)}{ENTER}')335    sleep(2)336    superConsole.SendKeys('^(c)')337    testRegex += 'caughtafter'338    #verification339    superConsole.SendKeys('outputRedirectStop{(}{)}{ENTER}')340    verifyResults(getTestOutput()[0], testRegex)341    #stderr should contain the exceptions342    errlines = getTestOutput()[1]343    Assert("KeyboardInterrupt" + newline in errlines,344           "KeyboardInterrupt not found in:" + str(errlines))345    #for i in xrange(len(errlines)):346    #    Assert(errlines[i].startswith(errors[i]), str(errlines) + " != " + str(errors))347def test_hasattr_interrupted():348    # hasattr() shouldn't swallow KeyboardInterrupt exceptions349    superConsole.SendKeys("class x{(}object{)}:{ENTER}")350    superConsole.SendKeys("    def __getattr__{(}self, name{)}:{ENTER}")351    superConsole.SendKeys("        while True: pass{ENTER}")352    superConsole.SendKeys("{ENTER}")353    superConsole.SendKeys("a = x{(}{)}{ENTER}")354    355    superConsole.SendKeys('outputRedirectStart{(}{)}{ENTER}')356    superConsole.SendKeys("hasattr{(}a, 'abc'{)}{ENTER}")357    superConsole.SendKeys('^(c)')358    superConsole.SendKeys('outputRedirectStop{(}{)}{ENTER}')359    Assert("KeyboardInterrupt" + newline in getTestOutput()[1])360def test_tab_insertion():361    '''362    Tab insertion363    '''364    #setup365    superConsole.SendKeys('outputRedirectStart{(}True{)}{ENTER}')366    testRegex = ""367    368    superConsole.SendKeys('print "j{TAB}{TAB}y"{ENTER}')369    testRegex += 'j    y'370    #verification371    superConsole.SendKeys('outputRedirectStop{(}{)}{ENTER}')372    verifyResults(getTestOutput()[0], testRegex)373    374def test_noeffect_keys():375    '''376    Make sure that home, delete, backspace, etc. at start have no effect377    '''378    #setup379    superConsole.SendKeys('outputRedirectStart{(}True{)}{ENTER}')380    testRegex = ""381    382    superConsole.SendKeys('{BACKSPACE}{DELETE}{HOME}{LEFT}print "start"{ENTER}')383    testRegex += 'start'384    385    #verification386    superConsole.SendKeys('outputRedirectStop{(}{)}{ENTER}')387    verifyResults(getTestOutput()[0], testRegex)388def test_tab_completion_caseinsensitive():389    '''390    Tab-completion is case-insensitive (wrt input)391    '''392    #setup393    superConsole.SendKeys('outputRedirectStart{(}True{)}{ENTER}')394    testRegex = ""395    396    superConsole.SendKeys('import System{ENTER}')397    superConsole.SendKeys('print System.r{TAB}{ENTER}')398    testRegex += "<type 'Random'>"399    400    #verification401    superConsole.SendKeys('outputRedirectStop{(}{)}{ENTER}')402    verifyResults(getTestOutput()[0], testRegex)403def test_history():404    '''405    Command history406    '''407    #setup408    superConsole.SendKeys('outputRedirectStart{(}True{)}{ENTER}')409    testRegex = ""410    411    superConsole.SendKeys('print "first"{ENTER}')412    testRegex += 'first'413    superConsole.SendKeys('print "second"{ENTER}')414    testRegex += 'second'415    superConsole.SendKeys('print "third"{ENTER}')416    testRegex += 'third'417    superConsole.SendKeys('print "fourth"{ENTER}')418    testRegex += 'fourth'419    superConsole.SendKeys('print "fifth"{ENTER}')420    testRegex += 'fifth'421    superConsole.SendKeys('{UP}{UP}{UP}{ENTER}')422    testRegex += 'third'423    superConsole.SendKeys('{UP}{ENTER}')424    testRegex += 'third'425    superConsole.SendKeys('{UP}{UP}{UP}{DOWN}{ENTER}')426    testRegex += 'second'427    superConsole.SendKeys('{UP}{ENTER}')428    testRegex += 'second'429    superConsole.SendKeys('{DOWN}{ENTER}')430    testRegex += 'third'431    superConsole.SendKeys('{DOWN}{ENTER}')432    testRegex += 'fourth'433    superConsole.SendKeys('{DOWN}{ENTER}')434    testRegex += 'fifth'435    superConsole.SendKeys('{UP}{UP}{ESC}print "sixth"{ENTER}')436    testRegex += 'sixth'437    superConsole.SendKeys('{UP}{ENTER}')438    testRegex += 'sixth'439    superConsole.SendKeys('{UP}{DOWN}{DOWN}{DOWN}{DOWN}{DOWN}{DOWN}{ENTER}')440    testRegex += 'sixth'441    442    #verification443    superConsole.SendKeys('outputRedirectStop{(}{)}{ENTER}')444    verifyResults(getTestOutput()[0], testRegex)445def test_raw_input():446    '''447    '''448    superConsole.SendKeys('outputRedirectStart{(}{)}{ENTER}')449    superConsole.SendKeys('x = raw_input{(}"foo"{)}{ENTER}')450    superConsole.SendKeys('{ENTER}')451    superConsole.SendKeys('print x{ENTER}')452    453    superConsole.SendKeys('x = raw_input{(}"foo"{)}{ENTER}')454    superConsole.SendKeys('abc{ENTER}')455    superConsole.SendKeys('print x{ENTER}')456    superConsole.SendKeys('outputRedirectStop{(}{)}{ENTER}')457    458    #verification459    lines = getTestOutput()[0]460    AreEqual(lines[2], '\n')461    AreEqual(lines[5], 'abc\n')462def unverified_raw_input():463    '''464    Intentionally not checking output on this test (based on465    CP14456) as redirecting stdout/stderr will hide the bug.466    '''467    superConsole.SendKeys('x = raw_input{(}"foo:"{)}{ENTER}')468    superConsole.SendKeys('{ENTER}')469#Run this first to corrupt other test cases if it's broken.470unverified_raw_input()471@disabled("CodePlex 4299")472def test_cp4299():473    superConsole.SendKeys('outputRedirectStart{(}{)}{ENTER}')474    superConsole.SendKeys('import sys{ENTER}')475    superConsole.SendKeys('print sys.ps1{ENTER}')476    superConsole.SendKeys('print sys.ps2{ENTER}')477    478    superConsole.SendKeys('sys.ps1 = "abc "{ENTER}')479    superConsole.SendKeys('sys.ps2 = "xyz "{ENTER}')480    superConsole.SendKeys('def f{(}{)}:{ENTER}    pass{ENTER}{ENTER}')481    superConsole.SendKeys('outputRedirectStop{(}{)}{ENTER}')482    lines = getTestOutput()[0]483    expected_lines = ['>>> import sys\n', 484                      '>>> print sys.ps1\n', '>>> \n', 485                      '>>> print sys.ps2\n', '... \n', 486                      '>>> sys.ps1 = "abc "\n', 'abc sys.ps2 = "xyz "\n', 487                      'abc def f():\n', 'xyz         pass\n', 'xyz         \n', 488                      'abc outputRedirectStop()\n']489    490    for i in xrange(len(lines)):491        AreEqual(lines[i], expected_lines[i])492    AreEqual(len(lines), len(expected_lines))            493    494def test_cp16520():495    superConsole.SendKeys('outputRedirectStart{(}{)}{ENTER}')496    superConsole.SendKeys('min{(}2,{ENTER}')497    superConsole.SendKeys('3{)}{ENTER}')498    superConsole.SendKeys('outputRedirectStop{(}{)}{ENTER}')499    500    #verification501    lines = getTestOutput()[0]502    expected_lines = [  ">>> min(2,\n",503                        "... 3)\n",504                        "2\n",505                        ">>> outputRedirectStop()\n"]506                   507    AreEqual(len(lines), len(expected_lines))508    for i in xrange(0, len(lines)):509        AreEqual(lines[i], expected_lines[i])                        510    511def test_decorator_cp21984():512    superConsole.SendKeys('outputRedirectStart{(}{)}{ENTER}')513    superConsole.SendKeys('{@}property{ENTER}')514    superConsole.SendKeys('def foo{(}{)}: pass{ENTER}{ENTER}')515    superConsole.SendKeys('outputRedirectStop{(}{)}{ENTER}')516    517    #verification518    lines = getTestOutput()[0]519    expected_lines = [  ">>> @property\n",520                        "... def foo(): pass\n",521                        "... \n",522                        ">>> outputRedirectStop()\n"]523                   524    AreEqual(len(lines), len(expected_lines))525    for i in xrange(0, len(lines)):526        AreEqual(lines[i], expected_lines[i])                        527def test_triple_strings():528    superConsole.SendKeys('outputRedirectStart{(}{)}{ENTER}')529    superConsole.SendKeys('"""{ENTER}')530    superConsole.SendKeys('hello"""{ENTER}')531    superConsole.SendKeys('outputRedirectStop{(}{)}{ENTER}')532    #verification533    lines = getTestOutput()[0]534    expected_lines = [  ">>> \"\"\"\n",535                        "... hello\"\"\"\n",536                        "'\\nhello'\n",537                        ">>> outputRedirectStop()\n"]538                   539    AreEqual(len(lines), len(expected_lines))540    for i in xrange(0, len(lines)):541        AreEqual(lines[i], expected_lines[i])  542def test_areraise():543    superConsole.SendKeys('outputRedirectStart{(}{)}{ENTER}')544    superConsole.SendKeys('def foo{(}{)}:{ENTER}{TAB}some(){ENTER}{ENTER}')545    superConsole.SendKeys(    'try:{ENTER}{TAB}foo{(}{)}{ENTER}{BACKSPACE}{BACKSPACE}{BACKSPACE}{BACKSPACE}')546    superConsole.SendKeys(    'except:{ENTER}{TAB}raise{ENTER}{ENTER}')547    sleep(3)548    superConsole.SendKeys('outputRedirectStop{(}{)}{ENTER}')549    lines = getTestOutput()[1]550    AreEqual(lines, ['Traceback (most recent call last):\r\n', '  File "<stdin>", line 2, in <module>\r\n', '  File "<stdin>", line 2, in foo\r\n', "NameError: global name 'some' is not defined\r\n"])551def test_syntax_errors():552    superConsole.SendKeys('outputRedirectStart{(}{)}{ENTER}')553    superConsole.SendKeys('def foo{(}{(}1{)}{)}: pass{ENTER}')554    superConsole.SendKeys('outputRedirectStop{(}{)}{ENTER}')555    lines = getTestOutput()[1]556    AreEqual(lines, ['  File "<stdin>", line 1\r\n', '    def foo((1)): pass\n', '\r\n', '             ^\r\n', "SyntaxError: unexpected token '1'\r\n", '\r\n'])557def test_missing_member_syntax_error_cp15428():558    superConsole.SendKeys('outputRedirectStart{(}{)}{ENTER}')559    superConsole.SendKeys('".".{ENTER}')560    superConsole.SendKeys('outputRedirectStop{(}{)}{ENTER}')561    lines = getTestOutput()[1]562    AreEqual(lines, ['  File "<stdin>", line 1\r\n', '    ".".\n', '\r\n', '        ^\r\n', "SyntaxError: syntax error\r\n", '\r\n'])563                    564def test_a_comment_newline():565    superConsole.SendKeys('outputRedirectStart{(}{)}{ENTER}')566    superConsole.SendKeys('def foo{(}{)}:{ENTER}    # hi{ENTER}    pass{ENTER}{ENTER}')567    superConsole.SendKeys('outputRedirectStop{(}{)}{ENTER}')568    lines = getTestOutput()[1]569    AreEqual(lines, [])570def test_aa_redirect_stdout():571    # CodePlex 25861, we should be able to return to the572    # REPL w/ output redirected.  If this doesn't work we573    # get an exception which fails the test.    574    f = file('test_superconsole_input.py', 'w')575    f.write("""576import sys577class _StreamLog(object):578    def __init__(self, ostream):579        self.ostream = ostream580    581    def write(self, *args):582        self.ostream.write("{")583        self.ostream.write(*args)584        self.ostream.write("}")585    586    def flush(self):587        self.ostream.flush()588sys.stderr = _StreamLog(sys.stderr)589sys.stdout = _StreamLog(sys.stdout)590""")591    f.close()592    try:593        superConsole.SendKeys('import test_superconsole_input{ENTER}')594        lines = getTestOutput()[0]595        superConsole.SendKeys('import sys{ENTER}')596        superConsole.SendKeys('sys.stdout = sys.__stdout__{ENTER}')597        superConsole.SendKeys('sys.stderr = sys.__stderr__{ENTER}')598        599    finally:600        nt.unlink('test_superconsole_input.py')601#------------------------------------------------------------------------------602#--__main__603try:604    if len(sys.argv)==2:605        print "Will run %s only..." % sys.argv[1]606        temp_func = eval(sys.argv[1])607        temp_func()608    else:609        run_test(__name__)610finally:611    # and finally test that F6 shuts it down612    superConsole.SendKeys('{F6}')613    superConsole.SendKeys('{ENTER}')614    sleep(5)...main.py
Source:main.py  
...6    kb = Keyboard()7    kb.sendCombo("r", mod=META)8    kb.typeKeys("notepad", ENTER)9    # kb.typeKeys("Hello World! 012345: This is a tilde (~)")10    # kb.sendKeys(ENTER, "This is probably super fast")11    # kb.typeKeys(ENTER, "This should technically type slowly")12    # kb.typeKeys(ENTER, "Tortoise mode", delay=0.5)13    kb.typeKeys("Hey there!", ENTER)14    kb.sendCombo("r", mod=META)15    kb.typeKeys("firefox", ENTER)16    sleep(1)17    kb.sendCombo(LEFT, mod=META)18    kb.sendCombo(ENTER)19    kb.execDelay = 0.420    kb.sendCombo(TAB, mod=ALT)21    kb.sendKeys("https://www.youtube.com/watch?v=_r2o3NdsfOA", ENTER)22    sleep(3)23    kb.sendKeys(" ")24    kb.sendCombo("t", mod=CTRL)25    kb.sendKeys("https://github.com/radiantly", ENTER)26    kb.sendCombo(TAB, mod=ALT)27    kb.sendKeys("\n" * 5)28    kb.typeKeys("I'm Joshua T.\n\n", delay=0.2)29    kb.sendCombo(TAB, mod=ALT)30    kb.sendCombo(F6)31    kb.sendKeys("https://radiantly.github.io", ENTER)32    kb.sendCombo(TAB, mod=ALT)33    kb.typeKeys("I'm an avid NodeJS and Python programmer, tech enthusiast and CTF player.")34    kb.sendCombo(TAB, mod=ALT)35    kb.sendCombo("t", mod=CTRL)36    kb.sendKeys("https://github.com/Jason13201", ENTER)37    kb.sendCombo(TAB, mod=ALT)38    kb.sendKeys("\n" * 5)39    kb.typeKeys("And I'm Jason H!\n\n", delay=0.2)40    # Feel free to change41    kb.typeKeys(42        "I'm a pro hacker, you'll probably find me hanging around in MLH hackathons and CTFs too!!"43    )44    sleep(1)45    kb.sendCombo("a", mod=CTRL)46    kb.sendKeys("\n" * 6)47    kb.typeKeys("Together, we've worked on a lot of projects")48    kb.sendCombo(TAB, mod=ALT)49    kb.sendCombo(F6)50    kb.sendKeys("https://devpost.com/software/hackerdash", ENTER)51    kb.sendCombo(TAB, mod=ALT)52    kb.typeKeys("\n\n<-- HackerDash!")53    kb.sendKeys(54        "\n(A dashboard for hackers that keeps them informed of the latest news and hackathons)"55    )56    # kb.sendKeys("\t" * 11)57    # for i in range(3):58    #     kb.sendKeys(ENTER)59    #     sleep(1.5)60    kb.sendCombo(TAB, mod=ALT)61    kb.sendKeys("\t" * 12)62    for i in range(4):63        kb.sendKeys(ENTER)64        sleep(2)65    kb.sendCombo(F6)66    kb.sendKeys("https://the-redirector.senorita.workers.dev", ENTER)67    kb.sendCombo(TAB, mod=ALT)68    kb.sendCombo(HOME, mod=SHIFT)69    for i in range(3):70        kb.sendCombo(UP, mod=SHIFT)71    kb.typeKeys("\n<-- The Redirector")72    kb.sendKeys("\n(A custom metadata link shortener built on CloudFlare Workers)")73    kb.typeKeys("\nThis may not look like much, but it's the easiest way to rickroll your friends ;)")74    kb.sendCombo(TAB, mod=ALT)75    kb.sendCombo(F6)76    kb.sendKeys("https://devpost.com/software/hackshare-tn675b", ENTER)77    kb.sendCombo(TAB, mod=ALT)78    kb.sendCombo(HOME, mod=SHIFT)79    for i in range(4):80        kb.sendCombo(UP, mod=SHIFT)81    kb.typeKeys("\n<-- Hack it, share it!")82    kb.sendKeys(83        "\n(A cross-platform flutter app that helps you share tips and tricks with the world)"84    )85    kb.sendCombo(TAB, mod=ALT)86    kb.sendKeys("\t" * 12)87    for i in range(3):88        kb.sendKeys(ENTER)89        sleep(2)90lastPush = time()91def button_callback(channel):92    global lastPush93    if time() - lastPush < 2:94        return95    lastPush = time()96    print("Button was pushed!")97    main()98if __name__ == "__main__":99    # main()100    io.setmode(io.BOARD)101    io.setup(11, io.IN, pull_up_down=io.PUD_DOWN)102    io.add_event_detect(11, io.RISING, callback=button_callback)...windows_input.py
Source:windows_input.py  
1###################################################################2#           Copyright (c) 2016 by TAOS Technologies, Inc.3#                     All rights reserved.4#5#  This file is proprietary and confidential to TAOS Technologies.6#  No part of this file may be reproduced, stored, transmitted,7#  disclosed or used in any form or by any means other than as8#  expressly provided by the written permission from Jianhui Tao9#10###################################################################11# -*- coding: utf-8 -*-12import os13from uiautomation import WindowControl14from util.cases import *15from util.sql import *16import clipboard17class TDTestCase:18    def init(self, conn, logSql):19        tdLog.debug("start to execute %s" % __file__)20        tdSql.init(conn.cursor(), logSql)21        self.host = conn._host22    def win_input_test(self):23        os.system("start")24        time.sleep(1)25        # è·åCMDçªå£26        # window = DocumentControl(searchDepth=3, Name='Text Area')27        window = WindowControl(searchDepth=1, AutomationId='Console Window')28        # åæ¢è±æè¾å
¥æ³29        # window.SendKeys('\\')30        # window.SendKeys('{Enter}')31        # window.SendKeys('{Shift}')32        # window.SendKeys('\\')33        # window.SendKeys('{Enter}')34        # 忢ç®å½35        window.SendKeys('c:')36        window.SendKeys('{Enter}')37        window.SendKeys('cd \\')38        window.SendKeys('{Enter}')39        window.SendKeys('cd c:\\TDengine')40        window.SendKeys('{Enter}')41        # å¯å¨taos.exe42        window.SendKeys('taos.exe -h %s || taos.exe' % (self.host))43        window.SendKeys('{Enter}')44        # è¾å
¥45        temp = ''46        for i in range(300):47            temp += 'a'48        sql = "insert into db.tb values(now,'%s');" % temp49        window.SendKeys(sql)50        window.SendKeys('{Enter}')51        window.SendKeys('{Ctrl}A')52        window.SendKeys('{Ctrl}C')53        # è·ååªåæ¿éé¢çå¤å¶å
容54        result = clipboard.paste()55        window.SendKeys('{Ctrl}C')56        window.SendKeys('exit')57        window.SendKeys('{Enter}')58        return result59    def run(self):60        tdSql.prepare()61        ret = tdSql.execute('create table tb (ts timestamp, i binary(300))')62        result = self.win_input_test()63        tdLog.info(result)64        tdSql.query("select * from tb")65        tdSql.checkRows(1)66    def stop(self):67        tdSql.close()68        tdLog.success("%s successfully executed" % __file__)69tdCases.addWindows(__file__, TDTestCase())...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!!
