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

Python单元测试中模拟get_value方法异常时测试失败的问题求助

Fixing Your Chains.get_chain Unit Test

Let's break down the issues with your code and fix the test step by step:

1. First, Fix the get_chain Instance Method

Your get_chain method is missing the self parameter (required for instance methods), and re-wrapping the exception in a new Exception object is unnecessary (it erases the original exception context). Here's the corrected method:

class Chains():
    def __init__(self, photon_chain, **kwargs):
        self.photon_chain = photon_chain
        # Handle other initialization parameters here
        self.chains = [local.feeder.ILUT, local.reacher.OHUT]

    def get_chain(self):  # Added self parameter
        if self.photon_chain:
            for i in self.chains:
                try:
                    return i.get_value(self.photon_chain)
                except Exception as exc:
                    _log.error(exc)
                    raise  # Re-raise the original exception instead of wrapping it

2. Fix the Unit Test Issues

Your test is failing for three key reasons:

  • Incorrect mock target path: You're mocking get_value directly, but you need to mock the exact get_value method that Chains is calling (i.e., the one on local.feeder.ILUT or local.reacher.OHUT).
  • No exception assertion: You're not telling the test framework to expect an exception, so when the method raises one, the test fails.
  • Missing self in the original method: This would have caused errors even before reaching the exception logic.

Here's the corrected test (using Python's built-in unittest framework for best practices):

from unittest import mock, TestCase

class TestChains(TestCase):
    def test_get_chain_raises_exception(self):
        # Initialize your Chains instance
        chain_instance = Chains(photon_chain='chainvalue')

        # Mock the get_value method of the first chain in the list
        # Replace 'your_module' with the actual module path where local.feeder.ILUT lives
        with mock.patch('your_module.local.feeder.ILUT.get_value', side_effect=Exception("Test failure")):
            # Assert that calling get_chain raises an Exception
            with self.assertRaises(Exception):
                chain_instance.get_chain()

        # Optional: Test the second chain's exception handling
        with mock.patch('your_module.local.reacher.OHUT.get_value', side_effect=Exception("Test failure")):
            with self.assertRaises(Exception):
                chain_instance.get_chain()

Key Explanations

  • Mock Path: The string passed to mock.patch must match the path to get_value as it's imported in the module where Chains is defined. For example, if your Chains class is in my_app.chains.py and imports from my_app.local.feeder import ILUT, the mock path would be my_app.local.feeder.ILUT.get_value.
  • Exception Assertion: Using self.assertRaises tells the test framework that an exception is expected, so it won't mark the test as failed when the exception is raised.
  • Re-raising Exceptions: Using raise instead of raise Exception(exc) preserves the original exception's type, message, and stack trace, which is better for debugging and test clarity.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 06:48:30