|
1 | 1 | """Tests for the document module.""" |
2 | 2 |
|
3 | 3 | import docx |
| 4 | +import pytest |
4 | 5 |
|
5 | 6 | from cmi_docx import document |
6 | 7 |
|
@@ -35,28 +36,58 @@ def test_find_in_runs() -> None: |
35 | 36 | assert actual[2].character_indices == (14, 19) |
36 | 37 |
|
37 | 38 |
|
38 | | -def test_replace() -> None: |
| 39 | +@pytest.mark.parametrize( |
| 40 | + ("runs", "needle", "replace", "expected"), |
| 41 | + [ |
| 42 | + ( |
| 43 | + ["Hello, world!"], |
| 44 | + "Hello", |
| 45 | + "Goodbye", |
| 46 | + "Goodbye, world!", |
| 47 | + ), |
| 48 | + ( |
| 49 | + ["Hello, world!", " Hello!"], |
| 50 | + "Hello", |
| 51 | + "Goodbye", |
| 52 | + "Goodbye, world! Goodbye!", |
| 53 | + ), |
| 54 | + ( |
| 55 | + ["Hello {{", "FULL_NAME}}"], |
| 56 | + "{{FULL_NAME}}", |
| 57 | + 'Shizuka "Lea" Sakai', |
| 58 | + 'Hello Shizuka "Lea" Sakai', |
| 59 | + ), |
| 60 | + ( |
| 61 | + ["This is James", " Bond ", "007!"], |
| 62 | + "James Bond 007", |
| 63 | + "Patrick", |
| 64 | + "This is Patrick!", |
| 65 | + ), |
| 66 | + ( |
| 67 | + ["This is Alec", " Travelyan ", "006!"], |
| 68 | + "This is Alec Travelyan 006!", |
| 69 | + "", |
| 70 | + "", |
| 71 | + ), |
| 72 | + ( |
| 73 | + ["This", " is ", "Patrick!"], |
| 74 | + "", |
| 75 | + "Nonsense", |
| 76 | + "This is Patrick!", |
| 77 | + ), |
| 78 | + ], |
| 79 | +) |
| 80 | +def test_replace(runs: list[str], needle: str, replace: str, expected: str) -> None: |
39 | 81 | """Test replacing text in a document.""" |
40 | 82 | doc = docx.Document() |
41 | | - doc.add_paragraph("Hello, world!") |
42 | | - extend_document = document.ExtendDocument(doc) |
43 | | - |
44 | | - extend_document.replace("Hello", "Goodbye") |
45 | | - |
46 | | - assert doc.paragraphs[0].text == "Goodbye, world!" |
47 | | - |
48 | | - |
49 | | -def test_replace_across_runs() -> None: |
50 | | - """Test replacing text across runs in a document.""" |
51 | | - doc = docx.Document() |
52 | | - paragraph = doc.add_paragraph("Hello, world!") |
53 | | - paragraph.add_run(" Maintain, World!") |
54 | | - paragraph.add_run(" Goodbye, World!") |
| 83 | + paragraph = doc.add_paragraph(runs[0]) |
| 84 | + for run in runs[1:]: |
| 85 | + paragraph.add_run(run) |
55 | 86 | extend_document = document.ExtendDocument(doc) |
56 | 87 |
|
57 | | - extend_document.replace("world! Maintain, World! Goodbye", "Goodbye") |
| 88 | + extend_document.replace(needle, replace) |
58 | 89 |
|
59 | | - assert doc.paragraphs[0].text == "Hello, Goodbye, World!" |
| 90 | + assert doc.paragraphs[0].text == expected |
60 | 91 |
|
61 | 92 |
|
62 | 93 | def test_insert_paragraph_by_object() -> None: |
|
0 commit comments