org.powermock.api.support.membermodification.MemberMatcher Java Examples
The following examples show how to use
org.powermock.api.support.membermodification.MemberMatcher.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: OvsdbBridgeUpdateCommandTest.java From ovsdb with Eclipse Public License 1.0 | 6 votes |
@Test public void testExecute() throws Exception { updatedBridgeRows.put(mock(UUID.class), mock(Bridge.class)); OvsdbConnectionInstance ovsdbConnectionInstance = mock(OvsdbConnectionInstance.class); when(ovsdbBridgeUpdateCommand.getOvsdbConnectionInstance()).thenReturn(ovsdbConnectionInstance); InstanceIdentifier<Node> connectionIId = mock(InstanceIdentifier.class); when(ovsdbConnectionInstance.getInstanceIdentifier()).thenReturn(connectionIId); Optional<Node> connection = Optional.of(mock(Node.class)); PowerMockito.mockStatic(SouthboundUtil.class); when(SouthboundUtil.readNode(any(ReadWriteTransaction.class), any(InstanceIdentifier.class))) .thenReturn(connection); ReadWriteTransaction transaction = mock(ReadWriteTransaction.class); MemberModifier.suppress(MemberMatcher.method(OvsdbBridgeUpdateCommand.class, "updateBridge", ReadWriteTransaction.class, Bridge.class, InstanceIdentifier.class)); ovsdbBridgeUpdateCommand.execute(transaction); verify(ovsdbBridgeUpdateCommand).updateBridge(any(ReadWriteTransaction.class), any(Bridge.class), any(InstanceIdentifier.class)); }
Example #2
Source File: OvsdbBridgeRemovedCommandTest.java From ovsdb with Eclipse Public License 1.0 | 6 votes |
@Test public void testExecute() throws Exception { //suppress calls to parent get methods MemberModifier.suppress(MemberMatcher.method(OvsdbBridgeRemovedCommand.class, "getUpdates")); when(ovsdbBridgeRemovedCommand.getUpdates()).thenReturn(mock(TableUpdates.class)); MemberModifier.suppress(MemberMatcher.method(OvsdbBridgeRemovedCommand.class, "getDbSchema")); when(ovsdbBridgeRemovedCommand.getDbSchema()).thenReturn(mock(DatabaseSchema.class)); PowerMockito.mockStatic(TyperUtils.class); Map<UUID, Bridge> map = new HashMap<>(); when(TyperUtils.extractRowsRemoved(eq(Bridge.class), any(TableUpdates.class), any(DatabaseSchema.class))) .thenReturn(map); ReadWriteTransaction transaction = mock(ReadWriteTransaction.class); ovsdbBridgeRemovedCommand.execute(transaction); verify(ovsdbBridgeRemovedCommand).getUpdates(); verify(ovsdbBridgeRemovedCommand).getDbSchema(); }
Example #3
Source File: OvsdbControllerUpdateCommandTest.java From ovsdb with Eclipse Public License 1.0 | 6 votes |
@Test public void testExecute() throws Exception { Map<UUID, Controller> updatedControllerRows = new HashMap<>(); updatedControllerRows.put(mock(UUID.class), mock(Controller.class)); MemberModifier.field(OvsdbControllerUpdateCommand.class, "updatedControllerRows") .set(ovsdbControllerUpdateCommand, updatedControllerRows); MemberModifier.suppress(MemberMatcher.method(OvsdbControllerUpdateCommand.class, "updateController", ReadWriteTransaction.class, Map.class, Map.class)); MemberModifier.suppress(MemberMatcher.method(OvsdbControllerUpdateCommand.class, "updateController", ReadWriteTransaction.class, Map.class)); // updatedBridgeRows null case ReadWriteTransaction transaction = mock(ReadWriteTransaction.class); ovsdbControllerUpdateCommand.execute(transaction); verify(ovsdbControllerUpdateCommand).updateController(any(ReadWriteTransaction.class), any(Map.class)); // updatedBridgeRows not null case Map<UUID, Bridge> updatedBridgeRows = new HashMap<>(); updatedBridgeRows.put(mock(UUID.class), mock(Bridge.class)); MemberModifier.field(OvsdbControllerUpdateCommand.class, "updatedBridgeRows").set(ovsdbControllerUpdateCommand, updatedBridgeRows); }
Example #4
Source File: TestTableOrderProvider.java From datacollector with Apache License 2.0 | 6 votes |
@Before public void setup() throws Exception { PowerMockito.replace( MemberMatcher.method( JdbcUtil.class, "getReferredTables", Connection.class, String.class, String.class ) ).with((proxy, method, args) -> new HashSet<>(referredTablesTestRelation.getReferredTableMap().get((String)args[2]))); tableOrderProvider = new TableOrderProviderFactory(PowerMockito.mock(Connection.class), tableOrderStrategy).create(); for (String table : referredTablesTestRelation.getTableListingOrder()) { final TableContext tableContext = getTableContext(table); tableContextsMap.put(table, tableContext); } }
Example #5
Source File: OvsdbConnectionManagerTest.java From ovsdb with Eclipse Public License 1.0 | 6 votes |
@Test public void testDisconnect() throws Exception { OvsdbNodeAugmentation ovsdbNode = mock(OvsdbNodeAugmentation.class); ConnectionInfo connectionInfo = mock(ConnectionInfo.class); when(ovsdbNode.getConnectionInfo()).thenReturn(connectionInfo); suppress(MemberMatcher.method(OvsdbConnectionManager.class, "getConnectionInstance", ConnectionInfo.class)); OvsdbConnectionInstance ovsdbConnectionInstance = mock(OvsdbConnectionInstance.class); when(ovsdbConnManager.getConnectionInstance(any(ConnectionInfo.class))).thenReturn(ovsdbConnectionInstance); when(ovsdbConnectionInstance.getInstanceIdentifier()).thenReturn(mock(InstanceIdentifier.class)); suppress(MemberMatcher.method(OvsdbConnectionManager.class, "removeInstanceIdentifier", ConnectionInfo.class)); // TODO: Write unit tests for entity ownership service related code. suppress(MemberMatcher.method(OvsdbConnectionManager.class, "unregisterEntityForOwnership", OvsdbConnectionInstance.class)); ovsdbConnManager.disconnect(ovsdbNode); verify(ovsdbConnectionInstance).disconnect(); }
Example #6
Source File: OvsdbConnectionManagerTest.java From ovsdb with Eclipse Public License 1.0 | 6 votes |
@SuppressWarnings("unchecked") @Test public void testConnectedButCallBacksNotRegistered() throws Exception { ConnectionInfo key = mock(ConnectionInfo.class); PowerMockito.mockStatic(SouthboundMapper.class); when(SouthboundMapper.createConnectionInfo(any(OvsdbClient.class))).thenReturn(key); suppress(MemberMatcher.method(OvsdbConnectionManager.class, "getInstanceIdentifier", ConnectionInfo.class)); when(ovsdbConnManager.getInstanceIdentifier(key)).thenReturn(mock(InstanceIdentifier.class)); suppress(MemberMatcher.method(OvsdbConnectionManager.class, "getConnectionInstance", ConnectionInfo.class)); when(ovsdbConnManager.getConnectionInstance(key)).thenReturn(null); OvsdbConnectionInstance client = mock(OvsdbConnectionInstance.class); suppress(MemberMatcher.method(OvsdbConnectionManager.class, "putConnectionInstance", ConnectionInfo.class, OvsdbConnectionInstance.class)); doNothing().when(client).createTransactInvokers(); PowerMockito.whenNew(OvsdbConnectionInstance.class).withArguments(any(ConnectionInfo.class), any(OvsdbClient.class), any(TransactionInvoker.class), any(InstanceIdentifier.class)) .thenReturn(client); assertEquals("Error, did not receive correct OvsdbConnectionInstance object", client, ovsdbConnManager.connectedButCallBacksNotRegistered(externalClient)); }
Example #7
Source File: OvsdbConnectionManagerTest.java From ovsdb with Eclipse Public License 1.0 | 6 votes |
@Test public void testConnected() throws Exception { OvsdbConnectionInstance client = mock(OvsdbConnectionInstance.class); suppress(MemberMatcher.method(OvsdbConnectionManager.class, "connectedButCallBacksNotRegistered", OvsdbClient.class)); when(ovsdbConnManager.connectedButCallBacksNotRegistered(any(OvsdbClient.class))).thenReturn(client); doNothing().when(client).registerCallbacks(any()); //TODO: Write unit tests for EntityOwnershipService when(client.getInstanceIdentifier()).thenReturn(mock(InstanceIdentifier.class)); field(OvsdbConnectionManager.class, "entityConnectionMap").set(ovsdbConnManager, entityConnectionMap); suppress(MemberMatcher.method(OvsdbConnectionManager.class, "getEntityFromConnectionInstance", OvsdbConnectionInstance.class)); //TODO: Write unit tests for entity ownership service related code. suppress(MemberMatcher.method(OvsdbConnectionManager.class, "registerEntityForOwnership", OvsdbConnectionInstance.class)); ReadTransaction tx = mock(ReadTransaction.class); when(db.newReadOnlyTransaction()).thenReturn(tx); when(tx.read(any(LogicalDatastoreType.class), any(InstanceIdentifier.class))) .thenReturn(mock(FluentFuture.class)); when(client.getInstanceIdentifier()).thenReturn(mock(InstanceIdentifier.class)); ovsdbConnManager.connected(externalClient); }
Example #8
Source File: TargetFinderTest.java From recheck with GNU Affero General Public License v3.0 | 5 votes |
@Before public void setUp() throws Exception { final Field field = MemberMatcher.field( TargetFinder.class, "logger" ); field.set( TargetFinder.class, targetFinderLogger ); when( action.getTargetElement() ).thenReturn( element ); when( window.getBestMatch( any( IdentifyingAttributes.class ) ) ).thenReturn( component ); when( window.getTextWithComponents() ).thenReturn( "text with components" ); }
Example #9
Source File: OvsdbBridgeUpdateCommandTest.java From ovsdb with Eclipse Public License 1.0 | 5 votes |
@SuppressWarnings("unchecked") @Test public void testUpdateBridge() throws Exception { MemberModifier .suppress(MemberMatcher.method(OvsdbBridgeUpdateCommand.class, "buildConnectionNode", Bridge.class)); ReadWriteTransaction transaction = mock(ReadWriteTransaction.class); doNothing().when(transaction).merge(any(LogicalDatastoreType.class), any(InstanceIdentifier.class), any(Node.class)); // suppress calls to private methods MemberModifier .suppress(MemberMatcher.method(OvsdbBridgeUpdateCommand.class, "getInstanceIdentifier", Bridge.class)); MemberModifier.suppress(MemberMatcher.method(OvsdbBridgeUpdateCommand.class, "buildBridgeNode", Bridge.class)); MemberModifier.suppress(MemberMatcher.method(OvsdbBridgeUpdateCommand.class, "deleteEntries", ReadWriteTransaction.class, List.class)); MemberModifier.suppress(MemberMatcher.method(OvsdbBridgeUpdateCommand.class, "protocolEntriesToRemove", InstanceIdentifier.class, Bridge.class)); MemberModifier.suppress(MemberMatcher.method(OvsdbBridgeUpdateCommand.class, "externalIdsToRemove", InstanceIdentifier.class, Bridge.class)); MemberModifier.suppress(MemberMatcher.method(OvsdbBridgeUpdateCommand.class, "bridgeOtherConfigsToRemove", InstanceIdentifier.class, Bridge.class)); MemberModifier.suppress(MemberMatcher.method(OvsdbBridgeUpdateCommand.class, "getNodeId", Bridge.class)); Bridge bridge = mock(Bridge.class); InstanceIdentifier<Node> connectionIId = mock(InstanceIdentifier.class); Whitebox.invokeMethod(ovsdbBridgeUpdateCommand, "updateBridge", transaction, bridge, connectionIId); verify(ovsdbBridgeUpdateCommand, times(3)).deleteEntries(any(ReadWriteTransaction.class), eq(null)); }
Example #10
Source File: OvsdbConnectionManagerTest.java From ovsdb with Eclipse Public License 1.0 | 5 votes |
@Test public void testGetClient() { OvsdbConnectionInstance ovsdbClient = mock(OvsdbConnectionInstance.class); OvsdbClient client = mock(OvsdbClient.class); when(ovsdbClient.getOvsdbClient()).thenReturn(client); //Test getClient(ConnectionInfo connectionInfo) ConnectionInfo key = mock(ConnectionInfo.class); suppress(MemberMatcher.method(OvsdbConnectionManager.class, "getConnectionInstance", ConnectionInfo.class)); when(ovsdbConnManager.getConnectionInstance(key)).thenReturn(ovsdbClient); assertEquals("Error getting correct OvsdbClient object", ovsdbClient.getOvsdbClient(), ovsdbConnManager.getClient(key)); //Test getClient(OvsdbBridgeAttributes mn) OvsdbBridgeAttributes mn = mock(OvsdbBridgeAttributes.class); suppress(MemberMatcher.method(OvsdbConnectionManager.class, "getConnectionInstance", OvsdbBridgeAttributes.class)); when(ovsdbConnManager.getConnectionInstance(mn)).thenReturn(ovsdbClient); assertEquals("Error getting correct OvsdbClient object", ovsdbClient.getOvsdbClient(), ovsdbConnManager.getClient(mn)); //Test getClient(Node node) Node node = mock(Node.class); suppress(MemberMatcher.method(OvsdbConnectionManager.class, "getConnectionInstance", Node.class)); when(ovsdbConnManager.getConnectionInstance(node)).thenReturn(ovsdbClient); assertEquals("Error getting correct OvsdbClient object", ovsdbClient.getOvsdbClient(), ovsdbConnManager.getClient(node)); }
Example #11
Source File: OvsdbConnectionManagerTest.java From ovsdb with Eclipse Public License 1.0 | 5 votes |
@Test @Ignore public void testInit() { mock(ConnectionInfo.class); suppress(MemberMatcher.method(OvsdbConnectionManager.class, "getConnectionInstance", ConnectionInfo.class)); OvsdbConnectionInstance ovsdbConnectionInstance = mock(OvsdbConnectionInstance.class); when(ovsdbConnManager.getConnectionInstance(any(ConnectionInfo.class))).thenReturn(ovsdbConnectionInstance); // client not null // ovsdbConnectionManager.init(key); verify(ovsdbConnectionInstance).registerCallbacks(any()); }
Example #12
Source File: OvsdbConnectionManagerTest.java From ovsdb with Eclipse Public License 1.0 | 5 votes |
@Test public void testDisconnected() throws Exception { ConnectionInfo key = mock(ConnectionInfo.class); PowerMockito.mockStatic(SouthboundMapper.class); when(SouthboundMapper.createConnectionInfo(any(OvsdbClient.class))).thenReturn(key); OvsdbConnectionInstance ovsdbConnectionInstance = mock(OvsdbConnectionInstance.class); clients = new ConcurrentHashMap<>(); clients.put(key, ovsdbConnectionInstance); MemberModifier.field(OvsdbConnectionManager.class, "clients").set(ovsdbConnManager, clients); suppress(MemberMatcher.method(OvsdbConnectionManager.class, "getConnectionInstance", ConnectionInfo.class)); when(ovsdbConnManager.getConnectionInstance(any(ConnectionInfo.class))).thenReturn(ovsdbConnectionInstance); doNothing().when(txInvoker).invoke(any(TransactionCommand.class)); when(SouthboundMapper.suppressLocalIpPort(any(ConnectionInfo.class))).thenReturn(key); // TODO: Write unit tests for EntityOwnershipService suppress(MemberMatcher.method(OvsdbConnectionManager.class, "unregisterEntityForOwnership", OvsdbConnectionInstance.class)); instanceIdentifiers = new ConcurrentHashMap<>(); field(OvsdbConnectionManager.class, "instanceIdentifiers").set(ovsdbConnManager, instanceIdentifiers); field(OvsdbConnectionManager.class, "nodeIdVsConnectionInstance").set(ovsdbConnManager, new HashMap<>()); MemberModifier.suppress(MemberMatcher.method(OvsdbConnectionManager.class, "reconcileConnection", InstanceIdentifier.class, OvsdbNodeAugmentation.class)); ReadTransaction tx = mock(ReadTransaction.class); when(db.newReadOnlyTransaction()).thenReturn(tx); when(tx.read(any(LogicalDatastoreType.class), any(InstanceIdentifier.class))) .thenReturn(mock(FluentFuture.class)); when(tx.exists(any(LogicalDatastoreType.class), any(InstanceIdentifier.class))) .thenReturn(mock(FluentFuture.class)); when(ovsdbConnectionInstance.getInstanceIdentifier()).thenReturn(mock(InstanceIdentifier.class)); ovsdbConnManager.disconnected(externalClient); Map<ConnectionInfo, OvsdbConnectionInstance> testClients = Whitebox.getInternalState(ovsdbConnManager, "clients"); assertEquals("Error, size of the hashmap is incorrect", 0, testClients.size()); }
Example #13
Source File: TerminationPointUpdateCommandTest.java From ovsdb with Eclipse Public License 1.0 | 5 votes |
@SuppressWarnings("unchecked") @Test public void testExecute() { Map<InstanceIdentifier<OvsdbTerminationPointAugmentation>, OvsdbTerminationPointAugmentation> created = new HashMap<>(); created.put(mock(InstanceIdentifier.class), mock(OvsdbTerminationPointAugmentation.class)); PowerMockito.mockStatic(TransactUtils.class); PowerMockito.when(TransactUtils.extractCreated(any(DataChangeEvent.class), eq(OvsdbTerminationPointAugmentation.class))).thenReturn(created); MemberModifier.suppress(MemberMatcher.method(TerminationPointUpdateCommand.class, "updateTerminationPoint", TransactionBuilder.class, BridgeOperationalState.class, InstanceIdentifier.class, OvsdbTerminationPointAugmentation.class, InstanceIdentifierCodec.class)); doNothing().when(terminationPointUpdateCommand).updateTerminationPoint(any(TransactionBuilder.class), any(BridgeOperationalState.class), any(InstanceIdentifier.class), any(OvsdbTerminationPointAugmentation.class), any(InstanceIdentifierCodec.class)); Map<InstanceIdentifier<OvsdbTerminationPointAugmentation>, OvsdbTerminationPointAugmentation> updated = new HashMap<>(); updated.put(mock(InstanceIdentifier.class), mock(OvsdbTerminationPointAugmentation.class)); PowerMockito.when(TransactUtils.extractUpdated(any(DataChangeEvent.class), eq(OvsdbTerminationPointAugmentation.class))).thenReturn(updated); TransactionBuilder transactionBuilder = mock(TransactionBuilder.class); terminationPointUpdateCommand.execute(transactionBuilder, mock(BridgeOperationalState.class), mock(DataChangeEvent.class), mock(InstanceIdentifierCodec.class)); // TODO Verify something useful }
Example #14
Source File: ProtocolRemovedCommandTest.java From ovsdb with Eclipse Public License 1.0 | 5 votes |
@SuppressWarnings("unchecked") @Test @Ignore("This needs to be rewritten") public void testExecute() throws Exception { PowerMockito.suppress(MemberMatcher.methodsDeclaredIn(InstanceIdentifier.class)); ProtocolEntry protocol = mock(ProtocolEntry.class); when(protocol.getProtocol()).thenAnswer( (Answer<Class<? extends OvsdbBridgeProtocolBase>>) invocation -> OvsdbBridgeProtocolOpenflow10.class); BridgeOperationalState bridgeOpState = mock(BridgeOperationalState.class); when(bridgeOpState.getProtocolEntry(any(InstanceIdentifier.class))).thenReturn(Optional.of(protocol)); InstanceIdentifier<ProtocolEntry> protocolIid = mock(InstanceIdentifier.class); removed.add(protocolIid); ProtocolRemovedCommand protocolRemovedCommand = mock(ProtocolRemovedCommand.class, Mockito.CALLS_REAL_METHODS); MemberModifier.field(ProtocolRemovedCommand.class,"removed").set(protocolRemovedCommand, removed); MemberModifier.field(ProtocolRemovedCommand.class,"updatedBridges").set(protocolRemovedCommand, updatedBridges); when(updatedBridges.get(any(InstanceIdentifier.class))).thenReturn(mock(OvsdbBridgeAugmentation.class)); Operations op = (Operations) setField("op"); Mutate<GenericTableSchema> mutate = mock(Mutate.class); when(op.mutate(any(Bridge.class))).thenReturn(mutate); Column<GenericTableSchema, Set<String>> column = mock(Column.class); Bridge bridge = mock(Bridge.class); when(bridge.getProtocolsColumn()).thenReturn(column); when(column.getSchema()).thenReturn(mock(ColumnSchema.class)); when(column.getData()).thenReturn(new HashSet<>()); when(mutate.addMutation(any(ColumnSchema.class), any(Mutator.class), any(Set.class))).thenReturn(mutate); TransactionBuilder transaction = mock(TransactionBuilder.class); when(transaction.getTypedRowWrapper(any(Class.class))).thenReturn(bridge); protocolRemovedCommand.execute(transaction, bridgeOpState, mock(DataChangeEvent.class), mock(InstanceIdentifierCodec.class)); Mockito.verify(transaction).add(any(Operation.class)); }
Example #15
Source File: UtilsTest.java From BetonQuest with GNU General Public License v3.0 | 5 votes |
@Before public void setUp() { PowerMockito.mockStatic(BetonQuest.class); BetonQuest betonQuestInstance = Mockito.mock(BetonQuest.class); PowerMockito.suppress(MemberMatcher.methodsDeclaredIn(JavaPlugin.class)); PowerMockito.when(BetonQuest.getInstance()).thenReturn(betonQuestInstance); PowerMockito.mockStatic(LogUtils.class); PowerMockito.when(LogUtils.getLogger()).thenReturn(Logger.getGlobal()); PowerMockito.mockStatic(Config.class); PowerMockito.when(Config.getString("config.journal.lines_per_page")).thenReturn("13"); PowerMockito.when(Config.getString("config.journal.chars_per_line")).thenReturn("19"); }
Example #16
Source File: AbstractActionImpl_execute_Test.java From recheck with GNU Affero General Public License v3.0 | 5 votes |
@Before public void setUp() throws Exception { when( element.getIdentifyingAttributes() ).thenReturn( actionIdentAttributes ); final Field field = MemberMatcher.field( AbstractAction.class, "logger" ); field.set( AbstractAction.class, actionLogger ); }
Example #17
Source File: TestHiveMetadataProcessor.java From datacollector with Apache License 2.0 | 5 votes |
@Before public void setup() throws Exception { // do not resolve JDBC URL PowerMockito.spy(HiveMetastoreUtil.class); // do not run Hive queries PowerMockito.suppress( MemberMatcher.method( HMSCache.class, "getOrLoad", HMSCacheType.class, String.class, HiveQueryExecutor.class ) ); // Do not create issues PowerMockito.suppress( MemberMatcher.method( HiveConfigBean.class, "init", Stage.Context.class, String.class, List.class ) ); PowerMockito.replace( MemberMatcher.method( HiveConfigBean.class, "getHiveConnection" ) ).with((proxy, method, args) -> null); PowerMockito.replace(MemberMatcher.method(HiveQueryExecutor.class, "executeDescribeDatabase")) .with((proxy, method, args) -> "/user/hive/warehouse/" + args[0].toString() + ".db/"); }
Example #18
Source File: TestHDFSTargetWholeFile.java From datacollector with Apache License 2.0 | 5 votes |
@Test public void testWholeFilePartialCopy() throws Exception { testPartialOrFailedWrites( MemberMatcher.method(RecordWriterManager.class, "commitWriter", RecordWriter.class), (proxy, method, args) -> { //Close the recordWriter so contents are written. RecordWriter recordWriter = (RecordWriter) args[0]; recordWriter.close(); //Make it no op so that the _tmp_ file is left behind return null; }, false ); }
Example #19
Source File: TestHDFSTargetWholeFile.java From datacollector with Apache License 2.0 | 5 votes |
@Test public void testWholeFileWriteFailed() throws Exception { testPartialOrFailedWrites( MemberMatcher.method(RecordWriter.class, "write", Record.class), (proxy, method, args) -> { //Fail the write by throwing an IOException throw new IOException("Write Failed"); }, true ); }
Example #20
Source File: OvsdbBridgeUpdateCommandTest.java From ovsdb with Eclipse Public License 1.0 | 4 votes |
@Test public void testBuildBridgeNode() throws Exception { NodeBuilder bridgeNodeBuilder = mock(NodeBuilder.class); PowerMockito.whenNew(NodeBuilder.class).withNoArguments().thenReturn(bridgeNodeBuilder); //suppress call to getNodeId() MemberModifier.suppress(MemberMatcher.method(OvsdbBridgeUpdateCommand.class, "getNodeId", Bridge.class)); when(bridgeNodeBuilder.setNodeId(any(NodeId.class))).thenReturn(bridgeNodeBuilder); OvsdbBridgeAugmentationBuilder ovsdbBridgeAugmentationBuilder = mock(OvsdbBridgeAugmentationBuilder.class); PowerMockito.whenNew(OvsdbBridgeAugmentationBuilder.class).withNoArguments() .thenReturn(ovsdbBridgeAugmentationBuilder); Bridge bridge = mock(Bridge.class); when(bridge.getName()).thenReturn("bridge name"); PowerMockito.whenNew(OvsdbBridgeName.class).withAnyArguments().thenReturn(mock(OvsdbBridgeName.class)); when(ovsdbBridgeAugmentationBuilder.setBridgeName(any(OvsdbBridgeName.class))) .thenReturn(ovsdbBridgeAugmentationBuilder); when(bridge.getUuid()).thenReturn(mock(UUID.class)); PowerMockito.whenNew(Uuid.class).withAnyArguments().thenReturn(mock(Uuid.class)); when(ovsdbBridgeAugmentationBuilder.setBridgeUuid(any(Uuid.class))).thenReturn(ovsdbBridgeAugmentationBuilder); //suppress calls to the set methods MemberModifier.suppress(MemberMatcher.method(OvsdbBridgeUpdateCommand.class, "setDataPath", OvsdbBridgeAugmentationBuilder.class, Bridge.class)); MemberModifier.suppress(MemberMatcher.method(OvsdbBridgeUpdateCommand.class, "setDataPathType", OvsdbBridgeAugmentationBuilder.class, Bridge.class)); MemberModifier.suppress(MemberMatcher.method(OvsdbBridgeUpdateCommand.class, "setProtocol", OvsdbBridgeAugmentationBuilder.class, Bridge.class)); MemberModifier.suppress(MemberMatcher.method(OvsdbBridgeUpdateCommand.class, "setExternalIds", OvsdbBridgeAugmentationBuilder.class, Bridge.class)); MemberModifier.suppress(MemberMatcher.method(OvsdbBridgeUpdateCommand.class, "setOtherConfig", OvsdbBridgeAugmentationBuilder.class, Bridge.class)); MemberModifier.suppress(MemberMatcher.method(OvsdbBridgeUpdateCommand.class, "setFailMode", OvsdbBridgeAugmentationBuilder.class, Bridge.class)); MemberModifier.suppress(MemberMatcher.method(OvsdbBridgeUpdateCommand.class, "setOpenFlowNodeRef", OvsdbBridgeAugmentationBuilder.class, Bridge.class)); MemberModifier.suppress(MemberMatcher.method(OvsdbBridgeUpdateCommand.class, "setManagedBy", OvsdbBridgeAugmentationBuilder.class)); when(ovsdbBridgeAugmentationBuilder.build()).thenReturn(mock(OvsdbBridgeAugmentation.class)); when(bridgeNodeBuilder.addAugmentation(eq(OvsdbBridgeAugmentation.class), any(OvsdbBridgeAugmentation.class))) .thenReturn(bridgeNodeBuilder); Node node = mock(Node.class); when(bridgeNodeBuilder.build()).thenReturn(node); assertEquals(node, Whitebox.invokeMethod(ovsdbBridgeUpdateCommand, "buildBridgeNode", bridge)); }
Example #21
Source File: OvsdbNodeUpdateCommandTest.java From ovsdb with Eclipse Public License 1.0 | 4 votes |
@SuppressWarnings("unchecked") @Test public void testExecute() throws Exception { Map<InstanceIdentifier<OvsdbNodeAugmentation>, OvsdbNodeAugmentation> updated = new HashMap<>(); InstanceIdentifier<OvsdbNodeAugmentation> iid = mock(InstanceIdentifier.class); OvsdbNodeAugmentation ovsdbNode = mock(OvsdbNodeAugmentation.class); updated.put(iid, ovsdbNode); PowerMockito.mockStatic(TransactUtils.class); PowerMockito.when( TransactUtils.extractCreatedOrUpdated(any(DataChangeEvent.class), eq(OvsdbNodeAugmentation.class))) .thenReturn(updated); ConnectionInfo connectionInfo = mock(ConnectionInfo.class); when(ovsdbNode.getConnectionInfo()).thenReturn(connectionInfo); when(connectionInfo.getRemoteIp()).thenReturn(mock(IpAddress.class)); when(connectionInfo.getRemotePort()).thenReturn(mock(PortNumber.class)); OpenVSwitch ovs = mock(OpenVSwitch.class); TransactionBuilder transaction = mock(TransactionBuilder.class); when(transaction.getTypedRowWrapper(eq(OpenVSwitch.class))).thenReturn(ovs); OpenvswitchExternalIds externalId = new OpenvswitchExternalIdsBuilder() .setExternalIdKey(EXTERNAL_ID_KEY) .setExternalIdValue(EXTERNAL_ID_VALUE) .build(); when(ovsdbNode.getOpenvswitchExternalIds()).thenReturn(Map.of(externalId.key(), externalId)); PowerMockito.suppress(MemberMatcher.method(OvsdbNodeUpdateCommand.class, "stampInstanceIdentifier", TransactionBuilder.class, InstanceIdentifier.class, InstanceIdentifierCodec.class)); PowerMockito.suppress(MemberMatcher.methodsDeclaredIn(InstanceIdentifier.class)); doNothing().when(ovs).setExternalIds(any(ImmutableMap.class)); Mutate<GenericTableSchema> mutate = mock(Mutate.class); Operations op = setOpField(); Column<GenericTableSchema, Map<String, String>> column = mock(Column.class); when(ovs.getExternalIdsColumn()).thenReturn(column); when(column.getSchema()).thenReturn(mock(ColumnSchema.class)); when(column.getData()).thenReturn(new HashMap<>()); when(op.mutate(any(OpenVSwitch.class))).thenReturn(mutate); when(transaction.add(any(Operation.class))).thenReturn(transaction); OpenvswitchOtherConfigs otherConfig = new OpenvswitchOtherConfigsBuilder() .setOtherConfigKey(OTHER_CONFIG_KEY) .setOtherConfigValue(OTHER_CONFIG_VALUE) .build(); when(ovsdbNode.getOpenvswitchOtherConfigs()).thenReturn(Map.of(otherConfig.key(), otherConfig)); doNothing().when(ovs).setOtherConfig(any(ImmutableMap.class)); when(ovs.getOtherConfigColumn()).thenReturn(column); ovsdbNodeUpdateCommand.execute(transaction, mock(BridgeOperationalState.class), changes, mock(InstanceIdentifierCodec.class)); verify(ovs, times(2)).getExternalIdsColumn(); verify(transaction, times(2)).add(eq(null)); }
Example #22
Source File: DatadogHttpClientTest.java From flink with Apache License 2.0 | 4 votes |
@Before public void suppressValidateApiKey() { PowerMockito.suppress(MemberMatcher.method(DatadogHttpClient.class, "validateApiKey")); }
Example #23
Source File: OvsdbPortUpdateCommandTest.java From ovsdb with Eclipse Public License 1.0 | 4 votes |
@Test @SuppressWarnings("unchecked") public void testUpdateTerminationPoints() throws Exception { portUpdatedRows = new HashMap<>(); Port port = mock(Port.class); UUID uuid = mock(UUID.class); portUpdatedRows.put(uuid, port); field(OvsdbPortUpdateCommand.class, "portUpdatedRows").set(ovsdbPortUpdateCommand, portUpdatedRows); Column<GenericTableSchema, String> bridgeColumn = mock(Column.class); when(port.getNameColumn()).thenReturn(bridgeColumn); when(bridgeColumn.getData()).thenReturn(TERMINATION_POINT_NAME); InstanceIdentifier<Node> nodeIid = InstanceIdentifier.create(NetworkTopology.class) .child(Topology.class, new TopologyKey(SouthboundConstants.OVSDB_TOPOLOGY_ID)) .child(Node.class, new NodeKey(new NodeId("nodeId"))); Optional<InstanceIdentifier<Node>> bridgeIid = Optional.of(nodeIid); PowerMockito.doReturn(bridgeIid).when(ovsdbPortUpdateCommand, "getTerminationPointBridge", any(UUID.class)); NodeId bridgeId = mock(NodeId.class); PowerMockito.mockStatic(SouthboundMapper.class); PowerMockito.when(SouthboundMapper.createManagedNodeId(any(InstanceIdentifier.class))).thenReturn(bridgeId); PowerMockito.whenNew(TpId.class).withAnyArguments().thenReturn(mock(TpId.class)); TerminationPointKey tpKey = mock(TerminationPointKey.class); PowerMockito.whenNew(TerminationPointKey.class).withAnyArguments().thenReturn(tpKey); TerminationPointBuilder tpBuilder = mock(TerminationPointBuilder.class); PowerMockito.whenNew(TerminationPointBuilder.class).withNoArguments().thenReturn(tpBuilder); when(tpBuilder.withKey(any(TerminationPointKey.class))).thenReturn(tpBuilder); when(tpKey.getTpId()).thenReturn(mock(TpId.class)); when(tpBuilder.setTpId(any(TpId.class))).thenReturn(tpBuilder); InstanceIdentifier<TerminationPoint> tpPath = mock(InstanceIdentifier.class); PowerMockito.doReturn(tpPath).when(ovsdbPortUpdateCommand, "getInstanceIdentifier", any(InstanceIdentifier.class), any(Port.class)); OvsdbTerminationPointAugmentationBuilder tpAugmentationBuilder = mock( OvsdbTerminationPointAugmentationBuilder.class); PowerMockito.whenNew(OvsdbTerminationPointAugmentationBuilder.class).withNoArguments() .thenReturn(tpAugmentationBuilder); PowerMockito.suppress(MemberMatcher.method(OvsdbPortUpdateCommand.class, "buildTerminationPoint", ReadWriteTransaction.class, InstanceIdentifier.class, OvsdbTerminationPointAugmentationBuilder.class, Node.class, Entry.class)); Column<GenericTableSchema, Set<UUID>> interfacesColumn = mock(Column.class); when(port.getInterfacesColumn()).thenReturn(interfacesColumn); Set<UUID> uuids = new HashSet<>(); UUID uuid2 = mock(UUID.class); uuids.add(uuid2); when(interfacesColumn.getData()).thenReturn(uuids); ifUpdatedRows = new HashMap<>(); interfaceOldRows = new HashMap<>(); Interface iface = mock(Interface.class); ifUpdatedRows.put(uuid2, iface); Interface interfaceUpdate = mock(Interface.class); ifUpdatedRows.put(uuid, interfaceUpdate); interfaceOldRows.put(uuid2, iface); field(OvsdbPortUpdateCommand.class, "interfaceUpdatedRows").set(ovsdbPortUpdateCommand, ifUpdatedRows); field(OvsdbPortUpdateCommand.class, "interfaceOldRows").set(ovsdbPortUpdateCommand, interfaceOldRows); PowerMockito.suppress(MemberMatcher.method(OvsdbPortUpdateCommand.class, "buildTerminationPoint", OvsdbTerminationPointAugmentationBuilder.class, Interface.class)); when(tpAugmentationBuilder.build()).thenReturn(mock(OvsdbTerminationPointAugmentation.class)); when(tpBuilder.addAugmentation(eq(OvsdbTerminationPointAugmentation.class), any(OvsdbTerminationPointAugmentation.class))).thenReturn(tpBuilder); when(tpBuilder.build()).thenReturn(mock(TerminationPoint.class)); portOldRows = new HashMap<>(); portOldRows.put(uuid, port); MemberModifier.field(OvsdbPortUpdateCommand.class, "portOldRows").set(ovsdbPortUpdateCommand, portOldRows); ReadWriteTransaction transaction = mock(ReadWriteTransaction.class); doNothing().when(transaction).merge(any(LogicalDatastoreType.class), any(InstanceIdentifier.class), any(TerminationPoint.class)); doNothing().when(transaction).put(any(LogicalDatastoreType.class), any(InstanceIdentifier.class), any(TerminationPoint.class)); Column<GenericTableSchema, String> interfaceColumn = mock(Column.class); when(interfaceUpdate.getNameColumn()).thenReturn(interfaceColumn); when(interfaceColumn.getData()).thenReturn(INTERFACE_NAME); when(ovsdbPortUpdateCommand.getOvsdbConnectionInstance()).thenReturn(mock(OvsdbConnectionInstance.class)); PowerMockito.doReturn(bridgeIid).when(ovsdbPortUpdateCommand, "getTerminationPointBridge", any(ReadWriteTransaction.class), any(Node.class), anyString()); PowerMockito.when(SouthboundMapper.createManagedNodeId(any(InstanceIdentifier.class))).thenReturn(bridgeId); PowerMockito.whenNew(TopologyKey.class).withAnyArguments().thenReturn(mock(TopologyKey.class)); PowerMockito.whenNew(NodeKey.class).withAnyArguments().thenReturn(mock(NodeKey.class)); Node node = mock(Node.class); Whitebox.invokeMethod(ovsdbPortUpdateCommand, "updateTerminationPoints", transaction, node); verify(ovsdbPortUpdateCommand).getInstanceIdentifier(any(InstanceIdentifier.class), any(Port.class)); verify(transaction, times(2)).merge(any(LogicalDatastoreType.class), any(InstanceIdentifier.class), any(TerminationPoint.class)); }
Example #24
Source File: OpenVSwitchUpdateCommandTest.java From ovsdb with Eclipse Public License 1.0 | 4 votes |
@SuppressWarnings("unchecked") @Test // TODO This test needs to be re-done @Ignore("Broken mock-based test") public void testExecute() throws Exception { PowerMockito.mockStatic(TyperUtils.class); UUID uuid = mock(UUID.class); OpenVSwitch ovs = mock(OpenVSwitch.class); when(TyperUtils.extractRowsUpdated(eq(OpenVSwitch.class), any(TableUpdates.class), any(DatabaseSchema.class))) .thenReturn(ImmutableMap.of(uuid, ovs)); OpenVSwitch ovs1 = mock(OpenVSwitch.class); when(TyperUtils.extractRowsOld(eq(OpenVSwitch.class), any(TableUpdates.class), any(DatabaseSchema.class))) .thenReturn(ImmutableMap.of(uuid, ovs1)); //mock getUpdates() and getDbSchema() when(openVSwitchUpdateCommand.getUpdates()).thenReturn(updates); when(openVSwitchUpdateCommand.getDbSchema()).thenReturn(dbSchema); //Test getInstanceIdentifier(): case 1: // ovs.getExternalIdsColumn().getData().containsKey(SouthboundConstants.IID_EXTERNAL_ID_KEY)) == true Column<GenericTableSchema, Map<String, String>> column = mock(Column.class); when(ovs.getExternalIdsColumn()).thenReturn(column); when(column.getData()).thenReturn(ImmutableMap.of(SouthboundConstants.IID_EXTERNAL_ID_KEY, "iidString")); PowerMockito.mockStatic(SouthboundUtil.class); MemberModifier.suppress(MemberMatcher.method(OpenVSwitchUpdateCommand.class, "getOvsdbConnectionInstance")); InstanceIdentifier<Node> iid = mock(InstanceIdentifier.class); // when((InstanceIdentifier<Node>) SouthboundUtil.deserializeInstanceIdentifier( // any(InstanceIdentifierCodec.class), anyString())).thenReturn(iid); OvsdbConnectionInstance ovsdbConnectionInstance = mock(OvsdbConnectionInstance.class); when(ovsdbConnectionInstance.getInstanceIdentifier()).thenReturn(iid); when(openVSwitchUpdateCommand.getOvsdbConnectionInstance()).thenReturn(ovsdbConnectionInstance); doNothing().when(ovsdbConnectionInstance).setInstanceIdentifier(any(InstanceIdentifier.class)); OvsdbNodeAugmentationBuilder ovsdbNodeBuilder = mock(OvsdbNodeAugmentationBuilder.class); PowerMockito.whenNew(OvsdbNodeAugmentationBuilder.class).withNoArguments().thenReturn(ovsdbNodeBuilder); //suppress the setter methods of the class MemberModifier.suppress(MemberMatcher.method(OpenVSwitchUpdateCommand.class, "setOvsVersion", OvsdbNodeAugmentationBuilder.class, OpenVSwitch.class)); MemberModifier.suppress(MemberMatcher.method(OpenVSwitchUpdateCommand.class, "setDbVersion", OvsdbNodeAugmentationBuilder.class, OpenVSwitch.class)); MemberModifier.suppress(MemberMatcher.method(OpenVSwitchUpdateCommand.class, "setDataPathTypes", OvsdbNodeAugmentationBuilder.class, OpenVSwitch.class)); MemberModifier.suppress(MemberMatcher.method(OpenVSwitchUpdateCommand.class, "setInterfaceTypes", OvsdbNodeAugmentationBuilder.class, OpenVSwitch.class)); MemberModifier.suppress(MemberMatcher.method(OpenVSwitchUpdateCommand.class, "setExternalIds", ReadWriteTransaction.class, OvsdbNodeAugmentationBuilder.class, OpenVSwitch.class, OpenVSwitch.class)); MemberModifier.suppress(MemberMatcher.method(OpenVSwitchUpdateCommand.class, "setOtherConfig", InstanceIdentifierCodec.class, ReadWriteTransaction.class, OvsdbNodeAugmentationBuilder.class, OpenVSwitch.class, OpenVSwitch.class)); MemberModifier.suppress(MemberMatcher.method(OpenVSwitchUpdateCommand.class, "getConnectionInfo")); when(openVSwitchUpdateCommand.getConnectionInfo()).thenReturn(mock(ConnectionInfo.class)); when(ovsdbNodeBuilder.setConnectionInfo(any(ConnectionInfo.class))).thenReturn(ovsdbNodeBuilder); NodeBuilder nodeBuilder = mock(NodeBuilder.class); PowerMockito.whenNew(NodeBuilder.class).withNoArguments().thenReturn(nodeBuilder); //suppress getNodeId() MemberModifier.suppress( MemberMatcher.method(OpenVSwitchUpdateCommand.class, "getNodeId", InstanceIdentifierCodec.class, OpenVSwitch.class)); when(nodeBuilder.setNodeId(any(NodeId.class))).thenReturn(nodeBuilder); when(ovsdbNodeBuilder.build()).thenReturn(mock(OvsdbNodeAugmentation.class)); when(nodeBuilder.addAugmentation(eq(OvsdbNodeAugmentation.class), any(OvsdbNodeAugmentation.class))) .thenReturn(nodeBuilder); when(nodeBuilder.build()).thenReturn(mock(Node.class)); ReadWriteTransaction transaction = mock(ReadWriteTransaction.class); doNothing().when(transaction).merge(any(LogicalDatastoreType.class), any(InstanceIdentifier.class), any(Node.class)); openVSwitchUpdateCommand.execute(transaction); verify(openVSwitchUpdateCommand, times(2)).getUpdates(); verify(openVSwitchUpdateCommand, times(2)).getDbSchema(); //Test getInstanceIdentifier(): case 2: ovs.getExternalIdsColumn() is null when(ovs.getExternalIdsColumn()).thenReturn(null); when(ovs.getUuid()).thenReturn(uuid); openVSwitchUpdateCommand.execute(transaction); verify(openVSwitchUpdateCommand, times(4)).getUpdates(); verify(openVSwitchUpdateCommand, times(4)).getDbSchema(); }
Example #25
Source File: OvsdbConnectionManagerTest.java From ovsdb with Eclipse Public License 1.0 | 4 votes |
@SuppressWarnings("unchecked") @Test public void testConnect() throws Exception { OvsdbNodeAugmentation ovsdbNode = mock(OvsdbNodeAugmentation.class); ConnectionInfo connectionInfo = mock(ConnectionInfo.class); when(ovsdbNode.getConnectionInfo()).thenReturn(connectionInfo); IpAddress ipAddr = mock(IpAddress.class); when(connectionInfo.getRemoteIp()).thenReturn(ipAddr); PowerMockito.mockStatic(SouthboundMapper.class); InetAddress ip = mock(InetAddress.class); when(SouthboundMapper.createInetAddress(any(IpAddress.class))).thenReturn(ip); PowerMockito.mockStatic(OvsdbConnectionService.class); // when(OvsdbConnectionService.getService()).thenReturn(ovsdbConnection); PortNumber port = mock(PortNumber.class); when(connectionInfo.getRemotePort()).thenReturn(port); when(port.getValue()).thenReturn(Uint16.valueOf(8080)); OvsdbClient client = mock(OvsdbClient.class); when(ovsdbConnection.connect(any(InetAddress.class), anyInt())).thenReturn(client); //client not null case suppress(MemberMatcher.method(OvsdbConnectionManager.class, "putInstanceIdentifier", ConnectionInfo.class, InstanceIdentifier.class)); suppress(MemberMatcher.method(OvsdbConnectionManager.class, "connectedButCallBacksNotRegistered", OvsdbClient.class)); doNothing().when(ovsdbConnManager).putInstanceIdentifier(any(ConnectionInfo.class), any(InstanceIdentifier.class)); OvsdbConnectionInstance ovsdbConnectionInstance = mock(OvsdbConnectionInstance.class); when(ovsdbConnManager.connectedButCallBacksNotRegistered(any(OvsdbClient.class))) .thenReturn(ovsdbConnectionInstance); when(ovsdbConnectionInstance.getInstanceIdentifier()).thenReturn(mock(InstanceIdentifier.class)); field(OvsdbConnectionManager.class, "entityConnectionMap").set(ovsdbConnManager, entityConnectionMap); suppress(MemberMatcher.method(OvsdbConnectionManager.class, "getEntityFromConnectionInstance", OvsdbConnectionInstance.class)); //TODO: Write unit tests for entity ownership service related code. suppress(MemberMatcher.method(OvsdbConnectionManager.class, "registerEntityForOwnership", OvsdbConnectionInstance.class)); assertEquals("ERROR", client, ovsdbConnManager.connect(PowerMockito.mock(InstanceIdentifier.class), ovsdbNode)); }
Example #26
Source File: ExceptionIT.java From datacollector with Apache License 2.0 | 4 votes |
@Test @Ignore("Investigate/fix sporadic failure (sometimes generates 4 errors intead of expected 4): SDC-6773") public void testNumSQLErrors() throws Exception { TableConfigBeanImpl tableConfigBean = new TableJdbcSourceTestBuilder.TableConfigBeanTestBuilder() .tablePattern("%") .schema(database) .build(); TableJdbcSource tableJdbcSource = new TableJdbcSourceTestBuilder(JDBC_URL, true, USER_NAME, PASSWORD) .tableConfigBeans(ImmutableList.of(tableConfigBean)) .numSQLErrorRetries(3) .build(); PushSourceRunner runner = new PushSourceRunner.Builder(TableJdbcDSource.class, tableJdbcSource) .addOutputLane("a") .setOnRecordError(OnRecordError.TO_ERROR) .build(); Map<String, String> offsets = new HashMap<>(); runner.runInit(); AtomicInteger exceptionHappenedTimes = new AtomicInteger(0); try { PowerMockito.replace( MemberMatcher.method( TableJdbcRunnable.class, CREATE_AND_ADD_RECORD_METHOD, ResultSet.class, TableRuntimeContext.class, BatchContext.class ) ).with((proxy, method, args) -> { throw new SQLException(EXCEPTION_MESSAGE); }); PowerMockito.replace( MemberMatcher.method( TableJdbcRunnable.class, HANDLE_SQL_EXCEPTION_METHOD, SQLException.class) ).with((proxy, method, args) -> { SQLException sqlException = (SQLException) args[0]; Assert.assertEquals(EXCEPTION_MESSAGE, sqlException.getMessage()); int expectedExceptionHappenedTimes = exceptionHappenedTimes.getAndIncrement(); int actualExceptionHappenedTimes = (Integer) Whitebox.getInternalState(proxy, NUM_SQL_ERRORS_FIELD); Assert.assertEquals(expectedExceptionHappenedTimes, actualExceptionHappenedTimes); return method.invoke(proxy, args); }); runner.runProduce(offsets, 10, output -> { //NOOP }); //Await for runner stop and // NOTE: need poll interval to avoid ConcurrentModificationException from StageRunner#getErrors Awaitility.await().pollInterval(1, TimeUnit.MILLISECONDS).atMost(Duration.FIVE_MINUTES).until( () -> runner.getErrors().size() == 1 ); Assert.assertEquals(3, exceptionHappenedTimes.get()); } finally { runner.runDestroy(); } }
Example #27
Source File: ExtraOffsetConditionIT.java From datacollector with Apache License 2.0 | 4 votes |
/** * This method helps manipulate the current time to be less than what we have * stored in {@link #batchRecords} for the next batch * So every batch will get 2 records. */ private void setTimeContextForProduce(TableJdbcSource tableJdbcSource, int batchNumber) { Calendar finalCalendar = Calendar.getInstance(); Date currentDateTime = finalCalendar.getTime(); finalCalendar.set(Calendar.YEAR, 1970); finalCalendar.set(Calendar.MONTH, 0); finalCalendar.set(Calendar.DAY_OF_MONTH, 1); finalCalendar.set(Calendar.HOUR_OF_DAY, 0); finalCalendar.set(Calendar.MINUTE, 0); finalCalendar.set(Calendar.SECOND, 0); finalCalendar.set(Calendar.MILLISECOND, 0); for (Map.Entry<String, Field.Type> offsetFieldToTypeEntry : transactionOffsetFields.entrySet()) { String fieldPath = offsetFieldToTypeEntry.getKey(); int year = finalCalendar.get(Calendar.YEAR); int month = finalCalendar.get(Calendar.MONTH); int day = finalCalendar.get(Calendar.DAY_OF_MONTH); int hour = finalCalendar.get(Calendar.HOUR_OF_DAY); int minutes = finalCalendar.get(Calendar.MINUTE); int seconds = finalCalendar.get(Calendar.SECOND); int milliSeconds = finalCalendar.get(Calendar.MILLISECOND); //Basically use the next timestamp which should be picked for the next batch //and pretty much use it as current time (which the extra condition will evaluate to) //For the last batch use the current dateTime. Date date = (batchNumber < BATCHES - 1) ? batchRecords.get(batchNumber + 1).get(0).get().getValueAsListMap().get(fieldPath).getValueAsDatetime() : currentDateTime; Calendar temp = Calendar.getInstance(); temp.setTime(date); switch (offsetFieldToTypeEntry.getValue()) { case DATE: year = temp.get(Calendar.YEAR); month = temp.get(Calendar.MONTH); day = temp.get(Calendar.DAY_OF_MONTH); break; case TIME: hour = temp.get(Calendar.HOUR_OF_DAY); minutes = temp.get(Calendar.MINUTE); seconds = temp.get(Calendar.SECOND); milliSeconds = temp.get(Calendar.MILLISECOND); break; case DATETIME: case LONG: year = temp.get(Calendar.YEAR); month = temp.get(Calendar.MONTH); day = temp.get(Calendar.DAY_OF_MONTH); hour = temp.get(Calendar.HOUR_OF_DAY); minutes = temp.get(Calendar.MINUTE); seconds = temp.get(Calendar.SECOND); milliSeconds = temp.get(Calendar.MILLISECOND); break; default: throw new IllegalArgumentException("Unsupported Field Type {}" + offsetFieldToTypeEntry.getValue()); } finalCalendar.set(Calendar.YEAR, year); finalCalendar.set(Calendar.MONTH, month); finalCalendar.set(Calendar.DAY_OF_MONTH, day); finalCalendar.set(Calendar.HOUR_OF_DAY, hour); finalCalendar.set(Calendar.MINUTE, minutes); finalCalendar.set(Calendar.SECOND, seconds); finalCalendar.set(Calendar.MILLISECOND, milliSeconds); } PowerMockito.replace( MemberMatcher.method( TableJdbcRunnable.class, "initTableEvalContextForProduce", TableJdbcELEvalContext.class, TableRuntimeContext.class, Calendar.class ) ).with((proxy, method, args) -> { args[2] = finalCalendar; return method.invoke(proxy, args); }); }
Example #28
Source File: TestBigQueryTarget.java From datacollector with Apache License 2.0 | 4 votes |
@Before public void setup() { PowerMockito.replace( MemberMatcher.method(GoogleCloudCredentialsConfig.class, "getCredentials", Stage.Context.class, List.class) ).with((proxy,method,args) -> PowerMockito.mock(Credentials.class)); }
Example #29
Source File: TestErrorRecord.java From datacollector with Apache License 2.0 | 4 votes |
@SuppressWarnings("unchecked") private void runAndCheckErrorRecords(String errorStage, String expectedFieldValue) throws Exception { final List<Record> badHandlerErrorRecords = new ArrayList<>(); latch = new CountDownLatch(1); ProductionPipelineRunner runner = new ProductionPipelineRunner( TestUtil.MY_PIPELINE, "0", null, new Configuration(), buildInfo, runtimeInfo, new MetricRegistry(), null, null, null ); runner.setDeliveryGuarantee(DeliveryGuarantee.AT_LEAST_ONCE); runner.setObserveRequests(new ArrayBlockingQueue<>(100, true /*FIFO*/)); runner.setOffsetTracker(new TestUtil.SourceOffsetTrackerImpl(Collections.singletonMap(Source.POLL_SOURCE_OFFSET_KEY, "1"))); ProductionPipeline pipeline = new ProductionPipelineBuilder( TestUtil.MY_PIPELINE, "0", new Configuration(), runtimeInfo, buildInfo, MockStages.createStageLibrary(), runner, null, Mockito.mock(BlobStoreTask.class), Mockito.mock(LineagePublisherTask.class), Mockito.mock(StatsCollector.class) ).build( MockStages.userContext(), MockStages.createPipelineConfigurationSourceProcessorTarget(), System.currentTimeMillis() ); pipeline.registerStatusListener(new TestProductionPipeline.MyStateListener()); pipelineStateStore.saveState( "admin", TestUtil.MY_PIPELINE, "0", PipelineStatus.RUNNING, null, null, null, null, 0, 0 ); PowerMockito.replace(MemberMatcher.method( BadRecordsHandler.class, "handle", String.class, String.class, ErrorSink.class, SourceResponseSinkImpl.class )).with((proxy, method, args) -> { ErrorSink errorSink = (ErrorSink) args[2]; for (Map.Entry<String, List<Record>> entry : errorSink.getErrorRecords().entrySet()) { for (Record record : entry.getValue()) { badHandlerErrorRecords.add(record); } } return null; }); captureMockStages(errorStage, new AtomicBoolean(false)); ProductionPipelineRunnable runnable = new ProductionPipelineRunnable(null, this.runner.getRunner(StandaloneRunner.class), pipeline, TestUtil.MY_PIPELINE, "0", Collections.<Future<?>> emptyList()); Thread t = new Thread(runnable); t.start(); latch.await(); runnable.stop(false); t.join(); Assert.assertTrue(runnable.isStopped()); checkErrorRecords(pipeline.getErrorRecords(errorStage, 10), errorStage, expectedFieldValue, true); checkErrorRecords(badHandlerErrorRecords, errorStage, expectedFieldValue, false); }
Example #30
Source File: TerminationPointUpdateCommandTest.java From ovsdb with Eclipse Public License 1.0 | 4 votes |
@SuppressWarnings({ "unchecked", "rawtypes" }) @Test public void testUpdateTerminationPoint() throws Exception { TransactionBuilder transaction = mock(TransactionBuilder.class); BridgeOperationalState state = mock(BridgeOperationalState.class); OvsdbTerminationPointAugmentation terminationPoint = mock(OvsdbTerminationPointAugmentation.class); when(terminationPoint.getName()).thenReturn(TERMINATION_POINT_NAME); Node node = mock(Node.class); when(node.augmentation(OvsdbBridgeAugmentation.class)).thenReturn(mock(OvsdbBridgeAugmentation.class)); Optional<Node> optNode = Optional.of(node); when(state.getBridgeNode(any(InstanceIdentifier.class))).thenReturn(optNode); // Test updateInterface() Interface ovsInterface = mock(Interface.class); when(transaction.getTypedRowWrapper(eq(Interface.class))).thenReturn(ovsInterface); Interface extraInterface = mock(Interface.class); when(transaction.getTypedRowWrapper(eq(Interface.class))).thenReturn(extraInterface); doNothing().when(extraInterface).setName(anyString()); Operations op = OvsdbNodeUpdateCommandTest.setOpField(); Update update = mock(Update.class); when(op.update(any(Interface.class))).thenReturn(update); Column<GenericTableSchema, String> column = mock(Column.class); when(extraInterface.getNameColumn()).thenReturn(column); ColumnSchema<GenericTableSchema, String> columnSchema = mock(ColumnSchema.class); when(column.getSchema()).thenReturn(columnSchema); when(columnSchema.opEqual(anyString())).thenReturn(mock(Condition.class)); Where where = mock(Where.class); when(update.where(any(Condition.class))).thenReturn(where); when(where.build()).thenReturn(mock(Operation.class)); when(transaction.add(any(Operation.class))).thenReturn(transaction); PowerMockito.suppress(MemberMatcher.methodsDeclaredIn(TerminationPointCreateCommand.class)); PowerMockito.suppress(MemberMatcher.methodsDeclaredIn(InstanceIdentifier.class)); // Test updatePort() Port port = mock(Port.class); when(transaction.getTypedRowWrapper(eq(Port.class))).thenReturn(port); Port extraPort = mock(Port.class); when(transaction.getTypedRowWrapper(eq(Port.class))).thenReturn(extraPort); doNothing().when(extraPort).setName(anyString()); when(op.update(any(Port.class))).thenReturn(update); when(extraPort.getNameColumn()).thenReturn(column); InstanceIdentifier<OvsdbTerminationPointAugmentation> iid = mock(InstanceIdentifier.class); terminationPointUpdateCommand.updateTerminationPoint(transaction, state, iid, terminationPoint, mock(InstanceIdentifierCodec.class)); verify(transaction, times(1)).add(any(Operation.class)); }