@Test public void ex4_killAward() { when(observer.getLogLine()).thenReturn(EX4_0); test.onApplicationEvent(observer); MatchPlayers player = Utils.searchFor(EX4_RIGHT, match); assertNotNull(player); assertEquals(false, player.isAward()); when(observer.getLogLine()).thenReturn(EX4_1); test.onApplicationEvent(observer); when(observer.getLogLine()).thenReturn(EX4_2); test.onApplicationEvent(observer); when(observer.getLogLine()).thenReturn(EX4_3); test.onApplicationEvent(observer); when(observer.getLogLine()).thenReturn(EX4_4); test.onApplicationEvent(observer); player = Utils.searchFor(EX4_RIGHT, match); assertNotNull(player); assertEquals(true, player.isAward()); }
@Test public void incremental() throws Exception { Compilation compilation = new Compilation(); compilation .addSource("some.pkg.Stuff") .addLine("package some.pkg;") .addLine("import org.kohsuke.stapler.export.*;") .addLine("@" + SourceGeneratingAnnotation.class.getCanonicalName()) .addLine("@ExportedBean public class Stuff {") .addLine(" @Exported public int getCount() {return 0;}") .addLine("}"); compilation.doCompile(null, "-source", "6"); assertEquals(Collections.emptyList(), compilation.getDiagnostics()); assertEqualsCRLF( "some.pkg.Stuff\n", Utils.getGeneratedResource(compilation, ExportedBeanAnnotationProcessor.STAPLER_BEAN_FILE)); compilation = new Compilation(compilation); compilation .addSource("some.pkg.MoreStuff") .addLine("package some.pkg;") .addLine("import org.kohsuke.stapler.export.*;") .addLine("@ExportedBean public class MoreStuff {") .addLine(" @Exported public int getCount() {return 0;}") .addLine("}"); compilation.doCompile(null, "-source", "6"); assertEquals(Collections.emptyList(), compilation.getDiagnostics()); assertEqualsCRLF( "some.pkg.MoreStuff\nsome.pkg.Stuff\n", Utils.getGeneratedResource(compilation, ExportedBeanAnnotationProcessor.STAPLER_BEAN_FILE)); }
@Test public void pingPong() throws Exception { connect(); Utils.rollMockClock(0); // No ping pong happened yet. assertEquals(Long.MAX_VALUE, peer.getLastPingTime()); assertEquals(Long.MAX_VALUE, peer.getPingTime()); ListenableFuture<Long> future = peer.ping(); assertEquals(Long.MAX_VALUE, peer.getLastPingTime()); assertEquals(Long.MAX_VALUE, peer.getPingTime()); assertFalse(future.isDone()); Ping pingMsg = (Ping) outbound(writeTarget); Utils.rollMockClock(5); // The pong is returned. inbound(writeTarget, new Pong(pingMsg.getNonce())); pingAndWait(writeTarget); assertTrue(future.isDone()); long elapsed = future.get(); assertTrue("" + elapsed, elapsed > 1000); assertEquals(elapsed, peer.getLastPingTime()); assertEquals(elapsed, peer.getPingTime()); // Do it again and make sure it affects the average. future = peer.ping(); pingMsg = (Ping) outbound(writeTarget); Utils.rollMockClock(50); inbound(writeTarget, new Pong(pingMsg.getNonce())); elapsed = future.get(); assertEquals(elapsed, peer.getLastPingTime()); assertEquals(7250, peer.getPingTime()); }
@Test public void basicOutput() { Compilation compilation = new Compilation(); compilation .addSource("some.pkg.Stuff") .addLine("package some.pkg;") .addLine("import org.kohsuke.stapler.export.*;") .addLine("@ExportedBean public class Stuff {") .addLine(" /* this is not Javadoc */") .addLine(" @Exported public int getCount() {return 0;}") .addLine(" /** This gets the display name. */") .addLine(" @Exported(name=\"name\") public String getDisplayName() {return null;}") .addLine("}"); compilation.doCompile(null, "-source", "6"); assertEquals(Collections.emptyList(), compilation.getDiagnostics()); assertEqualsCRLF( "some.pkg.Stuff\n", Utils.getGeneratedResource( compilation, "META-INF/annotations/org.kohsuke.stapler.export.ExportedBean")); assertEqualsCRLF( "some.pkg.Stuff\n", Utils.getGeneratedResource(compilation, ExportedBeanAnnotationProcessor.STAPLER_BEAN_FILE)); assertEquals( "{getDisplayName=This gets the display name. }", Utils.normalizeProperties( Utils.getGeneratedResource(compilation, "some/pkg/Stuff.javadoc"))); }
@Test public void subclassOfExportedBean() { Compilation compilation = new Compilation(); compilation .addSource("some.pkg.Stuff") .addLine("package some.pkg;") .addLine("import org.kohsuke.stapler.export.*;") .addLine("public class Stuff extends " + Super.class.getCanonicalName() + " {") .addLine(" @Override public int getCount() {return 0;}") .addLine("}"); compilation.doCompile(null, "-source", "6"); assertEquals(Collections.emptyList(), compilation.getDiagnostics()); /* #7188605: broken in JDK 6u33 + org.jvnet.hudson:annotation-indexer:1.2: assertEquals("some.pkg.Stuff\n", Utils.getGeneratedResource(compilation, "META-INF/annotations/org.kohsuke.stapler.export.ExportedBean")); */ // TODO is it intentional that these are not listed here? (example: // hudson.plugins.mercurial.MercurialSCM) assertEquals( null, Utils.getGeneratedResource(compilation, ExportedBeanAnnotationProcessor.STAPLER_BEAN_FILE)); assertEquals( null, Utils.normalizeProperties( Utils.getGeneratedResource(compilation, "some/pkg/Stuff.javadoc"))); }
@Test public void noJavadoc() { Compilation compilation = new Compilation(); compilation .addSource("some.pkg.Stuff") .addLine("package some.pkg;") .addLine("import org.kohsuke.stapler.export.*;") .addLine("@ExportedBean public class Stuff {") .addLine(" @Exported public int getCount() {return 0;}") .addLine("}"); compilation.doCompile(null, "-source", "6"); assertEquals(Collections.emptyList(), compilation.getDiagnostics()); assertEqualsCRLF( "some.pkg.Stuff\n", Utils.getGeneratedResource( compilation, "META-INF/annotations/org.kohsuke.stapler.export.ExportedBean")); assertEqualsCRLF( "some.pkg.Stuff\n", Utils.getGeneratedResource(compilation, ExportedBeanAnnotationProcessor.STAPLER_BEAN_FILE)); // TODO should it be null, i.e. is it desired to create an empty *.javadoc file? assertEquals( "{}", Utils.normalizeProperties( Utils.getGeneratedResource(compilation, "some/pkg/Stuff.javadoc"))); }
private Script parseScriptString(String string) throws Exception { String[] words = string.split("[ \\t\\n]"); UnsafeByteArrayOutputStream out = new UnsafeByteArrayOutputStream(); for (String w : words) { if (w.equals("")) continue; if (w.matches("^-?[0-9]*$")) { // Number long val = Long.parseLong(w); if (val >= -1 && val <= 16) out.write(Script.encodeToOpN((int) val)); else Script.writeBytes( out, Utils.reverseBytes(Utils.encodeMPI(BigInteger.valueOf(val), false))); } else if (w.matches("^0x[0-9a-fA-F]*$")) { // Raw hex data, inserted NOT pushed onto stack: out.write(Hex.decode(w.substring(2))); } else if (w.length() >= 2 && w.startsWith("'") && w.endsWith("'")) { // Single-quoted string, pushed as data. NOTE: this is poor-man's // parsing, spaces/tabs/newlines in single-quoted strings won't work. Script.writeBytes(out, w.substring(1, w.length() - 1).getBytes(Charset.forName("UTF-8"))); } else if (ScriptOpCodes.getOpCode(w) != OP_INVALIDOPCODE) { // opcode, e.g. OP_ADD or OP_1: out.write(ScriptOpCodes.getOpCode(w)); } else if (w.startsWith("OP_") && ScriptOpCodes.getOpCode(w.substring(3)) != OP_INVALIDOPCODE) { // opcode, e.g. OP_ADD or OP_1: out.write(ScriptOpCodes.getOpCode(w.substring(3))); } else { throw new RuntimeException("Invalid Data"); } } return new Script(out.toByteArray()); }
@Test public void retryFailedBroadcast() throws Exception { // If we create a spend, it's sent to a peer that swallows it, and the peergroup is // removed/re-added then // the tx should be broadcast again. InboundMessageQueuer p1 = connectPeer(1); connectPeer(2); // Send ourselves a bit of money. Block b1 = TestUtils.makeSolvedTestBlock(blockStore, address); inbound(p1, b1); assertNull(outbound(p1)); assertEquals(Utils.toNanoCoins(50, 0), wallet.getBalance()); // Now create a spend, and expect the announcement on p1. Address dest = new ECKey().toAddress(params); Wallet.SendResult sendResult = wallet.sendCoins(peerGroup, dest, Utils.toNanoCoins(1, 0)); assertFalse(sendResult.broadcastComplete.isDone()); Transaction t1 = (Transaction) outbound(p1); assertFalse(sendResult.broadcastComplete.isDone()); // p1 eats it :( A bit later the PeerGroup is taken down. peerGroup.removeWallet(wallet); peerGroup.addWallet(wallet); // We want to hear about it again. Now, because we've disabled the randomness for the unit tests // it will // re-appear on p1 again. Of course in the real world it would end up with a different set of // peers and // select randomly so we get a second chance. Transaction t2 = (Transaction) outbound(p1); assertEquals(t1, t2); }
@Test public void testRemoveUserFromGroup() throws Exception { LdapGroup g1 = Utils.createTestGroup(CN); String[] usernames = {"U1_" + System.currentTimeMillis(), "U2_" + System.currentTimeMillis()}; if (HELPER.setGroup(g1)) { LOG.log(Level.INFO, "updated Group {0}", CN); } List<LdapUser> users = Utils.createTestUsers(usernames); for (LdapUser user : users) { g1.addUser(user); } HELPER.setGroup(g1); g1 = (LdapGroup) HELPER.getGroup(CN); int count = g1.getUsers().size(); LOG.log(Level.INFO, "user count Group {0} is {1}", new Object[] {CN, count}); g1.debug(); assertTrue(count > 1); g1.rmUser(users.get(0)); HELPER.setGroup(g1); g1 = (LdapGroup) HELPER.getGroup(CN); LOG.log(Level.INFO, "user count Group {0} is {1}", new Object[] {CN, g1.getUsers().size()}); g1.debug(); assertTrue(g1.getUsers().size() == (count - 1)); Utils.removeTestGroup(g1); Utils.removeTestUsers(users); }
@Test public void testBinaryStrings() { assertEquals("11111111", Utils.maskToBinaryString(0xff)); assertEquals("11101111", Utils.maskToBinaryString(239)); assertEquals("10100011", Utils.maskToBinaryString(163)); assertEquals("111111111", Utils.maskToBinaryString(0x1ff)); assertEquals("0", Utils.maskToBinaryString(0)); }
@Test public void testFormParameters() throws Exception { final Map<String, String[]> patternMap = new HashMap<String, String[]>(); patternMap.put("title", new String[] {"Developing PaaS Components"}); patternMap.put("authors", new String[] {"Shalini M"}); patternMap.put("price", new String[] {"100$"}); final NetworkListener listener = httpServer.getListener(LISTENER_NAME); startHttpServer( new HttpHandler() { @Override public void service(Request request, Response response) throws Exception { final Map<String, String[]> paramMap = request.getParameterMap(); boolean isOk = paramMap.size() == patternMap.size(); if (isOk) { // if sizes are equal - compare content for (Map.Entry<String, String[]> patternEntry : patternMap.entrySet()) { final String key = patternEntry.getKey(); final String[] value = patternEntry.getValue(); isOk = paramMap.containsKey(key) && Arrays.equals(value, paramMap.get(key)); if (!isOk) break; } } if (isOk) { response.setStatus(200, "FINE"); } else { response.setStatus(500, "Attributes don't match"); } } }, "/bookstore/BookStoreServlet"); final MemoryManager mm = listener.getTransport().getMemoryManager(); final Buffer requestPart1 = Buffers.wrap(mm, Utils.loadResourceFile("form-params-payload1.dat")); final Buffer requestPart2 = Buffers.wrap(mm, Utils.loadResourceFile("form-params-payload2.dat")); Buffer responseBuffer = send("localhost", PORT, Buffers.appendBuffers(mm, requestPart1, requestPart2)) .get(10, TimeUnit.SECONDS); // Successful response length is 37 bytes. This includes the status // line and a content-length boolean isFailure = responseBuffer.remaining() != 37; if (isFailure) { byte[] response = new byte[responseBuffer.remaining()]; responseBuffer.get(response); String hex = toHexString(response); fail("unexpected response length=" + response.length + " content=[" + hex + "]"); } }
@Test public void testUpdateGroup() throws Exception { LdapGroup g1 = Utils.createTestGroup(CN); assertNull(g1.get("description")); g1.set("description", "Group " + CN); HELPER.setGroup(g1); g1 = (LdapGroup) HELPER.getGroup(CN); assertEquals(g1.get("description"), "Group " + CN); Utils.removeTestGroup(g1); }
@Test public void testAddUserToGroup() throws Exception { LdapGroup g1 = Utils.createTestGroup(CN); g1.addUser(testUser1); if (HELPER.setGroup(g1)) { LOG.log(Level.INFO, "updated Group {0}", CN); } g1 = (LdapGroup) HELPER.getGroup(CN); g1.debug(); Utils.removeTestGroup(g1); }
@Test public void testCreateGroup() throws Exception { Node g1 = HELPER.getGroup(CN); assertTrue(g1.isEmpty()); LdapGroup t1 = Utils.getTestGroup("test"); t1 = Utils.updatedGroup(t1, CN); if (HELPER.setGroup(t1)) { LOG.log(Level.INFO, "created Group {0}", CN); } g1 = HELPER.getGroup(CN); assertFalse(g1.isEmpty()); }
@Test public void testContains() throws Exception { assertEquals(false, Utils.contains(null, null)); assertEquals(false, Utils.contains(new Object[0], null)); assertEquals(true, Utils.contains(new Object[1], null)); assertEquals(false, Utils.contains(Arrays.asList("Hello", "World").toArray(), null)); assertEquals(false, Utils.contains(Arrays.asList("Hello", "World").toArray(), null)); assertEquals(true, Utils.contains(Arrays.asList("Hello", "World").toArray(), "Hello")); assertEquals(true, Utils.contains(Arrays.asList("Hello", "World").toArray(), "World")); assertEquals(true, Utils.contains(Arrays.asList("Hello", null, "World").toArray(), "Hello")); assertEquals(true, Utils.contains(Arrays.asList("Hello", null, "World").toArray(), null)); assertEquals(true, Utils.contains(Arrays.asList("Hello", null, "World").toArray(), "World")); }
public void timeLockedTransaction(boolean useNotFound) throws Exception { connectWithVersion(useNotFound ? 70001 : 60001); // Test that if we receive a relevant transaction that has a lock time, it doesn't result in a // notification // until we explicitly opt in to seeing those. ECKey key = new ECKey(); Wallet wallet = new Wallet(unitTestParams); wallet.addKey(key); peer.addWallet(wallet); final Transaction[] vtx = new Transaction[1]; wallet.addEventListener( new AbstractWalletEventListener() { @Override public void onCoinsReceived( Wallet wallet, Transaction tx, BigInteger prevBalance, BigInteger newBalance) { vtx[0] = tx; } }); // Send a normal relevant transaction, it's received correctly. Transaction t1 = TestUtils.createFakeTx(unitTestParams, Utils.toNanoCoins(1, 0), key); inbound(writeTarget, t1); GetDataMessage getdata = (GetDataMessage) outbound(writeTarget); if (useNotFound) { inbound(writeTarget, new NotFoundMessage(unitTestParams, getdata.getItems())); } else { bouncePing(); } pingAndWait(writeTarget); Threading.waitForUserCode(); assertNotNull(vtx[0]); vtx[0] = null; // Send a timelocked transaction, nothing happens. Transaction t2 = TestUtils.createFakeTx(unitTestParams, Utils.toNanoCoins(2, 0), key); t2.setLockTime(999999); inbound(writeTarget, t2); Threading.waitForUserCode(); assertNull(vtx[0]); // Now we want to hear about them. Send another, we are told about it. wallet.setAcceptRiskyTransactions(true); inbound(writeTarget, t2); getdata = (GetDataMessage) outbound(writeTarget); if (useNotFound) { inbound(writeTarget, new NotFoundMessage(unitTestParams, getdata.getItems())); } else { bouncePing(); } pingAndWait(writeTarget); Threading.waitForUserCode(); assertEquals(t2, vtx[0]); }
@Test public void testAddUsersToGroup() throws Exception { testUser2 = HELPER.getUserTemplate("U_" + System.currentTimeMillis()); testUser2.set("cn", testUser2.getUid()); HELPER.setUser(testUser2); LdapGroup g1 = Utils.createTestGroup(CN); g1.addUser(testUser1); g1.addUser(testUser2); HELPER.setGroup(g1); g1 = (LdapGroup) HELPER.getGroup(CN); LOG.log(Level.INFO, "user count Group {0} is {1}", new Object[] {CN, g1.getUsers().size()}); assertTrue(g1.getUsers().size() > 2); Utils.removeTestGroup(g1); }
@Before public void setUp() throws Exception { unitTestParams = UnitTestParams.get(); wallet = new Wallet(unitTestParams); wallet.addKey(new ECKey()); resetBlockStore(); Transaction tx1 = createFakeTx( unitTestParams, Utils.toNanoCoins(2, 0), wallet.getKeys().get(0).toAddress(unitTestParams)); // add a second input so can test granularity of byte cache. Transaction prevTx = new Transaction(unitTestParams); TransactionOutput prevOut = new TransactionOutput( unitTestParams, prevTx, Utils.toNanoCoins(1, 0), wallet.getKeys().get(0).toAddress(unitTestParams)); prevTx.addOutput(prevOut); // Connect it. tx1.addInput(prevOut); Transaction tx2 = createFakeTx( unitTestParams, Utils.toNanoCoins(1, 0), new ECKey().toAddress(unitTestParams)); Block b1 = createFakeBlock(blockStore, tx1, tx2).block; BitcoinSerializer bs = new BitcoinSerializer(unitTestParams); ByteArrayOutputStream bos = new ByteArrayOutputStream(); bs.serialize(tx1, bos); tx1BytesWithHeader = bos.toByteArray(); tx1Bytes = tx1.bitcoinSerialize(); bos.reset(); bs.serialize(tx2, bos); tx2BytesWithHeader = bos.toByteArray(); tx2Bytes = tx2.bitcoinSerialize(); bos.reset(); bs.serialize(b1, bos); b1BytesWithHeader = bos.toByteArray(); b1Bytes = b1.bitcoinSerialize(); }
@Test public void fastCatchup() throws Exception { connect(); // Check that blocks before the fast catchup point are retrieved using getheaders, and after // using getblocks. // This test is INCOMPLETE because it does not check we handle >2000 blocks correctly. Block b1 = createFakeBlock(blockStore).block; blockChain.add(b1); Utils.rollMockClock(60 * 10); // 10 minutes later. Block b2 = makeSolvedTestBlock(b1); Utils.rollMockClock(60 * 10); // 10 minutes later. Block b3 = makeSolvedTestBlock(b2); Utils.rollMockClock(60 * 10); Block b4 = makeSolvedTestBlock(b3); // Request headers until the last 2 blocks. peer.setDownloadParameters((Utils.now().getTime() / 1000) - (600 * 2) + 1, false); peer.startBlockChainDownload(); GetHeadersMessage getheaders = (GetHeadersMessage) outbound(writeTarget); List<Sha256Hash> expectedLocator = new ArrayList<Sha256Hash>(); expectedLocator.add(b1.getHash()); expectedLocator.add(unitTestParams.getGenesisBlock().getHash()); assertEquals(getheaders.getLocator(), expectedLocator); assertEquals(getheaders.getStopHash(), Sha256Hash.ZERO_HASH); // Now send all the headers. HeadersMessage headers = new HeadersMessage( unitTestParams, b2.cloneAsHeader(), b3.cloneAsHeader(), b4.cloneAsHeader()); // We expect to be asked for b3 and b4 again, but this time, with a body. expectedLocator.clear(); expectedLocator.add(b2.getHash()); expectedLocator.add(b1.getHash()); expectedLocator.add(unitTestParams.getGenesisBlock().getHash()); inbound(writeTarget, headers); GetBlocksMessage getblocks = (GetBlocksMessage) outbound(writeTarget); assertEquals(expectedLocator, getblocks.getLocator()); assertEquals(Sha256Hash.ZERO_HASH, getblocks.getStopHash()); // We're supposed to get an inv here. InventoryMessage inv = new InventoryMessage(unitTestParams); inv.addItem(new InventoryItem(InventoryItem.Type.Block, b3.getHash())); inbound(writeTarget, inv); GetDataMessage getdata = (GetDataMessage) outbound(writeTarget); assertEquals(b3.getHash(), getdata.getItems().get(0).hash); // All done. inbound(writeTarget, b3); pingAndWait(writeTarget); closePeer(peer); }
@Test public void exceptionListener() throws Exception { wallet.addEventListener( new AbstractWalletEventListener() { @Override public void onCoinsReceived( Wallet wallet, Transaction tx, BigInteger prevBalance, BigInteger newBalance) { throw new NullPointerException("boo!"); } }); final Throwable[] throwables = new Throwable[1]; Threading.uncaughtExceptionHandler = new Thread.UncaughtExceptionHandler() { @Override public void uncaughtException(Thread thread, Throwable throwable) { throwables[0] = throwable; } }; // In real usage we're not really meant to adjust the uncaught exception handler after stuff // started happening // but in the unit test environment other tests have just run so the thread is probably still // kicking around. // Force it to crash so it'll be recreated with our new handler. Threading.USER_THREAD.execute( new Runnable() { @Override public void run() { throw new RuntimeException(); } }); connect(); Transaction t1 = new Transaction(unitTestParams); t1.addInput(new TransactionInput(unitTestParams, t1, new byte[] {})); t1.addOutput(Utils.toNanoCoins(1, 0), new ECKey().toAddress(unitTestParams)); Transaction t2 = new Transaction(unitTestParams); t2.addInput(t1.getOutput(0)); t2.addOutput(Utils.toNanoCoins(1, 0), wallet.getChangeAddress()); inbound(writeTarget, t2); final InventoryItem inventoryItem = new InventoryItem(InventoryItem.Type.Transaction, t2.getInput(0).getOutpoint().getHash()); final NotFoundMessage nfm = new NotFoundMessage(unitTestParams, Lists.newArrayList(inventoryItem)); inbound(writeTarget, nfm); pingAndWait(writeTarget); Threading.waitForUserCode(); assertTrue(throwables[0] instanceof NullPointerException); Threading.uncaughtExceptionHandler = null; }
@Test public void testThreeGeoTIFFStringTags() { metadata.addGeoAscii(2300, "4576"); metadata.addGeoAscii(2400, "aaaaaaaa"); metadata.addGeoAscii(2401, "bbbb"); final List<TIFFField> list = Utils.createGeoTIFFFields(metadata); assertNotNull(list); assertEquals(2, list.size()); final TIFFField dirField = list.get(0); final TIFFField asciiField = list.get(1); assertEquals(GeoTIFFTagSet.TAG_GEO_KEY_DIRECTORY, dirField.getTag()); assertEquals(GeoTIFFTagSet.TAG_GEO_ASCII_PARAMS, asciiField.getTag()); assertEquals(TIFFField.TIFF_SHORT, dirField.getType()); assertEquals(TIFFField.TIFF_ASCII, asciiField.getType()); assertEquals(16, dirField.getCount()); assertEquals(3, asciiField.getCount()); final char[] expected = { 1, 1, 2, 3, 2300, GeoTIFFTagSet.TAG_GEO_ASCII_PARAMS, 5, 0, 2400, GeoTIFFTagSet.TAG_GEO_ASCII_PARAMS, 9, 5, 2401, GeoTIFFTagSet.TAG_GEO_ASCII_PARAMS, 5, 14 }; assertArrayEquals(expected, dirField.getAsChars()); assertEquals("4576|", asciiField.getAsString(0)); assertEquals("aaaaaaaa|", asciiField.getAsString(1)); assertEquals("bbbb|", asciiField.getAsString(2)); }
@Test public void testThreeGeoTIFFTagsWithOneDouble() { metadata.addGeoShortParam(2300, 4576); metadata.addGeoDoubleParam(2400, 4.5); metadata.addGeoShortParam(2401, 3456); final List<TIFFField> list = Utils.createGeoTIFFFields(metadata); assertNotNull(list); assertEquals(2, list.size()); final TIFFField dirField = list.get(0); final TIFFField doubleField = list.get(1); assertEquals(GeoTIFFTagSet.TAG_GEO_KEY_DIRECTORY, dirField.getTag()); assertEquals(GeoTIFFTagSet.TAG_GEO_DOUBLE_PARAMS, doubleField.getTag()); assertEquals(TIFFField.TIFF_SHORT, dirField.getType()); assertEquals(TIFFField.TIFF_DOUBLE, doubleField.getType()); assertEquals(16, dirField.getCount()); assertEquals(1, doubleField.getCount()); final char[] expected = { 1, 1, 2, 3, 2300, 0, 1, 4576, 2400, GeoTIFFTagSet.TAG_GEO_DOUBLE_PARAMS, 1, 0, 2401, 0, 1, 3456 }; assertArrayEquals(expected, dirField.getAsChars()); assertEquals(true, Arrays.equals(new double[] {4.5}, doubleField.getAsDoubles())); }
@Test public void earliestKeyTime() throws Exception { long now = Utils.currentTimeSeconds(); // mock long yesterday = now - 86400; assertEquals(now, group.getEarliestKeyCreationTime()); Utils.rollMockClock(10000); group.freshKey(KeyChain.KeyPurpose.RECEIVE_FUNDS); Utils.rollMockClock(10000); group.freshKey(KeyChain.KeyPurpose.RECEIVE_FUNDS); // Check that all keys are assumed to be created at the same instant the seed is. assertEquals(now, group.getEarliestKeyCreationTime()); ECKey key = new ECKey(); key.setCreationTimeSeconds(yesterday); group.importKeys(key); assertEquals(yesterday, group.getEarliestKeyCreationTime()); }
public static boolean arrayContains(byte[] sup, byte[] sub) { if (sup.length < sub.length) return false; String superstring = Utils.bytesToHexString(sup); String substring = Utils.bytesToHexString(sub); int ind = superstring.indexOf(substring); StringBuilder sb = new StringBuilder(); for (int i = 0; i < superstring.indexOf(substring); i++) sb.append(" "); // System.out.println(superstring); // System.out.println(sb.append(substring).toString()); // System.out.println(); return ind > -1; }
@Test public void deterministicUpgradeUnencrypted() throws Exception { // Check that a group that contains only random keys has its HD chain created using the private // key bytes of // the oldest random key, so upgrading the same wallet twice gives the same outcome. group = new KeyChainGroup(params); group.setLookaheadSize(LOOKAHEAD_SIZE); // Don't want slow tests. ECKey key1 = new ECKey(); Utils.rollMockClock(86400); ECKey key2 = new ECKey(); group.importKeys(key2, key1); List<Protos.Key> protobufs = group.serializeToProtobuf(); group.upgradeToDeterministic(0, null); assertFalse(group.isDeterministicUpgradeRequired()); DeterministicKey dkey1 = group.freshKey(KeyChain.KeyPurpose.RECEIVE_FUNDS); DeterministicSeed seed1 = group.getActiveKeyChain().getSeed(); assertNotNull(seed1); group = KeyChainGroup.fromProtobufUnencrypted(params, protobufs); group.upgradeToDeterministic(0, null); // Should give same result as last time. DeterministicKey dkey2 = group.freshKey(KeyChain.KeyPurpose.RECEIVE_FUNDS); DeterministicSeed seed2 = group.getActiveKeyChain().getSeed(); assertEquals(seed1, seed2); assertEquals(dkey1, dkey2); // Check we used the right (oldest) key despite backwards import order. byte[] truncatedBytes = Arrays.copyOfRange(key1.getSecretBytes(), 0, 16); assertArrayEquals(seed1.getEntropyBytes(), truncatedBytes); }
@Test public void testStabilityAfterWrongMagic() throws Exception { HttpHandler a = new HttpHandler() { @Override public void service(Request request, Response response) throws Exception { response.setStatus(200, "FINE"); } }; startHttpServer(a); // Send junk data final Socket s = new Socket("localhost", PORT); try { s.getOutputStream().write("junkjunkjunk".getBytes()); s.getOutputStream().flush(); while (s.getInputStream().read() != -1) {} } finally { s.close(); } AjpForwardRequestPacket forward = new AjpForwardRequestPacket("GET", "/bob", PORT, 0); for (int i = 0; i < 1024; i++) { send(forward.toByteArray()); AjpResponse ajpResponse = Utils.parseResponse(readAjpMessage()); Assert.assertEquals(200, ajpResponse.getResponseCode()); Assert.assertEquals("FINE", ajpResponse.getResponseMessage()); closeClient(); } }
@Test public void invDownloadTxMultiPeer() throws Exception { // Check co-ordination of which peer to download via the memory pool. VersionMessage ver = new VersionMessage(unitTestParams, 100); InetSocketAddress address = new InetSocketAddress("127.0.0.1", 4242); Peer peer2 = new Peer(unitTestParams, ver, new PeerAddress(address), blockChain, memoryPool); peer2.addWallet(wallet); VersionMessage peerVersion = new VersionMessage(unitTestParams, OTHER_PEER_CHAIN_HEIGHT); peerVersion.clientVersion = 70001; peerVersion.localServices = VersionMessage.NODE_NETWORK; connect(); InboundMessageQueuer writeTarget2 = connect(peer2, peerVersion); // Make a tx and advertise it to one of the peers. BigInteger value = Utils.toNanoCoins(1, 0); Transaction tx = createFakeTx(unitTestParams, value, this.address); InventoryMessage inv = new InventoryMessage(unitTestParams); InventoryItem item = new InventoryItem(InventoryItem.Type.Transaction, tx.getHash()); inv.addItem(item); inbound(writeTarget, inv); // We got a getdata message. GetDataMessage message = (GetDataMessage) outbound(writeTarget); assertEquals(1, message.getItems().size()); assertEquals(tx.getHash(), message.getItems().get(0).hash); assertTrue(memoryPool.maybeWasSeen(tx.getHash())); // Advertising to peer2 results in no getdata message. inbound(writeTarget2, inv); pingAndWait(writeTarget2); assertNull(outbound(writeTarget2)); }
@Test public void testVersionAndModelTiePoint() { metadata.addModelTiePoint(1, 2, 3, 4, 5, 6); metadata.addModelTiePoint(2, 3, 4, 5, 6, 7); metadata.addModelTiePoint(3, 4, 5, 6, 7, 8); final List<TIFFField> list = Utils.createGeoTIFFFields(metadata); assertNotNull(list); assertEquals(2, list.size()); final TIFFField dirField = list.get(0); assertEquals(GeoTIFFTagSet.TAG_GEO_KEY_DIRECTORY, dirField.getTag()); assertEquals(TIFFField.TIFF_SHORT, dirField.getType()); assertEquals(4, dirField.getCount()); assertArrayEquals(new char[] {1, 1, 2, 0}, dirField.getAsChars()); final TIFFField tiePointField = list.get(1); assertEquals(GeoTIFFTagSet.TAG_MODEL_TIE_POINT, tiePointField.getTag()); assertEquals(TIFFField.TIFF_DOUBLE, tiePointField.getType()); assertEquals(3 * 6, tiePointField.getCount()); final double[] expected = { 1, 2, 3, 4, 5, 6, 2, 3, 4, 5, 6, 7, 3, 4, 5, 6, 7, 8 }; assertEquals(true, Arrays.equals(expected, tiePointField.getAsDoubles())); }
@Test public void testThreeGeoTIFFTagsWithOneAscii() { metadata.addGeoShortParam(2300, 4576); metadata.addGeoAscii(2400, "String"); metadata.addGeoShortParam(2401, 3456); final List<TIFFField> list = Utils.createGeoTIFFFields(metadata); assertNotNull(list); assertEquals(2, list.size()); final TIFFField dirField = list.get(0); final TIFFField asciiField = list.get(1); assertEquals(GeoTIFFTagSet.TAG_GEO_KEY_DIRECTORY, dirField.getTag()); assertEquals(GeoTIFFTagSet.TAG_GEO_ASCII_PARAMS, asciiField.getTag()); assertEquals(TIFFField.TIFF_SHORT, dirField.getType()); assertEquals(TIFFField.TIFF_ASCII, asciiField.getType()); assertEquals(16, dirField.getCount()); assertEquals(1, asciiField.getCount()); final char[] expected = { 1, 1, 2, 3, 2300, 0, 1, 4576, 2400, GeoTIFFTagSet.TAG_GEO_ASCII_PARAMS, 7, 0, 2401, 0, 1, 3456 }; assertArrayEquals(expected, dirField.getAsChars()); assertEquals("String|", asciiField.getAsString(0)); }
@Test public void FiveToBoolean() { int x = 5; int size = 4; boolean[] expected = {false, true, false, true}; assertTrue(Arrays.equals(expected, Utils.fromInt(x, size))); }