简体   繁体   English

如何编写方法以验证反射方法的名称和参数

[英]How to Write Method to Verify Reflection Method Names and Parameters

We were writing a Selenium test core by using Python webdriver. 我们正在使用Python Webdriver编写Selenium测试核心。 The main idea is to read from a CSV file with the format: 主要思想是从以下格式的CSV文件中读取:

method_name,parameter 1,parameter 2, parameter 3, ..., parameter n

And then by using reflection, the test core will call the method based on the "method name" and parameters. 然后,通过使用反射,测试核心将基于“方法名称”和参数来调用该方法。

def runTest(self):
        try:
            test_case_reader = csv.reader(open(self.file_path, 'rb'), delimiter=',')
            self.logger.info("Running test case %s" % self.file_path)
            for row in test_case_reader:
                if (len(row) > 1):
                    method_name, parameters = row[0], row[1:]
                    parameters = filter(None, parameters)
                    method = getattr(self, method_name)
                    self.logger.info("executing method %s parameters %s" % (method_name, parameters))
                    method(*parameters)
                    self.wait()
        except AssertionError, e:
            self.logger.error(e)
            self.fail("Test case failed: %s" % self.file_path)

The main idea of this script is to provide a better productivity and ease of usage, since QA won't have to interact with python code to write automation test cases. 这个脚本的主要思想是提供使用更好的效率和易用性,因为QA将不必与Python代码交互编写自动化测试用例。

But due to human error, sometimes there will be a typo or parameter mismatched. 但是由于人为错误,有时会出现错字或参数不匹配的情况。

So I'm going to add a method to verify all CSV files if method names and parameters are correct. 因此,如果方法名称和参数正确,我将添加一种方法来验证所有CSV文件。 Is there any built-in reflection to do this kind of checking? 是否有任何内置反射可以进行这种检查?

Update: 更新:

For the parameters I'd like to check if parameters count match the required parameters of the method. 对于参数,我想检查参数计数是否与方法的必需参数匹配。 Some of the methods has optional parameters too. 一些方法也具有可选参数。

Example: 例:

method_1 (parameter1, parameter2, parameter3, parameter4 = None, parameter5 = None)

For method_1 , valid parameters count are: 3, 4, and 5. 对于method_1 ,有效的参数计数为:3、4和5。

Answer: 回答:

Not the perfect & tidy solution but this is the method for now and it's working: 这不是完美而整洁的解决方案,但这是目前的方法,并且可以正常工作:

def verifyFile(self):
    test_case_reader = csv.reader(open(self.file_path, 'rb'), delimiter=',')
    for row in test_case_reader:
        if (len(row) <= 1):
            break

        method_name, parameters = row[0], row[1:]
        if (method_name == ''):
            break

        parameters = filter(None, parameters)
        if not hasattr(self, method_name):
            self.logger.error("test case '%s' method name '%s': Method not found" % (self.file_path, method_name))
            break
        t = inspect.getargspec(getattr(self, method_name))
        max = len(t.args)
        if (type(t.defaults) == NoneType):
            min = max
        else:
            min = max - len(t.defaults)
        if not min <= len(parameters) + 1 <= max:
            self.logger.error("test case '%s' method name '%s': Parameter count not matches (%d - %d)" % (self.file_path, method_name, min, max))

For the method, you can easily call hasattr to see if it exists. 对于该方法,您可以轻松地调用hasattr来查看它是否存在。 In your case, it's just : 就您而言,它只是:

for row in test_case_reader:
    method_name = get_method_name() # Your code here
    if not hasattr(self, method_name):
        self.logger.error("No method name %s", method_name)

For the parameter, it's a little more complex, as python is a dynamic language. 对于该参数,它有点复杂,因为python是一种动态语言。 You may want to use a parameter checking or a contract library. 您可能要使用参数检查或合同库。 If the parameter problem is simple enough, there may be a simpler solution. 如果参数问题足够简单,则可能有更简单的解决方案。 What do you want to check about parameters ? 您要检查哪些参数?

EDIT : 编辑:

For the parameter, you can use inspect.getargspec to get the number of arguments of the function and check if it's correct. 对于参数,可以使用inspect.getargspec来获取函数的参数数量,并检查其是否正确。

def check_args(func, n):
    args, varargs, keywords, defaults = inspect.getargspec(func)
    max = len(arg)
    min = max - len(defaults)
    if not min <= n <= max:
        # error

This don't take into account the use of *args and **kwargs but you can easily change it to do so. 这没有考虑到*args**kwargs的使用,但是您可以轻松地对其进行更改。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM