如何检查模块/类/方法是否已更改并记录更改?

时间:2010-11-08 15:34:18

标签: python unit-testing comparison code-analysis

我正在尝试比较两个模块/类/方法,并找出类/方法是否已更改。我们允许用户更改类/方法,并且在处理之后,我们使这些更改持久化,而不会覆盖旧的类/方法。但是,在我们提交新类之前,我们需要确定代码是否已更改,以及方法的功能是否已更改,例如输出不同,性能也会延迟相同的输入数据。我对性能变化很满意,但我的问题是代码的变化以及如何记录 - 改变了什么。我写了类似下面的内容

class TestIfClassHasChanged(unittest.TestCase):
    def setUp(self):
       self.old = old_class()
       self.new = new_class()    
    def test_if_code_has_changed(self): 
       # simple case for one method
       old_codeobject = self.old.area.func_code.co_code
       new_codeobject = self.new.area.func_code.co_code
       self.assertEqual(old_codeobject, new_codeobject)

其中area()是两个类中的方法。但是,如果我有很多方法,我在这里看到的是循环所有方法。可以在类或模块级别执行此操作吗?

其次,如果我发现代码对象不相等,我想记录更改。我使用inspect.getsource(self.old.area)inspect.getsource(self.new.area)比较两者来获得差异,是否有更好的方法可以做到这一点?

2 个答案:

答案 0 :(得分:1)

您应该使用版本控制程序来帮助管理开发。这是您从vc程序获得的特定d =功能之一是跟踪更改的能力。您可以在当前源代码和先前签入之间进行差异,以测试是否有任何更改。

答案 1 :(得分:0)

  

如果我有很多方法,我所看到的   这里是循环所有方法。   可以在课堂或模块上完成此操作   水平?

我不会问你为什么要做这样的事情?但是,你可以在这里举个例子

import inspect
import collections

# Here i will loop over all the function in a module

module = __import__('inspect')   # this is fun !!!

# Get all function in the module.
list_functions = inspect.getmembers(module, inspect.isfunction)

# Get classes and methods correspond .
list_class = inspect.getmembers(module, inspect.isclass)

class_method = collections.defaultdict(list)

for class_name, class_obj in list_class:
    for method in inspect.getmembers(class_obj, inspect.ismethod):
        class_method[class_name].append(method)