|
1 | 1 | import datetime |
2 | 2 | import numbers |
3 | 3 | from typing import TYPE_CHECKING, Any |
| 4 | +from unittest.mock import Mock |
4 | 5 |
|
5 | 6 | import pytest |
6 | 7 |
|
@@ -774,50 +775,16 @@ def test_dicttoxml_with_cdata(self) -> None: |
774 | 775 | result = dicttoxml.dicttoxml(data, cdata=True, attr_type=False, root=False) |
775 | 776 | assert b"<key><![CDATA[value]]></key>" == result |
776 | 777 |
|
777 | | - def test_get_unique_id_with_duplicates(self) -> None: |
| 778 | + def test_get_unique_id_with_duplicates(self, monkeypatch: "MonkeyPatch") -> None: |
778 | 779 | """Test get_unique_id when duplicates are generated.""" |
779 | | - # We need to modify the original get_unique_id to simulate a pre-existing ID list |
780 | | - import json2xml.dicttoxml as module |
| 780 | + ids = ["existing_id"] |
| 781 | + make_id_mock = Mock(side_effect=["existing_id", "new_id"]) |
| 782 | + monkeypatch.setattr(dicttoxml, "make_id", make_id_mock) |
781 | 783 |
|
782 | | - # Save original function |
783 | | - original_get_unique_id = module.get_unique_id |
784 | | - |
785 | | - # Track make_id calls |
786 | | - call_count = 0 |
787 | | - original_make_id = module.make_id |
788 | | - |
789 | | - def mock_make_id(element: str, start: int = 100000, end: int = 999999) -> str: |
790 | | - nonlocal call_count |
791 | | - call_count += 1 |
792 | | - if call_count == 1: |
793 | | - return "test_123456" # First call - will collide |
794 | | - else: |
795 | | - return "test_789012" # Second call - unique |
796 | | - |
797 | | - # Patch get_unique_id to use a pre-populated ids list |
798 | | - def patched_get_unique_id(element: str) -> str: |
799 | | - # Start with a pre-existing ID to force collision |
800 | | - ids = ["test_123456"] |
801 | | - this_id = module.make_id(element) |
802 | | - dup = True |
803 | | - while dup: |
804 | | - if this_id not in ids: |
805 | | - dup = False |
806 | | - ids.append(this_id) |
807 | | - else: |
808 | | - this_id = module.make_id(element) # This exercises line 52 |
809 | | - return ids[-1] |
810 | | - |
811 | | - module.make_id = mock_make_id |
812 | | - module.get_unique_id = patched_get_unique_id |
| 784 | + unique_id = dicttoxml.get_unique_id("some_element", ids=ids) |
813 | 785 |
|
814 | | - try: |
815 | | - result = dicttoxml.get_unique_id("test") |
816 | | - assert result == "test_789012" |
817 | | - assert call_count == 2 |
818 | | - finally: |
819 | | - module.make_id = original_make_id |
820 | | - module.get_unique_id = original_get_unique_id |
| 786 | + assert unique_id == "new_id" |
| 787 | + assert make_id_mock.call_count == 2 |
821 | 788 |
|
822 | 789 | def test_convert_with_bool_direct(self) -> None: |
823 | 790 | """Test convert function with boolean input directly.""" |
|
0 commit comments