刘光辉
5 小时以前 06f314545ac3514d7ce28939920866ae8188d31c
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
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
package jnpf.elnService.template;
 
import feign.Request;
import feign.Response;
import jnpf.base.vo.DownloadVO;
import jnpf.elnEntity.ElnDocumentFileVo;
import jnpf.exception.DataException;
import jnpf.file.FileApi;
import jnpf.file.FileUploadApi;
import jnpf.model.ExportModel;
import jnpf.model.FileListVO;
import jnpf.model.upload.UploadFileModel;
import jnpf.util.JsonUtil;
import org.dromara.x.file.storage.core.FileInfo;
import org.junit.Test;
import org.springframework.web.multipart.MultipartFile;
 
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
 
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
 
public class ElnTemplateFileServiceTest {
 
    @Test
    public void copiesUniqueAuthoritativeDocxAndClosesResponses() {
        Fixture fixture = new Fixture();
 
        String attachments = fixture.service.copyDocx(sourceAttachments(), "target-template");
 
        List<ElnDocumentFileVo> files = JsonUtil.getJsonToList(attachments, ElnDocumentFileVo.class);
        assertEquals(1, files.size());
        assertEquals("target-template.docx", files.get(0).getFileId());
        assertEquals("docx", files.get(0).getFileExtension());
        assertNotEquals("source.docx", files.get(0).getFileId());
        assertArrayEquals(Fixture.DOCX, fixture.uploadApi.files.get("target-template.docx"));
        assertEquals(Collections.singletonList("target-template.docx"), fixture.uploadApi.replacedIds);
        assertEquals(2, fixture.uploadApi.closedBodies);
        assertEquals("annex", fixture.uploadApi.downloads.get(0).getFolderName());
        assertEquals("source.docx", fixture.uploadApi.downloads.get(0).getObjectName());
        assertEquals("WebAnnexFile/", fixture.uploadApi.lastFolder);
        assertEquals(0, fixture.uploadApi.uploadCalls);
    }
 
    @Test
    public void retriesByOverwritingTheSameDeterministicTarget() {
        Fixture fixture = new Fixture();
 
        fixture.service.copyDocx(sourceAttachments(), "target-template");
        fixture.service.copyDocx(sourceAttachments(), "target-template");
 
        assertEquals(2, fixture.uploadApi.replacedIds.size());
        assertEquals("target-template.docx", fixture.uploadApi.replacedIds.get(0));
        assertEquals("target-template.docx", fixture.uploadApi.replacedIds.get(1));
        assertEquals(2, fixture.uploadApi.files.size());
        assertTrue(fixture.uploadApi.files.containsKey("target-template.docx"));
    }
 
    @Test
    public void rejectsReplaceFalseWithoutReturningAttachmentJson() {
        Fixture fixture = new Fixture();
        fixture.uploadApi.replaceResult = false;
 
        expectDataException(() -> fixture.service.copyDocx(sourceAttachments(), "target-template"));
 
        assertEquals(1, fixture.uploadApi.replacedIds.size());
    }
 
    @Test
    public void rejectsFailedTargetReadback() {
        Fixture fixture = new Fixture();
        fixture.uploadApi.failTargetReadback = true;
 
        expectDataException(() -> fixture.service.copyDocx(sourceAttachments(), "target-template"));
    }
 
    @Test
    public void rejectsTargetDigestMismatch() {
        Fixture fixture = new Fixture();
        fixture.uploadApi.corruptTargetReadback = true;
 
        expectDataException(() -> fixture.service.copyDocx(sourceAttachments(), "target-template"));
    }
 
    @Test
    public void rejectsAmbiguousEmptyAndOversizedSourceDocuments() {
        Fixture fixture = new Fixture();
        expectDataException(() -> fixture.service.copyDocx(
                "[{\"fileId\":\"a.docx\",\"fileExtension\":\"docx\"},"
                        + "{\"fileId\":\"b.docx\",\"fileExtension\":\"docx\"}]", "target"));
 
        fixture.uploadApi.files.put("source.docx", new byte[0]);
        expectDataException(() -> fixture.service.copyDocx(sourceAttachments(), "target"));
 
        fixture.uploadApi.reportedLength = 50 * 1024 * 1024 + 1;
        expectDataException(() -> fixture.service.copyDocx(sourceAttachments(), "target"));
    }
 
    @Test
    public void acceptsUnknownContentLengthAfterReadingActualBytes() {
        Fixture fixture = new Fixture();
        fixture.uploadApi.reportedLength = -1;
 
        String attachments = fixture.service.copyDocx(sourceAttachments(), "target-template");
 
        assertTrue(attachments.contains("target-template.docx"));
    }
 
    private static String sourceAttachments() {
        return "[{\"fileId\":\"source.docx\",\"name\":\"source.docx\","
                + "\"fileExtension\":\"docx\"}]";
    }
 
    private static void expectDataException(Runnable action) {
        try {
            action.run();
            fail("预期抛出 DataException");
        } catch (DataException expected) {
            assertFalse(expected.getMessage().trim().isEmpty());
        }
    }
 
    private static final class Fixture {
        private static final byte[] DOCX = "docx-content".getBytes(StandardCharsets.UTF_8);
        private final StubFileApi fileApi = new StubFileApi();
        private final StubFileUploadApi uploadApi = new StubFileUploadApi();
        private final ElnTemplateFileService service = new ElnTemplateFileService(fileApi, uploadApi);
 
        private Fixture() {
            uploadApi.files.put("source.docx", DOCX);
        }
    }
 
    private static final class StubFileApi implements FileApi {
        @Override
        public String getPath(String type) {
            assertEquals("annex", type);
            return "WebAnnexFile/";
        }
 
        @Override
        public DownloadVO exportFile(ExportModel exportModel) {
            return null;
        }
 
        @Override
        public String getLocalBasePath() {
            return null;
        }
 
        @Override
        public String getAllowPreviewFileType() {
            return null;
        }
 
        @Override
        public Boolean fileExists(String type, String fileName) {
            return null;
        }
    }
 
    private static final class StubFileUploadApi implements FileUploadApi {
        private final Map<String, byte[]> files = new LinkedHashMap<>();
        private final List<String> replacedIds = new ArrayList<>();
        private final List<UploadFileModel> downloads = new ArrayList<>();
        private boolean replaceResult = true;
        private boolean failTargetReadback;
        private boolean corruptTargetReadback;
        private Integer reportedLength;
        private int uploadCalls;
        private int closedBodies;
        private String lastFolder;
 
        @Override
        public FileInfo uploadFile(MultipartFile multipartFile, String folderName, String fileName) {
            uploadCalls++;
            return null;
        }
 
        @Override
        public boolean replaceFile(MultipartFile multipartFile, String folderName, String fileName) {
            replacedIds.add(fileName);
            lastFolder = folderName;
            if (replaceResult) {
                try {
                    files.put(fileName, multipartFile.getBytes());
                } catch (IOException e) {
                    throw new IllegalStateException(e);
                }
            }
            return replaceResult;
        }
 
        @Override
        public byte[] getByte(String fileName, String folderName) {
            return null;
        }
 
        @Override
        public List<FileListVO> getFileList(String folderName) {
            return Collections.emptyList();
        }
 
        @Override
        public Response downFile(UploadFileModel model) {
            downloads.add(model);
            boolean target = model.getObjectName().startsWith("target-");
            if (target && failTargetReadback) {
                return response(404, null);
            }
            byte[] bytes = files.get(model.getObjectName());
            if (target && corruptTargetReadback && bytes != null) {
                bytes = "different-content".getBytes(StandardCharsets.UTF_8);
            }
            return response(bytes == null ? 404 : 200, bytes);
        }
 
        private Response response(int status, byte[] bytes) {
            return Response.builder()
                    .status(status)
                    .reason(status == 200 ? "OK" : "Not Found")
                    .request(Request.create(Request.HttpMethod.GET, "http://file/download",
                            Collections.<String, Collection<String>>emptyMap(), null, Charset.defaultCharset()))
                    .body(bytes == null ? null : new TrackingBody(bytes,
                            reportedLength == null ? bytes.length : reportedLength, this))
                    .build();
        }
 
        @Override
        public FileInfo getFile(String fileId) {
            return null;
        }
 
        @Override
        public String getDefaultPlatform() {
            return null;
        }
 
        @Override
        public List<FileListVO> getVisualList(String folderName) {
            return Collections.emptyList();
        }
    }
 
    private static final class TrackingBody implements Response.Body {
        private final byte[] bytes;
        private final int length;
        private final StubFileUploadApi owner;
 
        private TrackingBody(byte[] bytes, int length, StubFileUploadApi owner) {
            this.bytes = bytes;
            this.length = length;
            this.owner = owner;
        }
 
        @Override
        public Integer length() {
            return length;
        }
 
        @Override
        public boolean isRepeatable() {
            return true;
        }
 
        @Override
        public InputStream asInputStream() {
            return new ByteArrayInputStream(bytes);
        }
 
        @Override
        public Reader asReader(Charset charset) {
            throw new UnsupportedOperationException();
        }
 
        @Override
        public void close() {
            owner.closedBodies++;
        }
    }
}