@@ -112,3 +112,72 @@ def test_edge_cases():
112112 ) # Email regex
113113 assert regex .match ("test@example.com" ) is True # Should match
114114 assert regex .match ("invalid-email" ) is False # Should not match
115+
116+
117+ # Fixture to create a CompiledRegex object for testing
118+ @pytest .fixture
119+ def compiled_regex ():
120+ return CompiledRegex (r"\d+" )
121+
122+
123+ # Test cases for the `search` method
124+ def test_search_found (compiled_regex ):
125+ text = "There are 123 apples and 456 oranges."
126+ result = compiled_regex .search (text )
127+ assert result == "123" # First match should be "123"
128+
129+
130+ def test_search_not_found (compiled_regex ):
131+ text = "There are no numbers here."
132+ result = compiled_regex .search (text )
133+ assert result is None # No match should return None
134+
135+
136+ # Test cases for the `findall` method
137+ def test_findall_multiple_matches (compiled_regex ):
138+ text = "There are 123 apples and 456 oranges."
139+ result = compiled_regex .findall (text )
140+ assert result == ["123" , "456" ] # All matches should be returned
141+
142+
143+ def test_findall_no_matches (compiled_regex ):
144+ text = "There are no numbers here."
145+ result = compiled_regex .findall (text )
146+ assert result == [] # No matches should return an empty list
147+
148+
149+ def test_findall_empty_string (compiled_regex ):
150+ text = ""
151+ result = compiled_regex .findall (text )
152+ assert result == [] # Empty string should return an empty list
153+
154+
155+ # Test cases for the `sub` method
156+ def test_sub_single_replacement (compiled_regex ):
157+ text = "There are 123 apples."
158+ result = compiled_regex .sub ("NUM" , text )
159+ assert result == "There are NUM apples." # Single replacement
160+
161+
162+ def test_sub_multiple_replacements (compiled_regex ):
163+ text = "There are 123 apples and 456 oranges."
164+ result = compiled_regex .sub ("NUM" , text )
165+ assert result == "There are NUM apples and NUM oranges." # Multiple replacements
166+
167+
168+ def test_sub_no_matches (compiled_regex ):
169+ text = "There are no numbers here."
170+ result = compiled_regex .sub ("NUM" , text )
171+ assert result == text # No matches, original text should be returned
172+
173+
174+ def test_sub_empty_string (compiled_regex ):
175+ text = ""
176+ result = compiled_regex .sub ("NUM" , text )
177+ assert result == "" # Empty string should remain unchanged
178+
179+
180+ # Edge case: Invalid regex pattern
181+ def test_invalid_regex_pattern ():
182+ with pytest .raises (ValueError ):
183+ CompiledRegex (r"*invalid" ) # Invalid regex pattern should raise ValueError
0 commit comments