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:my.adam.smo.ServerCorrectnessTest.java

@Test
public void correctCommunication() {
    int arg1 = 1;
    int arg2 = 2;

    TestServices.NewUsefullTestService httpService = TestServices.NewUsefullTestService.newStub(httpChannel);
    TestServices.NewUsefullTestService socketService = TestServices.NewUsefullTestService
            .newStub(socketChannel);/*from ww  w .j  a v  a 2 s. c  om*/

    TestServices.NewUsefullTestService.BlockingInterface httpBlockingService = TestServices.NewUsefullTestService
            .newBlockingStub(httpBlockingChannel);
    TestServices.NewUsefullTestService.BlockingInterface socketBlockingService = TestServices.NewUsefullTestService
            .newBlockingStub(socketBlockingChannel);

    TestServices.In in = TestServices.In.newBuilder().setOperand1(arg1).setOperand2(arg2).build();

    httpService.doGoodJob(new DummyRpcController(), in, new RpcCallback<TestServices.Out>() {
        @Override
        public void run(TestServices.Out parameter) {
            Assert.assertEquals(result, parameter.getResult());
            logger.debug("httpAsyncCallDone");
        }
    });

    socketService.doGoodJob(new DummyRpcController(), in, new RpcCallback<TestServices.Out>() {
        @Override
        public void run(TestServices.Out parameter) {
            Assert.assertEquals(result, parameter.getResult());
            logger.debug("socketAsyncCallDone");
        }
    });

    try {
        Assert.assertEquals(result, httpBlockingService.doGoodJob(new DummyRpcController(), in).getResult());
        Assert.assertEquals(result, socketBlockingService.doGoodJob(new DummyRpcController(), in).getResult());
    } catch (ServiceException e) {
        logger.error("err", e);
        Assert.fail("call failed");
    }
}

From source file:com.smartitengineering.util.opensearch.io.impl.dom.DomIOImplTest.java

public void testMinimalWrite() {
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    OpenSearchDescriptorWriter writer = new OpenSearchDescriptorWriter(outputStream, MIN_DESC, true);
    try {//  w  w w .java 2 s  .c  om
        final long start = System.currentTimeMillis();
        writer.write();
        final long end = System.currentTimeMillis();
        System.out.println("Time taken to write: " + (end - start));
    } catch (IOException ex) {
        ex.printStackTrace();
        Assert.fail(ex.getMessage());
    }
    final String toString = outputStream.toString();
    System.out.println(toString);
    assertEquals(MIN, toString);
}

From source file:eu.trentorise.smartcampus.ac.provider.repository.persistence.AcDaoPersistenceImplTest.java

public void testCreateAuthority() {
    Authority auth = new Authority();
    auth.setName("new_auth");
    auth.setRedirectUrl("new_url");

    Assert.assertNull(dao.readAuthorityByName("new_auth"));
    dao.create(auth);//from   w ww . jav  a2 s . c  o m
    Assert.assertNotNull(dao.readAuthorityByName("new_auth"));

    auth = new Authority();
    auth.setName("new_auth1");
    auth.setRedirectUrl(AUTH_URL_PRESENT);
    try {
        dao.create(auth);
        Assert.fail("Exception not throw");
    } catch (IllegalArgumentException e) {
    }

    Assert.assertNull(dao.readAuthorityByName("new_auth1"));

    auth = new Authority();
    auth.setName(AUTH_NAME_PRESENT);
    auth.setRedirectUrl(AUTH_URL_NOT_PRESENT);
    try {
        dao.create(auth);
        Assert.fail("Exception not throw");
    } catch (IllegalArgumentException e) {
    }

    Assert.assertNull(dao.readAuthorityByName(AUTH_URL_NOT_PRESENT));

}

From source file:eu.cloud4soa.soa.git.GitProxyTest.java

@Test
public void testRegisterPublicKeyForUser() {

    User user = new User();
    user.setFullname("Test");
    user.setUriID(userInstanceUriId);/*from w  w w. java 2s  . c  om*/
    user.setUsername("testUsername");
    List<Object> arrayList = new ArrayList<Object>();
    arrayList.add(user);
    when(userdao.findBy("uriID", userInstanceUriId)).thenReturn(arrayList);

    String rsa_pub_key = "aabbcc";
    when(pubkeydao.findByUserAndPubkey(user, rsa_pub_key)).thenReturn(new ArrayList<PubKey>());

    String[] array = gitservices.registerPublicKeyForUser(userInstanceUriId, rsa_pub_key);
    Assert.assertEquals("0", array[0]);
    Assert.assertEquals("OK", array[1]);

    ArrayList<PubKey> arrayList1 = new ArrayList<PubKey>();
    arrayList1.add(new PubKey());
    when(pubkeydao.findByUserAndPubkey(user, rsa_pub_key)).thenReturn(arrayList1);

    array = gitservices.registerPublicKeyForUser(userInstanceUriId, rsa_pub_key);
    Assert.assertEquals("1", array[0]);

    try {
        String originalContent = FileUtils.readFileToString(new File(originalAuthFile));
        String contentModified = FileUtils.readFileToString(authTempFile);
        int compareResult = originalContent.compareTo(contentModified);
        Assert.assertNotSame("File contents are equals!", 0, compareResult);
    } catch (IOException ex) {
        logger.error("Error in reading the file: " + ex.getMessage());
        Assert.fail("Error in reading the file: " + ex.getMessage());
    }
}

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

@Test
public void testCancelCombineTaskSorting() {

    super.initEnvironment(3 * 1024 * 1024);
    super.addInput(new DelayingInfinitiveInputIterator(100), 1);
    super.addOutput(new NirvanaOutputList());

    final CombineTask<PactRecord> testTask = new CombineTask<PactRecord>();
    super.getTaskConfig().setLocalStrategy(LocalStrategy.COMBININGSORT);
    super.getTaskConfig().setMemorySize(3 * 1024 * 1024);
    super.getTaskConfig().setNumFilehandles(2);

    final int[] keyPos = 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), keyPos, keyClasses);

    super.registerTask(testTask, MockFailingCombiningReduceStub.class);

    Thread taskRunner = new Thread() {
        @Override/*w w w . j ava2  s  .  co  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:eu.stratosphere.nephele.services.iomanager.IOManagerITCase.java

/**
 * This test instantiates multiple channels and writes to them in parallel and re-reads the data in 
 * parallel. It is designed to check the ability of the IO manager to correctly handle multiple threads.
 *//*from  w w w  .  j a v  a 2  s.c  om*/
@Test
public void parallelChannelsTest() throws Exception {
    LOG.info("Starting parallel channels test.");

    final Random rnd = new Random(SEED);
    final AbstractInvokable memOwner = new DefaultMemoryManagerTest.DummyInvokable();

    Channel.ID[] ids = new Channel.ID[NUM_CHANNELS];
    BlockChannelWriter[] writers = new BlockChannelWriter[NUM_CHANNELS];
    BlockChannelReader[] readers = new BlockChannelReader[NUM_CHANNELS];
    ChannelWriterOutputView[] outs = new ChannelWriterOutputView[NUM_CHANNELS];
    ChannelReaderInputView[] ins = new ChannelReaderInputView[NUM_CHANNELS];

    int[] writingCounters = new int[NUM_CHANNELS];
    int[] readingCounters = new int[NUM_CHANNELS];

    // instantiate the channels and writers
    for (int i = 0; i < NUM_CHANNELS; i++) {
        ids[i] = this.ioManager.createChannel();
        writers[i] = this.ioManager.createBlockChannelWriter(ids[i]);

        List<MemorySegment> memSegs = this.memoryManager.allocatePages(memOwner,
                rnd.nextInt(NUMBER_OF_SEGMENTS - 2) + 2);
        outs[i] = new ChannelWriterOutputView(writers[i], memSegs, this.memoryManager.getPageSize());
    }

    Value val = new Value();

    // write a lot of values unevenly distributed over the channels
    int nextLogCount = 0;
    float nextLogFraction = 0.0f;

    LOG.info("Writing to channels...");
    for (int i = 0; i < NUMBERS_TO_BE_WRITTEN; i++) {

        if (i == nextLogCount) {
            LOG.info("... " + (int) (nextLogFraction * 100) + "% done.");
            nextLogFraction += 0.05;
            nextLogCount = (int) (nextLogFraction * NUMBERS_TO_BE_WRITTEN);
        }

        int channel = skewedSample(rnd, NUM_CHANNELS - 1);

        val.value = String.valueOf(writingCounters[channel]++);
        val.write(outs[channel]);
    }
    LOG.info("Writing done, flushing contents...");

    // close all writers
    for (int i = 0; i < NUM_CHANNELS; i++) {
        this.memoryManager.release(outs[i].close());
    }
    outs = null;
    writers = null;

    // instantiate the readers for sequential read
    LOG.info("Reading channels sequentially...");
    for (int i = 0; i < NUM_CHANNELS; i++) {
        List<MemorySegment> memSegs = this.memoryManager.allocatePages(memOwner,
                rnd.nextInt(NUMBER_OF_SEGMENTS - 2) + 2);

        LOG.info("Reading channel " + (i + 1) + "/" + NUM_CHANNELS + '.');

        final BlockChannelReader reader = this.ioManager.createBlockChannelReader(ids[i]);
        final ChannelReaderInputView in = new ChannelReaderInputView(reader, memSegs, false);
        int nextVal = 0;

        try {
            while (true) {
                val.read(in);
                int intValue = 0;
                try {
                    intValue = Integer.parseInt(val.value);
                } catch (NumberFormatException nfex) {
                    Assert.fail("Invalid value read from reader. Valid decimal number expected.");
                }
                Assert.assertEquals("Written and read values do not match during sequential read.", nextVal,
                        intValue);
                nextVal++;
            }
        } catch (EOFException eofex) {
            // expected
        }

        Assert.assertEquals("NUmber of written numbers differs from number of read numbers.",
                writingCounters[i], nextVal);

        this.memoryManager.release(in.close());
    }
    LOG.info("Sequential reading done.");

    // instantiate the readers
    LOG.info("Reading channels randomly...");
    for (int i = 0; i < NUM_CHANNELS; i++) {

        List<MemorySegment> memSegs = this.memoryManager.allocatePages(memOwner,
                rnd.nextInt(NUMBER_OF_SEGMENTS - 2) + 2);

        readers[i] = this.ioManager.createBlockChannelReader(ids[i]);
        ins[i] = new ChannelReaderInputView(readers[i], memSegs, false);
    }

    nextLogCount = 0;
    nextLogFraction = 0.0f;

    // read a lot of values in a mixed order from the channels
    for (int i = 0; i < NUMBERS_TO_BE_WRITTEN; i++) {

        if (i == nextLogCount) {
            LOG.info("... " + (int) (nextLogFraction * 100) + "% done.");
            nextLogFraction += 0.05;
            nextLogCount = (int) (nextLogFraction * NUMBERS_TO_BE_WRITTEN);
        }

        while (true) {
            final int channel = skewedSample(rnd, NUM_CHANNELS - 1);
            if (ins[channel] != null) {
                try {
                    val.read(ins[channel]);
                    int intValue;
                    try {
                        intValue = Integer.parseInt(val.value);
                    } catch (NumberFormatException nfex) {
                        Assert.fail("Invalid value read from reader. Valid decimal number expected.");
                        return;
                    }

                    Assert.assertEquals("Written and read values do not match.", readingCounters[channel]++,
                            intValue);

                    break;
                } catch (EOFException eofex) {
                    this.memoryManager.release(ins[channel].close());
                    ins[channel] = null;
                }
            }
        }

    }
    LOG.info("Random reading done.");

    // close all readers
    for (int i = 0; i < NUM_CHANNELS; i++) {
        if (ins[i] != null) {
            this.memoryManager.release(ins[i].close());
        }
        readers[i].closeAndDelete();
    }

    ins = null;
    readers = null;

    // check that files are deleted
    for (int i = 0; i < NUM_CHANNELS; i++) {
        File f = new File(ids[i].getPath());
        Assert.assertFalse("Channel file has not been deleted.", f.exists());
    }
}

From source file:org.jboss.shrinkwrap.jetty_6.test.JettyDeploymentIntegrationUnitTestCase.java

/**
 * Doesn't really test anything now; shows end-user view only
 *///w  w w.j  av a2 s.  c o m
@Test
public void requestWebapp() throws Exception {

    // Get an HTTP Client
    final HttpClient client = new DefaultHttpClient();

    // Make an HTTP Request, adding in a custom parameter which should be echoed back to us
    final String echoValue = "ShrinkWrap>Jetty Integration";
    final List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("jsp", PATH_JSP));
    params.add(new BasicNameValuePair("echo", echoValue));
    final URI uri = URIUtils.createURI("http", "localhost", HTTP_BIND_PORT,
            NAME_WEBAPP + SEPARATOR + servletClass.getSimpleName(), URLEncodedUtils.format(params, "UTF-8"),
            null);
    final HttpGet request = new HttpGet(uri);

    // Execute the request
    log.info("Executing request to: " + request.getURI());
    final HttpResponse response = client.execute(request);
    final HttpEntity entity = response.getEntity();
    if (entity == null) {
        Assert.fail("Request returned no entity");
    }

    // Read the result, ensure it's what we're expecting (should be the value of request param "echo")
    final BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent()));
    final String line = reader.readLine();
    Assert.assertEquals("Unexpected response from Servlet", echoValue, line);

}

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

@Test
public void testStream1CrossTask() {

    int keyCnt1 = 10;
    int valCnt1 = 1;

    int keyCnt2 = 100;
    int valCnt2 = 4;

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

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

    super.registerTask(testTask, MockCrossStub.class);

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

    int expCnt = keyCnt1 * valCnt1 * keyCnt2 * valCnt2;

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

    this.outList.clear();

}

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

@Test
public void testSortBoth2MatchTask() {

    int keyCnt1 = 20;
    int valCnt1 = 1;

    int keyCnt2 = 20;
    int valCnt2 = 1;

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

    MatchTask<PactRecord, PactRecord, PactRecord> testTask = new MatchTask<PactRecord, PactRecord, PactRecord>();
    super.getTaskConfig().setLocalStrategy(LocalStrategy.SORT_BOTH_MERGE);
    super.getTaskConfig().setMemorySize(6 * 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, MockMatchStub.class);

    try {/*from w ww. j a  v  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);

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

    this.outList.clear();

}

From source file:$.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/>/* ww  w  .  j  a  v a2  s.c om*/
     * 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"));

    }