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:com.imaginary.home.cloud.CloudTest.java

private void setupRelay() throws Exception {
    if (pairingCode == null) {
        setupPairing();// ww w  .  j  a  v  a 2s.  c o m
    }
    HashMap<String, Object> map = new HashMap<String, Object>();
    long key = (System.currentTimeMillis() % 100000);

    map.put("pairingCode", pairingCode);
    map.put("name", "Test Controller " + key);

    HttpClient client = getClient();

    HttpPost method = new HttpPost(cloudAPI + "/relay");
    long timestamp = System.currentTimeMillis();

    method.addHeader("Content-Type", "application/json");
    method.addHeader("x-imaginary-version", VERSION);
    method.addHeader("x-imaginary-timestamp", String.valueOf(timestamp));

    //noinspection deprecation
    method.setEntity(new StringEntity((new JSONObject(map)).toString(), "application/json", "UTF-8"));

    HttpResponse response;
    StatusLine status;

    try {
        response = client.execute(method);
        status = response.getStatusLine();
    } catch (IOException e) {
        e.printStackTrace();
        throw new CommunicationException(e);
    }
    if (status.getStatusCode() == HttpServletResponse.SC_CREATED) {
        String json = EntityUtils.toString(response.getEntity());
        JSONObject keys = new JSONObject(json);

        relayKeyId = (keys.has("apiKeyId") && !keys.isNull("apiKeyId")) ? keys.getString("apiKeyId") : null;
        relayKeySecret = (keys.has("apiKeySecret") && !keys.isNull("apiKeySecret"))
                ? keys.getString("apiKeySecret")
                : null;
        pairingCode = null;
    } else {
        Assert.fail("Failed to setup pairing for relay keys (" + status.getStatusCode() + ": "
                + EntityUtils.toString(response.getEntity()));
    }
}

From source file:eu.stratosphere.pact.runtime.task.util.OutputEmitterTest.java

@Test
public void testNullKey() {
    // Test for IntValue
    @SuppressWarnings("unchecked")
    final TypeComparator<Record> intComp = new RecordComparatorFactory(new int[] { 0 },
            new Class[] { IntValue.class }).createComparator();
    final ChannelSelector<SerializationDelegate<Record>> oe1 = new OutputEmitter<Record>(
            ShipStrategyType.PARTITION_HASH, intComp);
    final SerializationDelegate<Record> delegate = new SerializationDelegate<Record>(
            new RecordSerializerFactory().getSerializer());

    Record rec = new Record(2);
    rec.setField(1, new IntValue(1));
    delegate.setInstance(rec);/*from   ww w. j a v a2 s  .  c  om*/

    try {
        oe1.selectChannels(delegate, 100);
    } catch (NullKeyFieldException re) {
        Assert.assertEquals(0, re.getFieldNumber());
        return;
    }
    Assert.fail("Expected a NullKeyFieldException.");
}

From source file:com.vmware.identity.idm.server.LocalOsIdentityProviderTest.java

@Test
public void TestAuth() throws Exception {
    // ---------------------
    // authenticate
    // ---------------------
    UserInfo user = _users.values().iterator().next();
    localOsProvider.authenticate(new PrincipalId(user.getName(), domainName), user.getPassword());
    if (providerHasAlias()) {
        localOsProvider.authenticate(new PrincipalId(user.getName(), domainAlias), user.getPassword());
    }//from www. ja  va 2  s .c o m

    try {
        localOsProvider.authenticate(new PrincipalId(user.getName(), domainName), "def");
        Assert.fail("Authenticate call expected to fail.");
    } catch (LoginException ex) // expected
    {
    }

    try {
        localOsProvider.authenticate(new PrincipalId(UUID.randomUUID().toString(), domainName), "def");
        Assert.fail("Authenticate call expected to fail.");
    } catch (LoginException ex) // expected
    {
    }
}

From source file:com.mnxfst.testing.server.cfg.TestPTestServerConfigurationParser.java

@Test
public void testParserServeConfigurationWithArrayHavingAnXMLDocHostnameEmpty() {

    try {/*from   ww w .  j a  v a2s .c o m*/
        byte[] test = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><ptest-server><hostname>   </hostname></ptest-server>"
                .getBytes();
        new PTestServerConfigurationParser().parseServerConfiguration(test);
        Assert.fail("Invalid file contents");
    } catch (ServerConfigurationFailedException e) {
    }
}

From source file:byps.test.TestRemoteStreams.java

private void internalTestThrowExOnRead(boolean throwEx, boolean throwError)
        throws InterruptedException, IOException {
    log.info("internalTestThrowExOnRead(throwEx=" + throwEx + ", throwError=" + throwError);

    Map<Integer, InputStream> streams = new TreeMap<Integer, InputStream>();
    for (int i = 0; i < 3; i++) {
        String str = "hello-" + i;
        byte[] buf = str.getBytes();
        InputStream istrm = new MyInputStream(buf, i == 1 && throwEx, i == 1 && throwError);
        streams.put(i, istrm);/*from w  w w .  j av a 2  s  .c  om*/
        log.info("strm[" + i + "]=" + str);
    }

    // An exception is thrown in HWireClient.
    try {
        log.info("setImages...");
        remote.setImages(streams, -1);
        Assert.fail("Exception expected");

        // The server waits for the stream in HActiveMessages.getIncomingOrOutgoingStream().
        // But the stream is never sent due to the text exception.
        // The client handles the exception by sending a cancel message.
        // This message interrupts the server. It needs at most HConstants.CLEANUP_MILLIS
        // until all streams of the message are internally released. 
        // Then the remote.setImages() will return.

    } catch (BException e) {
        log.info("setImages ex=" + e + ", OK");

        // The exception is an IOERROR, if the exception thrown in the stream is
        // received first.
        // This exception cancels the message and it might happen, that we receive
        // the CANCELLED
        // exception from first.
        TestUtils.assertTrue(log, "Exception Code",
                e.code == BExceptionC.IOERROR || e.code == BExceptionC.CANCELLED);
    }

    // All streams must have been closed
    log.info("streams must be closed");
    int nbOfClosed = 0;
    int keepMessageSeconds = ((int) HConstants.KEEP_MESSAGE_AFTER_FINISHED / 1000) + 1;
    for (int retry = 0; retry < 10 * keepMessageSeconds; retry++) {
        for (int i = 0; i < streams.size(); i++) {
            MyInputStream istrm = (MyInputStream) streams.get(i);
            log.info("InputStream[" + i + "].isClosed=" + istrm.isClosed);
            if (istrm.isClosed)
                nbOfClosed++;
        }
        if (nbOfClosed == streams.size())
            break;
        nbOfClosed = 0;
        Thread.sleep(100);
    }
    for (int i = 0; i < streams.size(); i++) {
        MyInputStream istrm = (MyInputStream) streams.get(i);
        TestUtils.assertEquals(log, "InputStream[" + i + "].isClosed, stream=" + istrm, true, istrm.isClosed);
    }

    log.info(")internalTestThrowExOnRead");
}

From source file:com.github.magicsky.sya.checkers.TestSourceReader.java

/**
 * Waits until the given file is indexed. Fails if this does not happen within the
 * given time.//from ww  w . java 2s.  c  o m
 *
 * @param file
 * @param maxmillis
 * @throws Exception
 * @since 4.0
 */
public static void waitUntilFileIsIndexed(IIndex index, IFile file, int maxmillis) throws Exception {
    long fileTimestamp = file.getLocalTimeStamp();
    IIndexFileLocation indexFileLocation = IndexLocationFactory.getWorkspaceIFL(file);

    long endTime = System.currentTimeMillis() + maxmillis;
    int timeLeft = maxmillis;
    while (timeLeft >= 0) {
        Assert.assertTrue(CCorePlugin.getIndexManager().joinIndexer(timeLeft, new NullProgressMonitor()));
        index.acquireReadLock();
        try {
            IIndexFile[] files = index.getFiles(ILinkage.CPP_LINKAGE_ID, indexFileLocation);
            if (files.length > 0 && areAllFilesNotOlderThan(files, fileTimestamp)) {
                Assert.assertTrue(
                        CCorePlugin.getIndexManager().joinIndexer(timeLeft, new NullProgressMonitor()));
                return;
            }
            files = index.getFiles(ILinkage.C_LINKAGE_ID, indexFileLocation);
            if (files.length > 0 && areAllFilesNotOlderThan(files, fileTimestamp)) {
                Assert.assertTrue(
                        CCorePlugin.getIndexManager().joinIndexer(timeLeft, new NullProgressMonitor()));
                return;
            }
        } finally {
            index.releaseReadLock();
        }

        Thread.sleep(50);
        timeLeft = (int) (endTime - System.currentTimeMillis());
    }
    Assert.fail("Indexing of " + file.getFullPath() + " did not complete in " + maxmillis / 1000. + " sec");
}

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

@Test
public void testCancelDataSinkTask() {

    super.initEnvironment(MEMORY_MANAGER_SIZE, NETWORK_BUFFER_SIZE);
    super.addInput(new InfiniteInputIterator(), 0);

    final DataSinkTask<Record> testTask = new DataSinkTask<Record>();
    Configuration stubParams = new Configuration();
    super.getTaskConfig().setStubParameters(stubParams);

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

    Thread taskRunner = new Thread() {
        @Override//ww w. ja  v a2  s.c  o m
        public void run() {
            try {
                testTask.invoke();
            } catch (Exception ie) {
                ie.printStackTrace();
                Assert.fail("Task threw exception although it was properly canceled");
            }
        }
    };
    taskRunner.start();

    TaskCancelThread tct = new TaskCancelThread(1, taskRunner, testTask);
    tct.start();

    try {
        tct.join();
        taskRunner.join();
    } catch (InterruptedException ie) {
        Assert.fail("Joining threads failed");
    }

    // assert that temp file was created
    File tempTestFile = new File(this.tempTestPath);
    Assert.assertTrue("Temp output file does not exist", tempTestFile.exists());

}

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

@Test
public void testCancelBlockCrossTaskInit() {

    int keyCnt = 10;
    int valCnt = 1;

    super.initEnvironment(1 * 1024 * 1024);
    super.addInput(new UniformPactRecordGenerator(keyCnt, valCnt, false), 1);
    super.addInput(new DelayingInfinitiveInputIterator(100), 2);
    super.addOutput(this.outList);

    final CrossTask<PactRecord, PactRecord, PactRecord> testTask = new CrossTask<PactRecord, PactRecord, PactRecord>();
    super.getTaskConfig().setLocalStrategy(LocalStrategy.NESTEDLOOP_BLOCKED_OUTER_FIRST);
    super.getTaskConfig().setMemorySize(1 * 1024 * 1024);

    super.registerTask(testTask, MockCrossStub.class);

    Thread taskRunner = new Thread() {
        @Override//from w  w w . jav  a2s . c  o m
        public void run() {
            try {
                testTask.invoke();
            } catch (Exception ie) {
                ie.printStackTrace();
                Assert.fail("Task threw exception although it was properly canceled");
            }
        }
    };
    taskRunner.start();

    TaskCancelThread tct = new TaskCancelThread(1, taskRunner, testTask);
    tct.start();

    try {
        tct.join();
        taskRunner.join();
    } catch (InterruptedException ie) {
        Assert.fail("Joining threads failed");
    }

}

From source file:com.mnxfst.testing.server.cfg.TestPTestServerConfigurationParser.java

@Test
public void testParserServeConfigurationWithArrayHavingAnXMLDocMissingPort() {

    try {/*from w  w w . j  a v a 2 s .  co  m*/
        byte[] test = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><ptest-server><hostname>test</hostname></ptest-server>"
                .getBytes();
        new PTestServerConfigurationParser().parseServerConfiguration(test);
        Assert.fail("Invalid file contents");
    } catch (ServerConfigurationFailedException e) {
    }
}

From source file:BQJDBC.QueryResultTest.Timeouttest.java

@Test
public void QueryResultTest09() {
    final String sql = "SELECT corpus, corpus_date FROM publicdata:samples.shakespeare GROUP BY corpus, corpus_date ORDER BY corpus_date DESC LIMIT 3;";
    final String description = "Shakespeare's 3 latest";
    String[][] expectation = new String[][] { { "kinghenryviii", "tempest", "winterstale" },
            { "1612", "1611", "1610" } };

    this.logger.info("Test number: 09");
    this.logger.info("Running query:" + sql);

    java.sql.ResultSet Result = null;
    try {// w  ww.ja v a  2  s.c  o 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());
    }
}