1 /* 2 * Copyright (C) 2011 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 package com.android.loganalysis.parser; 17 18 import com.android.loganalysis.item.IItem; 19 20 import junit.framework.TestCase; 21 22 import java.util.ArrayList; 23 import java.util.List; 24 25 /** 26 * Unit tests for {@link AbstractSectionParser} 27 */ 28 public class AbstractSectionParserTest extends TestCase { 29 AbstractSectionParser mParser = null; 30 31 @Override setUp()32 public void setUp() throws Exception { 33 super.setUp(); 34 mParser = new AbstractSectionParser() { 35 @Override 36 public IItem parse(List<String> lines) { 37 for (String line : lines) { 38 parseLine(line); 39 } 40 commit(); 41 return null; 42 } 43 }; 44 } 45 46 private static class FakeBlockParser implements IParser { 47 private String mExpected = null; 48 private int mCalls = 0; 49 FakeBlockParser(String expected)50 public FakeBlockParser(String expected) { 51 mExpected = expected; 52 } 53 getCalls()54 public int getCalls() { 55 return mCalls; 56 } 57 58 @Override parse(List<String> input)59 public IItem parse(List<String> input) { 60 assertEquals(1, input.size()); 61 assertEquals("parseBlock() got unexpected input!", mExpected, input.get(0)); 62 mCalls += 1; 63 return null; 64 } 65 } 66 67 /** 68 * Verifies that {@link AbstractSectionParser} switches between parsers as expected 69 */ testSwitchParsers()70 public void testSwitchParsers() { 71 final String lineFormat = "howdy, parser %d!"; 72 final String linePattern = "I spy %d candles"; 73 final int nParsers = 4; 74 FakeBlockParser[] parsers = new FakeBlockParser[nParsers]; 75 final List<String> lines = new ArrayList<String>(2*nParsers); 76 77 for (int i = 0; i < nParsers; ++i) { 78 String line = String.format(lineFormat, i); 79 FakeBlockParser parser = new FakeBlockParser(line); 80 mParser.addSectionParser(parser, String.format(linePattern, i)); 81 parsers[i] = parser; 82 83 // add the parser trigger 84 lines.add(String.format(linePattern, i)); 85 // and then add the line that the parser is expecting 86 lines.add(String.format(lineFormat, i)); 87 } 88 89 mParser.parse(lines); 90 91 // Verify that all the parsers were run 92 for (int i = 0; i < nParsers; ++i) { 93 assertEquals(String.format("Parser %d has wrong call count!", i), 1, 94 parsers[i].getCalls()); 95 } 96 } 97 } 98 99