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.mnxfst.testing.server.cfg.TestPTestServerConfigurationParser.java

@Test
public void testEvaluateNodeListWithNullDocumentInput() {
    try {// w  w w .  jav a  2  s. c o  m
        PTestServerConfigurationParser p = new PTestServerConfigurationParser();
        p.evaluateNodeList(p.xpathExpressionAllHandlerSettings, null);
        Assert.fail("Expression is not  null and document is null");
    } catch (XPathExpressionException e) {
    }
}

From source file:com.comcast.viper.flume2storm.spout.FlumeSpoutTest.java

/**
 * @throws Exception//from w w w .  j a  va2  s  . co m
 */
@Test
public void testIt() throws Exception {
    final MkClusterParam mkClusterParam = new MkClusterParam();
    mkClusterParam.setSupervisors(2);
    mkClusterParam.setPortsPerSupervisor(2);
    Config daemonConf = new Config();
    daemonConf.put(Config.STORM_LOCAL_MODE_ZMQ, false);
    mkClusterParam.setDaemonConf(daemonConf);
    Testing.withLocalCluster(new TestJob() {
        @Override
        public void run(final ILocalCluster cluster) throws Exception {
            // Building the test topology
            final TopologyBuilder builder = new TopologyBuilder();
            Set<F2SEventEmitter> eventEmitters = new HashSet<F2SEventEmitter>();
            eventEmitters.add(new BasicF2SEventEmitter());
            FlumeSpout<SimpleConnectionParameters, SimpleServiceProvider> flumeSpout = new FlumeSpout<SimpleConnectionParameters, SimpleServiceProvider>(
                    eventEmitters, flumeSpoutConfig);
            builder.setSpout("FlumeSpout", flumeSpout, 2);
            final TestBolt psBolt = new TestBolt();
            builder.setBolt("TestBolt", psBolt, 2).shuffleGrouping("FlumeSpout");

            // Starting topology
            final Config conf = new Config();
            conf.setNumWorkers(4);
            conf.registerSerialization(F2SEvent.class, F2SEventSerializer.class);
            conf.setFallBackOnJavaSerialization(false);
            cluster.submitTopology("TestTopology", conf, builder.createTopology());

            Thread senderThread = new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        // Waiting that topology is ready
                        LOG.info("Waiting that receptors connect...");
                        if (!TestUtils.waitFor(new TestCondition() {
                            @Override
                            public boolean evaluate() {
                                return eventSender1.getStats().getNbClients() == 2
                                        && eventSender2.getStats().getNbClients() == 2;
                            }
                        }, TEST_TIMEOUT)) {
                            Assert.fail(
                                    "Receptors failed to connect to senders in time (" + TEST_TIMEOUT + " ms)");
                        }
                        LOG.info("Receptors connected... sending events");
                        // Load balancing events between the 2 event senders
                        int batchNb = 0;
                        List<F2SEvent> batch = null;
                        for (F2SEvent event : eventsToSent) {
                            if (batch == null) {
                                batch = new ArrayList<F2SEvent>(BATCH_SIZE);
                                batchNb++;
                            }
                            batch.add(event);
                            if (batch.size() == BATCH_SIZE) {
                                SimpleEventSender eventSender = batchNb % 2 == 0 ? eventSender1 : eventSender2;
                                eventSender.send(batch);
                                batch = null;
                            }
                        }
                        LOG.info("Sent {} events", eventsToSent.size());
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
            senderThread.start();

            // Waiting that it's done
            if (!TestUtils.waitFor(new TestCondition() {
                @Override
                public boolean evaluate() {
                    LOG.debug("Received so far: " + MemoryStorage.getInstance().getReceivedEvents().size());
                    return MemoryStorage.getInstance().getReceivedEvents().size() >= NB_EVENTS * 2;
                }
            }, TEST_TIMEOUT)) {
                Assert.fail("Failed to receive all events in time (" + TEST_TIMEOUT + " ms)");
            }

            // Testing results:
            // 1 - Each sender have sent half of the events
            assertThat(eventSender1.getStats().getNbEventsIn()).isEqualTo(NB_EVENTS);
            assertThat(eventSender1.getStats().getNbEventsOut()).isEqualTo(NB_EVENTS);
            assertThat(eventSender2.getStats().getNbEventsIn()).isEqualTo(NB_EVENTS);
            assertThat(eventSender2.getStats().getNbEventsOut()).isEqualTo(NB_EVENTS);
            // TODO 2 - Each spout have received half of the events
            // 2 - We received all the events correctly
            // Programming note: I used SortedSet and iterate over the 2 sets to
            // speed up the comparison
            assertThat(MemoryStorage.getInstance().getReceivedEvents().size()).isEqualTo(eventsToSent.size());
            Iterator<F2SEvent> it1 = eventsToSent.iterator();
            Iterator<F2SEvent> it2 = MemoryStorage.getInstance().getReceivedEvents().iterator();
            while (it1.hasNext() && it2.hasNext()) {
                assertThat(it1.next()).isEqualTo(it2.next());
            }
        }
    });
}

From source file:com.redhat.demo.CrmTest.java

/**
 * HTTP POST http://localhost:8181/cxf/crm/customerservice/customers is used to upload the contents of
 * the add_customer.xml file to add a new customer to the system.
 * <p/>/*  w w  w  . j  av a2  s  .c  om*/
 * On the server side, it matches the CustomerService's addCustomer() method
 *
 * @throws Exception
 */
@Test
public void postCustomerTest() throws IOException {
    LOG.info("Sent HTTP POST request to add customer");
    String inputFile = this.getClass().getResource("/add_customer.xml").getFile();
    File input = new File(inputFile);
    PostMethod post = new PostMethod(CUSTOMER_SERVICE_URL);
    post.addRequestHeader("Accept", "application/xml");
    RequestEntity entity = new FileRequestEntity(input, "application/xml; 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 'rest' quick start and deploy it to a local Fabric8 before running this test");
        LOG.error("Please read the README.md file in 'rest' 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:com.cubusmail.server.user.UserAccountDaoTest.java

@Test
public void testUpdateAddressFolders() {

    try {//from   w w  w . j a  v  a  2s  . c  om
        List<AddressFolder> folders = (List<AddressFolder>) this.applicationContext
                .getBean("testAddressFolders");
        for (AddressFolder folder : folders) {
            folder.setUserAccount(this.testUserAccount);
            this.userAccountDao.saveAddressFolder(folder);
        }

        folders.get(0).setName("NewName");
        this.userAccountDao.saveAddressFolder(folders.get(0));

        List<AddressFolder> updatedFolders = this.userAccountDao.retrieveAddressFolders(this.testUserAccount);
        Assert.assertNotNull(updatedFolders);
        Assert.assertTrue(updatedFolders.size() > 0);
        Assert.assertEquals(updatedFolders.get(0).getName(), folders.get(0).getName());
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        Assert.fail(e.getMessage());
    }
}

From source file:org.ednovo.gooru.factory.CoreCassandraDaoImpl.java

@Override
public Map<String, String> readKeys(String rowKeys, ColumnFamilyType columnFamilyType) {

    OperationResult<Rows<String, String>> result;
    Map<String, String> rowValue = new HashMap<String, String>();
    try {/*from   w  w w .ja  v  a2s . co m*/
        result = (OperationResult<Rows<String, String>>) getCassandraFactory().getKeyspace()
                .prepareQuery(map.get(columnFamilyType.getName())).getAllRows().setRowLimit(100)
                .withColumnRange(new RangeBuilder().setMaxSize(10).build())
                .setExceptionCallback(new ExceptionCallback() {
                    @Override
                    public boolean onException(ConnectionException e) {
                        try {
                            Thread.sleep(1000);
                            Assert.fail(e.getMessage());
                        } catch (InterruptedException i) {
                        }
                        return true;
                    }
                }).execute();
        Rows<String, String> record = result.getResult();
        for (Row<String, String> entry : record) {
            log.info("Row :" + entry.getKey() + " " + entry.getColumns().size());
            rowValue.put(entry.getKey(), entry.getColumns().size() + "");
        }
        return rowValue;
    } catch (ConnectionException e) {
        Assert.fail();
    }
    return null;
}

From source file:com.streamreduce.util.JiraClientIT.java

/**
 * Tests {@link JiraClient#getActivity(java.util.Set)}.
 *
 * @throws Exception if anything goes wrong
 *//*from   ww w .  j a v  a 2s  .c  o m*/
@Test
public void testJiraGetActivityParts() throws Exception {
    int maxResults = 100;
    List<Entry> testProjectActivity = jiraClient.getActivity(monitoredProjects, maxResults);

    Assert.assertTrue(testProjectActivity.size() > 0 && testProjectActivity.size() <= maxResults);

    for (Entry activity : testProjectActivity) {
        org.apache.abdera.model.Element activityObjectElement = activity
                .getFirstChild(new QName("http://activitystrea.ms/spec/1.0/", "object", "activity"));
        String projectKey = jiraClient.getProjectKeyOfEntry(activityObjectElement, monitoredProjects);

        // Prepare the inventory item
        inventoryItem.setExternalId(projectKey);

        Map<String, Object> activityParts = jiraClient.getPartsForActivity(inventoryItem, activity);

        Assert.assertNotNull(activityParts);

        String title = (String) activityParts.get("title");
        String content = (String) activityParts.get("content");
        Set<String> hashtags = (Set<String>) activityParts.get("hashtags");
        int expectedHashtagCount = 2; // #jira and #[project.key] is always expected

        try {
            Assert.assertNotNull(title);
            Assert.assertTrue(hashtags.contains("#" + projectKey.toLowerCase()));
            Assert.assertTrue(hashtags.contains("#jira"));

            // No good way to test content since it can be null a few different ways

            if (hashtags.contains("#issue")) {
                // Issue related tests
                expectedHashtagCount += 4; // #issue #[issue-type] #[issue-priority] #[issue-status]

                // There is no good way to test the actual issue hashtags because they could outdated
            } else if (hashtags.contains("#source")) {
                // Source related tests
                expectedHashtagCount += 2; // #source #[activity]

                Assert.assertFalse(hashtags.contains("#file")); // This is an ignored hashtag
                Assert.assertTrue(hashtags.contains("#changeset") || hashtags.contains("#review"));
            } else if (hashtags.contains("#wiki")) {
                // Wiki related tests
                if (!hashtags.contains("#blog") && !hashtags.contains("#page")) {
                    expectedHashtagCount += 1; // #wiki
                } else {
                    expectedHashtagCount += 2; // #wiki #[target]
                }

                Assert.assertFalse(hashtags.contains("#space")); // This is an ignored hashtag
                Assert.assertFalse(hashtags.contains("#article")); // This is an ignored hashtag
                Assert.assertFalse(hashtags.contains("#file")); // This is an ignored hashtag
            } else {
                Assert.fail("All Jira activity hashtags should contain at least one of he following: "
                        + "#issue, #source or #wiki");
            }

            // For comments and attachments, expected hashtags is one extra
            if (hashtags.contains("#comment") || hashtags.contains("#attachment")) {
                expectedHashtagCount += 1;
            }

            if (hashtags.contains("#issue") || (hashtags.contains("#wiki") && !hashtags.contains("#blog"))) {
                Assert.assertTrue(hashtags.size() >= expectedHashtagCount);
            } else {
                Assert.assertEquals(expectedHashtagCount, hashtags.size());
            }
        } catch (AssertionFailedError e) {
            // Add some extra output to make debugging easier
            System.out.println("Problematic title: " + activity.getTitle());
            System.out.println("Hashtags (Expected: " + expectedHashtagCount + "):");
            for (String hashtag : hashtags) {
                System.out.println("  " + hashtag);
            }
            throw e;
        }
    }
}

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.xml file to add a new customer to the system.
 * <p/>// w  ww . j  a v a2  s  . c  o  m
 * On the server side, it matches the CustomerService's addCustomer() method
 *
 * @throws Exception
 */
@Test
public void postCustomerTest() throws IOException {
    LOG.info("Sent HTTP POST request to add customer");
    String inputFile = this.getClass().getResource("/add_customer.xml").getFile();
    File input = new File(inputFile);
    PostMethod post = new PostMethod(CUSTOMER_SERVICE_URL);
    post.addRequestHeader("Accept", "application/xml");
    RequestEntity entity = new FileRequestEntity(input, "application/xml; 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:com.hoccer.tools.TestHelper.java

public static void assertMatches(String message, String regexp, String measured) {
    if (!measured.matches(regexp)) {
        Assert.fail(message + " but '" + regexp + "' does not match '" + measured + "'");
    }/*from  ww w.  j a va 2s . com*/
}

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

@Test
public void testSortFirstCoGroupTask() {

    int keyCnt1 = 200;
    int valCnt1 = 2;

    int keyCnt2 = 200;
    int valCnt2 = 4;

    super.initEnvironment(5 * 1024 * 1024);
    super.addInput(new UniformPactRecordGenerator(keyCnt1, valCnt1, false), 1);
    super.addInput(new UniformPactRecordGenerator(keyCnt2, valCnt2, true), 2);
    super.addOutput(this.outList);

    CoGroupTask<PactRecord, PactRecord, PactRecord> testTask = new CoGroupTask<PactRecord, PactRecord, PactRecord>();
    super.getTaskConfig().setLocalStrategy(LocalStrategy.SORT_FIRST_MERGE);
    super.getTaskConfig().setMemorySize(5 * 1024 * 1024);
    super.getTaskConfig().setNumFilehandles(4);

    final int[] keyPos1 = new int[] { 0 };
    final int[] keyPos2 = new int[] { 0 };
    @SuppressWarnings("unchecked")
    final Class<? extends Key>[] keyClasses = (Class<? extends Key>[]) new Class[] { PactInteger.class };

    PactRecordComparatorFactory.writeComparatorSetupToConfig(super.getTaskConfig().getConfiguration(),
            super.getTaskConfig().getPrefixForInputParameters(0), keyPos1, keyClasses);
    PactRecordComparatorFactory.writeComparatorSetupToConfig(super.getTaskConfig().getConfiguration(),
            super.getTaskConfig().getPrefixForInputParameters(1), keyPos2, keyClasses);

    super.registerTask(testTask, MockCoGroupStub.class);

    try {/* w  w  w .j  av a2s. c o  m*/
        testTask.invoke();
    } catch (Exception e) {
        LOG.debug(e);
        Assert.fail("Invoke method caused exception.");
    }

    int expCnt = valCnt1 * valCnt2 * Math.min(keyCnt1, keyCnt2) + Math.max(keyCnt1, keyCnt2)
            - Math.min(keyCnt1, keyCnt2);

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

    this.outList.clear();

}

From source file:cz.PA165.vozovyPark.dao.ServiceIntervalDAOTest.java

/**
 *
 *//*from  w  w  w.jav a2s.c om*/
@Test
public void testValidFindAll() {
    try {
        Vehicle mercedes = ServiceIntervalDAOTest.getVehicle("Mercedes", 20000, "R4 Diesel", "C",
                UserClassEnum.PRESIDENT, "2f-4a7i-121245", 2009);
        this.vehicleDao.createVehicle(mercedes);

        ServiceInterval interval1 = ServiceIntervalDAOTest.getServiceInterval(new ArrayList<Date>(),
                "Prehodeni koles", 7, mercedes);
        ServiceInterval interval2 = ServiceIntervalDAOTest.getServiceInterval(new ArrayList<Date>(),
                "Vymena oleje", 7, mercedes);
        serviceIntervalDAO.createSI(interval1);
        serviceIntervalDAO.createSI(interval2);

        em.getTransaction().begin();
        List<ServiceInterval> intervals = serviceIntervalDAO.findAll();
        em.getTransaction().commit();
        if (intervals.isEmpty()) {
            Assert.fail("Any entities were loaded from databse!");
        }
    } catch (Exception ex) {
        Assert.fail("Unexpected exception was throwed: " + ex + " " + ex.getMessage());
    }
}