How to use method of org.mockito.ArgumentCaptor class

Best Mockito code snippet using org.mockito.ArgumentCaptor.

Run Mockito automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

copy
1/**
2 * Licensed to the Apache Software Foundation (ASF) under one
3 * or more contributor license agreements.  See the NOTICE file
4 * distributed with this work for additional information
5 * regarding copyright ownership.  The ASF licenses this file
6 * to you under the Apache License, Version 2.0 (the
7 * "License"); you may not use this file except in compliance
8 * with the License.  You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
17 */
18package org.apache.storm.spout;
19
20import org.apache.storm.Config;
21import org.apache.storm.state.KeyValueState;
22import org.apache.storm.state.StateFactory;
23import org.apache.storm.task.TopologyContext;
24import org.apache.storm.tuple.Values;
25import org.apache.storm.utils.Utils;
26import org.junit.Before;
27import org.junit.Test;
28import org.mockito.ArgumentCaptor;
29import org.mockito.Mockito;
30
31import java.util.HashMap;
32import java.util.Map;
33
34import static org.apache.storm.spout.CheckPointState.State.COMMITTED;
35import static org.junit.Assert.assertEquals;
36import static org.apache.storm.spout.CheckPointState.Action;
37
38/**
39 * Unit test for {@link CheckpointSpout}
40 */
41public class CheckpointSpoutTest {
42    CheckpointSpout spout = new CheckpointSpout();
43    TopologyContext mockTopologyContext;
44    SpoutOutputCollector mockOutputCollector;
45
46    @Before
47    public void setUp() throws Exception {
48        mockTopologyContext = Mockito.mock(TopologyContext.class);
49        Mockito.when(mockTopologyContext.getThisComponentId()).thenReturn("test");
50        Mockito.when(mockTopologyContext.getThisTaskId()).thenReturn(1);
51        mockOutputCollector = Mockito.mock(SpoutOutputCollector.class);
52    }
53
54    @Test
55    public void testInitState() throws Exception {
56        spout.open(new HashMap(), mockTopologyContext, mockOutputCollector);
57
58        spout.nextTuple();
59        Values expectedTuple = new Values(-1L, Action.INITSTATE);
60        ArgumentCaptor<String> stream = ArgumentCaptor.forClass(String.class);
61        ArgumentCaptor<Values> values = ArgumentCaptor.forClass(Values.class);
62        ArgumentCaptor<Object> msgId = ArgumentCaptor.forClass(Object.class);
63        Mockito.verify(mockOutputCollector).emit(stream.capture(),
64                                                 values.capture(),
65                                                 msgId.capture());
66
67        assertEquals(CheckpointSpout.CHECKPOINT_STREAM_ID, stream.getValue());
68        assertEquals(expectedTuple, values.getValue());
69        assertEquals(-1L, msgId.getValue());
70
71        spout.ack(-1L);
72
73        Mockito.verify(mockOutputCollector).emit(stream.capture(),
74                                                 values.capture(),
75                                                 msgId.capture());
76
77        expectedTuple = new Values(-1L, Action.INITSTATE);
78        assertEquals(CheckpointSpout.CHECKPOINT_STREAM_ID, stream.getValue());
79        assertEquals(expectedTuple, values.getValue());
80        assertEquals(-1L, msgId.getValue());
81
82    }
83
84    @Test
85    public void testPrepare() throws Exception {
86        spout.open(new HashMap(), mockTopologyContext, mockOutputCollector);
87        ArgumentCaptor<String> stream = ArgumentCaptor.forClass(String.class);
88        ArgumentCaptor<Values> values = ArgumentCaptor.forClass(Values.class);
89        ArgumentCaptor<Object> msgId = ArgumentCaptor.forClass(Object.class);
90
91        spout.nextTuple();
92        spout.ack(-1L);
93        spout.nextTuple();
94        Mockito.verify(mockOutputCollector, Mockito.times(2)).emit(stream.capture(),
95                                                 values.capture(),
96                                                 msgId.capture());
97
98        Values expectedTuple = new Values(0L, Action.PREPARE);
99        assertEquals(CheckpointSpout.CHECKPOINT_STREAM_ID, stream.getValue());
100        assertEquals(expectedTuple, values.getValue());
101        assertEquals(0L, msgId.getValue());
102
103    }
104
105    @Test
106    public void testPrepareWithFail() throws Exception {
107        Map<String, Object> stormConf = new HashMap<>();
108        KeyValueState<String, CheckPointState> state =
109                (KeyValueState<String, CheckPointState>) StateFactory.getState("__state", stormConf, mockTopologyContext);
110        CheckPointState txState = new CheckPointState(-1, COMMITTED);
111        state.put("__state", txState);
112
113        spout.open(mockTopologyContext, mockOutputCollector, 0, state);
114        ArgumentCaptor<String> stream = ArgumentCaptor.forClass(String.class);
115        ArgumentCaptor<Values> values = ArgumentCaptor.forClass(Values.class);
116        ArgumentCaptor<Object> msgId = ArgumentCaptor.forClass(Object.class);
117
118        spout.nextTuple();
119        spout.ack(-1L);
120        Utils.sleep(10);
121        spout.nextTuple();
122        spout.ack(0L);
123        Utils.sleep(10);
124        spout.nextTuple();
125        spout.ack(0L);
126        Utils.sleep(10);
127        spout.nextTuple();
128        spout.fail(1L);
129        Utils.sleep(10);
130        spout.nextTuple();
131        spout.fail(1L);
132        Utils.sleep(10);
133        spout.nextTuple();
134        spout.ack(1L);
135        Utils.sleep(10);
136        spout.nextTuple();
137        spout.ack(0L);
138        Utils.sleep(10);
139        spout.nextTuple();
140        Mockito.verify(mockOutputCollector, Mockito.times(8)).emit(stream.capture(),
141                                                                   values.capture(),
142                                                                   msgId.capture());
143
144        Values expectedTuple = new Values(1L, Action.PREPARE);
145        assertEquals(CheckpointSpout.CHECKPOINT_STREAM_ID, stream.getValue());
146        assertEquals(expectedTuple, values.getValue());
147        assertEquals(1L, msgId.getValue());
148
149    }
150
151    @Test
152    public void testCommit() throws Exception {
153        Map<String, Object> stormConf = new HashMap();
154        stormConf.put(Config.TOPOLOGY_STATE_CHECKPOINT_INTERVAL, 0);
155        spout.open(stormConf, mockTopologyContext, mockOutputCollector);
156        ArgumentCaptor<String> stream = ArgumentCaptor.forClass(String.class);
157        ArgumentCaptor<Values> values = ArgumentCaptor.forClass(Values.class);
158        ArgumentCaptor<Object> msgId = ArgumentCaptor.forClass(Object.class);
159
160        spout.nextTuple();
161        spout.ack(-1L);
162        spout.nextTuple();
163        spout.ack(0L);
164        Utils.sleep(10);
165        spout.nextTuple();
166        spout.fail(0L);
167        Utils.sleep(10);
168        spout.nextTuple();
169        Mockito.verify(mockOutputCollector, Mockito.times(4)).emit(stream.capture(),
170                                                                   values.capture(),
171                                                                   msgId.capture());
172
173        Values expectedTuple = new Values(0L, Action.COMMIT);
174        assertEquals(CheckpointSpout.CHECKPOINT_STREAM_ID, stream.getValue());
175        assertEquals(expectedTuple, values.getValue());
176        assertEquals(0L, msgId.getValue());
177
178    }
179
180    @Test
181    public void testRecoveryRollback() throws Exception {
182        Map<String, Object> stormConf = new HashMap();
183
184        KeyValueState<String, CheckPointState> state =
185                (KeyValueState<String, CheckPointState>) StateFactory.getState("test-1", stormConf, mockTopologyContext);
186
187        CheckPointState checkPointState = new CheckPointState(100, CheckPointState.State.PREPARING);
188        state.put("__state", checkPointState);
189        spout.open(mockTopologyContext, mockOutputCollector, 0, state);
190        ArgumentCaptor<String> stream = ArgumentCaptor.forClass(String.class);
191        ArgumentCaptor<Values> values = ArgumentCaptor.forClass(Values.class);
192        ArgumentCaptor<Object> msgId = ArgumentCaptor.forClass(Object.class);
193
194        spout.nextTuple();
195        Mockito.verify(mockOutputCollector, Mockito.times(1)).emit(stream.capture(),
196                                                                   values.capture(),
197                                                                   msgId.capture());
198
199        Values expectedTuple = new Values(100L, Action.ROLLBACK);
200        assertEquals(CheckpointSpout.CHECKPOINT_STREAM_ID, stream.getValue());
201        assertEquals(expectedTuple, values.getValue());
202        assertEquals(100L, msgId.getValue());
203
204    }
205
206    @Test
207    public void testRecoveryRollbackAck() throws Exception {
208        Map<String, Object> stormConf = new HashMap();
209
210        KeyValueState<String, CheckPointState> state =
211                (KeyValueState<String, CheckPointState>) StateFactory.getState("test-1", stormConf, mockTopologyContext);
212
213        CheckPointState checkPointState = new CheckPointState(100, CheckPointState.State.PREPARING);
214        state.put("__state", checkPointState);
215        spout.open(mockTopologyContext, mockOutputCollector, 0, state);
216        ArgumentCaptor<String> stream = ArgumentCaptor.forClass(String.class);
217        ArgumentCaptor<Values> values = ArgumentCaptor.forClass(Values.class);
218        ArgumentCaptor<Object> msgId = ArgumentCaptor.forClass(Object.class);
219
220        spout.nextTuple();
221        spout.ack(100L);
222        spout.nextTuple();
223        spout.ack(99L);
224        spout.nextTuple();
225        Mockito.verify(mockOutputCollector, Mockito.times(3)).emit(stream.capture(),
226                                                                   values.capture(),
227                                                                   msgId.capture());
228
229        Values expectedTuple = new Values(100L, Action.PREPARE);
230        assertEquals(CheckpointSpout.CHECKPOINT_STREAM_ID, stream.getValue());
231        assertEquals(expectedTuple, values.getValue());
232        assertEquals(100L, msgId.getValue());
233
234    }
235
236    @Test
237    public void testRecoveryCommit() throws Exception {
238        Map<String, Object> stormConf = new HashMap();
239
240        KeyValueState<String, CheckPointState> state =
241                (KeyValueState<String, CheckPointState>) StateFactory.getState("test-1", stormConf, mockTopologyContext);
242
243        CheckPointState checkPointState = new CheckPointState(100, CheckPointState.State.COMMITTING);
244        state.put("__state", checkPointState);
245        spout.open(mockTopologyContext, mockOutputCollector, 0, state);
246        ArgumentCaptor<String> stream = ArgumentCaptor.forClass(String.class);
247        ArgumentCaptor<Values> values = ArgumentCaptor.forClass(Values.class);
248        ArgumentCaptor<Object> msgId = ArgumentCaptor.forClass(Object.class);
249
250        spout.nextTuple();
251        Mockito.verify(mockOutputCollector, Mockito.times(1)).emit(stream.capture(),
252                                                                   values.capture(),
253                                                                   msgId.capture());
254
255        Values expectedTuple = new Values(100L, Action.COMMIT);
256        assertEquals(CheckpointSpout.CHECKPOINT_STREAM_ID, stream.getValue());
257        assertEquals(expectedTuple, values.getValue());
258        assertEquals(100L, msgId.getValue());
259
260    }
261
262}
Full Screen
copy
1/*
2 * Licensed to the Apache Software Foundation (ASF) under one
3 * or more contributor license agreements.  See the NOTICE file
4 * distributed with this work for additional information
5 * regarding copyright ownership.  The ASF licenses this file
6 * to you under the Apache License, Version 2.0 (the
7 * "License"); you may not use this file except in compliance
8 * with the License.  You may obtain a copy of the License at
9 *
10 *     http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
17 */
18package org.apache.hadoop.hive.ql.exec;
19
20import static org.junit.Assert.assertFalse;
21import static org.junit.Assert.assertTrue;
22import static org.junit.Assert.fail;
23
24import java.util.ArrayList;
25import java.util.Arrays;
26import java.util.HashSet;
27import java.util.List;
28import java.util.Set;
29
30import org.apache.hadoop.hive.conf.HiveConf;
31import org.apache.hadoop.hive.conf.HiveConf.ConfVars;
32import org.apache.hadoop.hive.metastore.CheckResult.PartitionResult;
33import org.apache.hadoop.hive.metastore.HiveMetaStoreClient;
34import org.apache.hadoop.hive.metastore.IMetaStoreClient;
35import org.apache.hadoop.hive.metastore.Msck;
36import org.apache.hadoop.hive.metastore.api.FieldSchema;
37import org.apache.hadoop.hive.metastore.api.MetaException;
38import org.apache.hadoop.hive.metastore.api.Partition;
39import org.apache.hadoop.hive.metastore.api.SerDeInfo;
40import org.apache.hadoop.hive.metastore.api.StorageDescriptor;
41import org.apache.hadoop.hive.metastore.api.Table;
42import org.apache.hadoop.hive.metastore.utils.RetryUtilities;
43import org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat;
44import org.apache.hadoop.hive.ql.metadata.HiveException;
45import org.apache.hadoop.hive.ql.session.SessionState;
46import org.apache.hadoop.hive.ql.stats.StatsUtils;
47import org.apache.hadoop.mapred.TextInputFormat;
48import org.apache.hadoop.util.StringUtils;
49import org.junit.After;
50import org.junit.Assert;
51import org.junit.Before;
52import org.junit.BeforeClass;
53import org.junit.Test;
54import org.mockito.ArgumentCaptor;
55import org.mockito.Mockito;
56
57public class TestMsckCreatePartitionsInBatches {
58  private static HiveConf hiveConf;
59  private static Msck msck;
60  private final String catName = "hive";
61  private final String dbName = "default";
62  private final String tableName = "test_msck_batch";
63  private static IMetaStoreClient db;
64  private List<String> repairOutput;
65  private Table table;
66
67  @BeforeClass
68  public static void setupClass() throws HiveException, MetaException {
69    hiveConf = new HiveConf(TestMsckCreatePartitionsInBatches.class);
70    hiveConf.setIntVar(ConfVars.HIVE_MSCK_REPAIR_BATCH_SIZE, 5);
71    hiveConf.setVar(HiveConf.ConfVars.HIVE_AUTHORIZATION_MANAGER,
72        "org.apache.hadoop.hive.ql.security.authorization.plugin.sqlstd.SQLStdHiveAuthorizerFactory");
73    SessionState.start(hiveConf);
74    try {
75      db = new HiveMetaStoreClient(hiveConf);
76    } catch (MetaException e) {
77      throw new HiveException(e);
78    }
79    msck = new Msck( false, false);
80    msck.init(hiveConf);
81  }
82
83  @Before
84  public void before() throws Exception {
85    createPartitionedTable(catName, dbName, tableName);
86    table = db.getTable(catName, dbName, tableName);
87    repairOutput = new ArrayList<String>();
88  }
89
90  @After
91  public void after() throws Exception {
92    cleanUpTableQuietly(catName, dbName, tableName);
93  }
94
95  private Table createPartitionedTable(String catName, String dbName, String tableName) throws Exception {
96    try {
97      db.dropTable(catName, dbName, tableName);
98      Table table = new Table();
99      table.setCatName(catName);
100      table.setDbName(dbName);
101      table.setTableName(tableName);
102      FieldSchema col1 = new FieldSchema("key", "string", "");
103      FieldSchema col2 = new FieldSchema("value", "int", "");
104      FieldSchema col3 = new FieldSchema("city", "string", "");
105      StorageDescriptor sd = new StorageDescriptor();
106      sd.setSerdeInfo(new SerDeInfo());
107      sd.setInputFormat(TextInputFormat.class.getCanonicalName());
108      sd.setOutputFormat(HiveIgnoreKeyTextOutputFormat.class.getCanonicalName());
109      sd.setCols(Arrays.asList(col1, col2));
110      table.setPartitionKeys(Arrays.asList(col3));
111      table.setSd(sd);
112      db.createTable(table);
113      return db.getTable(catName, dbName, tableName);
114    } catch (Exception exception) {
115      fail("Unable to drop and create table " + StatsUtils.getFullyQualifiedTableName(dbName, tableName) + " because "
116          + StringUtils.stringifyException(exception));
117      throw exception;
118    }
119  }
120
121  private void cleanUpTableQuietly(String catName, String dbName, String tableName) {
122    try {
123      db.dropTable(catName, dbName, tableName);
124    } catch (Exception exception) {
125      fail("Unexpected exception: " + StringUtils.stringifyException(exception));
126    }
127  }
128
129  private Set<PartitionResult> createPartsNotInMs(int numOfParts) {
130    Set<PartitionResult> partsNotInMs = new HashSet<>();
131    for (int i = 0; i < numOfParts; i++) {
132      PartitionResult result = new PartitionResult();
133      result.setPartitionName("city=dummyCity_" + String.valueOf(i));
134      partsNotInMs.add(result);
135    }
136    return partsNotInMs;
137  }
138
139  /**
140   * Tests the number of times Hive.createPartitions calls are executed with total number of
141   * partitions to be added are equally divisible by batch size
142   *
143   * @throws Exception
144   */
145  @Test
146  public void testNumberOfCreatePartitionCalls() throws Exception {
147    // create 10 dummy partitions
148    Set<PartitionResult> partsNotInMs = createPartsNotInMs(10);
149    IMetaStoreClient spyDb = Mockito.spy(db);
150    // batch size of 5 and decaying factor of 2
151    msck.createPartitionsInBatches(spyDb, repairOutput, partsNotInMs, table, 5, 2, 0);
152    // there should be 2 calls to create partitions with each batch size of 5
153    ArgumentCaptor<Boolean> ifNotExistsArg = ArgumentCaptor.forClass(Boolean.class);
154    ArgumentCaptor<Boolean> needResultsArg = ArgumentCaptor.forClass(Boolean.class);
155    ArgumentCaptor<List<Partition>> argParts = ArgumentCaptor.forClass((Class) List.class);
156    Mockito.verify(spyDb, Mockito.times(2)).add_partitions(argParts.capture(), ifNotExistsArg.capture(), needResultsArg.capture());
157    // confirm the batch sizes were 5, 5 in the two calls to create partitions
158    List<List<Partition>> apds = argParts.getAllValues();
159    int retryAttempt = 1;
160    Assert.assertEquals(String.format("Unexpected batch size in retry attempt %d ", retryAttempt++),
161        5, apds.get(0).size());
162    Assert.assertEquals(String.format("Unexpected batch size in retry attempt %d ", retryAttempt++),
163        5, apds.get(1).size());
164    assertTrue(ifNotExistsArg.getValue());
165    assertFalse(needResultsArg.getValue());
166  }
167
168  /**
169   * Tests the number of times Hive.createPartitions calls are executed with total number of
170   * partitions to be added are not exactly divisible by batch size
171   *
172   * @throws Exception
173   */
174  @Test
175  public void testUnevenNumberOfCreatePartitionCalls() throws Exception {
176    // create 9 dummy partitions
177    Set<PartitionResult> partsNotInMs = createPartsNotInMs(9);
178    IMetaStoreClient spyDb = Mockito.spy(db);
179    // batch size of 5 and decaying factor of 2
180    msck.createPartitionsInBatches(spyDb, repairOutput, partsNotInMs, table, 5, 2, 0);
181    // there should be 2 calls to create partitions with batch sizes of 5, 4
182    ArgumentCaptor<Boolean> ifNotExistsArg = ArgumentCaptor.forClass(Boolean.class);
183    ArgumentCaptor<Boolean> needResultsArg = ArgumentCaptor.forClass(Boolean.class);
184    ArgumentCaptor<List<Partition>> argParts = ArgumentCaptor.forClass((Class) List.class);
185    Mockito.verify(spyDb, Mockito.times(2)).add_partitions(argParts.capture(), ifNotExistsArg.capture(), needResultsArg.capture());
186    // confirm the batch sizes were 5, 4 in the two calls to create partitions
187    List<List<Partition>> apds = argParts.getAllValues();
188    int retryAttempt = 1;
189    Assert.assertEquals(String.format("Unexpected batch size in retry attempt %d ", retryAttempt++),
190        5, apds.get(0).size());
191    Assert.assertEquals(String.format("Unexpected batch size in retry attempt %d ", retryAttempt++),
192        4, apds.get(1).size());
193    assertTrue(ifNotExistsArg.getValue());
194    assertFalse(needResultsArg.getValue());
195  }
196
197  /**
198   * Tests the number of times Hive.createPartitions calls are executed with total number of
199   * partitions exactly equal to batch size
200   *
201   * @throws Exception
202   */
203  @Test
204  public void testEqualNumberOfPartitions() throws Exception {
205    // create 13 dummy partitions
206    Set<PartitionResult> partsNotInMs = createPartsNotInMs(13);
207    IMetaStoreClient spyDb = Mockito.spy(db);
208    // batch size of 13 and decaying factor of 2
209    msck.createPartitionsInBatches(spyDb, repairOutput, partsNotInMs, table, 13, 2, 0);
210    // there should be 1 call to create partitions with batch sizes of 13
211    ArgumentCaptor<Boolean> ifNotExistsArg = ArgumentCaptor.forClass(Boolean.class);
212    ArgumentCaptor<Boolean> needResultsArg = ArgumentCaptor.forClass(Boolean.class);
213    ArgumentCaptor<List<Partition>> argParts = ArgumentCaptor.forClass((Class) List.class);
214    // there should be 1 call to create partitions with batch sizes of 13
215    Mockito.verify(spyDb, Mockito.times(1)).add_partitions(argParts.capture(), ifNotExistsArg.capture(),
216      needResultsArg.capture());
217    Assert.assertEquals("Unexpected number of batch size", 13,
218        argParts.getValue().size());
219    assertTrue(ifNotExistsArg.getValue());
220    assertFalse(needResultsArg.getValue());
221  }
222
223  /**
224   * Tests the number of times Hive.createPartitions calls are executed with total number of
225   * partitions to is less than batch size
226   *
227   * @throws Exception
228   */
229  @Test
230  public void testSmallNumberOfPartitions() throws Exception {
231    // create 10 dummy partitions
232    Set<PartitionResult> partsNotInMs = createPartsNotInMs(10);
233    IMetaStoreClient spyDb = Mockito.spy(db);
234    // batch size of 20 and decaying factor of 2
235    msck.createPartitionsInBatches(spyDb, repairOutput, partsNotInMs, table, 20, 2, 0);
236    // there should be 1 call to create partitions with batch sizes of 10
237    Mockito.verify(spyDb, Mockito.times(1)).add_partitions(Mockito.anyObject(), Mockito.anyBoolean(),
238      Mockito.anyBoolean());
239    ArgumentCaptor<Boolean> ifNotExistsArg = ArgumentCaptor.forClass(Boolean.class);
240    ArgumentCaptor<Boolean> needResultsArg = ArgumentCaptor.forClass(Boolean.class);
241    ArgumentCaptor<List<Partition>> argParts = ArgumentCaptor.forClass((Class) List.class);
242    // there should be 1 call to create partitions with batch sizes of 10
243    Mockito.verify(spyDb, Mockito.times(1)).add_partitions(argParts.capture(), ifNotExistsArg.capture(),
244      needResultsArg.capture());
245    Assert.assertEquals("Unexpected number of batch size", 10,
246        argParts.getValue().size());
247    assertTrue(ifNotExistsArg.getValue());
248    assertFalse(needResultsArg.getValue());
249  }
250
251  /**
252   * Tests the number of calls to createPartitions and the respective batch sizes when first call to
253   * createPartitions throws HiveException. The batch size should be reduced by the decayingFactor
254   *
255   * @throws Exception
256   */
257  @Test
258  public void testBatchingWhenException() throws Exception {
259    // create 13 dummy partitions
260    Set<PartitionResult> partsNotInMs = createPartsNotInMs(23);
261    IMetaStoreClient spyDb = Mockito.spy(db);
262    // first call to createPartitions should throw exception
263    Mockito.doThrow(HiveException.class).doCallRealMethod().doCallRealMethod().when(spyDb)
264      .add_partitions(Mockito.anyObject(), Mockito.anyBoolean(),
265        Mockito.anyBoolean());
266
267    // test with a batch size of 30 and decaying factor of 2
268    msck.createPartitionsInBatches(spyDb, repairOutput, partsNotInMs, table, 30, 2, 0);
269    // confirm the batch sizes were 23, 15, 8 in the three calls to create partitions
270    ArgumentCaptor<Boolean> ifNotExistsArg = ArgumentCaptor.forClass(Boolean.class);
271    ArgumentCaptor<Boolean> needResultsArg = ArgumentCaptor.forClass(Boolean.class);
272    ArgumentCaptor<List<Partition>> argParts = ArgumentCaptor.forClass((Class) List.class);
273    // there should be 3 calls to create partitions with batch sizes of 23, 15, 8
274    Mockito.verify(spyDb, Mockito.times(3)).add_partitions(argParts.capture(), ifNotExistsArg.capture(),
275      needResultsArg.capture());
276    List<List<Partition>> apds = argParts.getAllValues();
277    int retryAttempt = 1;
278    Assert.assertEquals(
279        String.format("Unexpected batch size in retry attempt %d ", retryAttempt++), 23,
280        apds.get(0).size());
281    Assert.assertEquals(
282        String.format("Unexpected batch size in retry attempt %d ", retryAttempt++), 15,
283        apds.get(1).size());
284    Assert.assertEquals(
285        String.format("Unexpected batch size in retry attempt %d ", retryAttempt++), 8,
286        apds.get(2).size());
287    assertTrue(ifNotExistsArg.getValue());
288    assertFalse(needResultsArg.getValue());
289  }
290
291  /**
292   * Tests the retries exhausted case when Hive.createPartitions method call always keep throwing
293   * HiveException. The batch sizes should exponentially decreased based on the decaying factor and
294   * ultimately give up when it reaches 0
295   *
296   * @throws Exception
297   */
298  @Test
299  public void testRetriesExhaustedBatchSize() throws Exception {
300    Set<PartitionResult> partsNotInMs = createPartsNotInMs(17);
301    IMetaStoreClient spyDb = Mockito.spy(db);
302    Mockito.doThrow(HiveException.class).when(spyDb)
303      .add_partitions(Mockito.anyObject(), Mockito.anyBoolean(), Mockito.anyBoolean());
304    // batch size of 5 and decaying factor of 2
305    Exception ex = null;
306    try {
307      msck.createPartitionsInBatches(spyDb, repairOutput, partsNotInMs, table, 30, 2, 0);
308    } catch (Exception retryEx) {
309      ex = retryEx;
310    }
311    assertFalse("Exception was expected but was not thrown", ex == null);
312    Assert.assertTrue("Unexpected class of exception thrown", ex instanceof RetryUtilities.RetryException);
313    // there should be 5 calls to create partitions with batch sizes of 17, 15, 7, 3, 1
314    ArgumentCaptor<Boolean> ifNotExistsArg = ArgumentCaptor.forClass(Boolean.class);
315    ArgumentCaptor<Boolean> needResultsArg = ArgumentCaptor.forClass(Boolean.class);
316    ArgumentCaptor<List<Partition>> argParts = ArgumentCaptor.forClass((Class) List.class);
317    // there should be 5 calls to create partitions with batch sizes of 17, 15, 7, 3, 1
318    Mockito.verify(spyDb, Mockito.times(5)).add_partitions(argParts.capture(), ifNotExistsArg.capture(),
319      needResultsArg.capture());
320    List<List<Partition>> apds = argParts.getAllValues();
321    int retryAttempt = 1;
322    Assert.assertEquals(
323        String.format("Unexpected batch size in retry attempt %d ", retryAttempt++), 17,
324        apds.get(0).size());
325    Assert.assertEquals(
326        String.format("Unexpected batch size in retry attempt %d ", retryAttempt++), 15,
327        apds.get(1).size());
328    Assert.assertEquals(
329        String.format("Unexpected batch size in retry attempt %d ", retryAttempt++), 7,
330        apds.get(2).size());
331    Assert.assertEquals(
332        String.format("Unexpected batch size in retry attempt %d ", retryAttempt++), 3,
333        apds.get(3).size());
334    Assert.assertEquals(
335        String.format("Unexpected batch size in retry attempt %d ", retryAttempt++), 1,
336        apds.get(4).size());
337    assertTrue(ifNotExistsArg.getValue());
338    assertFalse(needResultsArg.getValue());
339  }
340
341  /**
342   * Tests the maximum retry attempts provided by configuration
343   * @throws Exception
344   */
345  @Test
346  public void testMaxRetriesReached() throws Exception {
347    Set<PartitionResult> partsNotInMs = createPartsNotInMs(17);
348    IMetaStoreClient spyDb = Mockito.spy(db);
349    Mockito.doThrow(HiveException.class).when(spyDb)
350      .add_partitions(Mockito.anyObject(), Mockito.anyBoolean(), Mockito.anyBoolean());
351    // batch size of 5 and decaying factor of 2
352    Exception ex = null;
353    try {
354      msck.createPartitionsInBatches(spyDb, repairOutput, partsNotInMs, table, 30, 2, 2);
355    } catch (Exception retryEx) {
356      ex = retryEx;
357    }
358    assertFalse("Exception was expected but was not thrown", ex == null);
359    Assert.assertTrue("Unexpected class of exception thrown", ex instanceof RetryUtilities.RetryException);
360    ArgumentCaptor<Boolean> ifNotExistsArg = ArgumentCaptor.forClass(Boolean.class);
361    ArgumentCaptor<Boolean> needResultsArg = ArgumentCaptor.forClass(Boolean.class);
362    ArgumentCaptor<List<Partition>> argParts = ArgumentCaptor.forClass((Class) List.class);
363    Mockito.verify(spyDb, Mockito.times(2)).add_partitions(argParts.capture(), ifNotExistsArg.capture(), needResultsArg.capture());
364    List<List<Partition>> apds = argParts.getAllValues();
365    int retryAttempt = 1;
366    Assert.assertEquals(
367        String.format("Unexpected batch size in retry attempt %d ", retryAttempt++), 17,
368        apds.get(0).size());
369    Assert.assertEquals(
370        String.format("Unexpected batch size in retry attempt %d ", retryAttempt++), 15,
371        apds.get(1).size());
372    assertTrue(ifNotExistsArg.getValue());
373    assertFalse(needResultsArg.getValue());
374  }
375
376  /**
377   * Tests when max number of retries is set to 1. In this case the number of retries should
378   * be specified
379   * @throws Exception
380   */
381  @Test
382  public void testOneMaxRetries() throws Exception {
383    Set<PartitionResult> partsNotInMs = createPartsNotInMs(17);
384    IMetaStoreClient spyDb = Mockito.spy(db);
385    Mockito.doThrow(HiveException.class).when(spyDb)
386      .add_partitions(Mockito.anyObject(), Mockito.anyBoolean(), Mockito.anyBoolean());
387    // batch size of 5 and decaying factor of 2
388    Exception ex = null;
389    try {
390      msck.createPartitionsInBatches(spyDb, repairOutput, partsNotInMs, table, 30, 2, 1);
391    } catch (Exception retryEx) {
392      ex = retryEx;
393    }
394    assertFalse("Exception was expected but was not thrown", ex == null);
395    Assert.assertTrue("Unexpected class of exception thrown", ex instanceof RetryUtilities.RetryException);
396    // there should be 5 calls to create partitions with batch sizes of 17, 15, 7, 3, 1
397    ArgumentCaptor<Boolean> ifNotExistsArg = ArgumentCaptor.forClass(Boolean.class);
398    ArgumentCaptor<Boolean> needResultsArg = ArgumentCaptor.forClass(Boolean.class);
399    ArgumentCaptor<List<Partition>> argParts = ArgumentCaptor.forClass((Class) List.class);
400    // there should be 5 calls to create partitions with batch sizes of 17, 15, 7, 3, 1
401    Mockito.verify(spyDb, Mockito.times(1)).add_partitions(argParts.capture(), ifNotExistsArg.capture(),
402      needResultsArg.capture());
403    List<List<Partition>> apds = argParts.getAllValues();
404    int retryAttempt = 1;
405    Assert.assertEquals(
406        String.format("Unexpected batch size in retry attempt %d ", retryAttempt++), 17,
407        apds.get(0).size());
408    assertTrue(ifNotExistsArg.getValue());
409    assertFalse(needResultsArg.getValue());
410  }
411}
412
Full Screen
copy
1/*
2 * Licensed to the Apache Software Foundation (ASF) under one
3 * or more contributor license agreements. See the NOTICE file
4 * distributed with this work for additional information
5 * regarding copyright ownership. The ASF licenses this file
6 * to you under the Apache License, Version 2.0 (the
7 * "License"); you may not use this file except in compliance
8 * with the License. You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied. See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
18 */
19package org.apache.olingo.server.core;
20
21import static org.junit.Assert.assertEquals;
22import static org.junit.Assert.assertFalse;
23import static org.junit.Assert.assertTrue;
24
25import java.io.File;
26import java.io.FileReader;
27import java.io.IOException;
28import java.net.URI;
29
30import javax.servlet.http.HttpServlet;
31import javax.servlet.http.HttpServletRequest;
32import javax.servlet.http.HttpServletResponse;
33
34import org.apache.catalina.Context;
35import org.apache.catalina.startup.Tomcat;
36import org.apache.http.HttpHost;
37import org.apache.http.HttpRequest;
38import org.apache.http.HttpResponse;
39import org.apache.http.client.methods.HttpDelete;
40import org.apache.http.client.methods.HttpGet;
41import org.apache.http.client.methods.HttpPost;
42import org.apache.http.client.methods.HttpPut;
43import org.apache.http.entity.StringEntity;
44import org.apache.http.impl.client.DefaultHttpClient;
45import org.apache.olingo.commons.api.http.HttpMethod;
46import org.apache.olingo.commons.core.Encoder;
47import org.apache.olingo.server.api.OData;
48import org.apache.olingo.server.api.ODataHttpHandler;
49import org.apache.olingo.server.api.ServiceMetadata;
50import org.apache.olingo.server.core.requests.ActionRequest;
51import org.apache.olingo.server.core.requests.DataRequest;
52import org.apache.olingo.server.core.requests.FunctionRequest;
53import org.apache.olingo.server.core.requests.MediaRequest;
54import org.apache.olingo.server.core.requests.MetadataRequest;
55import org.apache.olingo.server.core.responses.CountResponse;
56import org.apache.olingo.server.core.responses.EntityResponse;
57import org.apache.olingo.server.core.responses.EntitySetResponse;
58import org.apache.olingo.server.core.responses.MetadataResponse;
59import org.apache.olingo.server.core.responses.NoContentResponse;
60import org.apache.olingo.server.core.responses.PrimitiveValueResponse;
61import org.apache.olingo.server.core.responses.PropertyResponse;
62import org.apache.olingo.server.core.responses.StreamResponse;
63import org.junit.Test;
64import org.mockito.ArgumentCaptor;
65import org.mockito.Mockito;
66
67public class ServiceDispatcherTest {
68  private static final int TOMCAT_PORT = 9900;
69  private Tomcat tomcat = new Tomcat();
70
71  public class SampleODataServlet extends HttpServlet {
72    private static final long serialVersionUID = 1L;
73    private final ServiceHandler handler; // must be stateless
74    private final ServiceMetadata metadata; // must be stateless
75
76    public SampleODataServlet(ServiceHandler handler, ServiceMetadata metadata) {
77      this.handler = handler;
78      this.metadata = metadata;
79    }
80
81    @Override
82    public void service(HttpServletRequest request, HttpServletResponse response)
83        throws IOException {
84      OData odata = OData4Impl.newInstance();
85
86      ODataHttpHandler handler = odata.createHandler(this.metadata);
87
88      handler.register(this.handler);
89      handler.process(request, response);
90    }
91  }
92  
93  public void beforeTest(ServiceHandler serviceHandler) throws Exception {
94    MetadataParser parser = new MetadataParser();
95    parser.parseAnnotations(true);
96    parser.useLocalCoreVocabularies(true);
97    parser.implicitlyLoadCoreVocabularies(true);
98    ServiceMetadata metadata = parser.buildServiceMetadata(new FileReader("src/test/resources/trippin.xml"));
99
100    File baseDir = new File(System.getProperty("java.io.tmpdir"));
101    tomcat.setBaseDir(baseDir.getAbsolutePath());
102    tomcat.getHost().setAppBase(baseDir.getAbsolutePath());
103    Context cxt = tomcat.addContext("/trippin", baseDir.getAbsolutePath());
104    Tomcat.addServlet(cxt, "trippin", new SampleODataServlet(serviceHandler, metadata));
105    cxt.addServletMapping("/*", "trippin");
106    tomcat.setPort(TOMCAT_PORT);
107    tomcat.start();
108  }
109
110  public void afterTest() throws Exception {
111    tomcat.stop();
112    tomcat.destroy();
113  }
114
115  interface TestResult {
116    void validate() throws Exception;
117  }
118
119  private HttpHost getLocalhost() {
120    return new HttpHost(tomcat.getHost().getName(), 9900);
121  }
122  
123  private HttpResponse httpGET(String url) throws Exception{
124    HttpRequest request = new HttpGet(url);
125    return httpSend(request);
126  }
127
128  private HttpResponse httpSend(HttpRequest request) throws Exception{
129    DefaultHttpClient http = new DefaultHttpClient();
130    HttpResponse response = http.execute(getLocalhost(), request);
131    return response;
132  }
133  
134  private void helpGETTest(ServiceHandler handler, String path, TestResult validator)
135      throws Exception {
136    beforeTest(handler);
137    httpGET("http://localhost:" + TOMCAT_PORT + "/" + path);
138    validator.validate();
139    afterTest();
140  }
141
142  private void helpTest(ServiceHandler handler, String path, String method, String payload,
143      TestResult validator) throws Exception {
144    beforeTest(handler);
145
146    DefaultHttpClient http = new DefaultHttpClient();
147    
148    String editUrl = "http://localhost:" + TOMCAT_PORT + "/" + path;
149    HttpRequest request = new HttpGet(editUrl);
150    if (method.equals("POST")) {
151      HttpPost post = new HttpPost(editUrl);
152      post.setEntity(new StringEntity(payload));
153      request = post;
154    } else if (method.equals("PUT")) {
155      HttpPut put = new HttpPut(editUrl);
156      put.setEntity(new StringEntity(payload));
157      request = put;
158    } else if (method.equals("DELETE")) {
159      HttpDelete delete = new HttpDelete(editUrl);
160      request = delete;
161    }
162    request.setHeader("Content-Type", "application/json;odata.metadata=minimal");
163    http.execute(getLocalhost(), request);
164
165    validator.validate();
166    afterTest();
167  }
168
169  @Test
170  public void testMetadata() throws Exception {
171    final ServiceHandler handler = Mockito.mock(ServiceHandler.class);
172    helpGETTest(handler, "trippin/$metadata", new TestResult() {
173      @Override
174      public void validate() throws Exception {
175        ArgumentCaptor<MetadataRequest> arg1 = ArgumentCaptor.forClass(MetadataRequest.class);
176        ArgumentCaptor<MetadataResponse> arg2 = ArgumentCaptor.forClass(MetadataResponse.class);
177        Mockito.verify(handler).readMetadata(arg1.capture(), arg2.capture());
178      }
179    });
180  }
181
182  @Test
183  public void testEntitySet() throws Exception {
184    final ServiceHandler handler = Mockito.mock(ServiceHandler.class);
185    helpGETTest(handler, "trippin/Airports", new TestResult() {
186      @Override
187      public void validate() throws Exception {
188        ArgumentCaptor<DataRequest> arg1 = ArgumentCaptor.forClass(DataRequest.class);
189        ArgumentCaptor<EntityResponse> arg2 = ArgumentCaptor.forClass(EntityResponse.class);
190        Mockito.verify(handler).read(arg1.capture(), arg2.capture());
191
192        DataRequest request = arg1.getValue();
193        // Need getName on ContextURL class
194        // assertEquals("",
195        // request.getContextURL(request.getOdata()).getName());
196        assertEquals("application/json;odata.metadata=minimal", request.getResponseContentType()
197            .toContentTypeString());
198      }
199    });
200  }
201
202  @Test
203  public void testEntitySetCount() throws Exception {
204    final ServiceHandler handler = Mockito.mock(ServiceHandler.class);
205    helpGETTest(handler, "trippin/Airports/$count", new TestResult() {
206      @Override
207      public void validate() throws Exception {
208        ArgumentCaptor<DataRequest> arg1 = ArgumentCaptor.forClass(DataRequest.class);
209        ArgumentCaptor<CountResponse> arg2 = ArgumentCaptor.forClass(CountResponse.class);
210        Mockito.verify(handler).read(arg1.capture(), arg2.capture());
211
212        DataRequest request = arg1.getValue();
213        // Need getName on ContextURL class
214        // assertEquals("",
215        // request.getContextURL(request.getOdata()).getName());
216        assertEquals("text/plain", request.getResponseContentType().toContentTypeString());
217      }
218    });
219  }
220
221  @Test
222  public void testEntity() throws Exception {
223    final ServiceHandler handler = Mockito.mock(ServiceHandler.class);
224    helpGETTest(handler, "trippin/Airports('0')", new TestResult() {
225      @Override
226      public void validate() throws Exception {
227        ArgumentCaptor<DataRequest> arg1 = ArgumentCaptor.forClass(DataRequest.class);
228        ArgumentCaptor<EntityResponse> arg2 = ArgumentCaptor.forClass(EntityResponse.class);
229        Mockito.verify(handler).read(arg1.capture(), arg2.capture());
230
231        DataRequest request = arg1.getValue();
232        assertEquals(1, request.getUriResourceEntitySet().getKeyPredicates().size());
233        assertEquals("application/json;odata.metadata=minimal", request.getResponseContentType()
234            .toContentTypeString());
235      }
236    });
237  }
238
239  @Test
240  public void testReadProperty() throws Exception {
241    final ServiceHandler handler = Mockito.mock(ServiceHandler.class);
242    helpGETTest(handler, "trippin/Airports('0')/IataCode", new TestResult() {
243      @Override
244      public void validate() throws Exception {
245        ArgumentCaptor<DataRequest> arg1 = ArgumentCaptor.forClass(DataRequest.class);
246        ArgumentCaptor<PropertyResponse> arg2 = ArgumentCaptor.forClass(PropertyResponse.class);
247        Mockito.verify(handler).read(arg1.capture(), arg2.capture());
248
249        DataRequest request = arg1.getValue();
250        assertTrue(request.isPropertyRequest());
251        assertFalse(request.isPropertyComplex());
252        assertEquals(1, request.getUriResourceEntitySet().getKeyPredicates().size());
253        assertEquals("application/json;odata.metadata=minimal", request.getResponseContentType()
254            .toContentTypeString());
255      }
256    });
257  }
258
259  @Test
260  public void testReadComplexProperty() throws Exception {
261    final ServiceHandler handler = Mockito.mock(ServiceHandler.class);
262    helpGETTest(handler, "trippin/Airports('0')/Location", new TestResult() {
263      @Override
264      public void validate() throws Exception {
265        ArgumentCaptor<DataRequest> arg1 = ArgumentCaptor.forClass(DataRequest.class);
266        ArgumentCaptor<PropertyResponse> arg2 = ArgumentCaptor.forClass(PropertyResponse.class);
267        Mockito.verify(handler).read(arg1.capture(), arg2.capture());
268
269        DataRequest request = arg1.getValue();
270        assertTrue(request.isPropertyRequest());
271        assertTrue(request.isPropertyComplex());
272        assertEquals(1, request.getUriResourceEntitySet().getKeyPredicates().size());
273        assertEquals("application/json;odata.metadata=minimal", request.getResponseContentType()
274            .toContentTypeString());
275      }
276    });
277  }
278
279  @Test
280  public void testReadProperty$Value() throws Exception {
281    final ServiceHandler handler = Mockito.mock(ServiceHandler.class);
282    helpGETTest(handler, "trippin/Airports('0')/IataCode/$value", new TestResult() {
283      @Override
284      public void validate() throws Exception {
285        ArgumentCaptor<DataRequest> arg1 = ArgumentCaptor.forClass(DataRequest.class);
286        ArgumentCaptor<PrimitiveValueResponse> arg2 = ArgumentCaptor
287            .forClass(PrimitiveValueResponse.class);
288        Mockito.verify(handler).read(arg1.capture(), arg2.capture());
289
290        DataRequest request = arg1.getValue();
291        assertTrue(request.isPropertyRequest());
292        assertFalse(request.isPropertyComplex());
293        assertEquals(1, request.getUriResourceEntitySet().getKeyPredicates().size());
294        assertEquals("text/plain", request.getResponseContentType().toContentTypeString());
295      }
296    });
297  }
298
299  @Test
300  public void testReadPropertyRef() throws Exception {
301    final ServiceHandler handler = Mockito.mock(ServiceHandler.class);
302    helpGETTest(handler, "trippin/Airports('0')/IataCode/$value", new TestResult() {
303      @Override
304      public void validate() throws Exception {
305        ArgumentCaptor<DataRequest> arg1 = ArgumentCaptor.forClass(DataRequest.class);
306        ArgumentCaptor<PrimitiveValueResponse> arg2 = ArgumentCaptor
307            .forClass(PrimitiveValueResponse.class);
308        Mockito.verify(handler).read(arg1.capture(), arg2.capture());
309
310        DataRequest request = arg1.getValue();
311        assertTrue(request.isPropertyRequest());
312        assertFalse(request.isPropertyComplex());
313        assertEquals(1, request.getUriResourceEntitySet().getKeyPredicates().size());
314        assertEquals("text/plain", request.getResponseContentType().toContentTypeString());
315      }
316    });
317  }
318
319  @Test
320  public void testFunctionImport() throws Exception {
321    final ServiceHandler handler = Mockito.mock(ServiceHandler.class);
322    helpGETTest(handler, "trippin/GetNearestAirport(lat=12.11,lon=34.23)", new TestResult() {
323      @Override
324      public void validate() throws Exception {
325        ArgumentCaptor<FunctionRequest> arg1 = ArgumentCaptor.forClass(FunctionRequest.class);
326        ArgumentCaptor<PropertyResponse> arg3 = ArgumentCaptor.forClass(PropertyResponse.class);
327        ArgumentCaptor<HttpMethod> arg2 = ArgumentCaptor.forClass(HttpMethod.class);
328        Mockito.verify(handler).invoke(arg1.capture(), arg2.capture(), arg3.capture());
329
330        arg1.getValue();
331      }
332    });
333  }
334
335  @Test
336  public void testActionImport() throws Exception {
337    final ServiceHandler handler = Mockito.mock(ServiceHandler.class);
338    helpTest(handler, "trippin/ResetDataSource", "POST", "", new TestResult() {
339      @Override
340      public void validate() throws Exception {
341        ArgumentCaptor<ActionRequest> arg1 = ArgumentCaptor.forClass(ActionRequest.class);
342        ArgumentCaptor<NoContentResponse> arg2 = ArgumentCaptor.forClass(NoContentResponse.class);
343        Mockito.verify(handler).invoke(arg1.capture(), Mockito.anyString(), arg2.capture());
344
345        arg1.getValue();
346      }
347    });
348  }
349
350  @Test
351  public void testReadMedia() throws Exception {
352    final ServiceHandler handler = Mockito.mock(ServiceHandler.class);
353    helpGETTest(handler, "trippin/Photos(1)/$value", new TestResult() {
354      @Override
355      public void validate() throws Exception {
356        ArgumentCaptor<MediaRequest> arg1 = ArgumentCaptor.forClass(MediaRequest.class);
357        ArgumentCaptor<StreamResponse> arg2 = ArgumentCaptor.forClass(StreamResponse.class);
358        Mockito.verify(handler).readMediaStream(arg1.capture(), arg2.capture());
359
360        MediaRequest request = arg1.getValue();
361        assertEquals("application/octet-stream", request.getResponseContentType()
362            .toContentTypeString());
363      }
364    });
365  }
366
367  @Test
368  public void testReadNavigation() throws Exception {
369    final ServiceHandler handler = Mockito.mock(ServiceHandler.class);
370    helpGETTest(handler, "trippin/People('russelwhyte')/Friends", new TestResult() {
371      @Override
372      public void validate() throws Exception {
373        ArgumentCaptor<DataRequest> arg1 = ArgumentCaptor.forClass(DataRequest.class);
374        ArgumentCaptor<EntitySetResponse> arg2 = ArgumentCaptor.forClass(EntitySetResponse.class);
375        Mockito.verify(handler).read(arg1.capture(), arg2.capture());
376
377        DataRequest request = arg1.getValue();
378        assertEquals("application/json;odata.metadata=minimal", request.getResponseContentType()
379            .toContentTypeString());
380      }
381    });
382  }
383
384  @Test
385  public void testReadReference() throws Exception {
386    final ServiceHandler handler = Mockito.mock(ServiceHandler.class);
387    helpGETTest(handler, "trippin/People('russelwhyte')/Friends/$ref", new TestResult() {
388      @Override
389      public void validate() throws Exception {
390        ArgumentCaptor<DataRequest> arg1 = ArgumentCaptor.forClass(DataRequest.class);
391        ArgumentCaptor<EntitySetResponse> arg2 = ArgumentCaptor.forClass(EntitySetResponse.class);
392        Mockito.verify(handler).read(arg1.capture(), arg2.capture());
393
394        DataRequest request = arg1.getValue();
395        assertEquals("application/json;odata.metadata=minimal", request.getResponseContentType()
396            .toContentTypeString());
397      }
398    });
399  }
400
401  @Test
402  public void testWriteReferenceCollection() throws Exception {
403    String payload = "{\n" + "\"@odata.id\": \"/Photos(11)\"\n" + "}";
404
405    final ServiceHandler handler = Mockito.mock(ServiceHandler.class);
406    helpTest(handler, "trippin/People('russelwhyte')/Friends/$ref", "POST", payload,
407        new TestResult() {
408          @Override
409          public void validate() throws Exception {
410            ArgumentCaptor<DataRequest> arg1 = ArgumentCaptor.forClass(DataRequest.class);
411            ArgumentCaptor<String> arg2 = ArgumentCaptor.forClass(String.class);
412            ArgumentCaptor<URI> arg3 = ArgumentCaptor.forClass(URI.class);
413            ArgumentCaptor<NoContentResponse> arg4 = ArgumentCaptor
414                .forClass(NoContentResponse.class);
415            Mockito.verify(handler).addReference(arg1.capture(), arg2.capture(), arg3.capture(),
416                arg4.capture());
417
418            DataRequest request = arg1.getValue();
419            assertEquals("application/json;odata.metadata=minimal", request
420                .getResponseContentType().toContentTypeString());
421          }
422        });
423  }
424
425  @Test
426  public void testWriteReference() throws Exception {
427    String payload = "{\n" + "\"@odata.id\": \"/Photos(11)\"\n" + "}";
428
429    final ServiceHandler handler = Mockito.mock(ServiceHandler.class);
430    helpTest(handler, "trippin/People('russelwhyte')/Friends('someone')/Photo/$ref", "PUT", payload,
431        new TestResult() {
432          @Override
433          public void validate() throws Exception {
434            ArgumentCaptor<DataRequest> arg1 = ArgumentCaptor.forClass(DataRequest.class);
435            ArgumentCaptor<String> arg2 = ArgumentCaptor.forClass(String.class);
436            ArgumentCaptor<URI> arg3 = ArgumentCaptor.forClass(URI.class);
437            ArgumentCaptor<NoContentResponse> arg4 = ArgumentCaptor
438                .forClass(NoContentResponse.class);
439            Mockito.verify(handler).updateReference(arg1.capture(), arg2.capture(), arg3.capture(),
440                arg4.capture());
441
442            DataRequest request = arg1.getValue();
443            assertEquals("application/json;odata.metadata=minimal", request
444                .getResponseContentType().toContentTypeString());
445          }
446        });
447  }
448  
449  @Test
450  public void test$id() throws Exception {
451    final ServiceHandler handler = Mockito.mock(ServiceHandler.class);
452    helpGETTest(handler, "trippin/$entity?$id="+Encoder.encode("http://localhost:" + TOMCAT_PORT
453        + "/trippin/People('russelwhyte')")+"&"+Encoder.encode("$")+"select=FirstName", new TestResult() {
454      @Override
455      public void validate() throws Exception {
456        ArgumentCaptor<DataRequest> arg1 = ArgumentCaptor.forClass(DataRequest.class);
457        ArgumentCaptor<EntityResponse> arg2 = ArgumentCaptor.forClass(EntityResponse.class);
458        Mockito.verify(handler).read(arg1.capture(), arg2.capture());
459
460        DataRequest request = arg1.getValue();
461        assertEquals("application/json;odata.metadata=minimal", request.getResponseContentType()
462            .toContentTypeString());
463      }
464    });
465  }  
466}
467
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

Most used method in ArgumentCaptor

Trigger code on LambdaTest Cloud Grid

Execute automation tests with on a cloud-based Grid of 3000+ real browsers and operating systems for both web and mobile applications.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)