如何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 defaultstr(dict)includes these. - If your method uses
repr(spec_dict)instead ofstr(spec_dict)to build the error message, adjust the expected message to match that formatting.
内容的提问来源于stack exchange,提问作者Catherine
相关产品推荐
相关产品推荐

