Java Code Examples for org.easymock.Capture#newInstance()

The following examples show how to use org.easymock.Capture#newInstance() . 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: GroovyDriverTestCase.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
@Override
@Before
public void setUp() throws Exception {
   super.setUp();
   GroovyValidator.clear();

   Capture<Device> deviceRef = Capture.newInstance();
   EasyMock
      .expect(mockDeviceDao.save(EasyMock.capture(deviceRef)))
      .andAnswer(() -> {
         Device device = deviceRef.getValue().copy();
         if(device.getId() == null) {
            device.setId(UUID.randomUUID());
         }
         if(device.getCreated() == null) {
            device.setCreated(new Date());
         }
         device.setModified(new Date());
         return device;
      })
      .anyTimes();
   mockDeviceDao.updateDriverState(EasyMock.notNull(), EasyMock.notNull());
   EasyMock.expectLastCall().anyTimes();
   EasyMock.replay(mockDeviceDao);
}
 
Example 2
Source File: LocalFallbackStrategyTest.java    From buck with Apache License 2.0 6 votes vote down vote up
@Test
public void testEventBusLogForFallbackDisabled() throws ExecutionException, InterruptedException {
  Capture<AbstractBuckEvent> eventCapture = Capture.newInstance(CaptureType.ALL);
  eventBus.post(EasyMock.capture(eventCapture));
  EasyMock.expectLastCall().times(3);
  EasyMock.replay(eventBus);

  testRemoteActionExceptionFallbackDisabledForBuildError();

  List<AbstractBuckEvent> events = eventCapture.getValues();
  Assert.assertTrue(events.get(0) instanceof LocalFallbackEvent.Started);
  Assert.assertTrue(events.get(1) instanceof ConsoleEvent);
  Assert.assertTrue(events.get(2) instanceof LocalFallbackEvent.Finished);
  LocalFallbackEvent.Finished finishedEvent = (LocalFallbackEvent.Finished) events.get(2);
  Assert.assertEquals(finishedEvent.getRemoteGrpcStatus(), Status.OK);
}
 
Example 3
Source File: ChromeDevToolsServiceImplTest.java    From chrome-devtools-java-client with Apache License 2.0 6 votes vote down vote up
@Test
public void testInvokeVoidMethod() throws WebSocketServiceException, IOException {
  MethodInvocation methodInvocation = new MethodInvocation();
  methodInvocation.setId(1L);
  methodInvocation.setMethod("SomeMethod");
  methodInvocation.setParams(new HashMap<>());
  methodInvocation.getParams().put("param", "value");

  Capture<String> messageCapture = Capture.newInstance();
  webSocketService.send(capture(messageCapture));

  replayAll();

  resolveMessage("{\"id\":1,\"result\":{}}");
  assertNull(service.invoke(null, Void.TYPE, null, methodInvocation));

  verifyAll();

  MethodInvocation sentInvocation =
      OBJECT_MAPPER.readerFor(MethodInvocation.class).readValue(messageCapture.getValue());
  assertEquals(methodInvocation.getId(), sentInvocation.getId());
  assertEquals(methodInvocation.getMethod(), sentInvocation.getMethod());
  assertEquals(methodInvocation.getParams(), sentInvocation.getParams());
}
 
Example 4
Source File: JavaClassBuilderImplTest.java    From chrome-devtools-java-client with Apache License 2.0 6 votes vote down vote up
@Test
public void testAddingImportsOnSamePackage() throws IOException {
  Capture<CompilationUnit> compilationUnitCapture = Capture.newInstance();

  sourceProject.addCompilationUnit(
      eq(PACKAGE_NAME), eq(CLASS_NAME), capture(compilationUnitCapture));

  replayAll();

  javaClassBuilder.addImport(PACKAGE_NAME, "Test");
  javaClassBuilder.addImport("java.util", "List");

  javaClassBuilder.build(sourceProject);

  assertEquals(
      "package com.github.kklisura;\n\n"
          + "import java.util.List;\n"
          + "\n"
          + "public class ClassName {\n"
          + "}\n"
          + "",
      compilationUnitCapture.getValue().toString());

  verifyAll();
}
 
Example 5
Source File: LocalFallbackStrategyTest.java    From buck with Apache License 2.0 5 votes vote down vote up
@Test
public void testEventsAreSent() throws ExecutionException, InterruptedException {
  Capture<LocalFallbackEvent> eventCapture = Capture.newInstance(CaptureType.ALL);
  eventBus.post(EasyMock.capture(eventCapture));
  EasyMock.expectLastCall().times(2);
  EasyMock.replay(eventBus);

  testRemoteActionError();

  List<LocalFallbackEvent> events = eventCapture.getValues();
  Assert.assertTrue(events.get(0) instanceof LocalFallbackEvent.Started);
  Assert.assertTrue(events.get(1) instanceof LocalFallbackEvent.Finished);
  LocalFallbackEvent.Finished finishedEvent = (LocalFallbackEvent.Finished) events.get(1);
  Assert.assertEquals(finishedEvent.getRemoteGrpcStatus(), Status.OK);
}
 
Example 6
Source File: JavaClassBuilderImplTest.java    From chrome-devtools-java-client with Apache License 2.0 5 votes vote down vote up
@Test
public void testGenerateGettersAndSetters() throws IOException {
  Capture<CompilationUnit> compilationUnitCapture = Capture.newInstance();

  sourceProject.addCompilationUnit(
      eq(PACKAGE_NAME), eq(CLASS_NAME), capture(compilationUnitCapture));

  replayAll();

  javaClassBuilder.addPrivateField("privateField", "String", "Private field description");

  javaClassBuilder.generateGettersAndSetters();

  javaClassBuilder.build(sourceProject);

  assertEquals(
      "package com.github.kklisura;\n"
          + "\n"
          + "public class ClassName {\n"
          + "\n"
          + "    private String privateField;\n"
          + "\n"
          + "    /**\n"
          + "     * Private field description\n"
          + "     */\n"
          + "    public String getPrivateField() {\n"
          + "        return privateField;\n"
          + "    }\n"
          + "\n"
          + "    /**\n"
          + "     * Private field description\n"
          + "     */\n"
          + "    public void setPrivateField(String privateField) {\n"
          + "        this.privateField = privateField;\n"
          + "    }\n"
          + "}\n",
      compilationUnitCapture.getValue().toString());

  verifyAll();
}
 
Example 7
Source File: TestPlaceSetAttributesHandler_Location.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
@Before
public void captureSaves() {
   savedPlaces = Capture.newInstance(CaptureType.ALL);
   EasyMock
      .expect(placeDao.save(EasyMock.capture(savedPlaces)))
      .andAnswer(() -> {
         Place p = savedPlaces.getValue().copy();
         p.setModified(new Date());
         return p;
      })
      .anyTimes();
}
 
Example 8
Source File: ChromeDevToolsServiceImplTest.java    From chrome-devtools-java-client with Apache License 2.0 5 votes vote down vote up
@Test
public void testInvokeVoidMethodThrowsWebSocketException()
    throws WebSocketServiceException, IOException {
  MethodInvocation methodInvocation = new MethodInvocation();
  methodInvocation.setId(1L);
  methodInvocation.setMethod("SomeMethod");
  methodInvocation.setParams(new HashMap<>());
  methodInvocation.getParams().put("param", "value");

  WebSocketServiceException webSocketServiceException =
      new WebSocketServiceException("WS Failed");

  Capture<String> messageCapture = Capture.newInstance();
  webSocketService.send(capture(messageCapture));
  expectLastCall().andThrow(webSocketServiceException);

  replayAll();

  ChromeDevToolsInvocationException capturedException = null;
  try {
    service.invoke(null, Void.TYPE, null, methodInvocation);
  } catch (ChromeDevToolsInvocationException ex) {
    capturedException = ex;
  }
  assertNotNull(capturedException);

  assertEquals("Failed sending web socket message.", capturedException.getMessage());
  assertEquals(webSocketServiceException, capturedException.getCause());

  verifyAll();

  MethodInvocation sentInvocation =
      OBJECT_MAPPER.readerFor(MethodInvocation.class).readValue(messageCapture.getValue());
  assertEquals(methodInvocation.getId(), sentInvocation.getId());
  assertEquals(methodInvocation.getMethod(), sentInvocation.getMethod());
}
 
Example 9
Source File: LocalFallbackStrategyTest.java    From buck with Apache License 2.0 5 votes vote down vote up
@Test
public void testRemoteGrpcException() throws ExecutionException, InterruptedException {
  Capture<LocalFallbackEvent> eventCapture = Capture.newInstance(CaptureType.ALL);
  eventBus.post(EasyMock.capture(eventCapture));
  EasyMock.expectLastCall().times(6);
  EasyMock.replay(eventBus);

  EasyMock.expect(strategyBuildResult.getBuildResult())
      .andReturn(Futures.immediateFailedFuture(Status.DEADLINE_EXCEEDED.asRuntimeException()))
      .times(2);
  BuildResult localResult = successBuildResult("//local/did:though");
  EasyMock.expect(buildStrategyContext.runWithDefaultBehavior())
      .andReturn(Futures.immediateFuture(Optional.of(localResult)))
      .once();
  EasyMock.expect(buildStrategyContext.getExecutorService()).andReturn(directExecutor).once();
  EasyMock.expect(strategyBuildResult.getRuleContext()).andReturn(ruleContext);

  EasyMock.replay(strategyBuildResult, buildStrategyContext);
  ruleContext.enterState(State.UPLOADING_ACTION, Optional.empty());
  ruleContext.enterState(State.EXECUTING, Optional.empty());
  FallbackStrategyBuildResult fallbackStrategyBuildResult =
      new FallbackStrategyBuildResult(
          RULE_NAME, strategyBuildResult, buildStrategyContext, eventBus, true, false, true);
  Assert.assertEquals(
      localResult.getStatus(),
      fallbackStrategyBuildResult.getBuildResult().get().get().getStatus());
  EasyMock.verify(strategyBuildResult, buildStrategyContext);

  List<LocalFallbackEvent> events = eventCapture.getValues();
  Assert.assertEquals(6, events.size());
  Assert.assertTrue(events.get(4) instanceof LocalFallbackEvent.Started);
  Assert.assertTrue(events.get(5) instanceof LocalFallbackEvent.Finished);
  LocalFallbackEvent.Finished finishedEvent = (LocalFallbackEvent.Finished) events.get(5);
  Assert.assertEquals(finishedEvent.getRemoteGrpcStatus(), Status.DEADLINE_EXCEEDED);
  Assert.assertEquals(finishedEvent.getLastNonTerminalState(), State.EXECUTING);
  Assert.assertEquals(finishedEvent.getExitCode(), OptionalInt.empty());
}
 
Example 10
Source File: DepsFunctionTest.java    From buck with Apache License 2.0 5 votes vote down vote up
private QueryEnvironment<QueryBuildTarget> makeFakeQueryEnvironment(TargetGraph targetGraph)
    throws Exception {
  QueryEnvironment env = createNiceMock(QueryEnvironment.class);

  Capture<String> stringCapture = Capture.newInstance();
  expect(env.getTargetsMatchingPattern(EasyMock.capture(stringCapture)))
      .andStubAnswer(
          () ->
              ImmutableSet.of(
                  QueryBuildTarget.of(BuildTargetFactory.newInstance(stringCapture.getValue()))));

  Capture<Iterable<QueryBuildTarget>> targetsCapture = Capture.newInstance();
  expect(env.getFwdDeps(EasyMock.capture(targetsCapture)))
      .andStubAnswer(
          () ->
              RichStream.from(targetsCapture.getValue())
                  .map(QueryBuildTarget.class::cast)
                  .map(QueryBuildTarget::getBuildTarget)
                  .map(targetGraph::get)
                  .flatMap(n -> targetGraph.getOutgoingNodesFor(n).stream())
                  .map(TargetNode::getBuildTarget)
                  .map(QueryBuildTarget::of)
                  .toImmutableSet());

  replay(env);

  return env;
}
 
Example 11
Source File: JavaInterfaceBuilderImplTest.java    From chrome-devtools-java-client with Apache License 2.0 5 votes vote down vote up
@Test
public void testAddingImportsOnSamePackage() throws IOException {
  Capture<CompilationUnit> compilationUnitCapture = Capture.newInstance();

  sourceProject.addCompilationUnit(
      eq(BASE_PACKAGE_NAME), eq(NAME), capture(compilationUnitCapture));

  replayAll();

  interfaceBuilder.addImport(BASE_PACKAGE_NAME, "Test");
  interfaceBuilder.addImport("java.util", "List");
  interfaceBuilder.addImport("java.util", "List");
  interfaceBuilder.addImport("java.util", "List");

  interfaceBuilder.build(sourceProject);

  assertEquals(
      "package com.github.kklisura;\n\n"
          + "import java.util.List;\n"
          + "\n"
          + "public interface InterfaceTest {\n"
          + "}\n"
          + "",
      compilationUnitCapture.getValue().toString());

  verifyAll();
}
 
Example 12
Source File: CommandBuilderTest.java    From chrome-devtools-java-client with Apache License 2.0 4 votes vote down vote up
@Test
public void testBuildCommandWithMethodWithArrayStringParam() {
  final Domain domain = new Domain();
  domain.setDomain("domainName");
  domain.setDescription("Description");

  final Command command = new Command();
  command.setName("command");
  command.setDescription("command description");

  final ArrayProperty arrayProperty = new ArrayProperty();
  arrayProperty.setName("enumParam1");
  arrayProperty.setOptional(Boolean.FALSE);
  arrayProperty.setDescription("enum param 1 description");

  RefArrayItem enumArrayItem = new RefArrayItem();
  enumArrayItem.setRef("SomeRefType");
  arrayProperty.setItems(enumArrayItem);
  command.setParameters(Collections.singletonList(arrayProperty));

  domain.setCommands(Collections.singletonList(command));

  expect(javaBuilderFactory.createInterfaceBuilder(BASE_PACKAGE_NAME, "DomainName"))
      .andReturn(interfaceBuilder);
  interfaceBuilder.setJavaDoc("Description");

  Capture<List<MethodParam>> methodParamCapture = Capture.newInstance();
  interfaceBuilder.addMethod(eq("command"), anyString(), capture(methodParamCapture), eq(null));

  final ArrayType resolvedRefType = new ArrayType();
  resolvedRefType.setId("arrayRefType");

  final StringArrayItem stringArrayItem = new StringArrayItem();
  resolvedRefType.setItems(stringArrayItem);

  expect(resolver.resolve("domainName", "SomeRefType")).andReturn(resolvedRefType);

  interfaceBuilder.addImport("java.util", "List");
  expectLastCall().times(2);

  replayAll();

  Builder build = commandBuilder.build(domain, resolver);

  verifyAll();

  assertTrue(build instanceof JavaInterfaceBuilder);
  assertEquals(interfaceBuilder, build);

  List<MethodParam> params = methodParamCapture.getValue();
  assertEquals(1, params.size());

  Assert.assertEquals(arrayProperty.getName(), params.get(0).getName());
  assertEquals("List<List<String>>", params.get(0).getType());
  assertEquals("ParamName", params.get(0).getAnnotations().get(0).getName());
  assertEquals(arrayProperty.getName(), params.get(0).getAnnotations().get(0).getValue());
}
 
Example 13
Source File: CommandBuilderTest.java    From chrome-devtools-java-client with Apache License 2.0 4 votes vote down vote up
@Test
public void testBuildCommandWithEvents() {
  final Domain domain = new Domain();
  domain.setDomain("domainName");
  domain.setDescription("Description");

  final Event event = new Event();
  event.setName("someEvent");
  event.setDescription("event description");

  final Event event1 = new Event();
  event1.setName("someEvent1");
  event1.setDescription("event description");
  event1.setDeprecated(Boolean.TRUE);
  event1.setExperimental(Boolean.TRUE);

  domain.setEvents(Arrays.asList(event, event1));

  expect(javaBuilderFactory.createInterfaceBuilder(BASE_PACKAGE_NAME, "DomainName"))
      .andReturn(interfaceBuilder);
  interfaceBuilder.setJavaDoc("Description");

  interfaceBuilder.addImport("com.github.kklisura.support.types", "EventListener");
  interfaceBuilder.addImport("com.github.kklisura.support.types", "EventHandler");
  interfaceBuilder.addImport("com.github.kklisura.events.domainname", "SomeEvent");

  interfaceBuilder.addImport("com.github.kklisura.support.types", "EventListener");
  interfaceBuilder.addImport("com.github.kklisura.support.types", "EventHandler");
  interfaceBuilder.addImport("com.github.kklisura.events.domainname", "SomeEvent1");

  Capture<List<MethodParam>> methodParamCapture = Capture.newInstance();
  interfaceBuilder.addMethod(
      eq("onSomeEvent"),
      eq("event description"),
      capture(methodParamCapture),
      eq("EventListener"));

  Capture<List<MethodParam>> methodParamCapture1 = Capture.newInstance();
  interfaceBuilder.addMethod(
      eq("onSomeEvent1"),
      eq("event description"),
      capture(methodParamCapture1),
      eq("EventListener"));

  interfaceBuilder.addParametrizedMethodAnnotation("onSomeEvent", "EventName", "someEvent");
  interfaceBuilder.addParametrizedMethodAnnotation("onSomeEvent1", "EventName", "someEvent1");

  interfaceBuilder.addMethodAnnotation("onSomeEvent1", "Deprecated");
  interfaceBuilder.addMethodAnnotation("onSomeEvent1", "Experimental");

  replayAll();

  Builder build = commandBuilder.build(domain, resolver);

  verifyAll();

  assertEquals(interfaceBuilder, build);

  List<MethodParam> value = methodParamCapture.getValue();
  assertEquals(1, value.size());
  assertEquals("eventListener", value.get(0).getName());
  assertEquals("EventHandler<SomeEvent>", value.get(0).getType());

  List<MethodParam> value1 = methodParamCapture1.getValue();
  assertEquals(1, value1.size());
  assertEquals("eventListener", value1.get(0).getName());
  assertEquals("EventHandler<SomeEvent1>", value1.get(0).getType());
}
 
Example 14
Source File: JavaInterfaceBuilderImplTest.java    From chrome-devtools-java-client with Apache License 2.0 4 votes vote down vote up
@Test
public void testBasicInterface() throws IOException {
  Capture<CompilationUnit> compilationUnitCapture = Capture.newInstance();

  sourceProject.addCompilationUnit(
      eq(BASE_PACKAGE_NAME), eq(NAME), capture(compilationUnitCapture));

  interfaceBuilder.setJavaDoc("");

  replayAll();

  interfaceBuilder.build(sourceProject);

  assertEquals(
      "package com.github.kklisura;\n" + "\n" + "public interface InterfaceTest {\n" + "}\n" + "",
      compilationUnitCapture.getValue().toString());

  verifyAll();
}
 
Example 15
Source File: UserTaskManagerTest.java    From cruise-control with BSD 2-Clause "Simplified" License 4 votes vote down vote up
@Test
public void testSessionsShareUserTask() {
  UUID testUserTaskId = UUID.randomUUID();

  UserTaskManager.UUIDGenerator mockUUIDGenerator = EasyMock.mock(UserTaskManager.UUIDGenerator.class);
  EasyMock.expect(mockUUIDGenerator.randomUUID()).andReturn(testUserTaskId).anyTimes();

  HttpSession mockHttpSession = EasyMock.mock(HttpSession.class);
  EasyMock.expect(mockHttpSession.getLastAccessedTime()).andReturn(100L).anyTimes();

  Map<String,  String []> requestParams1 = new HashMap<>();
  requestParams1.put("param", new String[]{"true"});
  HttpServletRequest mockHttpServletRequest1 = prepareRequest(mockHttpSession, null, "test", requestParams1);
  HttpServletResponse mockHttpServletResponse1 = EasyMock.mock(HttpServletResponse.class);
  Capture<String> userTaskHeader = Capture.newInstance();
  Capture<String> userTaskHeaderValue = Capture.newInstance();
  mockHttpServletResponse1.setHeader(EasyMock.capture(userTaskHeader), EasyMock.capture(userTaskHeaderValue));

  Map<String,  String []> requestParams2 = new HashMap<>();
  requestParams2.put("param", new String[]{"true"});
  HttpServletRequest mockHttpServletRequest2 = prepareRequest(mockHttpSession, null, "test", requestParams2);
  HttpServletResponse mockHttpServletResponse2 = EasyMock.mock(HttpServletResponse.class);
  mockHttpServletResponse2.setHeader(EasyMock.capture(userTaskHeader), EasyMock.capture(userTaskHeaderValue));

  Map<String,  String []> requestParams3 = new HashMap<>();
  requestParams3.put("param", new String[]{"true"});
  HttpServletRequest mockHttpServletRequest3 = prepareRequest(mockHttpSession, testUserTaskId.toString(), "test", requestParams3);
  HttpServletResponse mockHttpServletResponse3 = EasyMock.mock(HttpServletResponse.class);
  mockHttpServletResponse3.setHeader(EasyMock.capture(userTaskHeader), EasyMock.capture(userTaskHeaderValue));

  EasyMock.replay(mockUUIDGenerator, mockHttpSession, mockHttpServletResponse1, mockHttpServletResponse2, mockHttpServletResponse3);

  OperationFuture future = new OperationFuture("future");
  UserTaskManager userTaskManager = new UserTaskManager(1000, 5, TimeUnit.HOURS.toMillis(6),
                                                        100, new MockTime(), mockUUIDGenerator);
  userTaskManager.getOrCreateUserTask(mockHttpServletRequest1, mockHttpServletResponse1, uuid -> future, 0, true, null);
  userTaskManager.getOrCreateUserTask(mockHttpServletRequest2, mockHttpServletResponse2, uuid -> future, 0, true, null);
  // Test UserTaskManger can recognize the previous created task by taskId.
  userTaskManager.getOrCreateUserTask(mockHttpServletRequest3, mockHttpServletResponse3, uuid -> future, 0, true, null);

  // The 2nd request should reuse the UserTask created for the 1st request since they use the same session and send the same request.
  Assert.assertEquals(1, userTaskManager.numActiveSessionKeys());
}
 
Example 16
Source File: GossipDeviceStoreTest.java    From onos with Apache License 2.0 4 votes vote down vote up
@Test
public final void testCreateOrUpdateDeviceAncillary() throws IOException {
    // add
    DeviceDescription description =
            new DefaultDeviceDescription(DID1.uri(), SWITCH, MFR,
                    HW, SW1, SN, CID, A2);
    Capture<ClusterMessage> bcast = Capture.newInstance();

    Capture<InternalDeviceEvent> message = Capture.newInstance();
    Capture<MessageSubject> subject = Capture.newInstance();
    Capture<Function<InternalDeviceEvent, byte[]>> encoder = Capture.newInstance();

    resetCommunicatorExpectingSingleBroadcast(message, subject, encoder);
    DeviceEvent event = deviceStore.createOrUpdateDevice(PIDA, DID1, description);
    assertEquals(DEVICE_ADDED, event.type());
    assertDevice(DID1, SW1, event.subject());
    assertEquals(PIDA, event.subject().providerId());
    assertAnnotationsEquals(event.subject().annotations(), A2);
    assertFalse("Ancillary will not bring device up", deviceStore.isAvailable(DID1));
    verify(clusterCommunicator);
    assertInternalDeviceEvent(NID1, DID1, PIDA, description, message, subject, encoder);

    // update from primary
    DeviceDescription description2 =
            new DefaultDeviceDescription(DID1.uri(), SWITCH, MFR,
                    HW, SW2, SN, CID, A1);
    resetCommunicatorExpectingSingleBroadcast(message, subject, encoder);

    DeviceEvent event2 = deviceStore.createOrUpdateDevice(PID, DID1, description2);
    assertEquals(DEVICE_UPDATED, event2.type());
    assertDevice(DID1, SW2, event2.subject());
    assertEquals(PID, event2.subject().providerId());
    assertAnnotationsEquals(event2.subject().annotations(), A1, A2);
    assertTrue(deviceStore.isAvailable(DID1));
    verify(clusterCommunicator);
    assertInternalDeviceEvent(NID1, DID1, PID, description2, message, subject, encoder);

    // no-op update from primary
    resetCommunicatorExpectingNoBroadcast(message, subject, encoder);
    assertNull("No change expected", deviceStore.createOrUpdateDevice(PID, DID1, description2));

    verify(clusterCommunicator);
    assertFalse("no broadcast expected", bcast.hasCaptured());

    // For now, Ancillary is ignored once primary appears
    resetCommunicatorExpectingNoBroadcast(message, subject, encoder);

    assertNull("No change expected", deviceStore.createOrUpdateDevice(PIDA, DID1, description));

    verify(clusterCommunicator);
    assertFalse("no broadcast expected", bcast.hasCaptured());

    // But, Ancillary annotations will be in effect
    DeviceDescription description3 =
            new DefaultDeviceDescription(DID1.uri(), SWITCH, MFR,
                    HW, SW1, SN, CID, A2_2);
    resetCommunicatorExpectingSingleBroadcast(message, subject, encoder);

    DeviceEvent event3 = deviceStore.createOrUpdateDevice(PIDA, DID1, description3);
    assertEquals(DEVICE_UPDATED, event3.type());
    // basic information will be the one from Primary
    assertDevice(DID1, SW2, event3.subject());
    assertEquals(PID, event3.subject().providerId());
    // but annotation from Ancillary will be merged
    assertAnnotationsEquals(event3.subject().annotations(), A1, A2, A2_2);
    assertTrue(deviceStore.isAvailable(DID1));
    verify(clusterCommunicator);
    // note: only annotation from PIDA is sent over the wire
    assertInternalDeviceEvent(NID1, DID1, PIDA, description3,
                              asList(union(A2, A2_2)), message, subject, encoder);

}
 
Example 17
Source File: CommandBuilderTest.java    From chrome-devtools-java-client with Apache License 2.0 4 votes vote down vote up
@Test
public void testBuildCommandWithMethodWithArrayRefParam() {
  final Domain domain = new Domain();
  domain.setDomain("domainName");
  domain.setDescription("Description");

  final Command command = new Command();
  command.setName("command");
  command.setDescription("command description");

  final ArrayProperty arrayProperty = new ArrayProperty();
  arrayProperty.setName("enumParam1");
  arrayProperty.setOptional(Boolean.FALSE);
  arrayProperty.setDescription("enum param 1 description");

  RefArrayItem enumArrayItem = new RefArrayItem();
  enumArrayItem.setRef("SomeRefType");
  arrayProperty.setItems(enumArrayItem);
  command.setParameters(Collections.singletonList(arrayProperty));

  domain.setCommands(Collections.singletonList(command));

  expect(javaBuilderFactory.createInterfaceBuilder(BASE_PACKAGE_NAME, "DomainName"))
      .andReturn(interfaceBuilder);
  interfaceBuilder.setJavaDoc("Description");

  Capture<List<MethodParam>> methodParamCapture = Capture.newInstance();
  interfaceBuilder.addMethod(eq("command"), anyString(), capture(methodParamCapture), eq(null));

  final ArrayType resolvedRefType = new ArrayType();
  resolvedRefType.setId("arrayRefType");

  final com.github.kklisura.cdt.protocol.definition.types.type.array.items.RefArrayItem
      refArrayItem =
          new com.github.kklisura.cdt.protocol.definition.types.type.array.items.RefArrayItem();
  refArrayItem.setRef("TestRefArrayItem");
  resolvedRefType.setItems(refArrayItem);

  final StringType stringType = new StringType();
  stringType.setId("stringType");

  expect(resolver.resolve("domainName", "SomeRefType")).andReturn(resolvedRefType);
  expect(resolver.resolve("domainName", "TestRefArrayItem")).andReturn(stringType);

  interfaceBuilder.addImport("java.util", "List");
  expectLastCall().times(2);

  replayAll();

  Builder build = commandBuilder.build(domain, resolver);

  verifyAll();

  assertTrue(build instanceof JavaInterfaceBuilder);
  assertEquals(interfaceBuilder, build);

  List<MethodParam> params = methodParamCapture.getValue();
  assertEquals(1, params.size());

  Assert.assertEquals(arrayProperty.getName(), params.get(0).getName());
  assertEquals("List<List<String>>", params.get(0).getType());
  assertEquals("ParamName", params.get(0).getAnnotations().get(0).getName());
  assertEquals(arrayProperty.getName(), params.get(0).getAnnotations().get(0).getValue());
}
 
Example 18
Source File: CommandBuilderTest.java    From chrome-devtools-java-client with Apache License 2.0 4 votes vote down vote up
@Test
public void testBuildCommandWithMethodWithComplexReturnParams() {
  final Domain domain = new Domain();
  domain.setDomain("domainName");
  domain.setDescription("Description");

  final Command command = new Command();
  command.setName("getCommandSomeResult");
  command.setDescription("command description");

  final StringProperty stringParam = new StringProperty();
  stringParam.setName("stringParam1");
  stringParam.setDeprecated(Boolean.TRUE);

  final NumberProperty numberParam = new NumberProperty();
  numberParam.setName("numberParam1");
  numberParam.setExperimental(Boolean.TRUE);

  command.setReturns(Arrays.asList(stringParam, numberParam));
  domain.setCommands(Collections.singletonList(command));

  expect(
          javaBuilderFactory.createClassBuilder(
              TYPE_PACKAGE_NAME + ".domainname", "CommandSomeResult"))
      .andReturn(javaClassBuilder);

  javaClassBuilder.addPrivateField("stringParam1", "String", null);
  javaClassBuilder.addPrivateField("numberParam1", "Double", null);

  javaClassBuilder.addFieldAnnotation("stringParam1", "Deprecated");
  javaClassBuilder.addFieldAnnotation("numberParam1", "Experimental");

  javaClassBuilder.generateGettersAndSetters();

  expect(javaBuilderFactory.createInterfaceBuilder(BASE_PACKAGE_NAME, "DomainName"))
      .andReturn(interfaceBuilder);
  interfaceBuilder.setJavaDoc("Description");

  Capture<List<MethodParam>> methodParamCapture = Capture.newInstance();
  interfaceBuilder.addMethod(
      eq("getCommandSomeResult"),
      eq("command description"),
      capture(methodParamCapture),
      eq("CommandSomeResult"));

  interfaceBuilder.addImport("com.github.kklisura.types.domainname", "CommandSomeResult");

  replayAll();

  Builder build = commandBuilder.build(domain, resolver);

  verifyAll();

  assertTrue(build instanceof CombinedBuilders);

  List<Builder> builderList = ((CombinedBuilders) build).getBuilderList();
  assertEquals(2, builderList.size());

  assertEquals(javaClassBuilder, builderList.get(0));
  assertEquals(interfaceBuilder, builderList.get(1));

  assertTrue(methodParamCapture.getValue().isEmpty());
}
 
Example 19
Source File: CMODataClientBaseTest.java    From devops-cm-client with Apache License 2.0 3 votes vote down vote up
protected void setup() throws Exception {

        address = Capture.newInstance();

        examinee = new CMODataSolmanClient(
                SERVICE_ENDPOINT,
                SERVICE_USER,
                SERVICE_PASSWORD);

    }
 
Example 20
Source File: ChromeDevToolsServiceImplTest.java    From chrome-devtools-java-client with Apache License 2.0 3 votes vote down vote up
@Test
public void testEventReceivedWithUnsubscribeOnService() throws InterruptedException {
  // Non existing event handler
  service.accept("{\"method\":\"Domain.name\",\"params\":{\"testProperty\":\"testValue\"}}");

  Capture<TestMessage> testMessageCapture = Capture.newInstance();

  EventHandler<TestMessage> eventHandler = testMessageCapture::setValue;

  EventListener eventListener =
      service.addEventListener("Domain", "name", eventHandler, TestMessage.class);

  expectEventExecutorCall(1);

  replayAll();

  service.accept("{\"method\":\"Domain.name\",\"params\":{\"testProperty\":\"testValue\"}}");

  verifyAll();
  resetAll();

  assertNotNull(testMessageCapture.getValue());
  assertEquals("testValue", testMessageCapture.getValue().getTestProperty());

  service.removeEventListener(eventListener);

  testMessageCapture.reset();

  replayAll();

  service.accept("{\"method\":\"Domain.name\",\"params\":{\"testProperty\":\"testValue\"}}");

  verifyAll();

  assertFalse(testMessageCapture.hasCaptured());
}