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:BQJDBC.QueryResultTest.QueryResultTest.java

@Test
public void QueryResultTest07() {
    final String sql = "SELECT corpus, SUM(word_count) as w_c FROM publicdata:samples.shakespeare GROUP BY corpus HAVING w_c > 20000 ORDER BY w_c ASC LIMIT 5;";
    final String description = "A query which gets Shakespeare were there are more words then 20000 (only 5 is displayed ascending)";
    String[][] expectation = new String[][] {
            { "juliuscaesar", "twelfthnight", "titusandronicus", "kingjohn", "tamingoftheshrew" },
            { "21052", "21633", "21911", "21983", "22358" } };

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

    java.sql.ResultSet Result = null;
    try {/* w w w . ja v a  2s  . co m*/
        Result = QueryResultTest.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.mnxfst.testing.server.cfg.TestPTestServerConfigurationParser.java

@Test
public void testParserServeConfigurationWithArrayHavingNoXML() {

    try {//from w  w w.  j a  v  a2 s  .  com
        byte[] test = "this is by far no valid xml".getBytes();
        new PTestServerConfigurationParser().parseServerConfiguration(test);
        Assert.fail("Invalid file contents");
    } catch (ServerConfigurationFailedException e) {
        //
    }
}

From source file:com.aliyun.oss.perftests.PerftestRunner.java

private void calculateResult(final List<Long> latencyArray, OperationType type, int threadNum) {
    try {//ww w  .  ja va 2 s.c om
        int errNum = type == OperationType.PUT ? putErrNum : getErrNum;
        int totalNum = latencyArray.size() + errNum;
        if (totalNum <= 0) {
            return;
        }

        long thresholds[] = { 10, 50, 100, 1000, 3000, Long.MAX_VALUE };
        long thresholdNum[] = new long[6];
        long avgLatency = 0;
        Collections.sort(latencyArray);
        int j = 0;
        for (int i = 0; i < thresholds.length; i++) {
            for (; j < latencyArray.size() && latencyArray.get(j) <= thresholds[i]; j++) {
                thresholdNum[i]++;
                avgLatency += latencyArray.get(j);
            }
        }
        long passTime = endTime.getTime() - startTime.getTime();
        double qps = latencyArray.size() * 1000.0 / passTime;
        double errRate = errNum * 1.0 / totalNum;
        avgLatency = avgLatency / latencyArray.size();
        double throughput = qps * scenario.getContentLength() / 1048576;
        String contentStr = null;
        contentStr = String.format("TestType:%s\n", getTestName(type));
        contentStr += String.format("threads:%d, %s, %s\n", threadNum,
                getLengthString(scenario.getContentLength()),
                getTimeSpanString(scenario.getDurationInSeconds()));
        contentStr += String.format("Qps:%.1f Throughput:%.2fM AvgLatency:%dms\n", qps, throughput, avgLatency);
        contentStr += String.format("ErrorRate:%.2f\n", errRate);
        contentStr += "Latency Range:\n";
        contentStr += String.format("%d-%dms\t%.2f%s\n", 0, thresholds[0], thresholdNum[0] * 100.0 / totalNum,
                "%");
        for (int i = 0; i < thresholds.length - 2; i++) {
            contentStr += String.format("%d-%dms\t%.2f%s\n", thresholds[i], thresholds[i + 1],
                    thresholdNum[i + 1] * 100.0 / totalNum, "%");
        }
        contentStr += String.format("%dms+\t\t%.2f%s\n", thresholds[thresholds.length - 2],
                thresholdNum[thresholdNum.length - 1] * 100.0 / totalNum, "%");
        //print result
        System.out.printf("%s", contentStr);
        // write file
        writeResult(contentStr);
    } catch (Exception e) {
        log.error("Unexpected exception occurs when calculate result " + getTestName(type));
        Assert.fail(e.getMessage());
    }
}

From source file:org.deviceconnect.android.profile.restful.test.RESTfulDConnectTestCase.java

/**
 * HTTP??./*  w w  w . jav a  2  s  . c o  m*/
 * @param request HTTP
 * @param requiredAuth ????????????
 * @param count ?
 * @return ?
 */
protected final JSONObject sendRequest(final HttpUriRequest request, final boolean requiredAuth,
        final int count) {
    try {
        JSONObject response = sendRequestInternal(request, requiredAuth);
        int result = response.getInt(DConnectMessage.EXTRA_RESULT);
        if (result == DConnectMessage.RESULT_ERROR && count <= RETRY_COUNT) {
            if (!response.has(DConnectMessage.EXTRA_ERROR_CODE)) {
                return response;
            }
            int errorCode = response.getInt(DConnectMessage.EXTRA_ERROR_CODE);
            if (errorCode == DConnectMessage.ErrorCode.EXPIRED_ACCESS_TOKEN.getCode()) {
                mAccessToken = requestAccessToken(mClientId, mClientSecret, PROFILES);
                assertNotNull(mAccessToken);
                storeOAuthInfo(mClientId, mClientSecret, mAccessToken);

                URI uri = request.getURI();
                URIBuilder builder = new URIBuilder(uri);
                builder.addParameter(AuthorizationProfileConstants.PARAM_ACCESS_TOKEN, getAccessToken());

                final HttpUriRequest newRequest;
                if (request instanceof HttpGet) {
                    newRequest = new HttpGet(builder.toString());
                } else if (request instanceof HttpPost) {
                    HttpPost newPostRequest = new HttpPost(builder.toString());
                    newPostRequest.setEntity(((HttpPost) request).getEntity());
                    newRequest = newPostRequest;
                } else if (request instanceof HttpPut) {
                    HttpPut newPostRequest = new HttpPut(builder.toString());
                    newPostRequest.setEntity(((HttpPost) request).getEntity());
                    newRequest = newPostRequest;
                } else if (request instanceof HttpDelete) {
                    newRequest = new HttpDelete(builder.toString());
                } else {
                    fail("Invalid method is specified: " + request.getMethod());
                    return null;
                }
                return sendRequest(newRequest, requiredAuth, count + 1);
            }
        }
        return response;
    } catch (JSONException e) {
        Assert.fail("IOException: " + e.getMessage());
    }
    return null;
}

From source file:com.espertech.esper.regression.support.PatternTestHarness.java

private void checkResults(PatternTestStyle testStyle, String eventId) {
    // For each test descriptor, make sure the listener has received exactly the events expected
    int index = 0;
    log.debug(".checkResults Checking results for event " + eventId);

    for (EventExpressionCase descriptor : caseList.getResults()) {
        String expressionText = expressions[index].getText();

        LinkedHashMap<String, LinkedList<EventDescriptor>> allExpectedResults = descriptor.getExpectedResults();
        EventBean[] receivedResults = listeners[index].getLastNewData();
        index++;/*from   www  .j av  a  2  s  .  com*/

        // If nothing at all was expected for this event, make sure nothing was received
        if (!(allExpectedResults.containsKey(eventId))) {
            if ((receivedResults != null) && (receivedResults.length > 0)) {
                log.debug(".checkResults Incorrect result for style " + testStyle + " expression : "
                        + expressionText);
                log.debug(".checkResults Expected no results for event " + eventId + ", but received "
                        + receivedResults.length + " events");
                log.debug(".checkResults Received, have " + receivedResults.length + " entries");
                printList(receivedResults);
                TestCase.assertFalse(true);
            }
            continue;
        }

        LinkedList<EventDescriptor> expectedResults = allExpectedResults.get(eventId);

        // Compare the result lists, not caring about the order of the elements
        try {
            if (!(compareLists(receivedResults, expectedResults))) {
                log.debug(".checkResults Incorrect result for style " + testStyle + " expression : "
                        + expressionText);
                log.debug(".checkResults Expected size=" + expectedResults.size() + " received size="
                        + (receivedResults == null ? 0 : receivedResults.length));

                log.debug(".checkResults Expected, have " + expectedResults.size() + " entries");
                printList(expectedResults);
                log.debug(".checkResults Received, have "
                        + (receivedResults == null ? 0 : receivedResults.length) + " entries");
                printList(receivedResults);

                TestCase.assertFalse(true);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            Assert.fail("For statement '" + expressionText + "' failed to assert: " + ex.getMessage());
        }
    }
}

From source file:com.verisign.epp.codec.launch.EPPLaunchTst.java

/**
 * Tests the <code>EPPSignedMark</code> class. The tests include the
 * following:<br>/*  www.  j  a  v a2s  .c  o m*/
 * <br>
 * <ol>
 * <li>Test signing with private key, without certificates and verification
 * using public key
 * <li>Test signing with private key with certificates and verification
 * using CA certificate
 * <li>Test signed mark XML encode / decode with XML signature validation
 * <li>Test base64 encoding and decoding and XML signature validation
 * <li>Test signing and verification with revoked certificate
 * </ol>
 */
public void testSignedMark() {
    EPPCodecTst.printStart("testSignedMark");

    // Mark Owner
    EPPMarkContact holder = new EPPMarkContact();
    holder.setEntitlement(EPPMarkContact.ENTITLEMENT_OWNER);
    holder.setOrg("Example Inc.");
    holder.setEmail("holder@example.tld");
    // Address
    EPPMarkAddress holderAddress = new EPPMarkAddress();
    holderAddress.addStreet("123 Example Dr.");
    holderAddress.addStreet("Suite 100");
    holderAddress.setCity("Reston");
    holderAddress.setSp("VA");
    holderAddress.setPc("20190");
    holderAddress.setCc("US");
    holder.setAddress(holderAddress);

    // Mark Contact
    EPPMarkContact contact = new EPPMarkContact();
    contact.setType(EPPMarkContact.TYPE_OWNER);
    contact.setName("John Doe");
    contact.setOrg("Example Inc."); // Address
    EPPMarkAddress contactAddress = new EPPMarkAddress();
    contactAddress.addStreet("123 Example Dr.");
    contactAddress.addStreet("Suite 100");
    contactAddress.setCity("Reston");
    contactAddress.setSp("VA");
    contactAddress.setPc("20166-6503");
    contactAddress.setCc("US");
    contact.setAddress(contactAddress);
    contact.setVoice("+1.7035555555");
    contact.setVoiceExt("1234");
    contact.setFax("+1.7035555556");
    contact.setEmail("jdoe@example.tld");

    // Trademark
    EPPTrademark trademark = new EPPTrademark();
    trademark.setId("1234-2");
    trademark.setName("Example One");
    trademark.addHolder(holder);
    trademark.addContact(contact);
    trademark.setJurisdiction("US");
    trademark.addClass("35");
    trademark.addClass("36");
    trademark.addLabel("example-one");
    trademark.addLabel("exampleone");
    trademark.setGoodsAndServices("Dirigendas et eiusmodi featuring infringo in airfare et cartam servicia.");
    trademark.setRegNum("234235");
    trademark.setRegDate(new GregorianCalendar(2009, 8, 16).getTime());
    trademark.setExDate(new GregorianCalendar(2015, 8, 16).getTime());

    // Treaty or Statute
    EPPTreatyOrStatute treatyOrStatute = new EPPTreatyOrStatute();
    treatyOrStatute.setId("1234-2");
    treatyOrStatute.setName("Example One");
    treatyOrStatute.addHolder(holder);
    treatyOrStatute.addContact(contact);
    treatyOrStatute.addProtection(new EPPProtection("US", "Reston", "US"));
    treatyOrStatute.addLabel("example-one");
    treatyOrStatute.addLabel("exampleone");
    treatyOrStatute
            .setGoodsAndServices("Dirigendas et eiusmodi featuring infringo in airfare et cartam servicia.");
    treatyOrStatute.setRefNum("234235");
    treatyOrStatute.setProDate(new GregorianCalendar(2009, 8, 16).getTime());
    treatyOrStatute.setTitle("Example Title");
    treatyOrStatute.setExecDate(new GregorianCalendar(2015, 8, 16).getTime());

    // Court
    EPPCourt court = new EPPCourt();
    court.setId("1234-2");
    court.setName("Example One");
    court.addHolder(holder);
    court.addContact(contact);
    court.addLabel("example-one");
    court.addLabel("exampleone");
    court.setGoodsAndServices("Dirigendas et eiusmodi featuring infringo in airfare et cartam servicia.");
    court.setRefNum("234235");
    court.setProDate(new GregorianCalendar(2009, 8, 16).getTime());
    court.setCc("US");
    court.addRegions("Reston");
    court.setCourtName("Test Court");

    // Mark
    EPPMark mark = new EPPMark();
    mark.addTrademark(trademark);
    mark.addTreatyOrStatute(treatyOrStatute);
    mark.addCourt(court);

    EPPIssuer issuer = new EPPIssuer("2", "Example Inc.", "support@example.tld");
    issuer.setUrl("http://www.example.tld");
    issuer.setVoice("+1.7035555555");
    issuer.setVoiceExt("1234");

    /**
     * [1] Test signing with private key, without certificates and
     * verification using public key
     */
    EPPSignedMark signedMark = null;
    try {
        signedMark = new EPPSignedMark("1-2", issuer, new GregorianCalendar(2009, 8, 16).getTime(),
                new GregorianCalendar(2010, 8, 16).getTime(), mark);

        signedMark.sign(privateKey);
    } catch (EPPException ex) {
        Assert.fail("testSignedMark(): [1] Error signing the signed mark with private key: " + ex);
    }

    if (!signedMark.validate(publicKey)) {
        Assert.fail("testSignedMark(): [1] Error validating the signed mark using public key");
    }

    System.out.println("testSignedMark(): [1] Success");

    /**
     * [2] Test signing with private key with certificates and verification
     * using CA certificate
     */
    try {
        signedMark = new EPPSignedMark("2-2", issuer, new GregorianCalendar(2009, 8, 16).getTime(),
                new GregorianCalendar(2010, 8, 16).getTime(), mark);

        signedMark.sign(privateKey, certChain);
    } catch (EPPException ex) {
        Assert.fail(
                "testSignedMark(): [2] Error signing the signed mark with private key and certificates: " + ex);
    }

    // Create SMD of signed mark to vrsnSignedMark.smd
    try {
        byte[] smdXml = signedMark.encode();
        byte[] smdBase64 = Base64.encodeBase64(smdXml, true);
        FileOutputStream outStream = new FileOutputStream("vrsnSignedMark.smd");
        outStream.write("-----BEGIN ENCODED SMD-----\n".getBytes());
        outStream.write(smdBase64);
        outStream.write("-----END ENCODED SMD-----\n".getBytes());
        outStream.close();
    } catch (Exception ex) {
        Assert.fail("testSignedMark(): [2] Error creating vrsnSignedMark.smd SMD file for signed mark: " + ex);
    }

    // Create XML signed mark pretty printed
    try {
        FileOutputStream outStream = new FileOutputStream("vrsnSignedMark.xml");
        outStream.write(signedMark.toString().getBytes());
        outStream.close();
    } catch (Exception ex) {
        Assert.fail("testSignedMark(): [2] Error creating vrsnSignedMark.xml file for signed mark: " + ex);
    }

    if (!signedMark.validate(pkixParameters)) {
        Assert.fail("testSignedMark(): [2] Error validating with CA certificate");
    }

    System.out.println("testSignedMark(): [2] Success");

    /**
     * [3] Test signed mark XML encode / decode with XML signature
     * validation
     */

    // Test signed mark XML encode / decode
    EPPSignedMark signedMark2 = null;
    byte[] signedMarkXml = {};
    try {
        signedMarkXml = signedMark.encode();

        System.out.println("testSignedMark(): [3] Signed Mark XML 1 = [" + new String(signedMarkXml) + "]");

        signedMark2 = new EPPSignedMark(signedMarkXml);
    } catch (EPPException ex) {
        Assert.fail("testSignedMark(): [3] Error encoding and decoding from XML: " + ex);
    }

    byte[] signedMarkXml2 = {};
    try {
        signedMarkXml2 = signedMark2.encode();

        System.out.println("testSignedMark(): [3] Signed Mark XML 2 = [" + new String(signedMarkXml2) + "]");

        // Original signed mark matches decoded signed mark?
        //         int compareVal = (new String(signedMarkXml)).compareTo(new String(
        //               signedMarkXml2));
        //         if (compareVal != 0) {
        //            Assert.fail("testSignedMark(): [3] The signed mark XML is not equal, with compare value = "
        //                  + compareVal);
        //         }

        if (!signedMark2.validate(publicKey)) {
            Assert.fail(
                    "testSignedMark(): [3] Signed mark validation using public key error with encode/decode");
        }
        if (!signedMark2.validate(pkixParameters)) {
            Assert.fail(
                    "testSignedMark(): [3] Signed mark validation using PKIXParameters (trust store) error with encode/decode");
        }
    } catch (EPPException ex) {
        Assert.fail(
                "testSignedMark(): [3] Error validating the signed mark after encode / decode of XML: " + ex);
    }

    System.out.println("testSignedMark(): [3] Success");

    /**
     * [3.1] Test creating immutable signed mark from a signed mark and validating it.  
     */
    EPPSignedMark signedMark3 = null;
    byte[] signedMarkXml3 = {};
    try {
        signedMark3 = new EPPSignedMark(signedMarkXml);
    } catch (EPPException e) {
        Assert.fail("testSignedMark(): [3.1] Error creating decoding signed mark: " + e);
    }
    if (!signedMark3.validate(publicKey)) {
        Assert.fail("testSignedMark(): [3.1] Signed mark validation using public key error with encode/decode");
    }
    if (!signedMark2.validate(pkixParameters)) {
        Assert.fail(
                "testSignedMark(): [3.1] Signed mark validation using PKIXParameters (trust store) error with encode/decode");
    }

    /**
     * [4] Test base64 encoding and decoding and XML signature validation
     */
    EPPEncodedSignedMark encodedSignedMark = null;
    try {
        encodedSignedMark = new EPPEncodedSignedMark(signedMark);

        System.out.println(
                "testSignedMark(): [4] Signed Encoded Mark XML 1 = [" + new String(signedMarkXml) + "]");

        signedMark2 = new EPPSignedMark(signedMarkXml);
    } catch (EPPException ex) {
        Assert.fail("testSignedMark(): [4] Error encoding and decoding from XML: " + ex);
    }

    try {
        signedMarkXml2 = signedMark2.encode();

        System.out.println(
                "testSignedMark(): [4] Signed Encoded Mark XML 2 = [" + new String(signedMarkXml2) + "]");

        //         int compareVal = (new String(signedMarkXml)).compareTo(new String(
        //               signedMarkXml2));
        //         if (compareVal != 0) {
        //            Assert.fail("testSignedMark(): [4] The encoded signed mark XML is not equal, with compare value = "
        //                  + compareVal);
        //         }

        if (!signedMark2.validate(publicKey)) {
            Assert.fail(
                    "testSignedMark(): [4] Encoded signed mark validation using public key error with encode/decode");
        }
        if (!signedMark2.validate(pkixParameters)) {
            Assert.fail(
                    "testSignedMark(): [4] Signed mark validation using PKIXParameters (trust store) error with encode/decode");
        }
    } catch (EPPException ex) {
        Assert.fail(
                "testSignedMark(): [4] Error validating the signed mark after encode / decode of XML: " + ex);
    }

    System.out.println("testSignedMark(): [4] Success");

    /**
     * [5] Test signing and verification with revoked certificate
     */

    // Load the revoked certificate private key and certificate chain
    PrivateKey revokedPrivateKey = null;
    Certificate[] revokedCertChain = null;
    try {
        KeyStore.PrivateKeyEntry keyEntry = loadPrivateKeyEntry(KEYSTORE_REVOKED_FILENAME, KEYSTORE_KEY_ALIAS,
                KEYSTORE_PASSWORD);
        revokedPrivateKey = keyEntry.getPrivateKey();
        revokedCertChain = keyEntry.getCertificateChain();
    } catch (Exception ex) {
        Assert.fail("testSignedMark(): [5] Error loading removed private key and certificate chain: " + ex);
    }

    try {
        signedMark = new EPPSignedMark("5-2", issuer, new GregorianCalendar(2012, 8, 16).getTime(),
                new GregorianCalendar(2013, 8, 16).getTime(), mark);

        signedMark.sign(revokedPrivateKey);
    } catch (EPPException ex) {
        Assert.fail("testSignedMark(): [5] Error signing the signed mark with private key: " + ex);
    }

    if (signedMark.validate(pkixParameters)) {
        Assert.fail("testSignedMark(): [5] Validating signature with revoked certificate should have failed");
    }

    System.out.println("testSignedMark(): [5] Success");

    EPPCodecTst.printEnd("testSignedMark");
}

From source file:org.obiba.onyx.core.etl.participant.impl.ParticipantReaderTest.java

/**
 * Tests processing of an appointment list where a column is missing for a mandatory attribute (Birth Date).
 * //w w w . j a  v a2  s  .  co m
 * @throws IOException if the appointment list could not be read
 */
@Test
public void testProcessWithMissingMandatoryAttributeColumn() throws IOException {
    ParticipantReaderForTest reader = createParticipantReaderForTest(1, 2, 3, false,
            TEST_RESOURCES_DIR + "/appointmentList_missingMandatoryAttributeColumn.xls");

    try {
        reader.open(context);
        List<Participant> participants = new ArrayList<Participant>();

        while (reader.getRow() != null) {
            Participant participant = reader.read();
            if (participant != null)
                participants.add(participant);
        }
    } catch (Exception e) {
        String errorMessage = e.getMessage();
        Assert.assertEquals("Invalid worksheet; no column exists for mandatory field 'Birth Date'",
                errorMessage);
        return;
    }

    Assert.fail("Should have thrown an IllegalArgumentException");
}

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

@Test
public void testParserServeConfigurationWithArrayHavingABaseXMLDoc() {

    try {//  ww w  . ja va  2s .  c  om
        byte[] test = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>".getBytes();
        new PTestServerConfigurationParser().parseServerConfiguration(test);
        Assert.fail("Invalid file contents");
    } catch (ServerConfigurationFailedException e) {
        //
    }
}

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

@Test
public void testMissingKey() {
    // Test for IntValue
    @SuppressWarnings("unchecked")
    final TypeComparator<Record> intComp = new RecordComparatorFactory(new int[] { 1 },
            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(0);
    rec.setField(0, new IntValue(1));
    delegate.setInstance(rec);//from w w w . ja  v  a2  s  .  com

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

From source file:com.aliyun.oss.perftests.PerftestRunner.java

public void writeResult(final String contentStr) {
    FileWriter writer = null;/*from   ww w  . ja  v a 2  s .co  m*/
    try {
        writer = new FileWriter(fileName, true);
        writer.write(contentStr);
    } catch (IOException e) {
        // TODO: handle exception
        log.error(e.getMessage());
        Assert.fail(e.getMessage());
    } finally {
        try {
            if (writer != null) {
                writer.close();
            }
        } catch (Exception e2) {
            // TODO: handle exception
            log.error(e2.getMessage());
            Assert.fail(e2.getMessage());
        }
    }
}