Example #1
0
def checkMultipleCommands(scpiObj):
    _printHeader("Requesting more than one attribute per query")
    try:
        log = []
        for i in range(2, concatenatedCmds+1):
            lst = []
            for j in range(i):
                lst.append(_buildCommand2Test())
            cmds = "".join("%s;" % x for x in lst)[:-1]
            cmdsSplitted = "".join("\t\t%s\n" % cmd for cmd in cmds.split(';'))
            start_t = _time()
            answer = _send2Input(scpiObj, cmds)
            nAnswers = len(_cutMultipleAnswer(answer))
            log.append(_time() - start_t)
            print("\tRequest %d attributes in a single query: \n%s\tAnswer: "
                  "%r (%d, %g ms)\n" % (i, cmdsSplitted, answer, nAnswers,
                                        log[-1]*1000))
            if nAnswers != i:
                raise AssertionError("The answer doesn't have the %d expected "
                                     "elements" % (i))
            _interTestWait()
        # TODO: multiple writes
        result = True, "Many commands per query test PASSED"
    except Exception as e:
        print("\tUnexpected kind of exception! %s" % e)
        print_exc()
        result = False, "Many commands per query test FAILED"
    _printFooter(result[1])
    return result
Example #2
0
def checkMultipleCommands(scpiObj):
    _printHeader("Requesting more than one attribute per query")
    try:
        log = []
        for i in range(2, concatenatedCmds + 1):
            lst = []
            for j in range(i):
                lst.append(_buildCommand2Test())
            cmds = "".join("%s;" % x for x in lst)[:-1]
            cmdsSplitted = "".join("\t\t%s\n" % cmd for cmd in cmds.split(';'))
            start_t = _time()
            answer = _send2Input(scpiObj, cmds)
            nAnswers = len(_cutMultipleAnswer(answer))
            log.append(_time() - start_t)
            print("\tRequest %d attributes in a single query: \n%s\tAnswer: "
                  "%r (%d, %g ms)\n" %
                  (i, cmdsSplitted, answer, nAnswers, log[-1] * 1000))
            if nAnswers != i:
                raise AssertionError("The answer doesn't have the %d expected "
                                     "elements" % (i))
            _interTestWait()
        # TODO: multiple writes
        result = True, "Many commands per query test PASSED"
    except Exception as e:
        print("\tUnexpected kind of exception! %s" % e)
        print_exc()
        result = False, "Many commands per query test FAILED"
    _printFooter(result[1])
    return result
Example #3
0
def checkReadWithParams(scpiObj):
    _printHeader("Attribute read with parameters after the '?'")
    try:
        cmd = 'reader:with:parameters'
        longTest = ArrayTest(100)
        scpiObj.addCommand(cmd, readcb=longTest.readRange)
        answer = _send2Input(scpiObj, "DataFormat ASCII")
        if answer is None or len(answer) == 0:
            raise ValueError("Empty string")
        for i in range(10):
            bar, foo = _randint(0, 100), _randint(0, 100)
            start = min(bar, foo)
            end = max(bar, foo)
            # introduce a ' ' (write separator) after the '?' (read separator)
            cmdWithParams = "%s?%3s,%s" % (cmd, start, end)
            answer = _send2Input(scpiObj, cmdWithParams)
            print("\tRequest %s \n\tAnswer: %r (len %d)" % (cmdWithParams,
                                                            answer,
                                                            len(answer)))
            if answer is None or len(answer) == 0:
                raise ValueError("Empty string")
        cmdWithParams = "%s?%s,%s" % (cmd, start, end)
        result = True, "Read with parameters test PASSED"
    except Exception as e:
        print("\tUnexpected kind of exception! %s" % e)
        print_exc()
        result = False, "Read with parameters test FAILED"
    _printFooter(result[1])
    return result
Example #4
0
def checkReadWithParams(scpiObj):
    _printHeader("Attribute read with parameters after the '?'")
    try:
        cmd = 'reader:with:parameters'
        longTest = ArrayTest(100)
        scpiObj.addCommand(cmd, readcb=longTest.readRange)
        answer = _send2Input(scpiObj, "DataFormat ASCII")
        if answer is None or len(answer) == 0:
            raise ValueError("Empty string")
        for i in range(10):
            bar, foo = _randint(0, 100), _randint(0, 100)
            start = min(bar, foo)
            end = max(bar, foo)
            # introduce a ' ' (write separator) after the '?' (read separator)
            cmdWithParams = "%s?%3s,%s" % (cmd, start, end)
            answer = _send2Input(scpiObj, cmdWithParams)
            print("\tRequest %s \n\tAnswer: %r (len %d)" %
                  (cmdWithParams, answer, len(answer)))
            if answer is None or len(answer) == 0:
                raise ValueError("Empty string")
        cmdWithParams = "%s?%s,%s" % (cmd, start, end)
        result = True, "Read with parameters test PASSED"
    except Exception as e:
        print("\tUnexpected kind of exception! %s" % e)
        print_exc()
        result = False, "Read with parameters test FAILED"
    _printFooter(result[1])
    return result
Example #5
0
def checkTelnetHooks(scpiObj):
    _printHeader("Telnet hooks")
    try:
        ipv4 = Telnet("127.0.0.1", 5025)
        ipv6 = Telnet("::1", 5025)
        cmd = "*IDN?"

        def hook(who, what):
            _printInfo("\t\thook call, received: (%r, %r)" % (who, what))

        scpiObj.addConnectionHook(hook)
        _printInfo("\tipv4 send %s" % (cmd))
        ipv4.write(cmd)
        _printInfo("\tipv4 answer %r" % ipv4.read_until('\n'))
        _printInfo("\tipv6 send %s" % (cmd))
        ipv6.write(cmd)
        _printInfo("\tipv6 answer %r" % ipv6.read_until('\n'))
        scpiObj.removeConnectionHook(hook)
        ipv4.close()
        ipv6.close()
        result = True, "Telnet hooks test PASSED"
    except Exception as e:
        print("\tUnexpected kind of exception! %s" % e)
        print_exc()
        result = False, "Telnet hooks test FAILED"
    _printFooter(result[1])
    return result
Example #6
0
def addInvalidCmds(scpiObj):
    _printHeader("Testing to build invalid commands")
    try:
        scpiObj.addCommand(":startswithcolon", readcb=None)
    except NameError as e:
        print("\tNull name test PASSED")
    except Exception as e:
        print("\tUnexpected kind of exception! %s" % e)
        print_exc()
        return False, "Invalid commands test FAILED"
    try:
        scpiObj.addCommand("double::colons", readcb=None)
    except NameError as e:
        print("\tDouble colon name test PASSED")
    except Exception as e:
        print("\tUnexpected kind of exception! %s" % e)
        print_exc()
        return False, "Invalid commands test FAILED"
    try:
        scpiObj.addCommand("nestedSpecial:*special", readcb=None)
    except NameError as e:
        scpiObj._commandTree.pop('nestedSpecial')
        print("\tNested special command test PASSED")
    except Exception as e:
        print("\tUnexpected kind of exception! %s" % e)
        print_exc()
        return False, "Invalid commands test FAILED"
    result = True, "Invalid commands test PASSED"
    _printFooter(result[1])
    return result
Example #7
0
def addInvalidCmds(scpiObj):
    _printHeader("Testing to build invalid commands")
    try:
        scpiObj.addCommand(":startswithcolon", readcb=None)
    except NameError as e:
        print("\tNull name test PASSED")
    except Exception as e:
        print("\tUnexpected kind of exception! %s" % e)
        print_exc()
        return False, "Invalid commands test FAILED"
    try:
        scpiObj.addCommand("double::colons", readcb=None)
    except NameError as e:
        print("\tDouble colon name test PASSED")
    except Exception as e:
        print("\tUnexpected kind of exception! %s" % e)
        print_exc()
        return False, "Invalid commands test FAILED"
    try:
        scpiObj.addCommand("nestedSpecial:*special", readcb=None)
    except NameError as e:
        scpiObj._commandTree.pop('nestedSpecial')
        print("\tNested special command test PASSED")
    except Exception as e:
        print("\tUnexpected kind of exception! %s" % e)
        print_exc()
        return False, "Invalid commands test FAILED"
    result = True, "Invalid commands test PASSED"
    _printFooter(result[1])
    return result
Example #8
0
def checkLocks(scpiObj):
    _printHeader("system [write]lock")
    try:
        LockThreadedTest(scpiObj).launchTest()
        result = True, "system [write]lock test PASSED"
    except Exception as e:
        print("\tUnexpected kind of exception! %s" % e)
        print_exc()
        result = False, "system [write]lock test FAILED"
    _printFooter(result[1])
    return result
Example #9
0
def checkLocks(scpiObj):
    _printHeader("system [write]lock")
    try:
        LockThreadedTest(scpiObj).launchTest()
        result = True, "system [write]lock test PASSED"
    except Exception as e:
        print("\tUnexpected kind of exception! %s" % e)
        print_exc()
        result = False, "system [write]lock test FAILED"
    _printFooter(result[1])
    return result
Example #10
0
def checkNonexistingCommands(scpiObj):
    _printHeader("Testing to query commands that doesn't exist")
    try:
        baseCmd = _randomchoice(['SOURce', 'BASIcloop', 'ITERative'])
        subCmd = _randomchoice(['CURRent', 'VOLTage'])
        attr = _randomchoice(['UPPEr', 'LOWEr', 'VALUe'])
        fake = "FAKE"
        # * first level doesn't exist
        start_t = _time()
        cmd = "%s:%s:%s?" % (fake, subCmd, attr)
        answer = _send2Input(scpiObj, cmd)
        print("\tRequest non-existing command %s\n\tAnswer: %r (%g ms)" %
              (cmd, answer, (_time() - start_t) * 1000))
        # * intermediate level doesn't exist
        cmd = "%s:%s:%s?" % (baseCmd, fake, attr)
        answer = _send2Input(scpiObj, cmd)
        print("\tRequest non-existing command %s\n\tAnswer: %r (%g ms)" %
              (cmd, answer, (_time() - start_t) * 1000))
        # * Attribute level doesn't exist
        cmd = "%s:%s:%s?" % (baseCmd, subCmd, fake)
        answer = _send2Input(scpiObj, cmd)
        print("\tRequest non-existing command %s\n\tAnswer: %r (%g ms)" %
              (cmd, answer, (_time() - start_t) * 1000))
        # * Attribute that doesn't respond
        cmd = 'source:voltage:exception'
        answer = _send2Input(scpiObj, cmd)
        print("\tRequest existing command but that it raises an exception %s"
              "\n\tAnswer: %r (%g ms)" % (cmd, answer,
                                          (_time() - start_t) * 1000))
        # * Unexisting Channel
        baseCmd = "CHANnel%s" % (str(nChannels + 3).zfill(2))
        cmd = "%s:%s:%s?" % (baseCmd, subCmd, fake)
        answer = _send2Input(scpiObj, cmd)
        print("\tRequest non-existing channel %s\n\tAnswer: %r (%g ms)" %
              (cmd, answer, (_time() - start_t) * 1000))
        # * Channel below the minimum reference
        cmd = "CHANnel00:VOLTage:UPPEr?"
        answer = _send2Input(scpiObj, cmd)
        print("\tRequest non-existing channel %s\n\tAnswer: %r (%g ms)" %
              (cmd, answer, (_time() - start_t) * 1000))
        # * Channel above the maximum reference
        cmd = "CHANnel99:VOLTage:UPPEr?"
        answer = _send2Input(scpiObj, cmd)
        print("\tRequest non-existing channel %s\n\tAnswer: %r (%g ms)" %
              (cmd, answer, (_time() - start_t) * 1000))
        result = True, "Non-existing commands test PASSED"
    except Exception as e:
        print("\tUnexpected kind of exception! %s" % e)
        print_exc()
        result = False, "Non-existing commands test FAILED"
    _printFooter(result[1])
    return result
Example #11
0
def checkNonexistingCommands(scpiObj):
    _printHeader("Testing to query commands that doesn't exist")
    try:
        baseCmd = _randomchoice(['SOURce', 'BASIcloop', 'ITERative'])
        subCmd = _randomchoice(['CURRent', 'VOLTage'])
        attr = _randomchoice(['UPPEr', 'LOWEr', 'VALUe'])
        fake = "FAKE"
        # * first level doesn't exist
        start_t = _time()
        cmd = "%s:%s:%s?" % (fake, subCmd, attr)
        answer = _send2Input(scpiObj, cmd)
        print("\tRequest non-existing command %s\n\tAnswer: %r (%g ms)"
              % (cmd, answer, (_time()-start_t)*1000))
        # * intermediate level doesn't exist
        cmd = "%s:%s:%s?" % (baseCmd, fake, attr)
        answer = _send2Input(scpiObj, cmd)
        print("\tRequest non-existing command %s\n\tAnswer: %r (%g ms)"
              % (cmd, answer, (_time()-start_t)*1000))
        # * Attribute level doesn't exist
        cmd = "%s:%s:%s?" % (baseCmd, subCmd, fake)
        answer = _send2Input(scpiObj, cmd)
        print("\tRequest non-existing command %s\n\tAnswer: %r (%g ms)"
              % (cmd, answer, (_time()-start_t)*1000))
        # * Attribute that doesn't respond
        cmd = 'source:voltage:exception'
        answer = _send2Input(scpiObj, cmd)
        print("\tRequest existing command but that it raises an exception %s"
              "\n\tAnswer: %r (%g ms)" % (cmd, answer, (_time()-start_t)*1000))
        # * Unexisting Channel
        baseCmd = "CHANnel%s" % (str(nChannels+3).zfill(2))
        cmd = "%s:%s:%s?" % (baseCmd, subCmd, fake)
        answer = _send2Input(scpiObj, cmd)
        print("\tRequest non-existing channel %s\n\tAnswer: %r (%g ms)"
              % (cmd, answer, (_time()-start_t)*1000))
        # * Channel below the minimum reference
        cmd = "CHANnel00:VOLTage:UPPEr?"
        answer = _send2Input(scpiObj, cmd)
        print("\tRequest non-existing channel %s\n\tAnswer: %r (%g ms)"
              % (cmd, answer, (_time()-start_t)*1000))
        # * Channel above the maximum reference
        cmd = "CHANnel99:VOLTage:UPPEr?"
        answer = _send2Input(scpiObj, cmd)
        print("\tRequest non-existing channel %s\n\tAnswer: %r (%g ms)"
              % (cmd, answer, (_time()-start_t)*1000))
        result = True, "Non-existing commands test PASSED"
    except Exception as e:
        print("\tUnexpected kind of exception! %s" % e)
        print_exc()
        result = False, "Non-existing commands test FAILED"
    _printFooter(result[1])
    return result
Example #12
0
def checkCommandQueries(scpiObj):
    _printHeader("Testing to command queries")
    try:
        print("Launch tests:")
        cmd = "*IDN?"
        answer = _send2Input(scpiObj, cmd)
        print("\tInstrument identification (%s)\n\tAnswer: %s" % (cmd, answer))
        for baseCmd in ['SOURce', 'BASIcloop', 'ITERative']:
            _printHeader("Check %s part of the tree" % (baseCmd))
            _doCheckCommands(scpiObj, baseCmd)
        for ch in range(1, nChannels+1):
            baseCmd = "CHANnel%s" % (str(ch).zfill(2))
            _printHeader("Check %s part of the tree" % (baseCmd))
            _doCheckCommands(scpiObj, baseCmd)
            fn = _randomchoice(range(1, nSubchannels+1))
            innerCmd = "FUNCtion%s" % (str(fn).zfill(2))
            _printHeader("Check %s + MEAS:%s part of the tree"
                         % (baseCmd, innerCmd))
            _doCheckCommands(scpiObj, baseCmd, innerCmd)
        result = True, "Command queries test PASSED"
    except Exception as e:
        print("\tUnexpected kind of exception! %s" % e)
        print_exc()
        result = False, "Command queries test FAILED"
    _printFooter(result[1])
    return result
Example #13
0
def checkCommandQueries(scpiObj):
    _printHeader("Testing to command queries")
    try:
        print("Launch tests:")
        cmd = "*IDN?"
        answer = _send2Input(scpiObj, cmd)
        print("\tInstrument identification (%s)\n\tAnswer: %s" % (cmd, answer))
        for baseCmd in ['SOURce', 'BASIcloop', 'ITERative']:
            _printHeader("Check %s part of the tree" % (baseCmd))
            _doCheckCommands(scpiObj, baseCmd)
        for ch in range(1, nChannels + 1):
            baseCmd = "CHANnel%s" % (str(ch).zfill(2))
            _printHeader("Check %s part of the tree" % (baseCmd))
            _doCheckCommands(scpiObj, baseCmd)
            fn = _randomchoice(range(1, nSubchannels + 1))
            innerCmd = "FUNCtion%s" % (str(fn).zfill(2))
            _printHeader("Check %s + MEAS:%s part of the tree" %
                         (baseCmd, innerCmd))
            _doCheckCommands(scpiObj, baseCmd, innerCmd)
        result = True, "Command queries test PASSED"
    except Exception as e:
        print("\tUnexpected kind of exception! %s" % e)
        print_exc()
        result = False, "Command queries test FAILED"
    _printFooter(result[1])
    return result
Example #14
0
def checkIDN(scpiObj):
    _printHeader("Test instrument identification")
    try:
        identity = InstrumentIdentification('ALBA', 'test', 0, _version())
        scpiObj.addSpecialCommand('IDN', identity.idn)
        cmd = "*idn?"
        answer = _send2Input(scpiObj, cmd)
        print("\tRequest identification: %s\n\tAnswer: %r" % (cmd, answer))
        result = True, "Identification test PASSED"
    except Exception as e:
        print("\tUnexpected kind of exception! %s" % e)
        print_exc()
        result = False, "Identification test FAILED"
    _printFooter(result[1])
    return result
Example #15
0
def checkIDN(scpiObj):
    _printHeader("Test instrument identification")
    try:
        identity = InstrumentIdentification('ALBA', 'test', 0, _version())
        scpiObj.addSpecialCommand('IDN', identity.idn)
        cmd = "*idn?"
        answer = _send2Input(scpiObj, cmd)
        print("\tRequest identification: %s\n\tAnswer: %r" % (cmd, answer))
        result = True, "Identification test PASSED"
    except Exception as e:
        print("\tUnexpected kind of exception! %s" % e)
        print_exc()
        result = False, "Identification test FAILED"
    _printFooter(result[1])
    return result
Example #16
0
def checkWriteWithoutParams(scpiObj):
    _printHeader("Attribute write without parameters")
    try:
        cmd = 'writter:without:parameters'
        switch = WattrTest()
        scpiObj.addCommand(cmd, readcb=switch.switchTest)
        for i in range(3):
            cmd = "%s%s" % (cmd, " " * i)
            answer = _send2Input(scpiObj, cmd, checkAnswer=False)
            print("\tRequest %s \n\tAnswer: %r (len %d)" %
                  (cmd, answer, len(answer)))
        result = True, "Write without parameters test PASSED"
    except Exception as e:
        print("\tUnexpected kind of exception! %s" % e)
        print_exc()
        result = False, "Write without parameters test FAILED"
    _printFooter(result[1])
    return result
Example #17
0
def checkWriteWithoutParams(scpiObj):
    _printHeader("Attribute write without parameters")
    try:
        cmd = 'writter:without:parameters'
        switch = WattrTest()
        scpiObj.addCommand(cmd, readcb=switch.switchTest)
        for i in range(3):
            cmd = "%s%s" % (cmd, " "*i)
            answer = _send2Input(scpiObj, cmd)
            print("\tRequest %s \n\tAnswer: %r (len %d)" % (cmd, answer,
                                                            len(answer)))
            if answer is None or len(answer) == 0:
                raise ValueError("Empty string")
        result = True, "Write without parameters test PASSED"
    except Exception as e:
        print("\tUnexpected kind of exception! %s" % e)
        print_exc()
        result = False, "Write without parameters test FAILED"
    _printFooter(result[1])
    return result
Example #18
0
def lockTake(lockObj):
    testName = "Initial state test"
    _printHeader("Test the initial state of the %s object" % lockObj)
    _printInfo("%r" % (lockObj), 1)

    _printInfo("Check if it is lock", level=1, top=True)
    if lockObj.isLock():
        return False, "%s FAILED" % (testName)
    _printInfo("%s is not lock" % (lockObj), level=1, bottom=True)

    _printInfo("Check if it lock can be requested", level=1, top=True)
    if not lockObj.request():
        return False, "%s FAILED" % (testName)
    _printInfo("%r is now lock" % (lockObj), level=1, bottom=True)

    _printInfo("Check if it lock can be released", level=1, top=True)
    if not lockObj.release():
        return False, "%s FAILED" % (testName)
    _printInfo("%r is now released" % (lockObj), level=1, bottom=True)

    return True, "%s PASSED" % (testName)
Example #19
0
def lockTake(lockObj):
    testName = "Initial state test"
    _printHeader("Test the initial state of the %s object" % lockObj)
    _printInfo("%r" % (lockObj), 1)

    _printInfo("Check if it is lock", level=1, top=True)
    if lockObj.isLock():
        return False, "%s FAILED" % (testName)
    _printInfo("%s is not lock" % (lockObj), level=1, bottom=True)

    _printInfo("Check if it lock can be requested", level=1, top=True)
    if not lockObj.request():
        return False, "%s FAILED" % (testName)
    _printInfo("%r is now lock" % (lockObj), level=1, bottom=True)

    _printInfo("Check if it lock can be released", level=1, top=True)
    if not lockObj.release():
        return False, "%s FAILED" % (testName)
    _printInfo("%r is now released" % (lockObj), level=1, bottom=True)

    return True, "%s PASSED" % (testName)
Example #20
0
def checkArrayAnswers(scpiObj):
    _printHeader("Requesting an attribute the answer of which is an array")
    try:
        baseCmd = 'source'
        attrCmd = 'buffer'
        longTest = ArrayTest(100)
        scpiObj.addCommand(attrCmd, readcb=longTest.readTest)
        # current
        CurrentObj = ArrayTest(5)
        CurrentCmd = "%s:current:%s" % (baseCmd, attrCmd)
        scpiObj.addCommand(CurrentCmd, readcb=CurrentObj.readTest)
        # voltage
        VoltageObj = ArrayTest(5)
        VoltageCmd = "%s:voltage:%s" % (baseCmd, attrCmd)
        scpiObj.addCommand(VoltageCmd, readcb=VoltageObj.readTest)
        # queries
        answersLengths = {}
        for cmd in [attrCmd, CurrentCmd, VoltageCmd]:
            for format in ['ASCII', 'QUADRUPLE', 'DOUBLE', 'SINGLE', 'HALF']:
                answer = _send2Input(scpiObj,
                                     "DataFormat %s" % (format),
                                     checkAnswer=False)
                answer = _send2Input(scpiObj, cmd + '?')
                print("\tRequest %s \n\tAnswer: %r (len %d)" %
                      (cmd, answer, len(answer)))
                if format not in answersLengths:
                    answersLengths[format] = []
                answersLengths[format].append(len(answer))
        print("\n\tanswer lengths summary: %s" %
              "".join('\n\t\t{}:{}'.format(k, v)
                      for k, v in answersLengths.iteritems()))
        result = True, "Array answers test PASSED"
    except Exception as e:
        print("\tUnexpected kind of exception! %s" % e)
        print_exc()
        result = False, "Array answers test FAILED"
    _printFooter(result[1])
    return result
Example #21
0
def checkArrayAnswers(scpiObj):
    _printHeader("Requesting an attribute the answer of which is an array")
    try:
        baseCmd = 'source'
        attrCmd = 'buffer'
        longTest = ArrayTest(100)
        scpiObj.addCommand(attrCmd, readcb=longTest.readTest)
        # current
        CurrentObj = ArrayTest(5)
        CurrentCmd = "%s:current:%s" % (baseCmd, attrCmd)
        scpiObj.addCommand(CurrentCmd, readcb=CurrentObj.readTest)
        # voltage
        VoltageObj = ArrayTest(5)
        VoltageCmd = "%s:voltage:%s" % (baseCmd, attrCmd)
        scpiObj.addCommand(VoltageCmd, readcb=VoltageObj.readTest)
        # queries
        answersLengths = {}
        for cmd in [attrCmd, CurrentCmd, VoltageCmd]:
            for format in ['ASCII', 'QUADRUPLE', 'DOUBLE', 'SINGLE', 'HALF']:
                answer = _send2Input(scpiObj, "DataFormat %s" % (format))
                answer = _send2Input(scpiObj, cmd + '?')
                print("\tRequest %s \n\tAnswer: %r (len %d)" % (cmd, answer,
                                                                len(answer)))
                if format not in answersLengths:
                    answersLengths[format] = []
                answersLengths[format].append(len(answer))
        print("\n\tanswer lengths summary: %s"
              % "".join('\n\t\t{}:{}'.format(k, v)
                        for k, v in answersLengths.iteritems()))
        result = True, "Array answers test PASSED"
    except Exception as e:
        print("\tUnexpected kind of exception! %s" % e)
        print_exc()
        result = False, "Array answers test FAILED"
    _printFooter(result[1])
    return result
Example #22
0
def testScpi(debug=False):
    start_t = _time()
    _printHeader("Testing scpi main class (version %s)" % (_version()))
    # ---- BuildSpecial('IDN',specialSet,identity.idn)
    with scpi(local=True, debug=debug, writeLock=True) as scpiObj:
        if debug:
            print(".")
            scpiObj.logLevel(_logger_DEBUG)
            scpiObj.log2File(True)
            scpiObj._debug("Log information: %s" % (scpiObj.loggingFile()))
            print("..")
        results = []
        resultMsgs = []
        for test in [checkIDN,
                     addInvalidCmds,
                     addValidCommands,
                     checkCommandQueries,
                     checkCommandWrites,
                     checkNonexistingCommands,
                     checkArrayAnswers,
                     checkMultipleCommands,
                     checkReadWithParams,
                     checkWriteWithoutParams,
                     checkLocks]:
            result, msg = test(scpiObj)
            results.append(result)
            tag, value = msg.rsplit(' ', 1)
            resultMsgs.append([tag, value])
            _afterTestWait()
    if all(results):
        _printHeader("All tests passed: everything OK (%g s)"
                     % (_time()-start_t))
    else:
        _printHeader("ALERT!! NOT ALL THE TESTS HAS PASSED. Check the list "
                     "(%g s)" % (_time()-start_t))
    length = 0
    for pair in resultMsgs:
        if len(pair[0]) > length:
            length = len(pair[0])
    for result in resultMsgs:
        print("%s%s\t%s%s" % (result[0], " "*(length-len(result[0])),
                              result[1],
                              " *" if result[1] == 'FAILED' else ""))
    print("")
Example #23
0
def testScpi(debug=False):
    start_t = _time()
    _printHeader("Testing scpi main class (version %s)" % (_version()))
    # ---- BuildSpecial('IDN',specialSet,identity.idn)
    with scpi(local=True, debug=debug, writeLock=True) as scpiObj:
        if debug:
            print(".")
            scpiObj.logLevel(_logger_DEBUG)
            scpiObj.log2File(True)
            scpiObj._debug("Log information: %s" % (scpiObj.loggingFile()))
            print("..")
        results = []
        resultMsgs = []
        for test in [
                checkIDN, addInvalidCmds, addValidCommands,
                checkCommandQueries, checkCommandWrites,
                checkNonexistingCommands, checkArrayAnswers,
                checkMultipleCommands, checkReadWithParams,
                checkWriteWithoutParams, checkLocks
        ]:
            result, msg = test(scpiObj)
            results.append(result)
            tag, value = msg.rsplit(' ', 1)
            resultMsgs.append([tag, value])
            _afterTestWait()
    if all(results):
        _printHeader("All tests passed: everything OK (%g s)" %
                     (_time() - start_t))
    else:
        _printHeader("ALERT!! NOT ALL THE TESTS HAS PASSED. Check the list "
                     "(%g s)" % (_time() - start_t))
    length = 0
    for pair in resultMsgs:
        if len(pair[0]) > length:
            length = len(pair[0])
    for result in resultMsgs:
        print("%s%s\t%s%s" %
              (result[0], " " * (length - len(result[0])), result[1],
               " *" if result[1] == 'FAILED' else ""))
    print("")
Example #24
0
def multithreadingTake(lockObj):
    def sendEvent(eventLst, who):
        eventLst[who].set()
        while eventLst[who].isSet():  # wait to the thread to work
            _sleep(1)
    testName = "Lock take test"
    _printHeader("%s for %s" % (testName, lockObj))
    joinerEvent = _Event()
    joinerEvent.clear()
    userThreads = []
    requestEvents = []
    accessEvents = []
    releaseEvents = []
    printLock = _Lock()
    for i in range(2):
        requestEvent = _Event()
        accessEvent = _Event()
        releaseEvent = _Event()
        userThread = _Thread(target=threadFunction,
                             args=(lockObj, joinerEvent,
                                   requestEvent, accessEvent, releaseEvent,
                                   printLock),
                             name='%d' % (i))
        requestEvents.append(requestEvent)
        accessEvents.append(accessEvent)
        releaseEvents.append(releaseEvent)
        userThreads.append(userThread)
        userThread.start()
    # here is where the test starts ---
    try:
        _printInfo("Initial state %r\n" % (lockObj),
                   level=1, lock=printLock)
        if lockObj.isLock():
            return False, "%s FAILED" % (testName)

        _printInfo("Tell the threads to access",
                   level=1, lock=printLock, top=True)
        sendEvent(accessEvents, 0)
        sendEvent(accessEvents, 1)
        _printInfo("both should have had access",
                   level=1, lock=printLock, bottom=True)

        _printInfo("Thread 0 take the lock",
                   level=1, lock=printLock, top=True)
        sendEvent(requestEvents, 0)
        if not lockObj.isLock() or lockObj.owner != '0':
            raise Exception("It shall be lock by 0")
        _printInfo("Tell the threads to access",
                   level=1, lock=printLock)
        sendEvent(accessEvents, 0)
        sendEvent(accessEvents, 1)
        _printInfo("0 should, but 1 don't",
                   level=1, lock=printLock, bottom=True)

        _printInfo("Try to lock when it is already",
                   level=1, lock=printLock, top=True)
        sendEvent(requestEvents, 1)
        if not lockObj.isLock() or lockObj.owner != '0':
            raise Exception("It shall be lock by user 0")
        _printInfo("Tell the threads to access",
                   level=1, lock=printLock)
        sendEvent(accessEvents, 0)
        sendEvent(accessEvents, 1)
        _printInfo("0 should, but 1 don't",
                   level=1, lock=printLock, bottom=True)

        _printInfo("Try to release by a NON-owner",
                   level=1, lock=printLock, top=True)
        sendEvent(releaseEvents, 1)
        if not lockObj.isLock() or lockObj.owner != '0':
            raise Exception("It shall be lock by user 0")
        _printInfo("Tell the threads to access",
                   level=1, lock=printLock)
        sendEvent(accessEvents, 0)
        sendEvent(accessEvents, 1)
        _printInfo("0 should, but 1 don't",
                   level=1, lock=printLock, bottom=True)

        _printInfo("release the lock",
                   level=1, lock=printLock, top=True)
        sendEvent(releaseEvents, 0)
        if lockObj.isLock():
            raise Exception("It shall be released")
        _printInfo("Tell the threads to access",
                   level=1, lock=printLock)
        sendEvent(accessEvents, 0)
        sendEvent(accessEvents, 1)
        _printInfo("both should have had to",
                   level=1, lock=printLock, bottom=True)

        # TODO: timeout
        _printInfo("Thread 1 take the lock and expire it",
                   level=1, lock=printLock, top=True)
        sendEvent(requestEvents, 1)
        if not lockObj.isLock() or lockObj.owner != '1':
            raise Exception("It shall be lock by 1")
        _printInfo("Tell the threads to access",
                   level=1, lock=printLock)
        sendEvent(accessEvents, 0)
        sendEvent(accessEvents, 1)
        _printInfo("1 should, but 0 don't",
                   level=1, lock=printLock)
        _printInfo("Sleep %d seconds to expire the lock"
                   % TEST_EXPIRATION_TIME,
                   level=1, lock=printLock)
        _sleep(TEST_EXPIRATION_TIME)
        _printInfo("Tell the threads to access",
                   level=1, lock=printLock)
        sendEvent(accessEvents, 0)
        sendEvent(accessEvents, 1)
        _printInfo("both should have had to",
                   level=1, lock=printLock, bottom=True)

        answer = True, "%s PASSED" % (testName)
    except Exception as e:
        print(e)
        print_exc()
        answer = False, "%s FAILED" % (testName)
    joinerEvent.set()
    while len(userThreads) > 0:
        userThread = userThreads.pop()
        userThread.join(1)
        if userThread.isAlive():
            userThreads.append(userThread)
    print("All threads has finished")
    return answer
Example #25
0
def checkCommandWrites(scpiObj):
    _printHeader("Testing to command writes")
    try:
        # simple commands ---
        currentConfObj = WattrTest()
        scpiObj.addCommand('source:current:configure',
                           readcb=currentConfObj.readTest,
                           writecb=currentConfObj.writeTest)
        voltageConfObj = WattrTest()
        scpiObj.addCommand('source:voltage:configure',
                           readcb=voltageConfObj.readTest,
                           writecb=voltageConfObj.writeTest)
        for inner in ['current', 'voltage']:
            _doWriteCommand(scpiObj, "source:%s:configure" % (inner))
        _wait(1)  # FIXME: remove
        # channel commands ---
        _printHeader("Testing to channel command writes")
        baseCmd = 'writable'
        wObj = scpiObj.addComponent(baseCmd, scpiObj._commandTree)
        chCmd = 'channel'
        chObj = scpiObj.addChannel(chCmd, nChannels, wObj)
        chCurrentObj = WchannelTest(nChannels)
        chVoltageObj = WchannelTest(nChannels)
        for (subcomponent, subCmdObj) in [('current', chCurrentObj),
                                          ('voltage', chVoltageObj)]:
            subcomponentObj = scpiObj.addComponent(subcomponent, chObj)
            for (attrName, attrFunc) in [('upper', 'upperLimit'),
                                         ('lower', 'lowerLimit'),
                                         ('value', 'readTest')]:
                if hasattr(subCmdObj, attrFunc):
                    if attrName == 'value':
                        attrObj = scpiObj.addAttribute(
                            attrName,
                            subcomponentObj,
                            readcb=subCmdObj.readTest,
                            writecb=subCmdObj.writeTest,
                            default=True)
                    else:
                        cbFunc = getattr(subCmdObj, attrFunc)
                        attrObj = scpiObj.addAttribute(attrName,
                                                       subcomponentObj, cbFunc)
        print("\nChecking one write multiple reads\n")
        for i in range(nChannels):
            rndCh = _randint(1, nChannels)
            element = _randomchoice(['current', 'voltage'])
            _doWriteChannelCommand(scpiObj, "%s:%s" % (baseCmd, chCmd), rndCh,
                                   element, nChannels)
            _interTestWait()
        print("\nChecking multile writes multiple reads\n")
        for i in range(nChannels):
            testNwrites = _randint(2, nChannels)
            rndChs = []
            while len(rndChs) < testNwrites:
                rndCh = _randint(1, nChannels)
                while rndCh in rndChs:
                    rndCh = _randint(1, nChannels)
                rndChs.append(rndCh)
            element = _randomchoice(['current', 'voltage'])
            values = [_randint(-1000, 1000)] * testNwrites
            _doWriteChannelCommand(scpiObj, "%s:%s" % (baseCmd, chCmd), rndChs,
                                   element, nChannels, values)
            _interTestWait()
        print("\nChecking write with allowed values limitation\n")
        selectionCmd = 'source:selection'
        selectionObj = WattrTest()
        selectionObj.writeTest(False)
        scpiObj.addCommand(selectionCmd,
                           readcb=selectionObj.readTest,
                           writecb=selectionObj.writeTest,
                           allowedArgins=[True, False])
        _doWriteCommand(scpiObj, selectionCmd, True)
        # _doWriteCommand(scpiObj, selectionCmd, 'Fals')
        # _doWriteCommand(scpiObj, selectionCmd, 'True')
        try:
            _doWriteCommand(scpiObj, selectionCmd, 0)
        except:
            print("\tLimitation values succeed because it raises an exception "
                  "as expected")
        else:
            raise AssertionError("It has been write a value that "
                                 "should not be allowed")
        _interTestWait()
        result = True, "Command writes test PASSED"
    except Exception as e:
        print("\tUnexpected kind of exception! %s" % e)
        print_exc()
        result = False, "Command writes test FAILED"
    _printFooter(result[1])
    return result
Example #26
0
def addValidCommands(scpiObj):
    _printHeader("Testing to build valid commands")
    try:
        # ---- valid commands section
        currentObj = AttrTest()
        voltageObj = AttrTest()
        # * commands can de added by telling their full name:
        scpiObj.addCommand('source:current:upper',
                           readcb=currentObj.upperLimit,
                           writecb=currentObj.upperLimit)
        scpiObj.addCommand('source:current:lower',
                           readcb=currentObj.lowerLimit,
                           writecb=currentObj.lowerLimit)
        scpiObj.addCommand('source:current:value',
                           readcb=currentObj.readTest,
                           default=True)
        scpiObj.addCommand('source:voltage:upper',
                           readcb=voltageObj.upperLimit,
                           writecb=voltageObj.upperLimit)
        scpiObj.addCommand('source:voltage:lower',
                           readcb=voltageObj.lowerLimit,
                           writecb=voltageObj.lowerLimit)
        scpiObj.addCommand('source:voltage:value', readcb=voltageObj.readTest,
                           default=True)
        scpiObj.addCommand('source:voltage:exception',
                           readcb=voltageObj.exceptionTest)
        # * They can be also created in an iterative way
        baseCmdName = 'basicloop'
        for (subCmdName, subCmdObj) in [('current', currentObj),
                                        ('voltage', voltageObj)]:
            for (attrName, attrFunc) in [('upper', 'upperLimit'),
                                         ('lower', 'lowerLimit'),
                                         ('value', 'readTest')]:
                if hasattr(subCmdObj, attrFunc):
                    cbFunc = getattr(subCmdObj, attrFunc)
                    if attrName == 'value':
                        default = True
                    else:
                        default = False
                    scpiObj.addCommand('%s:%s:%s'
                                       % (baseCmdName, subCmdName, attrName),
                                       readcb=cbFunc, default=default)
                    # Basically is the same than the first example, but the
                    # addCommand is constructed with variables in neasted loops
        # * Another alternative to create the tree in an iterative way would be
        itCmd = 'iterative'
        itObj = scpiObj.addComponent(itCmd, scpiObj._commandTree)
        for (subcomponent, subCmdObj) in [('current', currentObj),
                                          ('voltage', voltageObj)]:
            subcomponentObj = scpiObj.addComponent(subcomponent, itObj)
            for (attrName, attrFunc) in [('upper', 'upperLimit'),
                                         ('lower', 'lowerLimit'),
                                         ('value', 'readTest')]:
                if hasattr(subCmdObj, attrFunc):
                    cbFunc = getattr(subCmdObj, attrFunc)
                    if attrName == 'value':
                        default = True
                    else:
                        default = False
                    attrObj = scpiObj.addAttribute(attrName, subcomponentObj,
                                                   cbFunc, default=default)
                else:
                    print("%s hasn't %s" % (subcomponentObj, attrFunc))
                    # In this case, the intermediate objects of the tree are
                    # build and it is in the innier loop where they have the
                    # attributes created.
                    #  * Use with very big care this option because the library
                    #  * don't guarantee that all the branches of the tree will
                    #  * have the appropiate leafs.
        # * Example of how can be added a node with channels in the scpi tree
        chCmd = 'channel'
        chObj = scpiObj.addChannel(chCmd, nChannels, scpiObj._commandTree)
        chCurrentObj = ChannelTest(nChannels)
        chVoltageObj = ChannelTest(nChannels)
        for (subcomponent, subCmdObj) in [('current', chCurrentObj),
                                          ('voltage', chVoltageObj)]:
            subcomponentObj = scpiObj.addComponent(subcomponent, chObj)
            for (attrName, attrFunc) in [('upper', 'upperLimit'),
                                         ('lower', 'lowerLimit'),
                                         ('value', 'readTest')]:
                if hasattr(subCmdObj, attrFunc):
                    cbFunc = getattr(subCmdObj, attrFunc)
                    if attrName == 'value':
                        default = True
                    else:
                        default = False
                    attrObj = scpiObj.addAttribute(attrName, subcomponentObj,
                                                   cbFunc, default=default)
        # * Example of how can be nested channel type components in a tree that
        #   already have this channels componets defined.
        measCmd = 'measurements'
        measObj = scpiObj.addComponent(measCmd, chObj)
        fnCmd = 'function'
        fnObj = scpiObj.addChannel(fnCmd, nSubchannels, measObj)
        chfnCurrentObj = SubchannelTest(nChannels, nSubchannels)
        chfnVoltageObj = SubchannelTest(nChannels, nSubchannels)
        for (subcomponent, subCmdObj) in [('current', chfnCurrentObj),
                                          ('voltage', chfnVoltageObj)]:
            subcomponentObj = scpiObj.addComponent(subcomponent, fnObj)
            for (attrName, attrFunc) in [('upper', 'upperLimit'),
                                         ('lower', 'lowerLimit'),
                                         ('value', 'readTest')]:
                if hasattr(subCmdObj, attrFunc):
                    cbFunc = getattr(subCmdObj, attrFunc)
                    if attrName == 'value':
                        default = True
                    else:
                        default = False
                    attrObj = scpiObj.addAttribute(attrName, subcomponentObj,
                                                   cbFunc, default=default)
        print("Command tree build: %r" % (scpiObj._commandTree))
        result = True, "Valid commands test PASSED"
        # TODO: channels with channels until the attributes
    except Exception as e:
        print("\tUnexpected kind of exception! %s" % e)
        print_exc()
        result = False, "Valid commands test FAILED"
    _printFooter(result[1])
    return result
Example #27
0
def addValidCommands(scpiObj):
    _printHeader("Testing to build valid commands")
    try:
        # ---- valid commands section
        currentObj = AttrTest()
        voltageObj = AttrTest()
        # * commands can de added by telling their full name:
        scpiObj.addCommand('source:current:upper',
                           readcb=currentObj.upperLimit,
                           writecb=currentObj.upperLimit)
        scpiObj.addCommand('source:current:lower',
                           readcb=currentObj.lowerLimit,
                           writecb=currentObj.lowerLimit)
        scpiObj.addCommand('source:current:value',
                           readcb=currentObj.readTest,
                           default=True)
        scpiObj.addCommand('source:voltage:upper',
                           readcb=voltageObj.upperLimit,
                           writecb=voltageObj.upperLimit)
        scpiObj.addCommand('source:voltage:lower',
                           readcb=voltageObj.lowerLimit,
                           writecb=voltageObj.lowerLimit)
        scpiObj.addCommand('source:voltage:value',
                           readcb=voltageObj.readTest,
                           default=True)
        scpiObj.addCommand('source:voltage:exception',
                           readcb=voltageObj.exceptionTest)
        # * They can be also created in an iterative way
        baseCmdName = 'basicloop'
        for (subCmdName, subCmdObj) in [('current', currentObj),
                                        ('voltage', voltageObj)]:
            for (attrName, attrFunc) in [('upper', 'upperLimit'),
                                         ('lower', 'lowerLimit'),
                                         ('value', 'readTest')]:
                if hasattr(subCmdObj, attrFunc):
                    cbFunc = getattr(subCmdObj, attrFunc)
                    if attrName == 'value':
                        default = True
                    else:
                        default = False
                    scpiObj.addCommand('%s:%s:%s' %
                                       (baseCmdName, subCmdName, attrName),
                                       readcb=cbFunc,
                                       default=default)
                    # Basically is the same than the first example, but the
                    # addCommand is constructed with variables in neasted loops
        # * Another alternative to create the tree in an iterative way would be
        itCmd = 'iterative'
        itObj = scpiObj.addComponent(itCmd, scpiObj._commandTree)
        for (subcomponent, subCmdObj) in [('current', currentObj),
                                          ('voltage', voltageObj)]:
            subcomponentObj = scpiObj.addComponent(subcomponent, itObj)
            for (attrName, attrFunc) in [('upper', 'upperLimit'),
                                         ('lower', 'lowerLimit'),
                                         ('value', 'readTest')]:
                if hasattr(subCmdObj, attrFunc):
                    cbFunc = getattr(subCmdObj, attrFunc)
                    if attrName == 'value':
                        default = True
                    else:
                        default = False
                    attrObj = scpiObj.addAttribute(attrName,
                                                   subcomponentObj,
                                                   cbFunc,
                                                   default=default)
                else:
                    print("%s hasn't %s" % (subcomponentObj, attrFunc))
                    # In this case, the intermediate objects of the tree are
                    # build and it is in the innier loop where they have the
                    # attributes created.
                    #  * Use with very big care this option because the library
                    #  * don't guarantee that all the branches of the tree will
                    #  * have the appropiate leafs.
        # * Example of how can be added a node with channels in the scpi tree
        chCmd = 'channel'
        chObj = scpiObj.addChannel(chCmd, nChannels, scpiObj._commandTree)
        chCurrentObj = ChannelTest(nChannels)
        chVoltageObj = ChannelTest(nChannels)
        for (subcomponent, subCmdObj) in [('current', chCurrentObj),
                                          ('voltage', chVoltageObj)]:
            subcomponentObj = scpiObj.addComponent(subcomponent, chObj)
            for (attrName, attrFunc) in [('upper', 'upperLimit'),
                                         ('lower', 'lowerLimit'),
                                         ('value', 'readTest')]:
                if hasattr(subCmdObj, attrFunc):
                    cbFunc = getattr(subCmdObj, attrFunc)
                    if attrName == 'value':
                        default = True
                    else:
                        default = False
                    attrObj = scpiObj.addAttribute(attrName,
                                                   subcomponentObj,
                                                   cbFunc,
                                                   default=default)
        # * Example of how can be nested channel type components in a tree that
        #   already have this channels componets defined.
        measCmd = 'measurements'
        measObj = scpiObj.addComponent(measCmd, chObj)
        fnCmd = 'function'
        fnObj = scpiObj.addChannel(fnCmd, nSubchannels, measObj)
        chfnCurrentObj = SubchannelTest(nChannels, nSubchannels)
        chfnVoltageObj = SubchannelTest(nChannels, nSubchannels)
        for (subcomponent, subCmdObj) in [('current', chfnCurrentObj),
                                          ('voltage', chfnVoltageObj)]:
            subcomponentObj = scpiObj.addComponent(subcomponent, fnObj)
            for (attrName, attrFunc) in [('upper', 'upperLimit'),
                                         ('lower', 'lowerLimit'),
                                         ('value', 'readTest')]:
                if hasattr(subCmdObj, attrFunc):
                    cbFunc = getattr(subCmdObj, attrFunc)
                    if attrName == 'value':
                        default = True
                    else:
                        default = False
                    attrObj = scpiObj.addAttribute(attrName,
                                                   subcomponentObj,
                                                   cbFunc,
                                                   default=default)
        print("Command tree build: %r" % (scpiObj._commandTree))
        result = True, "Valid commands test PASSED"
        # TODO: channels with channels until the attributes
    except Exception as e:
        print("\tUnexpected kind of exception! %s" % e)
        print_exc()
        result = False, "Valid commands test FAILED"
    _printFooter(result[1])
    return result
Example #28
0
def checkCommandWrites(scpiObj):
    _printHeader("Testing to command writes")
    try:
        # simple commands ---
        currentConfObj = WattrTest()
        scpiObj.addCommand('source:current:configure',
                           readcb=currentConfObj.readTest,
                           writecb=currentConfObj.writeTest)
        voltageConfObj = WattrTest()
        scpiObj.addCommand('source:voltage:configure',
                           readcb=voltageConfObj.readTest,
                           writecb=voltageConfObj.writeTest)
        for inner in ['current', 'voltage']:
            _doWriteCommand(scpiObj, "source:%s:configure" % (inner))
        _wait(1)  # FIXME: remove
        # channel commands ---
        _printHeader("Testing to channel command writes")
        baseCmd = 'writable'
        wObj = scpiObj.addComponent(baseCmd, scpiObj._commandTree)
        chCmd = 'channel'
        chObj = scpiObj.addChannel(chCmd, nChannels, wObj)
        chCurrentObj = WchannelTest(nChannels)
        chVoltageObj = WchannelTest(nChannels)
        for (subcomponent, subCmdObj) in [('current', chCurrentObj),
                                          ('voltage', chVoltageObj)]:
            subcomponentObj = scpiObj.addComponent(subcomponent, chObj)
            for (attrName, attrFunc) in [('upper', 'upperLimit'),
                                         ('lower', 'lowerLimit'),
                                         ('value', 'readTest')]:
                if hasattr(subCmdObj, attrFunc):
                    if attrName == 'value':
                        attrObj = scpiObj.addAttribute(attrName,
                                                       subcomponentObj,
                                                       readcb=subCmdObj.
                                                       readTest,
                                                       writecb=subCmdObj.
                                                       writeTest,
                                                       default=True)
                    else:
                        cbFunc = getattr(subCmdObj, attrFunc)
                        attrObj = scpiObj.addAttribute(attrName,
                                                       subcomponentObj, cbFunc)
        print("\nChecking one write multiple reads\n")
        for i in range(nChannels):
            rndCh = _randint(1, nChannels)
            element = _randomchoice(['current', 'voltage'])
            _doWriteChannelCommand(scpiObj, "%s:%s" % (baseCmd, chCmd), rndCh,
                                   element, nChannels)
            _interTestWait()
        print("\nChecking multile writes multiple reads\n")
        for i in range(nChannels):
            testNwrites = _randint(2, nChannels)
            rndChs = []
            while len(rndChs) < testNwrites:
                rndCh = _randint(1, nChannels)
                while rndCh in rndChs:
                    rndCh = _randint(1, nChannels)
                rndChs.append(rndCh)
            element = _randomchoice(['current', 'voltage'])
            values = [_randint(-1000, 1000)]*testNwrites
            _doWriteChannelCommand(scpiObj, "%s:%s" % (baseCmd, chCmd), rndChs,
                                   element, nChannels, values)
            _interTestWait()
        print("\nChecking write with allowed values limitation\n")
        selectionCmd = 'source:selection'
        selectionObj = WattrTest()
        selectionObj.writeTest(False)
        scpiObj.addCommand(selectionCmd, readcb=selectionObj.readTest,
                           writecb=selectionObj.writeTest,
                           allowedArgins=[True, False])
        _doWriteCommand(scpiObj, selectionCmd, True)
        # _doWriteCommand(scpiObj, selectionCmd, 'Fals')
        # _doWriteCommand(scpiObj, selectionCmd, 'True')
        try:
            _doWriteCommand(scpiObj, selectionCmd, 0)
        except:
            print("\tLimitation values succeed because it raises an exception "
                  "as expected")
        else:
            raise AssertionError("It has been write a value that "
                                 "should not be allowed")
        _interTestWait()
        result = True, "Command writes test PASSED"
    except Exception as e:
        print("\tUnexpected kind of exception! %s" % e)
        print_exc()
        result = False, "Command writes test FAILED"
    _printFooter(result[1])
    return result
Example #29
0
def multithreadingTake(lockObj):
    def sendEvent(eventLst, who):
        eventLst[who].set()
        while eventLst[who].isSet():  # wait to the thread to work
            _sleep(1)

    testName = "Lock take test"
    _printHeader("%s for %s" % (testName, lockObj))
    joinerEvent = _Event()
    joinerEvent.clear()
    userThreads = []
    requestEvents = []
    accessEvents = []
    releaseEvents = []
    printLock = _Lock()
    for i in range(2):
        requestEvent = _Event()
        accessEvent = _Event()
        releaseEvent = _Event()
        userThread = _Thread(target=threadFunction,
                             args=(lockObj, joinerEvent, requestEvent,
                                   accessEvent, releaseEvent, printLock),
                             name='%d' % (i))
        requestEvents.append(requestEvent)
        accessEvents.append(accessEvent)
        releaseEvents.append(releaseEvent)
        userThreads.append(userThread)
        userThread.start()
    # here is where the test starts ---
    try:
        _printInfo("Initial state %r\n" % (lockObj), level=1, lock=printLock)
        if lockObj.isLock():
            return False, "%s FAILED" % (testName)

        _printInfo("Tell the threads to access",
                   level=1,
                   lock=printLock,
                   top=True)
        sendEvent(accessEvents, 0)
        sendEvent(accessEvents, 1)
        _printInfo("both should have had access",
                   level=1,
                   lock=printLock,
                   bottom=True)

        _printInfo("Thread 0 take the lock", level=1, lock=printLock, top=True)
        sendEvent(requestEvents, 0)
        if not lockObj.isLock() or lockObj.owner != '0':
            raise Exception("It shall be lock by 0")
        _printInfo("Tell the threads to access", level=1, lock=printLock)
        sendEvent(accessEvents, 0)
        sendEvent(accessEvents, 1)
        _printInfo("0 should, but 1 don't",
                   level=1,
                   lock=printLock,
                   bottom=True)

        _printInfo("Try to lock when it is already",
                   level=1,
                   lock=printLock,
                   top=True)
        sendEvent(requestEvents, 1)
        if not lockObj.isLock() or lockObj.owner != '0':
            raise Exception("It shall be lock by user 0")
        _printInfo("Tell the threads to access", level=1, lock=printLock)
        sendEvent(accessEvents, 0)
        sendEvent(accessEvents, 1)
        _printInfo("0 should, but 1 don't",
                   level=1,
                   lock=printLock,
                   bottom=True)

        _printInfo("Try to release by a NON-owner",
                   level=1,
                   lock=printLock,
                   top=True)
        sendEvent(releaseEvents, 1)
        if not lockObj.isLock() or lockObj.owner != '0':
            raise Exception("It shall be lock by user 0")
        _printInfo("Tell the threads to access", level=1, lock=printLock)
        sendEvent(accessEvents, 0)
        sendEvent(accessEvents, 1)
        _printInfo("0 should, but 1 don't",
                   level=1,
                   lock=printLock,
                   bottom=True)

        _printInfo("release the lock", level=1, lock=printLock, top=True)
        sendEvent(releaseEvents, 0)
        if lockObj.isLock():
            raise Exception("It shall be released")
        _printInfo("Tell the threads to access", level=1, lock=printLock)
        sendEvent(accessEvents, 0)
        sendEvent(accessEvents, 1)
        _printInfo("both should have had to",
                   level=1,
                   lock=printLock,
                   bottom=True)

        # TODO: timeout
        _printInfo("Thread 1 take the lock and expire it",
                   level=1,
                   lock=printLock,
                   top=True)
        sendEvent(requestEvents, 1)
        if not lockObj.isLock() or lockObj.owner != '1':
            raise Exception("It shall be lock by 1")
        _printInfo("Tell the threads to access", level=1, lock=printLock)
        sendEvent(accessEvents, 0)
        sendEvent(accessEvents, 1)
        _printInfo("1 should, but 0 don't", level=1, lock=printLock)
        _printInfo("Sleep %d seconds to expire the lock" %
                   TEST_EXPIRATION_TIME,
                   level=1,
                   lock=printLock)
        _sleep(TEST_EXPIRATION_TIME)
        _printInfo("Tell the threads to access", level=1, lock=printLock)
        sendEvent(accessEvents, 0)
        sendEvent(accessEvents, 1)
        _printInfo("both should have had to",
                   level=1,
                   lock=printLock,
                   bottom=True)

        answer = True, "%s PASSED" % (testName)
    except Exception as e:
        print(e)
        print_exc()
        answer = False, "%s FAILED" % (testName)
    joinerEvent.set()
    while len(userThreads) > 0:
        userThread = userThreads.pop()
        userThread.join(1)
        if userThread.isAlive():
            userThreads.append(userThread)
    print("All threads has finished")
    return answer