在机器人框架中使用python进行多线程处理,涉及嵌套函数调用

时间:2015-09-23 11:49:57

标签: python multithreading robotframework

我有以下python代码“ex.py”,它试图执行具有完全相同功能的两个并行线程:

import thread

class PrtArg(object):

    def print_name1(tname,*args):
        cnt = 0
        print "Inside print_name1"
        while cnt < 10:
            cnt += 1
            print "%s : %s\n" % (tname, cnt)

    def print_name(tname,*args):
        cnt = 0
        print "Inside print_name"
        while cnt < 10:
            cnt += 1
            print "%s : %s\n" % (tname, cnt)

    def m_prt(self,*args):
        thread.start_new_thread(print_name, (args[0],))
        thread.start_new_thread(print_name1, (args[1],))

我有一个测试套件“example.robot”,其中包含以下内容:

*** Settings ***
Documentation    MultiThread Program
Library  ex.PrtArg

*** Test Cases ***
Test title
    [Documentation]  MultiThread
    [Tags]    DEBUG
    m_prt  a  b

*** Keywords

执行此操作时,出现以下错误:

==============================================================================
Ex :: MultiThread Program
==============================================================================
Test title :: MultiThread                                             | FAIL |
NameError: global name 'print_name' is not defined
------------------------------------------------------------------------------
Ex :: MultiThread Program                                            | FAIL |
1 critical test, 0 passed, 1 failed
1 test total, 0 passed, 1 failed
==============================================================================

现在,我遇到了this,它说“线程通常只应该从主线程与框架通信”。这不是上面的代码吗?我甚至没有回报价值。只需打印到控制台。正如预期的那样,当我将“example.robot”修改为以下内容时,它可以正常工作:

*** Settings ***
Documentation    MultiThread Program
Library  example4.PrtArg

*** Test Cases ***
Test title
    [Documentation]  MultiThread
    [Tags]    DEBUG
    print_name  a
    print_name1  b

*** Keywords ***

所以,我的问题是:

  1. 如何使用调用python库中其他函数的静态关键字运行测试用例?这可能吗?
  2. 机器人框架是否支持多线程?
  3. 我在这里错过了什么吗?

1 个答案:

答案 0 :(得分:1)

您应该尝试在静态中声明您的方法,因为它们位于类的实例中,而start_new_thread不会采用该方法。

所以你的代码看起来像那样

import thread

class PrtArg(object):
    @staticmethod
    def print_name1(tname,*args):
        cnt = 0
        print "Inside print_name1"
        while cnt < 10:
            cnt += 1
            print "%s : %s\n" % (tname, cnt)

    @staticmethod
    def print_name(tname,*args):
        cnt = 0
        print "Inside print_name"
        while cnt < 10:
            cnt += 1
            print "%s : %s\n" % (tname, cnt)

    def m_prt(self,*args):
        thread.start_new_thread(PrtArg.print_name, (args[0],))
        thread.start_new_thread(PrtArg.print_name1, (args[1],))