|
| 1 | +package org.json.junit.milestone4.tests; |
| 2 | + |
| 3 | +import org.json.JSONObject; |
| 4 | +import org.json.JSONObject.JSONNode; |
| 5 | +import org.json.XML; |
| 6 | +import org.junit.BeforeClass; |
| 7 | +import org.junit.Test; |
| 8 | + |
| 9 | +import java.io.InputStream; |
| 10 | +import java.nio.charset.StandardCharsets; |
| 11 | +import java.util.List; |
| 12 | +import java.util.Optional; |
| 13 | +import java.util.Scanner; |
| 14 | +import java.util.stream.Collectors; |
| 15 | + |
| 16 | +import static org.junit.Assert.*; |
| 17 | + |
| 18 | +/** |
| 19 | + * Unit tests for the JSONObject.toStream() extension (Milestone 4) – JUnit 4 / Java 8. |
| 20 | + */ |
| 21 | +public class JSONObjectStreamTest { |
| 22 | + |
| 23 | + private static JSONObject catalog; |
| 24 | + |
| 25 | + @BeforeClass |
| 26 | + public static void loadXml() throws Exception { |
| 27 | + try (InputStream in = JSONObjectStreamTest.class.getResourceAsStream("/books.xml")) { |
| 28 | + assertNotNull("books.xml must be on the class-path (src/test/resources)", in); |
| 29 | + |
| 30 | + String xml; |
| 31 | + try (Scanner scanner = new Scanner(in, StandardCharsets.UTF_8.name())) { |
| 32 | + scanner.useDelimiter("\\A"); |
| 33 | + xml = scanner.hasNext() ? scanner.next() : ""; |
| 34 | + } |
| 35 | + |
| 36 | + catalog = XML.toJSONObject(xml); |
| 37 | + } |
| 38 | + } |
| 39 | + |
| 40 | + @Test |
| 41 | + public void extractTitles() { |
| 42 | + List<String> titles = catalog.toStream() |
| 43 | + .filter(n -> n.getPath().endsWith("/title")) |
| 44 | + .map(n -> n.getValue().toString()) |
| 45 | + .collect(Collectors.toList()); |
| 46 | + |
| 47 | + assertEquals(12, titles.size()); |
| 48 | + assertTrue(titles.contains("XML Developer's Guide")); |
| 49 | + assertTrue(titles.contains("Visual Studio 7: A Comprehensive Guide")); |
| 50 | + } |
| 51 | + |
| 52 | + @Test |
| 53 | + public void findExactPath() { |
| 54 | + String wantedPath = "/catalog/book[0]/author"; |
| 55 | + Optional<JSONNode> node = catalog.toStream() |
| 56 | + .filter(n -> n.getPath().equals(wantedPath)) |
| 57 | + .findFirst(); |
| 58 | + |
| 59 | + assertTrue(node.isPresent()); |
| 60 | + assertEquals("Gambardella, Matthew", node.get().getValue()); |
| 61 | + } |
| 62 | + |
| 63 | + @Test |
| 64 | + public void filterCheapBooks() { |
| 65 | + List<JSONNode> cheapPrices = catalog.toStream() |
| 66 | + .filter(n -> n.getPath().endsWith("/price")) |
| 67 | + .filter(n -> Double.parseDouble(n.getValue().toString()) < 10.0) |
| 68 | + .collect(Collectors.toList()); |
| 69 | + |
| 70 | + assertEquals(8, cheapPrices.size()); |
| 71 | + assertTrue(cheapPrices.stream() |
| 72 | + .allMatch(n -> Double.parseDouble(n.getValue().toString()) < 10.0)); |
| 73 | + } |
| 74 | +} |
0 commit comments