1/*******************************************************************************
2 * Copyright (c) 2009, 2018 Mountainminds GmbH & Co. KG and Contributors
3 * All rights reserved. This program and the accompanying materials
4 * are made available under the terms of the Eclipse Public License v1.0
5 * which accompanies this distribution, and is available at
6 * http://www.eclipse.org/legal/epl-v10.html
7 *
8 * Contributors:
9 *    Marc R. Hoffmann - initial API and implementation
10 *
11 *******************************************************************************/
12package org.jacoco.report;
13
14import static org.junit.Assert.assertEquals;
15import static org.junit.Assert.assertFalse;
16import static org.junit.Assert.assertNotNull;
17import static org.junit.Assert.assertNull;
18import static org.junit.Assert.assertTrue;
19
20import java.io.ByteArrayInputStream;
21import java.io.ByteArrayOutputStream;
22import java.io.IOException;
23import java.io.InputStream;
24import java.io.OutputStream;
25import java.util.Collections;
26import java.util.HashMap;
27import java.util.HashSet;
28import java.util.Map;
29import java.util.Set;
30
31/**
32 * In-memory report output for test purposes.
33 */
34public class MemoryMultiReportOutput implements IMultiReportOutput {
35
36	private final Map<String, ByteArrayOutputStream> files = new HashMap<String, ByteArrayOutputStream>();
37
38	private final Set<String> open = new HashSet<String>();
39
40	private boolean closed = false;
41
42	public OutputStream createFile(final String path) throws IOException {
43		assertFalse("Duplicate output " + path, files.containsKey(path));
44		open.add(path);
45		final ByteArrayOutputStream out = new ByteArrayOutputStream() {
46			@Override
47			public void close() throws IOException {
48				open.remove(path);
49				super.close();
50			}
51		};
52		files.put(path, out);
53		return out;
54	}
55
56	public void close() throws IOException {
57		closed = true;
58	}
59
60	public void assertEmpty() {
61		assertEquals(Collections.emptySet(), files.keySet());
62	}
63
64	public void assertFile(String path) {
65		assertNotNull(String.format("Missing file %s. Actual files are %s.",
66				path, files.keySet()), files.get(path));
67	}
68
69	public void assertNoFile(String path) {
70		assertNull(String.format("Unexpected file %s.", path), files.get(path));
71	}
72
73	public void assertSingleFile(String path) {
74		assertEquals(Collections.singleton(path), files.keySet());
75	}
76
77	public byte[] getFile(String path) {
78		assertFile(path);
79		return files.get(path).toByteArray();
80	}
81
82	public InputStream getFileAsStream(String path) {
83		return new ByteArrayInputStream(getFile(path));
84	}
85
86	public void assertAllClosed() {
87		assertEquals(Collections.emptySet(), open);
88		assertTrue(closed);
89	}
90
91}
92