@Test
 public void removeConnection() throws Exception {
   ConnectionFactoryRegistry connectionFactoryLocator = new ConnectionFactoryRegistry();
   ConnectionFactory<TestApi2> connectionFactory =
       new StubOAuth2ConnectionFactory("clientId", "clientSecret", THROW_EXCEPTION);
   connectionFactoryLocator.addConnectionFactory(connectionFactory);
   StubConnectionRepository connectionRepository = new StubConnectionRepository();
   connectionRepository.addConnection(
       connectionFactory.createConnection(
           new ConnectionData(
               "oauth2Provider", "provider1User1", null, null, null, null, null, null, null)));
   connectionRepository.addConnection(
       connectionFactory.createConnection(
           new ConnectionData(
               "oauth2Provider", "provider1User2", null, null, null, null, null, null, null)));
   assertEquals(2, connectionRepository.findConnections("oauth2Provider").size());
   ConnectController connectController =
       new ConnectController(connectionFactoryLocator, connectionRepository);
   List<DisconnectInterceptor<?>> interceptors = getDisconnectInterceptor();
   connectController.setDisconnectInterceptors(interceptors);
   MockMvc mockMvc = standaloneSetup(connectController).build();
   mockMvc
       .perform(delete("/connect/oauth2Provider/provider1User1"))
       .andExpect(redirectedUrl("/connect/oauth2Provider"));
   assertEquals(1, connectionRepository.findConnections("oauth2Provider").size());
   assertFalse(((TestConnectInterceptor<?>) (interceptors.get(0))).preDisconnectInvoked);
   assertFalse(((TestConnectInterceptor<?>) (interceptors.get(0))).postDisconnectInvoked);
   assertNull(((TestConnectInterceptor<?>) (interceptors.get(0))).connectionFactory);
   assertTrue(((TestConnectInterceptor<?>) (interceptors.get(1))).preDisconnectInvoked);
   assertTrue(((TestConnectInterceptor<?>) (interceptors.get(1))).postDisconnectInvoked);
   assertSame(
       connectionFactory, ((TestConnectInterceptor<?>) (interceptors.get(1))).connectionFactory);
 }
  @Test
  @TestLogging(value = "cluster.service:TRACE")
  public void testDeleteCreateInOneBulk() throws Exception {
    internalCluster()
        .startNodesAsync(
            2, Settings.builder().put(DiscoveryModule.DISCOVERY_TYPE_KEY, "zen").build())
        .get();
    assertFalse(client().admin().cluster().prepareHealth().setWaitForNodes("2").get().isTimedOut());
    prepareCreate("test")
        .setSettings(IndexMetaData.SETTING_AUTO_EXPAND_REPLICAS, true)
        .addMapping("type")
        .get();
    ensureGreen("test");

    // now that the cluster is stable, remove publishing timeout
    assertAcked(
        client()
            .admin()
            .cluster()
            .prepareUpdateSettings()
            .setTransientSettings(Settings.builder().put(DiscoverySettings.PUBLISH_TIMEOUT, "0")));

    Set<String> nodes = new HashSet<>(Arrays.asList(internalCluster().getNodeNames()));
    nodes.remove(internalCluster().getMasterName());

    // block none master node.
    BlockClusterStateProcessing disruption =
        new BlockClusterStateProcessing(nodes.iterator().next(), getRandom());
    internalCluster().setDisruptionScheme(disruption);
    logger.info("--> indexing a doc");
    index("test", "type", "1");
    refresh();
    disruption.startDisrupting();
    logger.info("--> delete index and recreate it");
    assertFalse(
        client()
            .admin()
            .indices()
            .prepareDelete("test")
            .setTimeout("200ms")
            .get()
            .isAcknowledged());
    assertFalse(
        prepareCreate("test")
            .setTimeout("200ms")
            .setSettings(IndexMetaData.SETTING_AUTO_EXPAND_REPLICAS, true)
            .get()
            .isAcknowledged());
    logger.info("--> letting cluster proceed");
    disruption.stopDisrupting();
    ensureGreen(TimeValue.timeValueMinutes(30), "test");
    assertHitCount(client().prepareSearch("test").get(), 0);
  }
Пример #3
0
  @Test
  public void testIsRunning() throws Exception {
    FitNesseContext context = FitNesseUtil.makeTestContext();
    FitNesse fitnesse = context.fitNesse.dontMakeDirs();

    assertFalse(fitnesse.isRunning());

    fitnesse.start();
    assertTrue(fitnesse.isRunning());

    fitnesse.stop();
    assertFalse(fitnesse.isRunning());
  }
Пример #4
0
  @Test
  public void testLateRegisterSuccessBindFailed() throws Exception {
    TestEventLoopGroup group = new TestEventLoopGroup();
    try {
      ServerBootstrap bootstrap = new ServerBootstrap();
      bootstrap.group(group);
      bootstrap.channelFactory(
          new ChannelFactory<ServerChannel>() {
            @Override
            public ServerChannel newChannel() {
              return new LocalServerChannel() {
                @Override
                public ChannelFuture bind(SocketAddress localAddress) {
                  // Close the Channel to emulate what NIO and others impl do on bind failure
                  // See https://github.com/netty/netty/issues/2586
                  close();
                  return newFailedFuture(new SocketException());
                }

                @Override
                public ChannelFuture bind(SocketAddress localAddress, ChannelPromise promise) {
                  // Close the Channel to emulate what NIO and others impl do on bind failure
                  // See https://github.com/netty/netty/issues/2586
                  close();
                  return promise.setFailure(new SocketException());
                }
              };
            }
          });
      bootstrap.childHandler(new DummyHandler());
      bootstrap.localAddress(new LocalAddress("1"));
      ChannelFuture future = bootstrap.bind();
      assertFalse(future.isDone());
      group.promise.setSuccess();
      final BlockingQueue<Boolean> queue = new LinkedBlockingQueue<Boolean>();
      future.addListener(
          new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
              queue.add(future.channel().eventLoop().inEventLoop(Thread.currentThread()));
              queue.add(future.isSuccess());
            }
          });
      assertTrue(queue.take());
      assertFalse(queue.take());
    } finally {
      group.shutdownGracefully();
      group.terminationFuture().sync();
    }
  }
    public void start() {
      WorkerProcessBuilder builder = workerFactory.create();
      builder.applicationClasspath(classPathRegistry.getClassPath("ANT").getAsFiles());
      builder.sharedPackages("org.apache.tools.ant");
      builder.getJavaCommand().systemProperty("test.system.property", "value");
      builder.getJavaCommand().environment("TEST_ENV_VAR", "value");
      builder.worker(action);

      if (mainClass != null) {
        builder.getJavaCommand().setMain(mainClass);
      }

      proc = builder.build();
      try {
        proc.start();
        assertFalse(startFails);
      } catch (ExecException e) {
        assertTrue(startFails);
        return;
      }
      proc.getConnection().addIncoming(TestListenerInterface.class, exceptionListener);
      if (serverAction != null) {
        serverAction.execute(proc.getConnection());
      }
    }
  @Test
  public void testDataSourceRepo() throws SQLException, RepositoryException {
    DataSourceWorkflowRepository repo = new DataSourceWorkflowRepository(ds);

    // test id 1
    WorkflowCondition wc = repo.getWorkflowConditionById("1");
    assertEquals(wc.getConditionName(), "CheckCond");
    WorkflowConditionInstance condInst =
        GenericWorkflowObjectFactory.getConditionObjectFromClassName(
            wc.getConditionInstanceClassName());
    Metadata m = new Metadata();
    m.addMetadata("Met1", "Val1");
    m.addMetadata("Met2", "Val2");
    m.addMetadata("Met3", "Val3");
    assertTrue(condInst.evaluate(m, wc.getTaskConfig()));

    // test id 2
    wc = repo.getWorkflowConditionById("2");
    assertEquals(wc.getConditionName(), "FalseCond");
    condInst =
        GenericWorkflowObjectFactory.getConditionObjectFromClassName(
            wc.getConditionInstanceClassName());
    assertFalse(condInst.evaluate(m, wc.getTaskConfig()));

    // test id 3
    wc = repo.getWorkflowConditionById("3");
    assertEquals(wc.getConditionName(), "TrueCond");
    condInst =
        GenericWorkflowObjectFactory.getConditionObjectFromClassName(
            wc.getConditionInstanceClassName());
    assertTrue(condInst.evaluate(m, wc.getTaskConfig()));
  }
 @Test
 public void shouldDetectChangedFilesByTimeStamp() throws Exception {
   detector =
       new FileChangeDetector() {
         @Override
         protected long getModificationTimestamp(File classFile) {
           return timestamp;
         }
       };
   detector.setClasspathProvider(classpath);
   assertFalse(
       "Should have found changed files on first run", detector.findChangedFiles().isEmpty());
   assertTrue("Timestamp is unchanged", detector.findChangedFiles().isEmpty());
   timestamp += 100;
   assertFalse("Timestamp changed", detector.findChangedFiles().isEmpty());
 }
Пример #8
0
  @Test
  public void testUpsert() throws Exception {
    createIndex();
    ensureGreen();

    UpdateResponse updateResponse =
        client()
            .prepareUpdate("test", "type1", "1")
            .setUpsert(XContentFactory.jsonBuilder().startObject().field("field", 1).endObject())
            .setScript("ctx._source.field += 1", ScriptService.ScriptType.INLINE)
            .execute()
            .actionGet();
    assertTrue(updateResponse.isCreated());

    for (int i = 0; i < 5; i++) {
      GetResponse getResponse = client().prepareGet("test", "type1", "1").execute().actionGet();
      assertThat(getResponse.getSourceAsMap().get("field").toString(), equalTo("1"));
    }

    updateResponse =
        client()
            .prepareUpdate("test", "type1", "1")
            .setUpsert(XContentFactory.jsonBuilder().startObject().field("field", 1).endObject())
            .setScript("ctx._source.field += 1", ScriptService.ScriptType.INLINE)
            .execute()
            .actionGet();
    assertFalse(updateResponse.isCreated());

    for (int i = 0; i < 5; i++) {
      GetResponse getResponse = client().prepareGet("test", "type1", "1").execute().actionGet();
      assertThat(getResponse.getSourceAsMap().get("field").toString(), equalTo("2"));
    }
  }
  @Test
  @LocalData
  @Issue("jenkinsci/docker-plugin/issues/263")
  public void load080Config() {
    final DockerCloud dock = (DockerCloud) j.getInstance().getCloud("someCloud");
    assertThat(dock.getTemplates(), hasSize(6));

    final DockerTemplate template = dock.getTemplate("somedomain.com:5000/dockerbuild");
    assertThat(template, notNullValue());

    assertThat(template.getLabelString(), equalTo("dockerbuild-local"));
    assertThat(template.remoteFs, equalTo("/home/jenkins"));

    final DockerTemplateBase tBase = template.getDockerTemplateBase();
    assertThat(tBase, notNullValue());

    assertThat(tBase.getDockerCommandArray()[0], equalTo("/usr/bin/start-jenkins-slave.sh"));
    assertThat(tBase.getDnsString(), equalTo("8.8.8.8"));

    assertThat(tBase.getVolumesString(), equalTo("/dev/log:/dev/log"));
    assertThat(asList(tBase.getVolumes()), hasSize(1));
    assertThat(tBase.getVolumes()[0], equalTo("/dev/log:/dev/log"));

    assertFalse(tBase.bindAllPorts);
    assertTrue(tBase.privileged);
  }
 @Test
 public void connect_OAuth1Provider() throws Exception {
   ConnectionFactoryRegistry connectionFactoryLocator = new ConnectionFactoryRegistry();
   ConnectionFactory<TestApi1> connectionFactory =
       new StubOAuth1ConnectionFactory("clientId", "clientSecret");
   connectionFactoryLocator.addConnectionFactory(connectionFactory);
   ConnectController connectController = new ConnectController(connectionFactoryLocator, null);
   List<ConnectInterceptor<?>> interceptors = getConnectInterceptor();
   connectController.setConnectInterceptors(interceptors);
   connectController.afterPropertiesSet();
   MockMvc mockMvc = standaloneSetup(connectController).build();
   mockMvc
       .perform(post("/connect/oauth1Provider"))
       .andExpect(
           redirectedUrl("https://someprovider.com/oauth/authorize?oauth_token=requestToken"))
       .andExpect(
           request()
               .sessionAttribute(
                   "oauthToken",
                   samePropertyValuesAs(new OAuthToken("requestToken", "requestTokenSecret"))));
   // Check for preConnect() only. The postConnect() won't be invoked until after callback
   TestConnectInterceptor<?> textInterceptor1 = (TestConnectInterceptor<?>) (interceptors.get(0));
   assertTrue(textInterceptor1.preConnectInvoked);
   assertEquals("oauth1Provider", textInterceptor1.connectionFactory.getProviderId());
   assertFalse(((TestConnectInterceptor<?>) (interceptors.get(1))).preConnectInvoked);
 }
  @Test
  public void testSubmitBenchmark() throws Exception {
    final int iters =
        between(1, 3); // we run this more than once to make sure metadata is cleaned up propperly
    for (int i = 0; i < iters; i++) {
      final BenchmarkRequest request =
          BenchmarkTestUtil.randomRequest(
              client(), indices, numExecutorNodes, competitionSettingsMap);
      logger.info(
          "--> Submitting benchmark - competitors [{}] iterations [{}]",
          request.competitors().size(),
          request.settings().iterations());
      final BenchmarkResponse response = client().bench(request).actionGet();

      assertThat(response, notNullValue());
      assertThat(response.state(), equalTo(BenchmarkResponse.State.COMPLETE));
      assertFalse(response.hasErrors());
      assertThat(response.benchmarkName(), equalTo(BENCHMARK_NAME));
      assertThat(response.competitionResults().size(), equalTo(request.competitors().size()));

      for (CompetitionResult result : response.competitionResults().values()) {
        assertThat(result.nodeResults().size(), equalTo(numExecutorNodes));
        validateCompetitionResult(
            result, competitionSettingsMap.get(result.competitionName()), true);
      }
    }
  }
Пример #12
0
  @Test
  public void existReturnsWhetherAnEntityCanBeLoaded() throws Exception {

    flushTestUsers();
    assertTrue(userDao.exists(id));
    assertFalse(userDao.exists(id * 27));
  }
Пример #13
0
 @Test
 public void testLateRegisterSuccess() throws Exception {
   TestEventLoopGroup group = new TestEventLoopGroup();
   try {
     ServerBootstrap bootstrap = new ServerBootstrap();
     bootstrap.group(group);
     bootstrap.channel(LocalServerChannel.class);
     bootstrap.childHandler(new DummyHandler());
     bootstrap.localAddress(new LocalAddress("1"));
     ChannelFuture future = bootstrap.bind();
     assertFalse(future.isDone());
     group.promise.setSuccess();
     final BlockingQueue<Boolean> queue = new LinkedBlockingQueue<Boolean>();
     future.addListener(
         new ChannelFutureListener() {
           @Override
           public void operationComplete(ChannelFuture future) throws Exception {
             queue.add(future.channel().eventLoop().inEventLoop(Thread.currentThread()));
             queue.add(future.isSuccess());
           }
         });
     assertTrue(queue.take());
     assertTrue(queue.take());
   } finally {
     group.shutdownGracefully();
     group.terminationFuture().sync();
   }
 }
 @Test
 public void oauth2Callback() throws Exception {
   ConnectionFactoryRegistry connectionFactoryLocator = new ConnectionFactoryRegistry();
   ConnectionFactory<TestApi2> connectionFactory =
       new StubOAuth2ConnectionFactory("clientId", "clientSecret");
   connectionFactoryLocator.addConnectionFactory(connectionFactory);
   StubConnectionRepository connectionRepository = new StubConnectionRepository();
   ConnectController connectController =
       new ConnectController(connectionFactoryLocator, connectionRepository);
   List<ConnectInterceptor<?>> interceptors = getConnectInterceptor();
   connectController.setConnectInterceptors(interceptors);
   connectController.afterPropertiesSet();
   MockMvc mockMvc = standaloneSetup(connectController).build();
   assertEquals(0, connectionRepository.findConnections("oauth2Provider").size());
   mockMvc
       .perform(get("/connect/oauth2Provider").param("code", "oauth2Code"))
       .andExpect(redirectedUrl("/connect/oauth2Provider"));
   List<Connection<?>> connections = connectionRepository.findConnections("oauth2Provider");
   assertEquals(1, connections.size());
   assertEquals("oauth2Provider", connections.get(0).getKey().getProviderId());
   // Check for postConnect() only. The preConnect() is only invoked during the initial portion of
   // the flow
   assertFalse(((TestConnectInterceptor<?>) (interceptors.get(0))).postConnectInvoked);
   TestConnectInterceptor<?> testInterceptor2 = (TestConnectInterceptor<?>) (interceptors.get(1));
   assertTrue(testInterceptor2.postConnectInvoked);
 }
Пример #15
0
  @Test
  public void testRefCount() throws IOException {
    final ShardId shardId = new ShardId(new Index("index"), 1);
    DirectoryService directoryService = new LuceneManagedDirectoryService(random());
    Store store =
        new Store(
            shardId,
            ImmutableSettings.EMPTY,
            directoryService,
            randomDistributor(directoryService),
            new DummyShardLock(shardId));
    int incs = randomIntBetween(1, 100);
    for (int i = 0; i < incs; i++) {
      if (randomBoolean()) {
        store.incRef();
      } else {
        assertTrue(store.tryIncRef());
      }
      store.ensureOpen();
    }

    for (int i = 0; i < incs; i++) {
      store.decRef();
      store.ensureOpen();
    }

    store.incRef();
    final AtomicBoolean called = new AtomicBoolean(false);
    store.close();
    for (int i = 0; i < incs; i++) {
      if (randomBoolean()) {
        store.incRef();
      } else {
        assertTrue(store.tryIncRef());
      }
      store.ensureOpen();
    }

    for (int i = 0; i < incs; i++) {
      store.decRef();
      store.ensureOpen();
    }

    store.decRef();
    assertThat(store.refCount(), Matchers.equalTo(0));
    assertFalse(store.tryIncRef());
    try {
      store.incRef();
      fail(" expected exception");
    } catch (AlreadyClosedException ex) {

    }
    try {
      store.ensureOpen();
      fail(" expected exception");
    } catch (AlreadyClosedException ex) {

    }
  }
  @Test
  public void REGT_015_delete_multi_value_attributes_twice() {
    createFullUser("dma");
    createUpdateUserWithMultiDeleteFields();

    updateUser();
    updateUser();

    assertTrue(isValuePartOfEntitlementList(testUser.getEntitlements(), "right2"));
    assertFalse(isValuePartOfEntitlementList(returnUser.getEntitlements(), "right2"));
    assertFalse(isValuePartOfEntitlementList(databaseUser.getEntitlements(), "right2"));
    assertTrue(isValuePartOfX509CertificateList(testUser.getX509Certificates(), "certificate01"));
    assertFalse(
        isValuePartOfX509CertificateList(returnUser.getX509Certificates(), "certificate01"));
    assertFalse(
        isValuePartOfX509CertificateList(databaseUser.getX509Certificates(), "certificate01"));
  }
 @Bean
 public LifecycleBean lifecycleBean() {
   // The following call to enigma() literally invokes the local
   // enigma() method, not a CGLIB proxied version, since these methods
   // are essentially factory bean methods.
   LifecycleBean bean = new LifecycleBean(enigma());
   assertFalse(bean.isInitialized());
   return bean;
 }
 @Test
 public void shouldRemoveKeyAndValueWithExistingNull() throws Exception {
   this.map.put(123, null);
   assertThat(this.map.remove(123, "456"), is(false));
   assertThat(this.map.get(123), is(nullValue()));
   assertThat(this.map.remove(123, null), is(true));
   assertFalse(this.map.containsKey(123));
   assertThat(this.map.isEmpty(), is(true));
 }
 @Test
 public void shouldRemoveKeyAndValue() throws Exception {
   this.map.put(123, "123");
   assertThat(this.map.remove(123, "456"), is(false));
   assertThat(this.map.get(123), is("123"));
   assertThat(this.map.remove(123, "123"), is(true));
   assertFalse(this.map.containsKey(123));
   assertThat(this.map.isEmpty(), is(true));
 }
  @Test
  public void typeInfoDoesNotEqualForGenericTypesWithDifferentParent() {

    TypeInformation<ConcreteWrapper> first = ClassTypeInformation.from(ConcreteWrapper.class);
    TypeInformation<AnotherConcreteWrapper> second =
        ClassTypeInformation.from(AnotherConcreteWrapper.class);

    assertFalse(first.getProperty("wrapped").equals(second.getProperty("wrapped")));
  }
 public void assertCanExecute() {
   assertNull(getExecutable());
   assertEquals(getJavaHome(), Jvm.current().getJavaHome());
   String defaultEncoding = getImplicitJvmSystemProperties().get("file.encoding");
   if (defaultEncoding != null) {
     assertEquals(Charset.forName(defaultEncoding), Charset.defaultCharset());
   }
   assertFalse(isRequireGradleHome());
 }
  @Test
  public void testMasterAwareExecution() throws Exception {
    Settings settings = settingsBuilder().put("discovery.type", "local").build();

    ListenableFuture<String> master = internalCluster().startNodeAsync(settings);
    ListenableFuture<String> nonMaster =
        internalCluster()
            .startNodeAsync(settingsBuilder().put(settings).put("node.master", false).build());
    master.get();
    ensureGreen(); // make sure we have a cluster

    ClusterService clusterService =
        internalCluster().getInstance(ClusterService.class, nonMaster.get());

    final boolean[] taskFailed = {false};
    final CountDownLatch latch1 = new CountDownLatch(1);
    clusterService.submitStateUpdateTask(
        "test",
        new ClusterStateUpdateTask() {
          @Override
          public ClusterState execute(ClusterState currentState) throws Exception {
            latch1.countDown();
            return currentState;
          }

          @Override
          public void onFailure(String source, Throwable t) {
            taskFailed[0] = true;
            latch1.countDown();
          }
        });

    latch1.await();
    assertTrue("cluster state update task was executed on a non-master", taskFailed[0]);

    taskFailed[0] = true;
    final CountDownLatch latch2 = new CountDownLatch(1);
    clusterService.submitStateUpdateTask(
        "test",
        new ClusterStateNonMasterUpdateTask() {
          @Override
          public ClusterState execute(ClusterState currentState) throws Exception {
            taskFailed[0] = false;
            latch2.countDown();
            return currentState;
          }

          @Override
          public void onFailure(String source, Throwable t) {
            taskFailed[0] = true;
            latch2.countDown();
          }
        });
    latch2.await();
    assertFalse("non-master cluster state update task was not executed", taskFailed[0]);
  }
 @Test
 public void getMergedAnnotationAttributesFromInterfaceImplementedBySuperclass() {
   Class<?> element = ConcreteClassWithInheritedAnnotation.class;
   String name = TX_NAME;
   AnnotationAttributes attributes = getMergedAnnotationAttributes(element, name);
   assertNull(
       "Should not find @Transactional on ConcreteClassWithInheritedAnnotation", attributes);
   // Verify contracts between utility methods:
   assertFalse(isAnnotated(element, name));
 }
Пример #24
0
 @org.junit.Test
 public void testInit() {
   assertThat(test.getTestFramework(), instanceOf(JUnitTestFramework.class));
   assertNull(test.getTestClassesDir());
   assertNull(test.getClasspath());
   assertNull(test.getTestResultsDir());
   assertNull(test.getTestReportDir());
   assertThat(test.getIncludes(), isEmpty());
   assertThat(test.getExcludes(), isEmpty());
   assertFalse(test.getIgnoreFailures());
 }
 public void waitForStop() {
   if (startFails) {
     return;
   }
   try {
     proc.waitForStop();
     assertFalse("Expected process to fail", stopFails);
   } catch (ExecException e) {
     assertTrue("Unexpected failure in worker process", stopFails);
   }
 }
 @Test
 public void hasMetaAnnotationTypesOnClassWithMetaDepth2() {
   assertTrue(hasMetaAnnotationTypes(ComposedTransactionalComponentClass.class, TX_NAME));
   assertTrue(
       hasMetaAnnotationTypes(
           ComposedTransactionalComponentClass.class, Component.class.getName()));
   assertFalse(
       hasMetaAnnotationTypes(
           ComposedTransactionalComponentClass.class,
           ComposedTransactionalComponent.class.getName()));
 }
  @Test
  public void testResolveAndRethrowFailureWithNoMissingDependenciesShouldDoNothing()
      throws IOException, ParseException {
    ModuleDescriptor moduleDescriptor = createAnonymousModuleDescriptor();
    prepareTestsThatRetrieveDependencies(moduleDescriptor);
    prepareResolveReport();
    ResolvedConfiguration configuration = ivyDependencyResolver.resolve(configurationStub);

    assertFalse(configuration.hasError());
    configuration.rethrowFailure();
  }
Пример #28
0
  @Test
  public void testEqualsContract() {
    IBAN x = IBAN.parse(VALID_IBAN);
    IBAN y = IBAN.parse(VALID_IBAN);
    IBAN z = IBAN.parse(VALID_IBAN);

    assertFalse("No object equals null", x.equals(null));
    assertTrue("An object equals itself", x.equals(x));
    assertTrue("Equality is symmetric", x.equals(y) && y.equals(x));
    assertTrue("Equality is transitive", x.equals(y) && y.equals(z) && x.equals(z));
    assertEquals("Equal objects have the same hash code", x.hashCode(), y.hashCode());
  }
 @Test
 public void exits_that_havent_been_added_are_not_exitable() {
   final Exit exit = mockery.mock(Exit.class);
   mockery.checking(
       new Expectations() {
         {
           ignoring(exit);
         }
       });
   Location l = createLocation();
   assertFalse(l.exitable(exit));
 }
Пример #30
0
  @Test
  public void testRemoveAndFailAllReentrance() {
    EmbeddedChannel channel = new EmbeddedChannel(new ChannelInboundHandlerAdapter());
    final PendingWriteQueue queue = new PendingWriteQueue(channel.pipeline().firstContext());

    ChannelPromise promise = channel.newPromise();
    promise.addListener(
        new ChannelFutureListener() {
          @Override
          public void operationComplete(ChannelFuture future) throws Exception {
            queue.removeAndFailAll(new IllegalStateException());
          }
        });
    queue.add(1L, promise);

    ChannelPromise promise2 = channel.newPromise();
    queue.add(2L, promise2);
    queue.removeAndFailAll(new Exception());
    assertFalse(promise.isSuccess());
    assertFalse(promise2.isSuccess());
    assertFalse(channel.finish());
  }