File size: 5,886 Bytes
ffae8c1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
import hashlib
import os
import tempfile
import unittest

from pptx import Presentation

from services.pptx_template import (
    PANDOC_LAYOUTS,
    TemplateError,
    analyze_pptx,
    collect_layouts,
    create_reference_pptx,
    mapping_report,
    sequential_mapping,
    validate_layout_contract,
)
from services.converter import ExternalImageError, _embed_external_images


PROJECT_ROOT = os.path.dirname(os.path.dirname(__file__))
SOURCE_TEMPLATE = os.path.join(PROJECT_ROOT, "template.pptx")


def sha256(path):
    digest = hashlib.sha256()
    with open(path, "rb") as file:
        for chunk in iter(lambda: file.read(64 * 1024), b""):
            digest.update(chunk)
    return digest.hexdigest()


class TemplateServiceTests(unittest.TestCase):
    def test_collects_layouts_from_every_master(self):
        class Layout:
            def __init__(self, name):
                self.name = name
                self.placeholders = []

        class Master:
            def __init__(self, name, layouts):
                self.name = name
                self.slide_layouts = layouts

        class FakePresentation:
            slide_masters = [
                Master("A", [Layout("A1"), Layout("A2")]),
                Master("B", [Layout("B1")]),
            ]

        layouts = collect_layouts(FakePresentation())
        self.assertEqual(
            [(0, 0, "A1"), (0, 1, "A2"), (1, 0, "B1")],
            [(x["master_index"], x["layout_index"], x["name"]) for x in layouts],
        )

    def test_reads_all_seven_layouts_in_order(self):
        state = analyze_pptx(SOURCE_TEMPLATE)
        self.assertGreaterEqual(len(state["layouts"]), 7)
        self.assertEqual(list(PANDOC_LAYOUTS), sequential_mapping(state["layouts"])[:7])
        self.assertEqual(list(range(len(state["layouts"]))), [x["sequence"] for x in state["layouts"]])
        self.assertIn(
            "object/content",
            {item["type"] for item in state["layouts"][1]["placeholders"]},
        )

    def test_corrupt_pptx_has_friendly_error(self):
        with tempfile.NamedTemporaryFile("wb", suffix=".pptx") as corrupt:
            corrupt.write(b"not a pptx")
            corrupt.flush()
            with self.assertRaisesRegex(TemplateError, "不是有效的 PPTX"):
                analyze_pptx(corrupt.name)

    def test_empty_mapping_is_rejected(self):
        state = analyze_pptx(SOURCE_TEMPLATE)
        with self.assertRaisesRegex(TemplateError, "沒有選擇任何 Mapping"):
            create_reference_pptx(
                SOURCE_TEMPLATE,
                state["layouts"],
                ["不修改"] * len(state["layouts"]),
            )

    def test_duplicate_pandoc_mapping_is_reported_as_warning(self):
        state = analyze_pptx(SOURCE_TEMPLATE)
        mappings = sequential_mapping(state["layouts"])
        mappings[1] = "Title Slide"
        result = mapping_report(state["layouts"], mappings)
        self.assertIn("Title Slide", result["duplicates"])
        self.assertIn("WARNING", result["text"])

    def test_title_and_content_contract(self):
        with_content = {
            "placeholders": [
                {"type": "title", "idx": 0},
                {"type": "object/content", "idx": 1},
            ]
        }
        without_content = {"placeholders": [{"type": "title", "idx": 0}]}
        self.assertEqual("PASS", validate_layout_contract(with_content, "Title and Content")["status"])
        self.assertEqual("FAIL", validate_layout_contract(without_content, "Title and Content")["status"])

    def test_two_content_requires_two_object_placeholders(self):
        layout = {
            "placeholders": [
                {"type": "title", "idx": 0},
                {"type": "object/content", "idx": 1},
            ]
        }
        result = validate_layout_contract(layout, "Two Content")
        self.assertEqual("FAIL", result["status"])
        self.assertIn("目前 1 個", " ".join(result["errors"]))

    def test_duplicate_idx_is_warning_only(self):
        layout = {
            "placeholders": [
                {"type": "title", "idx": 1},
                {"type": "object/content", "idx": 2},
                {"type": "date", "idx": 2},
            ]
        }
        result = validate_layout_contract(layout, "Title and Content")
        self.assertEqual("WARNING", result["status"])
        self.assertIn("idx 重複", " ".join(result["warnings"]))

    def test_rename_round_trip_does_not_touch_source(self):
        before = sha256(SOURCE_TEMPLATE)
        state = analyze_pptx(SOURCE_TEMPLATE)
        # Map each existing layout to its current standard name. This exercises the
        # same rename/save path while retaining a structurally compatible template.
        mappings = [
            layout["name"] if layout["name"] in PANDOC_LAYOUTS else "不修改"
            for layout in state["layouts"]
        ]
        output = create_reference_pptx(SOURCE_TEMPLATE, state["layouts"], mappings)
        reopened = Presentation(output)
        output_names = [
            layout.name
            for master in reopened.slide_masters
            for layout in master.slide_layouts
        ]
        self.assertEqual([x["name"] for x in state["layouts"]], output_names)
        self.assertNotEqual(os.path.realpath(SOURCE_TEMPLATE), os.path.realpath(output))
        self.assertEqual(before, sha256(SOURCE_TEMPLATE))

    def test_external_image_security_still_rejects_http_and_local_paths(self):
        for source in ("http://example.com/image.png", "./private.png"):
            document = {
                "t": "Image",
                "c": [["", [], []], [], [source, ""]],
            }
            with self.subTest(source=source):
                with self.assertRaises(ExternalImageError):
                    _embed_external_images(document)


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