Example usage for junit.framework Assert fail

List of usage examples for junit.framework Assert fail

Introduction

In this page you can find the example usage for junit.framework Assert fail.

Prototype

static public void fail(String message) 

Source Link

Document

Fails a test with the given message.

Usage

From source file:eu.stratosphere.pact.runtime.task.ReduceTaskTest.java

@Test
public void testCombiningReduceTask() {
    final int keyCnt = 100;
    final int valCnt = 20;

    addInputComparator(this.comparator);
    setOutput(this.outList);
    getTaskConfig().setDriverStrategy(DriverStrategy.SORTED_GROUP_REDUCE);

    CombiningUnilateralSortMerger<Record> sorter = null;
    try {//from w  w w .ja v a2  s.  co  m
        sorter = new CombiningUnilateralSortMerger<Record>(new MockCombiningReduceStub(), getMemoryManager(),
                getIOManager(), new UniformRecordGenerator(keyCnt, valCnt, false), getOwningNepheleTask(),
                RecordSerializerFactory.get(), this.comparator.duplicate(), this.perSortMem, 4, 0.8f);
        addInput(sorter.getIterator());

        GroupReduceDriver<Record, Record> testTask = new GroupReduceDriver<Record, Record>();

        testDriver(testTask, MockCombiningReduceStub.class);
    } catch (Exception e) {
        LOG.debug(e);
        Assert.fail("Invoke method caused exception.");
    } finally {
        if (sorter != null) {
            sorter.close();
        }
    }

    int expSum = 0;
    for (int i = 1; i < valCnt; i++) {
        expSum += i;
    }

    Assert.assertTrue("Resultset size was " + this.outList.size() + ". Expected was " + keyCnt,
            this.outList.size() == keyCnt);

    for (Record record : this.outList) {
        Assert.assertTrue("Incorrect result", record.getField(1, IntValue.class).getValue() == expSum
                - record.getField(0, IntValue.class).getValue());
    }

    this.outList.clear();

}

From source file:io.fabric8.quickstarts.cxfcdi.CrmTest.java

/**
 * HTTP POST http://localhost:8181/cxf/crm/customerservice/customers is used to upload the contents of
 * the add_customer.json file to add a new customer to the system.
 * <p/>//w w  w. j a  va 2s  . com
 * On the server side, it matches the CustomerService's addCustomer() method
 *
 * @throws Exception
 */
@Test
public void postCustomerTestJson() throws IOException {
    LOG.info("Sent HTTP POST request to add customer");
    String inputFile = this.getClass().getResource("/add_customer.json").getFile();
    File input = new File(inputFile);
    PostMethod post = new PostMethod(CUSTOMER_SERVICE_URL);
    post.addRequestHeader("Accept", "application/json");
    RequestEntity entity = new FileRequestEntity(input, "application/json; charset=ISO-8859-1");
    post.setRequestEntity(entity);
    HttpClient httpclient = new HttpClient();
    String res = "";

    try {
        int result = httpclient.executeMethod(post);
        LOG.info("Response status code: " + result);
        LOG.info("Response body: ");
        res = post.getResponseBodyAsString();
        LOG.info(res);
    } catch (IOException e) {
        LOG.error("Error connecting to {}", CUSTOMER_SERVICE_URL);
        LOG.error(
                "You should build the 'cxf-cdi' quick start and deploy it to a local Fabric8 before running this test");
        LOG.error("Please read the README.md file in 'cxf-cdi' quick start root");
        Assert.fail("Connection error");
    } finally {
        // Release current connection to the connection pool once you are
        // done
        post.releaseConnection();
    }
    Assert.assertTrue(res.contains("Jack"));

}

From source file:BQJDBC.QueryResultTest.Timeouttest.java

@Test
public void QueryResultTest02() {
    final String sql = "SELECT corpus FROM publicdata:samples.shakespeare GROUP BY corpus ORDER BY corpus LIMIT 5";
    final String description = "The book names of shakespeare #GROUP_BY #ORDER_BY";
    String[][] expectation = new String[][] {
            { "1kinghenryiv", "1kinghenryvi", "2kinghenryiv", "2kinghenryvi", "3kinghenryvi" } };
    this.logger.info("Test number: 02");
    this.logger.info("Running query:" + sql);

    java.sql.ResultSet Result = null;
    try {/*from w w w  . j av a2  s . co m*/
        Result = Timeouttest.con.createStatement().executeQuery(sql);
    } catch (SQLException e) {
        this.logger.error("SQLexception" + e.toString());
        Assert.fail("SQLException" + e.toString());
    }
    Assert.assertNotNull(Result);

    this.logger.debug(description);

    HelperFunctions.printer(expectation);

    try {
        Assert.assertTrue("Comparing failed in the String[][] array",
                this.comparer(expectation, BQSupportMethods.GetQueryResult(Result)));
    } catch (SQLException e) {
        this.logger.error("SQLexception" + e.toString());
        Assert.fail(e.toString());
    }
}

From source file:com.amazonaws.http.AmazonHttpClientRequestTimeoutTest.java

@Test
public void testRequestTimerCancelledTask() throws IOException, InterruptedException {
    ClientConfiguration config = new ClientConfiguration().withRequestTimeout(5 * 1000).withMaxErrorRetry(0);
    HttpClientFactory httpClientFactory = new HttpClientFactory();
    HttpClient rawHttpClient = spy(httpClientFactory.createHttpClient(config));

    HttpResponseProxy responseProxy = createHttpResponseProxySpy();
    doReturn(responseProxy).when(rawHttpClient).execute(any(HttpRequestBase.class), any(HttpContext.class));

    String localhostEndpoint = "http://localhost:0";
    Request<?> request = new EmptyHttpRequest(localhostEndpoint, HttpMethodName.GET);

    AmazonHttpClient httpClient = new AmazonHttpClient(config, rawHttpClient, null);

    try {/*from w  ww . jav  a 2s  .  c  o m*/
        httpClient.execute(request, new NullResponseHandler(), new NullErrorResponseHandler(),
                new ExecutionContext());
        Assert.fail("Should have been unable to unmarshall the response!");
    } catch (AmazonClientException e) {
        Assert.assertTrue(e.getCause() instanceof RuntimeException);
        RuntimeException re = (RuntimeException) e.getCause();
        Assert.assertTrue(re.getMessage().contains("Unable to unmarshall response"));
    }

    /* Verify the response was buffered when enforcing the request timeout. */
    verify(responseProxy).setEntity(any(BufferedHttpEntity.class));

    /* Verify cancelled tasks are removed on demand and the core threads die out after the keep alive time. */
    ScheduledThreadPoolExecutor httpRequestTimer = httpClient.getHttpRequestTimer().getExecutor();
    Assert.assertEquals(0, httpRequestTimer.getCompletedTaskCount());
    Assert.assertEquals(0, httpRequestTimer.getQueue().size());
    Assert.assertEquals(1, httpRequestTimer.getPoolSize());
    Thread.sleep(httpRequestTimer.getKeepAliveTime(TimeUnit.MILLISECONDS) + 1000);
    Assert.assertEquals(0, httpRequestTimer.getPoolSize());

    httpClient.shutdown();
}

From source file:com.netflix.hystrix.contrib.metrics.controller.HystricsMetricsControllerTest.java

private void validateStream(EventInput eventInput, long waitTime) {
    long timeElapsed = System.currentTimeMillis();
    while (!eventInput.isClosed() && System.currentTimeMillis() - timeElapsed < waitTime) {
        final InboundEvent inboundEvent = eventInput.read();
        if (inboundEvent == null) {
            Assert.fail("Failed while verifying stream. Looks like connection has been closed.");
            break;
        }//w  ww.  ja  va  2s .  co  m
        String data = inboundEvent.readData(String.class);
        System.out.println(data);
        if (isStreamValid(data)) {
            return;
        }
    }
    Assert.fail("Failed while verifying stream");
}

From source file:de.hybris.vjdbc.VirtualDriverTest.java

@Test
public void testConnectWithAcceptedFlexUrlWithCustomDataSource() throws Exception {
    final Properties props = new Properties();

    Mockito.when(commandSinkProvider.create(
            Mockito.eq("http://localhost:9001/vjdbc/vjdbcServlet?tenant=my&flexMode=true"),
            Mockito.eq(OF_EMPTY_MAP))).thenThrow(new ExpectedException());

    try {//  w ww. ja v a  2s.com
        driver.connect(
                "jdbc:hybris:flexiblesearch:http://localhost:9001/vjdbc/vjdbcServlet?tenant=my,booSystem",
                props);
        Assert.fail("should have failed");
    } catch (SQLException e) {
        assertFirstLineOfSQLException("de.hybris.vjdbc.VirtualDriverTest$ExpectedException", e);
    }

    Mockito.verify(virtualConnectionBuilder).setProperties(props);
    Mockito.verify(virtualConnectionBuilder, Mockito.times(0)).setUrl("");
    Mockito.verify(virtualConnectionBuilder).setDataSourceString(Mockito.eq("booSystem"));
}

From source file:eu.stratosphere.pact.runtime.task.DataSinkTaskTest.java

@Test
public void testUnionDataSinkTask() {

    int keyCnt = 100;
    int valCnt = 20;

    super.initEnvironment(MEMORY_MANAGER_SIZE, NETWORK_BUFFER_SIZE);
    super.addInput(new UniformRecordGenerator(keyCnt, valCnt, 0, 0, false), 0);
    super.addInput(new UniformRecordGenerator(keyCnt, valCnt, keyCnt, 0, false), 0);
    super.addInput(new UniformRecordGenerator(keyCnt, valCnt, keyCnt * 2, 0, false), 0);
    super.addInput(new UniformRecordGenerator(keyCnt, valCnt, keyCnt * 3, 0, false), 0);

    DataSinkTask<Record> testTask = new DataSinkTask<Record>();

    super.registerFileOutputTask(testTask, MockOutputFormat.class, new File(tempTestPath).toURI().toString());

    try {/*from  w  w w . j av a  2 s .  c om*/
        testTask.invoke();
    } catch (Exception e) {
        LOG.debug(e);
        Assert.fail("Invoke method caused exception.");
    }

    File tempTestFile = new File(this.tempTestPath);

    Assert.assertTrue("Temp output file does not exist", tempTestFile.exists());

    FileReader fr = null;
    BufferedReader br = null;
    try {
        fr = new FileReader(tempTestFile);
        br = new BufferedReader(fr);

        HashMap<Integer, HashSet<Integer>> keyValueCountMap = new HashMap<Integer, HashSet<Integer>>(keyCnt);

        while (br.ready()) {
            String line = br.readLine();

            Integer key = Integer.parseInt(line.substring(0, line.indexOf("_")));
            Integer val = Integer.parseInt(line.substring(line.indexOf("_") + 1, line.length()));

            if (!keyValueCountMap.containsKey(key)) {
                keyValueCountMap.put(key, new HashSet<Integer>());
            }
            keyValueCountMap.get(key).add(val);
        }

        Assert.assertTrue("Invalid key count in out file. Expected: " + keyCnt + " Actual: "
                + keyValueCountMap.keySet().size(), keyValueCountMap.keySet().size() == keyCnt * 4);

        for (Integer key : keyValueCountMap.keySet()) {
            Assert.assertTrue("Invalid value count for key: " + key + ". Expected: " + valCnt + " Actual: "
                    + keyValueCountMap.get(key).size(), keyValueCountMap.get(key).size() == valCnt);
        }

    } catch (FileNotFoundException e) {
        Assert.fail("Out file got lost...");
    } catch (IOException ioe) {
        Assert.fail("Caught IOE while reading out file");
    } finally {
        if (br != null) {
            try {
                br.close();
            } catch (Throwable t) {
            }
        }
        if (fr != null) {
            try {
                fr.close();
            } catch (Throwable t) {
            }
        }
    }
}

From source file:com.atlassian.jira.rest.client.TestUtil.java

public static <E> void assertNotEquals(E a, E b) {
    if (a == null) {
        Assert.assertFalse("[" + a + "] not equals [" + b + "]", b.equals(a));
    } else if (b == null) {
        Assert.assertFalse("[" + a + "] not equals [" + b + "]", a.equals(b));
    } else if (a.equals(b) || b.equals(a)) {
        Assert.fail("[" + a + "] not equals [" + b + "]");
    }//from  ww w. j a v  a 2  s.c o  m
}

From source file:hk.hku.cecid.corvus.ws.EBMSMessageHistoryQuerySenderTest.java

@Test
public void testWildcardCriteriaData() throws Exception {

    EBMSMessageHistoryRequestData expectData = new EBMSMessageHistoryRequestData();
    expectData.setEndPoint(TEST_ENDPOINT);

    expectData.setMessageBox("inbox");
    expectData.setStatus("DL");

    expectData.setMessageId("%");
    expectData.setService("%%%%%%%%");
    expectData.setAction("__%%%");
    expectData.setConversationId("%%%\\\\");
    expectData.setCpaId("%_%");

    this.target = new EBMSMessageHistoryQuerySender(this.testClassLogger, expectData);
    try {//  w  w w  . j  av  a  2s .c o m
        this.target.run();
    } catch (Error err) {
        Assert.fail("Error should Not be thrown here.");
    }

    EBMSMessageHistoryRequestData actualData = getHttpRequestData();
    Assert.assertEquals(expectData.getMessageId(), actualData.getMessageId());
    Assert.assertEquals(expectData.getService(), actualData.getService());
    Assert.assertEquals(expectData.getAction(), actualData.getAction());
    Assert.assertEquals(expectData.getCpaId(), actualData.getCpaId());
    Assert.assertEquals(expectData.getConversationId(), actualData.getConversationId());

    Assert.assertTrue("inbox".equals(actualData.getMessageBox()));
    Assert.assertTrue("DL".equals(actualData.getStatus()));
}

From source file:com.redblackit.war.X509HttpClientTest.java

/**
 * Validate request fails (for bad certificates when server only supports
 * clientAuthMandatory e.g. GlassFish//  w  w w.  j a v a2s. com
 * 
 * @param httpClientToTest
 * @param url
 */
private void validateRequestFails(HttpClient httpClientToTest, String url) throws Exception {

    HttpGet request = new HttpGet(url);
    logger.info("request:" + request);
    try {
        HttpResponse response = httpClientToTest.execute(request);

        StatusLine status = response.getStatusLine();
        logger.error(status);

        BasicResponseHandler responseHandler = new BasicResponseHandler();
        String responseBody = responseHandler.handleResponse(response).trim();
        final int xmlstart = responseBody.indexOf("<?xml");
        if (xmlstart > 0) {
            responseBody = responseBody.substring(xmlstart);
        }
        logger.error("responseBody*>>");
        logger.error(responseBody);
        logger.error("responseBody*<<");

        Assert.fail("expected exception for bad certifiate:but got response");
    } catch (SSLPeerUnverifiedException pue) {
        logger.debug("expected exception", pue);
    }

}