Best Python code snippet using fMBT_python
fmbt.py
Source:fmbt.py  
...69def setCoverage(coverage):70    return _fmbt_call_helper("coverage.set",coverage)71def coverageValue():72    return _fmbt_call_helper("coverage.getValue")73def fmbtlog(msg, flush=True):74    try: file("/tmp/fmbt.fmbtlog", "a").write("%s\n" % (msg,))75    except: pass76def fmbtlograw(msg, flush=True):77    try: file("/tmp/fmbt.fmbtlog", "a").write("%s\n" % (msg,))78    except: pass79def adapterlog(msg, flush=True):80    try:81        _adapterlogWriter(file(_g_adapterlogFilename, "a"),82                          formatAdapterLogMessage(msg,))83    except: pass84def setAdapterLogWriter(func):85    """86    Override low-level adapter log writer with the given function. The87    function should take two parameters: a file-like object and a log88    message. The message is formatted and ready to be written to the89    file. The default is90    lambda fileObj, formattedMsg: fileObj.write(formattedMsg)91    """92    global _adapterlogWriter93    _adapterlogWriter = func94def adapterLogFilename():95    """96    Returns the filename to which the default fmbt.adapterlog() is97    writing.98    """99    return _g_adapterlogFilename100def setAdapterLogFilename(filename):101    """102    Set filename to which the default fmbt.adapterlog() function will103    write messages104    """105    global _g_adapterlogFilename106    _g_adapterlogFilename = filename107def adapterLogWriter():108    """109    Return current low-level adapter log writer function.110    """111    global _adapterlogWriter112    return _adapterlogWriter113def reportOutput(msg):114    try: file("/tmp/fmbt.reportOutput", "a").write("%s\n" % (msg,))115    except: pass116def setAdapterLogTimeFormat(strftime_format):117    """118    Use given time format string in timestamping adapterlog messages119    """120    global _g_fmbt_adapterlogtimeformat121    _g_fmbt_adapterlogtimeformat = strftime_format122def formatAdapterLogMessage(msg, fmt="%s %s\n"):123    """124    Return timestamped adapter log message as a string (not unicode)125    """126    s = fmt % (formatTime(_g_fmbt_adapterlogtimeformat), msg)127    if type(s) == unicode:128        s = s.encode("utf8")129    return s130def getActionName():131    """deprecated, use actionName()"""132    return _g_actionName133def actionName():134    """135    Return the name of currently executed action (input or output).136    """137    return _g_actionName138def lastExecutedActionName():139    """140    Return the name of the previously executed action.141    Counts only really executed actions, not simulated.142    """143    return _g_lastExecutedActionName144def getTestStep():145    """deprecated, use testStep()"""146    return _g_testStep147def testStep():148    """149    Return the number of currently executed test step.150    """151    return _g_testStep152def simulated():153    """154    Returns True if fMBT is simulating execution of an action (guard155    or body block) instead of really executing it.156    """157    return len(_g_simulated_actions) > 0158def _adapterlogWriter(fileObj, formattedMsg):159    fileObj.write(formattedMsg)160def funcSpec(func):161    """162    Return function name and args as they could have been defined163    based on function object.164    """165    argspec = inspect.getargspec(func)166    if argspec.defaults:167        kwarg_count = len(argspec.defaults)168    else:169        kwarg_count = 0170    arg_count = len(argspec.args) - kwarg_count171    arglist = [str(arg) for arg in argspec.args[:arg_count]]172    kwargs = argspec.args[arg_count:]173    for index, kwarg in enumerate(kwargs):174        arglist.append("%s=%s" % (kwarg, repr(argspec.defaults[index])))175    if argspec.varargs:176        arglist.append("*%s" % (argspec.varargs,))177    if argspec.keywords:178        arglist.append("**%s" % (argspec.keywords,))179    try:180        funcspec = "%s(%s)" % (func.func_name, ", ".join(arglist))181    except:182        funcspec = "%s(fmbt.funcSpec error)" % (func.func_name,)183    return funcspec184_g_debug_socket = None185_g_debug_conn = None186def debug(session=0):187    """188    Start debugging with fmbt-debug from the point where this function189    was called. Execution will stop until connection to fmbt-debug190    [session] has been established.191    Parameters:192      session (integer, optional):193              debug session that identifies which fmbt-debug should194              connect to this process. The default is 0.195    Example:196      - execute on command line "fmbt-debug 42"197      - add fmbt.debug(42) in your Python code198      - run the Python code so that it will call fmbt.debug(42)199      - when done the debugging on the fmbt-debug prompt, enter "c"200        for continue.201    """202    import bdb203    import inspect204    import pdb205    import socket206    global _g_debug_conn, _g_debug_socket207    if not _g_debug_socket:208        PORTBASE = 0xf4bd # 62653, fMBD209        host = "127.0.0.1" # accept local host only, by default210        port = PORTBASE + session211        _g_debug_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)212        try:213            _g_debug_socket.bind((host, port))214            _g_debug_socket.listen(1)215            while True:216                (_g_debug_conn, addr) = _g_debug_socket.accept()217                _g_debug_conn.sendall("fmbt.debug\n")218                msg = _g_debug_conn.recv(len("fmbt-debug\n"))219                if msg.startswith("fmbt-debug"):220                    break221                _g_debug_conn.close()222        except socket.error:223            # already in use, perhaps fmbt-debug is already listening to224            # the socket and waiting for this process to connect225            try:226                _g_debug_socket.connect((host, port))227                _g_debug_conn = _g_debug_socket228                whos_there = _g_debug_conn.recv(len("fmbt-debug\n"))229                if not whos_there.startswith("fmbt-debug"):230                    _g_debug_conn.close()231                    _g_debug_socket = None232                    _g_debug_conn = None233                    raise ValueError(234                        'unexpected answer "%s", fmbt-debug expected' %235                        (whos_there.strip(),))236                _g_debug_conn.sendall("fmbt.debug\n")237            except socket.error:238                raise ValueError('debugger cannot listen or connect to %s:%s' % (host, port))239    if not _g_debug_conn:240        fmbtlog("debugger waiting for connection at %s:%s" % (host, port))241    # socket.makefile does not work due to buffering issues242    # therefore, use our own socket-to-file converter243    class SocketToFile(object):244        def __init__(self, socket_conn):245            self._conn = socket_conn246        def read(self, bytes=-1):247            msg = []248            rv = ""249            try:250                c = self._conn.recv(1)251            except KeyboardInterrupt:252                self._conn.close()253                raise254            while c and not rv:...ps.py
Source:ps.py  
...27            env=run_env)28        out, err = p.communicate(input=stdin)29    except Exception, e:30        return (None, None, str(e))31    fmbt.fmbtlog("%s: soe got status=%r out=%r err=%r" % (fmbt.actionName(), p.returncode, out, err))32    return (p.returncode, out, err)33def bg(cmd):34    global last_bg_pid35    fmbt.fmbtlog("%s: bg run %r" % (fmbt.actionName(), cmd))36    p = subprocess.Popen(cmd, shell=False,37                         stdin=subprocess.PIPE,38                         stdout=subprocess.PIPE,39                         stderr=subprocess.PIPE)40    fmbt.fmbtlog("%s: bg pid %s" % (fmbt.actionName(), p.pid))41    thread.start_new_thread(readlines_to_adapterlog, (p.stdout, "%s out: " % (p.pid,)))42    thread.start_new_thread(readlines_to_adapterlog, (p.stderr, "%s err: " % (p.pid,)))...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!!
