You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何编写Python单元测试验证g_control函数特定代码行存在性?

如何编写单元测试确保g_control包含指定代码行?

我有一个大型函数pass1(),代码如下:

def g_control(...): 
    <some line here that makes stats.invalid_currency a valid call>


def pass1(...): 
    ...
    stats = g_control(...)
    
    if stats.invalid_currency(..): 
        raise Exception('Something is missing in g_conrol')

我希望编写一个单元测试,确保g_control函数中存在某一特定代码行;若该行缺失,调用stats.invalid_currency时会抛出提示“stats has no attribute invalid currency”的属性错误,请问该如何实现?


两种可行的测试方案

方案1:通过执行pass1验证属性存在性

如果g_control缺失目标代码行,stats对象就不会有invalid_currency属性,调用时会触发AttributeError。我们可以利用这个行为编写测试:

用Python标准库unittest实现的示例代码:

import unittest
from your_module import pass1  # 替换成你的模块名

class TestGControlAttribute(unittest.TestCase):
    def test_invalid_currency_attribute_exists(self):
        try:
            # 传入pass1所需的实际参数
            pass1(...)
        except AttributeError as e:
            # 捕获到属性错误,说明目标代码行缺失
            self.assertEqual(str(e), "stats has no attribute 'invalid_currency'")
            self.fail("g_control中缺失创建invalid_currency属性的代码行")
        except Exception as e:
            # 捕获到pass1主动抛出的异常,说明属性存在,测试通过
            self.assertEqual(str(e), "Something is missing in g_conrol")

if __name__ == '__main__':
    unittest.main()

逻辑说明:

  • 若g_control生成的stats有invalid_currency属性,pass1会执行到判断逻辑并抛出自定义异常,测试捕获到这个异常即判定通过;
  • 若stats无该属性,调用时会先抛出AttributeError,测试捕获后直接标记失败并提示代码缺失。

方案2:直接检查g_control的源代码

如果不需要运行函数逻辑,只想直接验证目标代码行是否存在,可以用inspect模块读取函数源代码进行检查:

import unittest
import inspect
from your_module import g_control  # 替换成你的模块名

class TestGControlCodeLine(unittest.TestCase):
    def test_target_line_exists(self):
        # 获取g_control的完整源代码
        source_code = inspect.getsource(g_control)
        # 替换成你要检查的实际代码行(注意匹配缩进、空格等格式)
        target_line = "stats.invalid_currency = lambda x: x"
        
        # 断言目标行存在于源代码中
        self.assertIn(target_line, source_code, msg="g_control中缺失指定的代码行")

if __name__ == '__main__':
    unittest.main()

逻辑说明:

  • 通过inspect.getsource()获取函数的源代码文本;
  • 用assertIn断言目标代码行存在,不存在则测试失败并给出提示。

内容的提问来源于stack exchange,提问作者ifrj

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 01:03:18