|
| 1 | +package flow.netbeans.markdown.csl; |
| 2 | + |
| 3 | +import java.util.ArrayList; |
| 4 | +import java.util.Collections; |
| 5 | +import java.util.Comparator; |
| 6 | +import java.util.List; |
| 7 | +import org.junit.After; |
| 8 | +import org.junit.Assert; |
| 9 | +import org.junit.Before; |
| 10 | +import org.junit.Test; |
| 11 | +import org.netbeans.modules.csl.api.StructureItem; |
| 12 | +import org.pegdown.ast.HeaderNode; |
| 13 | +import org.pegdown.ast.TextNode; |
| 14 | + |
| 15 | +public class MarkdownTOCBuilderTest { |
| 16 | + |
| 17 | + private static final Comparator<StructureItem> BY_SORT_KEY = new Comparator<StructureItem>() { |
| 18 | + |
| 19 | + @Override |
| 20 | + public int compare(StructureItem o1, StructureItem o2) { |
| 21 | + return o1.getSortText().compareTo(o2.getSortText()); |
| 22 | + } |
| 23 | + |
| 24 | + }; |
| 25 | + |
| 26 | + @Before |
| 27 | + public void setUp() { |
| 28 | + } |
| 29 | + |
| 30 | + @After |
| 31 | + public void tearDown() { |
| 32 | + } |
| 33 | + |
| 34 | + /** |
| 35 | + * Test fix for <a href="https://github.com/madflow/flow-netbeans-markdown/issues/114">issue #114</a>. |
| 36 | + */ |
| 37 | + @Test |
| 38 | + public void testSortKeyReflectsDocumentStructure() { |
| 39 | + // given |
| 40 | + MarkdownTOCBuilder builder = new MarkdownTOCBuilder(null); |
| 41 | + final int count = 20; |
| 42 | + List<HeaderNode> nodes = createHeaderNodes(count); |
| 43 | + |
| 44 | + // when |
| 45 | + for (HeaderNode node : nodes) { |
| 46 | + builder.add(node); |
| 47 | + } |
| 48 | + builder.finish(count * 100); |
| 49 | + List<? extends StructureItem> items = builder.build(); |
| 50 | + |
| 51 | + // then |
| 52 | + List<? extends StructureItem> expItems = new ArrayList<StructureItem>(items); |
| 53 | + Collections.sort(expItems, BY_SORT_KEY); |
| 54 | + |
| 55 | + Assert.assertEquals("items are sorted by sort key", expItems, items); |
| 56 | + } |
| 57 | + |
| 58 | + private List<HeaderNode> createHeaderNodes(int count) { |
| 59 | + final List<HeaderNode> headerNodes = new ArrayList<HeaderNode>(); |
| 60 | + for (int index = 0; index < count; ++index) { |
| 61 | + headerNodes.add(createHeaderNode(index)); |
| 62 | + } |
| 63 | + |
| 64 | + return headerNodes; |
| 65 | + } |
| 66 | + |
| 67 | + private HeaderNode createHeaderNode(int index) { |
| 68 | + TextNode textNode = new TextNode("Heading " + (index + 1)); |
| 69 | + |
| 70 | + HeaderNode headerNode = new HeaderNode(1, textNode); |
| 71 | + |
| 72 | + headerNode.setStartIndex(index * 100); |
| 73 | + textNode.setStartIndex(headerNode.getStartIndex() + 2); |
| 74 | + textNode.setEndIndex(textNode.getStartIndex() + textNode.getText().length()); |
| 75 | + headerNode.setEndIndex(textNode.getEndIndex()); |
| 76 | + |
| 77 | + return headerNode; |
| 78 | + } |
| 79 | +} |
0 commit comments