001/*
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements.  See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership.  The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License.  You may obtain a copy of the License at
009 *
010 *     http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing, software
013 * distributed under the License is distributed on an "AS IS" BASIS,
014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 */
018package org.apache.hadoop.hbase.mapred;
019
020import static org.junit.Assert.assertEquals;
021import static org.junit.Assert.assertNotNull;
022import static org.junit.Assert.assertTrue;
023import static org.mockito.ArgumentMatchers.anyLong;
024import static org.mockito.Matchers.any;
025import static org.mockito.Mockito.mock;
026import static org.mockito.Mockito.times;
027
028import java.io.ByteArrayOutputStream;
029import java.io.IOException;
030import java.io.PrintStream;
031import org.apache.hadoop.hbase.HBaseClassTestRule;
032import org.apache.hadoop.hbase.HBaseConfiguration;
033import org.apache.hadoop.hbase.client.Result;
034import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
035import org.apache.hadoop.hbase.mapred.RowCounter.RowCounterMapper;
036import org.apache.hadoop.hbase.testclassification.MapReduceTests;
037import org.apache.hadoop.hbase.testclassification.MediumTests;
038import org.apache.hadoop.mapred.JobConf;
039import org.apache.hadoop.mapred.OutputCollector;
040import org.apache.hadoop.mapred.Reporter;
041import org.junit.ClassRule;
042import org.junit.Test;
043import org.junit.experimental.categories.Category;
044import org.mockito.Mockito;
045
046import org.apache.hbase.thirdparty.com.google.common.base.Joiner;
047
048@Category({ MapReduceTests.class, MediumTests.class })
049public class TestRowCounter {
050
051  @ClassRule
052  public static final HBaseClassTestRule CLASS_RULE =
053    HBaseClassTestRule.forClass(TestRowCounter.class);
054
055  @Test
056  @SuppressWarnings("deprecation")
057  public void shouldPrintUsage() throws Exception {
058    String expectedOutput = "rowcounter <outputdir> <tablename> <column1> [<column2>...]";
059    String result = new OutputReader(System.out) {
060      @Override
061      void doRead() {
062        assertEquals(-1, RowCounter.printUsage());
063      }
064    }.read();
065
066    assertTrue(result.startsWith(expectedOutput));
067  }
068
069  @Test
070  @SuppressWarnings("deprecation")
071  public void shouldExitAndPrintUsageSinceParameterNumberLessThanThree() throws Exception {
072    final String[] args = new String[] { "one", "two" };
073    String line = "ERROR: Wrong number of parameters: " + args.length;
074    String result = new OutputReader(System.err) {
075      @Override
076      void doRead() throws Exception {
077        assertEquals(-1, new RowCounter().run(args));
078      }
079    }.read();
080
081    assertTrue(result.startsWith(line));
082  }
083
084  @Test
085  @SuppressWarnings({ "deprecation", "unchecked" })
086  public void shouldRegInReportEveryIncomingRow() throws IOException {
087    int iterationNumber = 999;
088    RowCounter.RowCounterMapper mapper = new RowCounter.RowCounterMapper();
089    Reporter reporter = mock(Reporter.class);
090    for (int i = 0; i < iterationNumber; i++)
091      mapper.map(mock(ImmutableBytesWritable.class), mock(Result.class),
092        mock(OutputCollector.class), reporter);
093
094    Mockito.verify(reporter, times(iterationNumber)).incrCounter(any(), anyLong());
095  }
096
097  @Test
098  @SuppressWarnings({ "deprecation" })
099  public void shouldCreateAndRunSubmittableJob() throws Exception {
100    RowCounter rCounter = new RowCounter();
101    rCounter.setConf(HBaseConfiguration.create());
102    String[] args = new String[] { "\temp", "tableA", "column1", "column2", "column3" };
103    JobConf jobConfig = rCounter.createSubmittableJob(args);
104
105    assertNotNull(jobConfig);
106    assertEquals(0, jobConfig.getNumReduceTasks());
107    assertEquals("rowcounter", jobConfig.getJobName());
108    assertEquals(jobConfig.getMapOutputValueClass(), Result.class);
109    assertEquals(jobConfig.getMapperClass(), RowCounterMapper.class);
110    assertEquals(jobConfig.get(TableInputFormat.COLUMN_LIST),
111      Joiner.on(' ').join("column1", "column2", "column3"));
112    assertEquals(jobConfig.getMapOutputKeyClass(), ImmutableBytesWritable.class);
113  }
114
115  enum Outs {
116    OUT,
117    ERR
118  }
119
120  private static abstract class OutputReader {
121    private final PrintStream ps;
122    private PrintStream oldPrintStream;
123    private Outs outs;
124
125    protected OutputReader(PrintStream ps) {
126      this.ps = ps;
127    }
128
129    protected String read() throws Exception {
130      ByteArrayOutputStream outBytes = new ByteArrayOutputStream();
131      if (ps == System.out) {
132        oldPrintStream = System.out;
133        outs = Outs.OUT;
134        System.setOut(new PrintStream(outBytes));
135      } else if (ps == System.err) {
136        oldPrintStream = System.err;
137        outs = Outs.ERR;
138        System.setErr(new PrintStream(outBytes));
139      } else {
140        throw new IllegalStateException("OutputReader: unsupported PrintStream");
141      }
142
143      try {
144        doRead();
145        return new String(outBytes.toByteArray());
146      } finally {
147        switch (outs) {
148          case OUT: {
149            System.setOut(oldPrintStream);
150            break;
151          }
152          case ERR: {
153            System.setErr(oldPrintStream);
154            break;
155          }
156          default:
157            throw new IllegalStateException("OutputReader: unsupported PrintStream");
158        }
159      }
160    }
161
162    abstract void doRead() throws Exception;
163  }
164}