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

如何Mock Python字典的__str__方法?及异常抛出验证测试咨询

1. Mocking a Python Dictionary's __str__ Method

There are two practical ways to mock or override the __str__ method of a dictionary, depending on your testing needs:

Option 1: Temporarily mock an existing dict instance

If you need to change the string output of a specific dictionary for a test, use unittest.mock.patch.object to replace the method temporarily:

from unittest.mock import patch

my_dict = {"foo": "bar", "baz": [1, 2, 3]}

# Override __str__ for this instance only
with patch.object(my_dict, "__str__", return_value="Custom dict display text"):
    print(str(my_dict))  # Outputs: Custom dict display text

# Outside the context manager, __str__ works normally
print(str(my_dict))  # Outputs: {'foo': 'bar', 'baz': [1, 2, 3]}

Option 2: Create a custom dict subclass

If you need a reusable dictionary type with a permanent custom string representation (no mocking required), subclass dict and override __str__:

class CustomStrDict(dict):
    def __str__(self):
        return f"Dict: {', '.join([f'{key}={value}' for key, value in self.items()])}"

custom_dict = CustomStrDict({"name": "Alice", "age": 30})
print(str(custom_dict))  # Outputs: Dict: name=Alice, age=30
2. Writing Test Cases for Exception Validation

Let’s assume your validation method is named validate_spec (swap this with your actual method name). Below are test examples using both unittest and pytest to verify the exception behavior.

Example with unittest

import unittest
from your_module import validate_spec, SpecFormatException  # Import your code

class TestSpecValidation(unittest.TestCase):
    def test_missing_type_key_raises_correct_exception(self):
        invalid_spec = {"foo": "bar", "baz": [1, 2, 3]}
        
        # Capture the exception when it's raised
        with self.assertRaises(SpecFormatException) as ctx:
            validate_spec(invalid_spec)
        
        # Verify the error message matches exactly
        expected_msg = "'type' entry is missing in spec dict: {'foo': 'bar', 'baz': [1, 2, 3]}"
        self.assertEqual(str(ctx.exception), expected_msg)
    
    def test_invalid_type_value_raises_exception(self):
        # Optional: Test invalid 'type' values if your method checks this
        invalid_spec = {"type": "invalid_type"}
        
        with self.assertRaises(SpecFormatException) as ctx:
            validate_spec(invalid_spec)
        
        expected_msg = "'type' entry has invalid value: 'invalid_type'. Allowed values are ['typeA', 'typeB', 'typeC']"
        self.assertEqual(str(ctx.exception), expected_msg)

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

Example with pytest

import pytest
from your_module import validate_spec, SpecFormatException  # Import your code

def test_missing_type_key_raises_correct_exception():
    invalid_spec = {"foo": "bar", "baz": [1, 2, 3]}
    
    # Capture the exception
    with pytest.raises(SpecFormatException) as exc_info:
        validate_spec(invalid_spec)
    
    # Check the message matches exactly
    expected_msg = "'type' entry is missing in spec dict: {'foo': 'bar', 'baz': [1, 2, 3]}"
    assert str(exc_info.value) == expected_msg

def test_invalid_type_value_raises_exception():
    invalid_spec = {"type": "invalid_type"}
    
    with pytest.raises(SpecFormatException) as exc_info:
        validate_spec(invalid_spec)
    
    expected_msg = "'type' entry has invalid value: 'invalid_type'. Allowed values are ['typeA', 'typeB', 'typeC']"
    assert str(exc_info.value) == expected_msg

Important Notes:

  • Ensure your expected message exactly matches the output from your method—pay attention to formatting like spaces in lists (e.g., [1, 2, 3] instead of [1,2,3]) since Python’s default str(dict) includes these.
  • If your method uses repr(spec_dict) instead of str(spec_dict) to build the error message, adjust the expected message to match that formatting.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 08:36:25