@Test public void testSingleAsmMethod() { String[] lines = SINGLE_ASSEMBLY_METHOD; performAssemblyParsingOn(lines); IMetaMember member = map.get("org.adoptopenjdk.jitwatch.demo.SandboxTestLoad main ([Ljava.lang.String;)V"); assertNotNull(member); AssemblyMethod assemblyMethod = member.getAssembly(); assertNotNull(assemblyMethod); List<AssemblyBlock> asmBlocks = assemblyMethod.getBlocks(); assertEquals(1, asmBlocks.size()); AssemblyBlock block = asmBlocks.get(0); List<AssemblyInstruction> instructions = block.getInstructions(); assertEquals(5, instructions.size()); }
@Test public void testResponseWithContentLength() { EmbeddedChannel ch = new EmbeddedChannel(new HttpResponseDecoder()); ch.writeInbound( Unpooled.copiedBuffer( "HTTP/1.1 200 OK\r\n" + "Content-Length: 10\r\n" + "\r\n", CharsetUtil.US_ASCII)); byte[] data = new byte[10]; for (int i = 0; i < data.length; i++) { data[i] = (byte) i; } ch.writeInbound(Unpooled.wrappedBuffer(data, 0, data.length / 2)); ch.writeInbound(Unpooled.wrappedBuffer(data, 5, data.length / 2)); HttpResponse res = ch.readInbound(); assertThat(res.getProtocolVersion(), sameInstance(HttpVersion.HTTP_1_1)); assertThat(res.getStatus(), is(HttpResponseStatus.OK)); HttpContent firstContent = ch.readInbound(); assertThat(firstContent.content().readableBytes(), is(5)); assertEquals(Unpooled.wrappedBuffer(data, 0, 5), firstContent.content()); firstContent.release(); LastHttpContent lastContent = ch.readInbound(); assertEquals(5, lastContent.content().readableBytes()); assertEquals(Unpooled.wrappedBuffer(data, 5, 5), lastContent.content()); lastContent.release(); assertThat(ch.finish(), is(false)); assertThat(ch.readInbound(), is(nullValue())); }
@Test public void simpleMessageListener() { ConfigurableApplicationContext context = new AnnotationConfigApplicationContext(Config.class, SimpleMessageListenerTestBean.class); JmsListenerContainerTestFactory factory = context.getBean(JmsListenerContainerTestFactory.class); assertEquals( "One container should have been registered", 1, factory.getListenerContainers().size()); MessageListenerTestContainer container = factory.getListenerContainers().get(0); JmsListenerEndpoint endpoint = container.getEndpoint(); assertEquals("Wrong endpoint type", MethodJmsListenerEndpoint.class, endpoint.getClass()); MethodJmsListenerEndpoint methodEndpoint = (MethodJmsListenerEndpoint) endpoint; assertNotNull(methodEndpoint.getBean()); assertNotNull(methodEndpoint.getMethod()); SimpleMessageListenerContainer listenerContainer = new SimpleMessageListenerContainer(); methodEndpoint.setupListenerContainer(listenerContainer); assertNotNull(listenerContainer.getMessageListener()); assertTrue("Should have been started " + container, container.isStarted()); context.close(); // Close and stop the listeners assertTrue("Should have been stopped " + container, container.isStopped()); }
@Test public void testLastResponseWithTrailingHeader() { EmbeddedChannel ch = new EmbeddedChannel(new HttpResponseDecoder()); ch.writeInbound( Unpooled.copiedBuffer( "HTTP/1.1 200 OK\r\n" + "Transfer-Encoding: chunked\r\n" + "\r\n" + "0\r\n" + "Set-Cookie: t1=t1v1\r\n" + "Set-Cookie: t2=t2v2; Expires=Wed, 09-Jun-2021 10:18:14 GMT\r\n" + "\r\n", CharsetUtil.US_ASCII)); HttpResponse res = ch.readInbound(); assertThat(res.getProtocolVersion(), sameInstance(HttpVersion.HTTP_1_1)); assertThat(res.getStatus(), is(HttpResponseStatus.OK)); LastHttpContent lastContent = ch.readInbound(); assertThat(lastContent.content().isReadable(), is(false)); HttpHeaders headers = lastContent.trailingHeaders(); assertEquals(1, headers.names().size()); List<String> values = headers.getAll("Set-Cookie"); assertEquals(2, values.size()); assertTrue(values.contains("t1=t1v1")); assertTrue(values.contains("t2=t2v2; Expires=Wed, 09-Jun-2021 10:18:14 GMT")); lastContent.release(); assertThat(ch.finish(), is(false)); assertThat(ch.readInbound(), is(nullValue())); }
@Test public void testMapTypes00() throws Exception { SampleMapTypes src = new SampleMapTypes(); src.f0 = new HashMap<Integer, Integer>(); src.f1 = new HashMap<Integer, Integer>(); src.f1.put(1, 1); src.f1.put(2, 2); src.f1.put(3, 3); src.f2 = new HashMap<String, Integer>(); src.f2.put("k1", 1); src.f2.put("k2", 2); src.f2.put("k3", 3); byte[] raw = MessagePack.pack(src); SampleMapTypes dst = MessagePack.unpack(raw, SampleMapTypes.class); assertEquals(src.f0.size(), dst.f0.size()); assertEquals(src.f1.size(), dst.f1.size()); Iterator<Integer> srcf1 = src.f1.keySet().iterator(); while (srcf1.hasNext()) { Integer s1 = srcf1.next(); assertEquals(src.f1.get(s1), dst.f1.get(s1)); } assertEquals(src.f2.size(), dst.f2.size()); Iterator<String> srcf2 = src.f2.keySet().iterator(); while (srcf2.hasNext()) { String s2 = srcf2.next(); assertEquals(src.f2.get(s2), dst.f2.get(s2)); } }
private static void testLastResponseWithTrailingHeaderFragmented( byte[] content, int fragmentSize) { EmbeddedChannel ch = new EmbeddedChannel(new HttpResponseDecoder()); int headerLength = 47; // split up the header for (int a = 0; a < headerLength; ) { int amount = fragmentSize; if (a + amount > headerLength) { amount = headerLength - a; } // if header is done it should produce a HttpRequest boolean headerDone = a + amount == headerLength; assertEquals(headerDone, ch.writeInbound(Unpooled.wrappedBuffer(content, a, amount))); a += amount; } ch.writeInbound(Unpooled.wrappedBuffer(content, headerLength, content.length - headerLength)); HttpResponse res = ch.readInbound(); assertThat(res.getProtocolVersion(), sameInstance(HttpVersion.HTTP_1_1)); assertThat(res.getStatus(), is(HttpResponseStatus.OK)); LastHttpContent lastContent = ch.readInbound(); assertThat(lastContent.content().isReadable(), is(false)); HttpHeaders headers = lastContent.trailingHeaders(); assertEquals(1, headers.names().size()); List<String> values = headers.getAll("Set-Cookie"); assertEquals(2, values.size()); assertTrue(values.contains("t1=t1v1")); assertTrue(values.contains("t2=t2v2; Expires=Wed, 09-Jun-2021 10:18:14 GMT")); lastContent.release(); assertThat(ch.finish(), is(false)); assertThat(ch.readInbound(), is(nullValue())); }
// Concurrent insertion & then iterator test. public static void testNonBlockingIdentityHashMapIterator() throws InterruptedException { final int ITEM_COUNT1 = 1000; final int THREAD_COUNT = 5; final int PER_CNT = ITEM_COUNT1 / THREAD_COUNT; final int ITEM_COUNT = PER_CNT * THREAD_COUNT; // fix roundoff for odd thread counts NonBlockingIdentityHashMap<Long, TestKey> nbhml = new NonBlockingIdentityHashMap<Long, TestKey>(); // use a barrier to open the gate for all threads at once to avoid rolling // start and no actual concurrency final CyclicBarrier barrier = new CyclicBarrier(THREAD_COUNT); final ExecutorService ex = Executors.newFixedThreadPool(THREAD_COUNT); final CompletionService<Object> co = new ExecutorCompletionService<Object>(ex); for (int i = 0; i < THREAD_COUNT; i++) { co.submit(new NBHMLFeeder(nbhml, PER_CNT, barrier, i * PER_CNT)); } for (int retCount = 0; retCount < THREAD_COUNT; retCount++) { co.take(); } ex.shutdown(); assertEquals("values().size()", ITEM_COUNT, nbhml.values().size()); assertEquals("entrySet().size()", ITEM_COUNT, nbhml.entrySet().size()); int itemCount = 0; for (TestKey K : nbhml.values()) itemCount++; assertEquals("values().iterator() count", ITEM_COUNT, itemCount); }
@Test public void testSearchFromMemberId() throws Exception { assertEquals(3, service.searchFromMemberId("test1").size()); assertEquals(1, service.searchFromMemberId("test2").size()); assertNull(service.searchFromMemberId("testXXX")); assertNull(service.searchFromMemberId(null)); }
@Test public void testFindOne() { List<TestEntity> values = Arrays.asList(1, 2) .stream() .map( v -> { TestEntity t = new TestEntity(); t.setStringProperty(String.format("Hello %s time(s)", v)); return t; }) .collect(Collectors.toList()); repository.save(values); TestEntity actual = repository.findOne(values.get(1).getId()); assertNotNull("Checking that the result is not null.", actual); assertEquals( "Checking that the list is the expected size.", values.get(1).getId(), actual.getId()); assertEquals( "Checking that the list is the expected size.", values.get(1).getStringProperty(), actual.getStringProperty()); }
// Note this is a bit of a integration test not a strict unit test @Test public void testFillingAMoreComplicatedBoundingRectangle() throws Exception { double xStart = 0.0; double xStop = 25.5; double yStart = 0.0; double yStop = 33.33; double xStep = 0.4; double yStep = 0.6; RectangularROI roi = new RectangularROI(); roi.setPoint(Math.min(xStart, xStop), Math.min(yStart, yStop)); roi.setLengths(Math.abs(xStop - xStart), Math.abs(yStop - yStart)); RasterModel model = new RasterModel(); model.setxStep(xStep); model.setyStep(yStep); // Get the point list IPointGenerator<RasterModel, Point> gen = service.createGenerator(model, roi); List<Point> pointList = gen.createPoints(); int rows = (int) (Math.floor((xStop - xStart) / xStep) + 1); int cols = (int) (Math.floor((yStop - yStart) / yStep) + 1); // Check the list size assertEquals("Point list size should be correct", rows * cols, pointList.size()); // Check some points assertEquals(new Point(0, xStart, 0, yStart), pointList.get(0)); assertEquals(xStart + 3 * xStep, pointList.get(3).getX(), 1e-8); // TODO more GeneratorUtil.testGeneratorPoints(gen); }
@Test public void testNestedNeXus() throws Exception { int[] size = {8, 5}; // Create scan points for a grid and make a generator RasterModel rmodel = new RasterModel(); rmodel.setxName("xNex"); rmodel.setxStep(3d / size[1]); rmodel.setyName("yNex"); rmodel.setyStep(3d / size[0]); rmodel.setBoundingBox(new BoundingBox(0, 0, 3, 3)); IPointGenerator<?, IPosition> gen = service.createGenerator(rmodel); IPosition first = gen.iterator().next(); assertEquals(0d, first.get("xNex")); assertEquals(0d, first.get("yNex")); IPosition last = null; Iterator<IPosition> it = gen.iterator(); while (it.hasNext()) last = it.next(); assertEquals(3d, last.get("xNex")); assertEquals(3d, last.get("yNex")); }
@Test public void testException() throws Exception { Logger logger = Logger.getLogger(getClass()); logger.info(LOG_MESSAGE, new Exception("this is an exception")); assertEquals(1, GelfTestSender.getMessages().size()); GelfMessage gelfMessage = GelfTestSender.getMessages().get(0); assertEquals(LOG_MESSAGE, gelfMessage.getFullMessage()); assertEquals( AbstractGelfLogAppenderTest.class.getName(), gelfMessage.getField(LogMessageField.NamedLogField.SourceClassName.getFieldName())); assertEquals( "testException", gelfMessage.getField(LogMessageField.NamedLogField.SourceMethodName.getFieldName())); assertThat( gelfMessage.getField(MdcGelfMessageAssembler.FIELD_STACK_TRACE), containsString("this is an exception")); assertThat( gelfMessage.getField(MdcGelfMessageAssembler.FIELD_STACK_TRACE), containsString("skipped")); assertThat( gelfMessage.getField(MdcGelfMessageAssembler.FIELD_STACK_TRACE), containsString("skipped")); }
public final void testNonBlockingIdentityHashMapSize() { NonBlockingIdentityHashMap<Long, String> items = new NonBlockingIdentityHashMap<Long, String>(); items.put(Long.valueOf(100), "100"); items.put(Long.valueOf(101), "101"); assertEquals("keySet().size()", 2, items.keySet().size()); assertTrue("keySet().contains(100)", items.keySet().contains(Long.valueOf(100))); assertTrue("keySet().contains(101)", items.keySet().contains(Long.valueOf(101))); assertEquals("values().size()", 2, items.values().size()); assertTrue("values().contains(\"100\")", items.values().contains("100")); assertTrue("values().contains(\"101\")", items.values().contains("101")); assertEquals("entrySet().size()", 2, items.entrySet().size()); boolean found100 = false; boolean found101 = false; for (Entry<Long, String> entry : items.entrySet()) { if (entry.getKey().equals(Long.valueOf(100))) { assertEquals("entry[100].getValue()==\"100\"", "100", entry.getValue()); found100 = true; } else if (entry.getKey().equals(Long.valueOf(101))) { assertEquals("entry[101].getValue()==\"101\"", "101", entry.getValue()); found101 = true; } } assertTrue("entrySet().contains([100])", found100); assertTrue("entrySet().contains([101])", found101); }
// Delete CSR @Test public void Test5() throws Exception { driver.get(baseUrl + "/#/host/magehostmanager.magemojo.com/configuration/ssl"); driver.findElement(By.xpath("//a[contains(text(),'www.Testing5.com')]")).click(); assertEquals( "Download CSR www.Testing5.com", driver.findElement(By.xpath("//legend[4]")).getText()); driver.findElement(By.xpath("(//button[@type='button'])[8]")).click(); assertEquals( "Confirmation Window", driver.findElement(By.cssSelector("h3.modal-title.ng-binding")).getText()); assertTrue(isElementPresent(By.xpath("//div[3]/button[2]"))); driver.findElement(By.xpath("//div[3]/button")).click(); for (int second = 0; ; second++) { if (second >= 60) fail("timeout"); try { if ("Successfully deleted the CSR." .equals(driver.findElement(By.xpath("//div[@id='toast-container']/div")).getText())) break; } catch (Exception e) { } Thread.sleep(1000); } for (int second = 0; ; second++) { if (second >= 60) fail("timeout"); try { if (!isElementPresent(By.xpath("//a[contains(text(),'www.Testing5.com')]"))) break; } catch (Exception e) { } Thread.sleep(1000); } }
// Test some basic stuff; add a few keys, remove a few keys public void testBasic() { assertTrue(_nbhm.isEmpty()); assertThat(_nbhm.putIfAbsent("k1", "v1"), nullValue()); checkSizes(1); assertThat(_nbhm.putIfAbsent("k2", "v2"), nullValue()); checkSizes(2); assertTrue(_nbhm.containsKey("k2")); assertThat(_nbhm.put("k1", "v1a"), is("v1")); assertThat(_nbhm.put("k2", "v2a"), is("v2")); checkSizes(2); assertThat(_nbhm.putIfAbsent("k2", "v2b"), is("v2a")); assertThat(_nbhm.remove("k1"), is("v1a")); assertFalse(_nbhm.containsKey("k1")); checkSizes(1); assertThat(_nbhm.remove("k1"), nullValue()); assertThat(_nbhm.remove("k2"), is("v2a")); checkSizes(0); assertThat(_nbhm.remove("k2"), nullValue()); assertThat(_nbhm.remove("k3"), nullValue()); assertTrue(_nbhm.isEmpty()); assertThat(_nbhm.put("k0", "v0"), nullValue()); assertTrue(_nbhm.containsKey("k0")); checkSizes(1); assertThat(_nbhm.remove("k0"), is("v0")); assertFalse(_nbhm.containsKey("k0")); checkSizes(0); assertThat(_nbhm.replace("k0", "v0"), nullValue()); assertFalse(_nbhm.containsKey("k0")); assertThat(_nbhm.put("k0", "v0"), nullValue()); assertEquals(_nbhm.replace("k0", "v0a"), "v0"); assertEquals(_nbhm.get("k0"), "v0a"); assertThat(_nbhm.remove("k0"), is("v0a")); assertFalse(_nbhm.containsKey("k0")); checkSizes(0); assertThat(_nbhm.replace("k1", "v1"), nullValue()); assertFalse(_nbhm.containsKey("k1")); assertThat(_nbhm.put("k1", "v1"), nullValue()); assertEquals(_nbhm.replace("k1", "v1a"), "v1"); assertEquals(_nbhm.get("k1"), "v1a"); assertThat(_nbhm.remove("k1"), is("v1a")); assertFalse(_nbhm.containsKey("k1")); checkSizes(0); // Insert & Remove KeyBonks until the table resizes and we start // finding Tombstone keys- and KeyBonk's equals-call with throw a // ClassCastException if it sees a non-KeyBonk. NonBlockingIdentityHashMap<KeyBonk, String> dumb = new NonBlockingIdentityHashMap<KeyBonk, String>(); for (int i = 0; i < 10000; i++) { final KeyBonk happy1 = new KeyBonk(i); assertThat(dumb.put(happy1, "and"), nullValue()); if ((i & 1) == 0) dumb.remove(happy1); final KeyBonk happy2 = new KeyBonk(i); // 'equals' but not '==' dumb.get(happy2); } }
@Test public void testRemoveLastComponent() { CompositeByteBuf buf = freeLater(compositeBuffer()); buf.addComponent(wrappedBuffer(new byte[] {1, 2})); assertEquals(1, buf.numComponents()); buf.removeComponent(0); assertEquals(0, buf.numComponents()); }
// Check that the iterator iterates the correct number of times private void checkSizes(String msg, int sz, Iterator it, int expectedSize) { assertEquals(msg, expectedSize, sz); int result = 0; while (it.hasNext()) { result++; it.next(); } assertEquals(msg, expectedSize, result); }
@Test public void testSearchFromMemberIdAndPracticeMonth() throws Exception { assertEquals(2, service.searchFromMemberIdAndPracticeMonth("test1", 2010, 10).size()); assertEquals(1, service.searchFromMemberIdAndPracticeMonth("test1", 2010, 12).size()); assertEquals(1, service.searchFromMemberIdAndPracticeMonth("test2", 2010, 10).size()); assertEquals(1, service.searchFromMemberIdAndPracticeMonth("test2", 2010, 10).size()); assertNull(service.searchFromMemberIdAndPracticeMonth("test1", 2010, 2)); assertNull(service.searchFromMemberIdAndPracticeMonth("testXXX", 2010, 10)); }
@Test public void testArticleData() { IArticle article = getExampleDoc(); assertEquals("Kevin Smith o nowym kostiumie Batmana: fani będą w szoku", article.getTitle()); assertThat(article.getContent(), startsWith("Reżyser Kevin Smith widział już kostium Batmana")); assertThat(article.getContent(), endsWith("Reżyserią filmu zajmie się Zack Snyder. AS")); assertEquals(parseDate("12 November 2013 13:32"), article.getDate()); }
@Test public void shouldBeAbleToChangeTheHeaderForResponse() throws Exception { Response response = new Response(200, "OK"); response.setHeader("Connection", "keep-alive"); response.setHeader("foo", "bar"); assertEquals("keep-alive", response.getHeader("Connection")); assertEquals("bar", response.getHeader("foo")); assertEquals("foo: bar\nConnection: keep-alive", response.toHTTPHeaderString()); }
@Test public void testSetPrivateFields() { EntityWithPrivateFields entity = sql2o .createQuery("select 1 id, 'hello' value from (values(0))") .executeAndFetchFirst(EntityWithPrivateFields.class); assertEquals(1, entity.getId()); assertEquals("hello1", entity.getValue()); }
@Test public void testSuperPojo() { SuperPojo pojo = sql2o .createQuery("select 1 id, 'something' value from (values(0))") .executeAndFetchFirst(SuperPojo.class); assertEquals(1, pojo.getId()); assertEquals("something1", pojo.getValue()); }
private void testValidCopy(TestObject src, TestObject dest) { src.setName("freddie"); src.setAge(15); src.setSpouse(new TestObject()); assertFalse(src.getAge() == dest.getAge()); ReflectionUtils.shallowCopyFieldState(src, dest); assertEquals(src.getAge(), dest.getAge()); assertEquals(src.getSpouse(), dest.getSpouse()); }
@Test public void testFillingBoundingRectangle() throws Exception { // Create a simple bounding rectangle RectangularROI boundingRectangle = new RectangularROI(0, 0, 3, 3, 0); // Create a raster scan path RasterModel model = new RasterModel(); model.setxStep(1); model.setyStep(1); // Get the point list IPointGenerator<RasterModel, Point> gen = service.createGenerator(model, boundingRectangle); List<Point> pointList = gen.createPoints(); // Check correct number of points assertEquals(16, pointList.size()); // Check some random points are correct assertEquals(0.0, pointList.get(0).getX(), 1e-8); assertEquals(0.0, pointList.get(0).getY(), 1e-8); assertEquals(3.0, pointList.get(3).getX(), 1e-8); assertEquals(0.0, pointList.get(3).getY(), 1e-8); assertEquals(3.0, pointList.get(7).getX(), 1e-8); assertEquals(1.0, pointList.get(7).getY(), 1e-8); assertEquals(3.0, pointList.get(11).getX(), 1e-8); assertEquals(2.0, pointList.get(11).getY(), 1e-8); GeneratorUtil.testGeneratorPoints(gen); }
@Test public void itThrowsA400BadRequestWebApplicationException() throws Exception { try { new ISODateParam("X#H"); fail("should have thrown a WebApplicationException but didn't"); } catch (WebApplicationException e) { assertEquals(400, e.getResponse().getStatus()); assertEquals( "Invalid parameter: X#H (not a valid ISO 8601 date).", e.getResponse().getEntity()); } }
@Test public void testExecuteAndFetchResultSet() throws SQLException { List<Integer> list = sql2o .createQuery( "select 1 val from (values(0)) union select 2 from (values(0)) union select 3 from (values(0))") .executeScalarList(); assertEquals((int) list.get(0), 1); assertEquals((int) list.get(1), 2); assertEquals((int) list.get(2), 3); }
@Test public void testCommentsData() { IArticle article = getExampleDoc(); List<IComment> comments = article.getComments(); assertEquals(2, comments.size()); IComment comment = comments.get(0); assertEquals("ja", comment.getAuthor()); assertEquals("Ci co przeżywają że Affleck będzie batmanem do debile.", comment.getContent()); assertEquals(parseDate("12 November 2013 18:40"), comment.getDate()); }
@Test public void validCopyOnSubTypeWithNewField() { TestObjectSubclassWithNewField src = new TestObjectSubclassWithNewField(); TestObjectSubclassWithNewField dest = new TestObjectSubclassWithNewField(); src.magic = 11; // Will check inherited fields are copied testValidCopy(src, dest); // Check subclass fields were copied assertEquals(src.magic, dest.magic); assertEquals(src.prot, dest.prot); }
@Test public void testDynamicExecuteScalar() { Object origVal = sql2o.createQuery("select 1").executeScalar(); assertTrue(Integer.class.equals(origVal.getClass())); assertEquals((Integer) 1, origVal); Long intVal = sql2o.createQuery("select 1").executeScalar(Long.class); assertEquals((Long) 1l, intVal); Short shortVal = sql2o.createQuery("select 2").executeScalar(Short.class); Short expected = 2; assertEquals(expected, shortVal); }
@Test public void testComplexTypes() { ComplexEntity pojo = sql2o .createQuery( "select 1 id, 1 \"entity.id\", 'something' \"entity.value\" from (values(0))", "testComplexTypes") .executeAndFetchFirst(ComplexEntity.class); assertEquals(1, pojo.id); assertEquals(1, pojo.entity.getId()); assertEquals("something1", pojo.entity.getValue()); }