/**
   * Verifies that we find the correct results for the following constellation.
   *
   * <ol>
   *   <li>Build with result, build result = SUCCESS
   *   <li>Build with no result
   *   <li>Build with result, build result = FAILURE
   *   <li>Build with no result
   *   <li>Baseline
   * </ol>
   *
   * @throws Exception the exception
   */
  @SuppressWarnings("rawtypes")
  @Test
  public void testHasReferenceResult() throws Exception {
    AbstractBuild withSuccessResult = mock(AbstractBuild.class);
    AbstractBuild noResult2 = mock(AbstractBuild.class);
    AbstractBuild withFailureResult = mock(AbstractBuild.class);
    AbstractBuild noResult1 = mock(AbstractBuild.class);
    AbstractBuild baseline = mock(AbstractBuild.class);
    when(baseline.getPreviousBuild()).thenReturn(noResult1);
    when(noResult1.getPreviousBuild()).thenReturn(withFailureResult);
    when(withFailureResult.getPreviousBuild()).thenReturn(noResult2);
    when(noResult2.getPreviousBuild()).thenReturn(withSuccessResult);

    TestResultAction failureAction = mock(TestResultAction.class);
    when(withFailureResult.getAction(TestResultAction.class)).thenReturn(failureAction);
    when(failureAction.isSuccessful()).thenReturn(false);
    BuildResult failureResult = mock(BuildResult.class);
    when(failureAction.getResult()).thenReturn(failureResult);

    TestResultAction successAction = mock(TestResultAction.class);
    when(withSuccessResult.getAction(TestResultAction.class)).thenReturn(successAction);
    when(successAction.isSuccessful()).thenReturn(true);
    BuildResult successResult = mock(BuildResult.class);
    AnnotationContainer container = mock(AnnotationContainer.class);
    when(successResult.getContainer()).thenReturn(container);
    when(successAction.getResult()).thenReturn(successResult);

    BuildHistory history = createHistory(baseline);

    assertTrue("Build has no previous result", history.hasPreviousResult());
    assertSame("Build has wrong previous result", failureResult, history.getPreviousResult());
    assertSame("Build has wrong reference result", container, history.getReferenceAnnotations());
  }
  @Test
  public void findEncryptedPartsShouldReturnMultipleEncryptedParts() throws Exception {
    MimeMessage message = new MimeMessage();
    MimeMultipart multipartMixed = new MimeMultipart();
    multipartMixed.setSubType("mixed");
    MimeMessageHelper.setBody(message, multipartMixed);

    MimeMultipart mulitpartEncryptedOne = new MimeMultipart();
    mulitpartEncryptedOne.setSubType("encrypted");
    MimeBodyPart bodyPartOne = new MimeBodyPart(mulitpartEncryptedOne);
    multipartMixed.addBodyPart(bodyPartOne);

    MimeBodyPart bodyPartTwo = new MimeBodyPart(null, "text/plain");
    multipartMixed.addBodyPart(bodyPartTwo);

    MimeMultipart mulitpartEncryptedThree = new MimeMultipart();
    mulitpartEncryptedThree.setSubType("encrypted");
    MimeBodyPart bodyPartThree = new MimeBodyPart(mulitpartEncryptedThree);
    multipartMixed.addBodyPart(bodyPartThree);

    List<Part> encryptedParts = MessageDecryptVerifier.findEncryptedParts(message);
    assertEquals(2, encryptedParts.size());
    assertSame(bodyPartOne, encryptedParts.get(0));
    assertSame(bodyPartThree, encryptedParts.get(1));
  }
 @Test
 public void findPreviousInput() throws Exception {
   buildInputTree();
   assertSame(input, RootKeyListener.previousInputPanel(input2));
   assertSame(input2, RootKeyListener.previousInputPanel(input3));
   assertSame(input3, RootKeyListener.previousInputPanel(input));
 }
  @Test
  public void testSetImage() {
    MockImage sessionImage = new MockImage();
    MockImage defaultImage = new MockImage();

    WImage image = new WImage();
    image.setImage(defaultImage);

    image.setLocked(true);
    setActiveContext(createUIContext());
    Assert.assertSame(
        "Default image should be returned when no user specific image set",
        defaultImage,
        image.getImage());
    Assert.assertTrue(
        "Should be in default state when no user specific image set", image.isDefaultState());

    setActiveContext(createUIContext());
    image.setImage(sessionImage);
    Assert.assertSame("Session image should be returned when set", sessionImage, image.getImage());
    Assert.assertFalse(
        "Should not be in default state when session image set", image.isDefaultState());

    resetContext();
    Assert.assertSame("Default image should not be changed", defaultImage, image.getImage());
  }
  @Test
  public void testCachedPrepared() throws Exception {
    BitronixTransactionManager tm = TransactionManagerServices.getTransactionManager();
    tm.setTransactionTimeout(60);
    tm.begin();

    Connection connection = poolingDataSource1.getConnection();

    PreparedStatement prepareStatement1 =
        connection.prepareStatement("SELECT 1 FROM nothing WHERE a=? AND b=? AND c=? AND d=?");
    PreparedStatement prepareStatement2 =
        connection.prepareStatement("SELECT 1 FROM nothing WHERE a=? AND b=? AND c=? AND d=?");

    Assert.assertSame(prepareStatement1, prepareStatement2);

    prepareStatement2.close();

    prepareStatement2 =
        connection.prepareStatement("SELECT 1 FROM nothing WHERE a=? AND b=? AND c=? AND d=?");
    Assert.assertSame(prepareStatement1, prepareStatement2);

    prepareStatement1.close();
    prepareStatement2.close();

    connection.close();
    tm.shutdown();
  }
  @Test
  public void testRendererClassAccessors() {
    TableTreeNode node = new TableTreeNode(null, WText.class, true);
    Assert.assertSame("Incorrect renderer class", WText.class, node.getRendererClass());

    node.setRendererClass(WTextField.class);
    Assert.assertSame(
        "Incorrect renderer class after setRenderClass", WTextField.class, node.getRendererClass());
  }
 @Test
 public void testCountrySetGet() {
   Country country = new Country(COUNTRY_ID, COUNTRY_NAME);
   Assert.assertSame(country.getCountryId(), COUNTRY_ID);
   Assert.assertSame(country.getCountryName(), COUNTRY_NAME);
   Country country2 = new Country("", "");
   country2.setCountryId(COUNTRY_ID);
   country2.setCountryName(COUNTRY_NAME);
   Assert.assertEquals(country, country2);
 }
 @Test
 public void testGetIssueLinkRendererModuleDescriptorSurvivesPluginThrowingExceptions()
     throws Exception {
   Assert.assertSame(
       defaultRenderer,
       RemoteIssueLinkUtils.getIssueLinkRendererModuleDescriptor(pluginAccessor, null));
   Assert.assertSame(
       goodDescriptorRenderer,
       RemoteIssueLinkUtils.getIssueLinkRendererModuleDescriptor(pluginAccessor, "application"));
 }
  // Javadoc inherited.
  public Object perform(MethodActionEvent event) throws Throwable {

    CacheEntry entry = (CacheEntry) event.getArgument(CacheEntry.class);
    if (hasEntry) {
      Assert.assertSame(expectedKey, entry.getKey());
      Assert.assertSame(expectedValue, entry.getValue());
    } else {
      Assert.assertNull(entry);
    }

    return null;
  }
 @Test
 public void appendBriefDescription() {
   ResolvedPrimitiveType primitiveType = new ResolvedPrimitiveType(boolean.class, 'Z', "boolean");
   StringBuilder buffer = new StringBuilder();
   StringBuilder returned = primitiveType.appendBriefDescription(buffer);
   assertSame(buffer, returned);
   assertEquals("boolean", returned.toString());
   buffer = new StringBuilder("something already ");
   returned = primitiveType.appendBriefDescription(buffer);
   assertSame(buffer, returned);
   assertEquals("something already boolean", returned.toString());
 }
 @Test
 public void appendErasedSignature() {
   ResolvedPrimitiveType primitiveType = new ResolvedPrimitiveType(boolean.class, 'Z', "boolean");
   StringBuilder buffer = new StringBuilder();
   StringBuilder returned = primitiveType.appendErasedSignature(buffer);
   assertSame(buffer, returned);
   assertEquals("Z", returned.toString());
   buffer = new StringBuilder("something already ");
   returned = primitiveType.appendErasedSignature(buffer);
   assertSame(buffer, returned);
   assertEquals("something already Z", returned.toString());
 }
  @Test
  public final void shouldReturnOrdersById() throws Exception {
    // given
    Entity order1 = mock(Entity.class);
    when(order1.getId()).thenReturn(1L);

    Entity order2 = mock(Entity.class);
    when(order2.getId()).thenReturn(2L);

    Entity order3 = mock(Entity.class);
    when(order3.getId()).thenReturn(3L);

    @SuppressWarnings("unchecked")
    Iterator<Long> iterator = mock(Iterator.class);
    when(iterator.hasNext()).thenReturn(true, true, true, true, false);
    when(iterator.next()).thenReturn(1L, 2L, 3L, 4L);

    @SuppressWarnings("unchecked")
    Set<Long> selectedOrderIds = mock(Set.class);
    when(selectedOrderIds.iterator()).thenReturn(iterator);
    when(selectedOrderIds.size()).thenReturn(4);

    SearchCriteriaBuilder criteria = mock(SearchCriteriaBuilder.class);
    when(criteria.add(Mockito.any(SearchCriterion.class))).thenReturn(criteria);

    SearchResult result = mock(SearchResult.class);
    when(criteria.list()).thenReturn(result);

    when(result.getTotalNumberOfEntities()).thenReturn(3);
    when(result.getEntities()).thenReturn(Lists.newArrayList(order1, order2, order3));

    DataDefinition orderDD = mock(DataDefinition.class);
    when(orderDD.find()).thenReturn(criteria);

    when(dataDefinitionService.get(OrdersConstants.PLUGIN_IDENTIFIER, OrdersConstants.MODEL_ORDER))
        .thenReturn(orderDD);

    // when
    List<Entity> resultList = workPlanService.getSelectedOrders(selectedOrderIds);

    // then
    Assert.assertEquals(3, resultList.size());

    Assert.assertNotNull(resultList.get(0));
    Assert.assertSame(1L, resultList.get(0).getId());

    Assert.assertNotNull(resultList.get(1));
    Assert.assertSame(2L, resultList.get(1).getId());

    Assert.assertNotNull(resultList.get(2));
    Assert.assertSame(3L, resultList.get(2).getId());
  }
  /** Test the TabDeletionException constructor with an inner/cause exception. */
  @Test
  public void testConstructorWithCause() {
    String causeMessage = "Need a cool word for this unit test";
    String exMessage = "Found it: antepenultimate.";

    Tab deletedTab = context.mock(Tab.class);

    Exception cause = new Exception(causeMessage);
    TabDeletionException sut = new TabDeletionException(exMessage, cause, deletedTab);

    assertSame("Didn't get the input cause exception from getCause()", cause, sut.getCause());
    assertSame("Didn't get the input deleted Tab from getTab()", deletedTab, sut.getTab());
    assertEquals(
        "Didn't get the input exception message from getMessage()", exMessage, sut.getMessage());
  }
  @Test
  public void testGetUpdatedObjects() throws Exception {
    SalesforceConnector connector = Mockito.spy(new SalesforceConnector());
    connector.setConnection(connection);
    when(connection.getConfig()).thenReturn(createConnectorConfig("userX"));
    connector.setObjectStoreHelper(objectStoreHelper);
    Calendar lastUpdateTime = createCalendar(4, 15);
    when(objectStoreHelper.getTimestamp("Account")).thenReturn(lastUpdateTime);
    setServerTime(connection, 5, 15);

    when(connection.getUpdated(anyString(), any(Calendar.class), any(Calendar.class)))
        .thenReturn(getUpdatedResult);
    Calendar latestDateCovered = createCalendar(5, 10);
    when(getUpdatedResult.getLatestDateCovered()).thenReturn(latestDateCovered);
    when(getUpdatedResult.getIds()).thenReturn(new String[] {"1", "3"});

    List<Map<String, Object>> updatedObjects = new ArrayList<Map<String, Object>>();
    doReturn(updatedObjects)
        .when(connector)
        .retrieve("Account", Arrays.asList("1", "3"), Arrays.asList("Id", "Name"));

    assertSame(
        updatedObjects, connector.getUpdatedObjects("Account", 60, Arrays.asList("Id", "Name")));

    verify(connection)
        .getUpdated(eq("Account"), startTimeCaptor.capture(), endTimeCaptor.capture());
    assertStartTime(4, 15);
    assertEndTime(5, 15);
    verify(objectStoreHelper).updateTimestamp(getUpdatedResult, "Account");
  }
 @Test
 public void canAnswerLastGestureDetector() throws Exception {
   GestureDetector newDetector = new GestureDetector(Robolectric.application, null);
   assertNotSame(newDetector, ShadowGestureDetector.getLastActiveDetector());
   newDetector.onTouchEvent(null);
   assertSame(newDetector, ShadowGestureDetector.getLastActiveDetector());
 }
 @Test
 public void should_return_values_of_property() {
   List<Long> ids = new ArrayList<Long>();
   ids.add(yoda.getId());
   when(propertySupport.propertyValues(propertyName, Long.class, employees)).thenReturn(ids);
   assertSame(ids, properties.from(employees));
 }
 @Test
 public void shouldUseTheConfigurationSet() {
   WroConfiguration configuration = new WroConfiguration();
   victim.setConfiguration(configuration);
   victim.contextInitialized(mockServletContextEvent);
   Assert.assertSame(configuration, victim.getConfiguration());
 }
 @Test
 public void shouldUseTheWroManagerSet() {
   WroManagerFactory managerFactory = new BaseWroManagerFactory();
   victim.setManagerFactory(managerFactory);
   victim.contextInitialized(mockServletContextEvent);
   Assert.assertSame(managerFactory, victim.getManagerFactory());
 }
  @Test
  public void testShouldSanitizeOutputHtml() throws MessagingException {
    // Create text/plain body
    TextBody body = new TextBody(BODY_TEXT);

    // Create message
    MimeMessage message = new MimeMessage();
    MimeMessageHelper.setBody(message, body);

    // Prepare fixture
    HtmlSanitizer htmlSanitizer = mock(HtmlSanitizer.class);
    MessageViewInfoExtractor messageViewInfoExtractor =
        new MessageViewInfoExtractor(context, null, htmlSanitizer);
    String value = "--sanitized html--";
    when(htmlSanitizer.sanitize(any(String.class))).thenReturn(value);

    // Extract text
    List<Part> outputNonViewableParts = new ArrayList<>();
    ArrayList<Viewable> outputViewableParts = new ArrayList<>();
    MessageExtractor.findViewablesAndAttachments(
        message, outputViewableParts, outputNonViewableParts);
    ViewableExtractedText viewableExtractedText =
        messageViewInfoExtractor.extractTextFromViewables(outputViewableParts);

    assertSame(value, viewableExtractedText.html);
  }
Beispiel #20
0
  @Test
  public void shouldSetAndGetAdapter() throws Exception {
    assertNull(pager.getAdapter());

    pager.setAdapter(adapter);
    assertSame(adapter, pager.getAdapter());
  }
  @Test
  public void testNamespaceValueInFilter() throws Exception {

    XResource resourceA = createResource(getArchiveA());
    verifyResouceA(resourceA);

    // Bundle-SymbolicName: org.osgi.test.cases.framework.resolver.tb5
    // Require-Capability: test; filter:="(&(test=aName)(version>=1.1.0))"
    final JavaArchive archiveB =
        ShrinkWrap.create(JavaArchive.class, "org.osgi.test.cases.framework.resolver.tb5");
    archiveB.setManifest(
        new Asset() {
          public InputStream openStream() {
            OSGiManifestBuilder builder = OSGiManifestBuilder.newInstance();
            builder.addBundleManifestVersion(2);
            builder.addBundleSymbolicName(archiveB.getName());
            builder.addRequiredCapabilities("test;filter:=\"(&(test=aName)(version>=1.1.0))\"");
            return builder.openStream();
          }
        });
    XResource resourceB = createResource(archiveB);

    // Install and resolve A, B
    installResources(resourceA, resourceB);
    List<XResource> mandatory = Arrays.asList(resourceA, resourceB);
    Map<Resource, List<Wire>> map = resolver.resolve(getResolveContext(mandatory, null));
    applyResolverResults(map);

    List<Wire> wires = map.get(resourceB);
    Assert.assertEquals(1, wires.size());
    Assert.assertEquals("test", wires.get(0).getCapability().getNamespace());
    Assert.assertEquals("aName", getNamespaceValue(wires.get(0).getCapability()));
    Assert.assertSame(resourceA, wires.get(0).getProvider());
  }
Beispiel #22
0
 @Override
 public void run() {
   assertSame(this, Thread.currentThread());
   try {
     while (true) {
       Request request = requestQueue.take();
       Object result;
       try {
         result = invokeMethod(request.methodName, request.arguments);
       } catch (ThreadDeath death) {
         return;
       } catch (InvocationTargetException exception) {
         responseQueue.put(new Response(request.methodName, null, exception.getTargetException()));
         continue;
       } catch (Throwable throwable) {
         responseQueue.put(new Response(request.methodName, null, throwable));
         continue;
       }
       responseQueue.put(new Response(request.methodName, result, null));
     }
   } catch (ThreadDeath death) {
     return;
   } catch (InterruptedException ignored) {
     // SynchronousQueue sometimes throws InterruptedException while the threads are stopping.
   } catch (Throwable uncaught) {
     this.uncaughtThrowable = uncaught;
   }
 }
 @Test
 public void testRemoteInstanceRetrieval() throws Exception {
   when(this.mockConfig.getServerType()).thenReturn("remote");
   SolrInstance instance = this.mocker.getComponentUnderTest().get();
   Assert.assertNotNull(instance);
   Assert.assertSame(this.remote, instance);
 }
  public static boolean isValidComplexCyclicGraph(SerializableDoublyLinkedNode actual) {

    assertNotNull(actual);
    if (actual == null) {
      return false;
    }

    int i = 0;
    SerializableDoublyLinkedNode currNode = actual;
    for (; i < 5; ++i) {
      assertEquals("n" + Integer.toString(i), currNode.getData());
      if (!currNode.getData().equals("n" + Integer.toString(i))) {
        return false;
      }

      SerializableDoublyLinkedNode nextNode = currNode.getRightChild();
      SerializableDoublyLinkedNode prevNode = currNode.getLeftChild();

      assertNotNull("next node", nextNode);
      assertNotNull("prev node", prevNode);
      if (nextNode == null || prevNode == null) {
        return false;
      }

      assertSame("A", currNode, nextNode.getLeftChild());
      if (nextNode.getLeftChild() != currNode) {
        return false;
      }

      assertSame("B", currNode, prevNode.getRightChild());
      if (prevNode.getRightChild() != currNode) {
        return false;
      }

      currNode = currNode.getRightChild();
      if (currNode == actual) {
        break;
      }
    }

    assertFalse("i = " + i, i >= 4);
    if (i >= 4) {
      return false;
    }

    return true;
  }
  @Test
  public void test_reset() throws Exception {
    detector.onTouchEvent(motionEvent);
    assertSame(motionEvent, shadowOf(detector).getOnTouchEventMotionEvent());

    shadowOf(detector).reset();
    assertNull(shadowOf(detector).getOnTouchEventMotionEvent());
  }
 public void test_executeCommands_RoverStateIsNorthandcommandIsRRL_roverStateIsSouth() {
   Position.setLimits(5, 5);
   Position position = new Position(1, 2);
   Rover rover = new Rover(position, 'N');
   CommandFactory cf = CommandFactory.init();
   cf.executeCommands("RRL", rover);
   assertSame('E', rover.getState());
 }
 public void test_executeCommand_commandIsR_TurnLeft() {
   Position.setLimits(5, 5);
   Position position = new Position(1, 2);
   Rover rover = new Rover(position, 'N');
   CommandFactory cf = CommandFactory.init();
   cf.executeCommand('L', rover);
   assertSame('W', rover.getState());
 }
Beispiel #28
0
 @Test
 public void shouldUseInitiallySetManagerEvenIfAnInvalidAppFactoryClassNameIsSet()
     throws Exception {
   when(mockFilterConfig.getInitParameter(ConfigConstants.managerFactoryClassName.name()))
       .thenReturn("Invalid value");
   victim.init(mockFilterConfig);
   Assert.assertSame(mockManagerFactory, victim.getWroManagerFactory());
 }
  @Test
  public void shouldReturnCandidateLocationWhenAllCriteriaPass() {
    addCriteria(passesCriteria);

    mockAccurateLocation(locationManager);
    Location location = bestLocationDelegate.getBestLastKnownLocation();
    assertSame(location, candidateLocation);
  }
 @Test
 public void should_use_AssertionErrorFactory_when_overriding_error_message_is_not_specified() {
   MyOwnAssertionError expectedError = new MyOwnAssertionError("[description] my message");
   Description description = new TestDescription("description");
   info.description(description);
   when(errorFactory.newAssertionError(description)).thenReturn(expectedError);
   AssertionError failure = failures.failure(info, errorFactory);
   assertSame(expectedError, failure);
 }