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

单元测试Mock ConfigFactory.parse_file时遇AttributeError问题求解

解决方法

1. 修正@patch与测试方法参数的对应顺序

unittest的@patch装饰器是自下而上绑定测试方法参数的,你当前的参数顺序完全颠倒:

  • 最下方的@patch('oci.auth.signers.instance_principals_security_token_signer.InstancePrincipalsSecurityTokenSigner')对应测试方法的第一个参数
  • 中间的@patch('pyhocon.ConfigFactory.parse_file')对应测试方法的第二个参数
  • 最上方的@patch('t2.client.OverlayClient')对应测试方法的第三个参数

参数顺序错误导致你误将签名器的Mock当成ConfigFactory.parse_file的Mock设置返回值,真正的parse_file Mock被设置为返回字符串"test_token",调用其方法时自然触发'str' object has no attribute 'as_plain_ordered_dict'错误。

2. 正确Mock as_plain_ordered_dict方法

主代码中as_plain_ordered_dict()是带括号的方法调用,不是属性访问,无需使用PropertyMock,直接给Mock对象绑定方法返回值即可。

3. 简化测试参数传递

主函数中path_to_local_config是字符串类型,测试时直接传任意字符串即可(ConfigFactory.parse_file已被Mock,不会真的读取文件),无需Mock该参数。


修正后的测试代码示例

class Testt2StatsExporter(unittest.TestCase):

    @patch('t2.client.OverlayClient')
    @patch('pyhocon.ConfigFactory.parse_file')
    @patch('oci.auth.signers.instance_principals_security_token_signer.InstancePrincipalsSecurityTokenSigner')
    def test_create_telemetry_client(self, mock_signer, mock_parse_file, mock_client):
        # 配置parse_file的返回值及方法
        test_config = Mock()
        test_config.as_plain_ordered_dict.return_value = {'metricsConfig': 'test_config'}
        mock_parse_file.return_value = test_config

        # 配置签名器返回值
        mock_signer.return_value = "test_token"

        # 配置客户端返回值
        mock_client.return_value = True

        # 调用被测试函数,传入字符串参数
        self.assertEqual(True, _create_telemetry_client('/fake/path/config.conf'))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 09:27:39