method2testcases
stringlengths
118
3.08k
### Question: OpenSSLKey implements Serializable { public void encrypt(String password) throws GeneralSecurityException { encrypt(password.getBytes()); } OpenSSLKey(InputStream is); OpenSSLKey(String file); OpenSSLKey(PrivateKey key); OpenSSLKey(String algorithm, byte[] data); boolean isEncrypted(); void decrypt(String password); void decrypt(byte[] password); void encrypt(String password); void encrypt(byte[] password); void setEncryptionAlgorithm(String alg); PrivateKey getPrivateKey(); void writeTo(OutputStream output); void writeTo(Writer w); void writeTo(String file); @Override boolean equals(Object other); @Override int hashCode(); }### Answer: @Test public void testEqualsForKeysDifferingByEncrypted() throws Exception { OpenSSLKey key1 = new BouncyCastleOpenSSLKey(file.getAbsoluteFilename()); OpenSSLKey key2 = new BouncyCastleOpenSSLKey(file.getAbsoluteFilename()); key2.encrypt("too many secrets"); assertThat(key2, not(equalTo(key1))); } @Test public void testSerializableEncrypted() throws Exception { OpenSSLKey key = new BouncyCastleOpenSSLKey(file.getAbsoluteFilename()); key.encrypt("too many secrets"); OpenSSLKey copy = serialiseAndDeserialise(key); assertThat(copy, equalTo(key)); }
### Question: SigningPolicyParser { public Map<X500Principal, SigningPolicy> parse(String fileName) throws FileNotFoundException, SigningPolicyException { if ((fileName == null) || (fileName.trim().isEmpty())) { throw new IllegalArgumentException(); } logger.debug("Signing policy file name " + fileName); FileReader fileReader = null; try { fileReader = new FileReader(fileName); return parse(fileReader); } catch (Exception e) { throw new SigningPolicyException(e); } finally { if (fileReader != null) { try { fileReader.close(); } catch (Exception exp) { logger.debug("Error closing file reader", exp); } } } } Map<X500Principal, SigningPolicy> parse(String fileName); Map<X500Principal, SigningPolicy> parse(Reader reader); static Pattern getPattern(String patternStr); static final String ACCESS_ID_PREFIX; static final String ACCESS_ID_CA; static final String DEF_AUTH_X509; static final String DEF_AUTH_GLOBUS; static final String POS_RIGHTS; static final String NEG_RIGHTS; static final String CONDITION_PREFIX; static final String CONDITION_SUBJECT; static final String VALUE_CA_SIGN; static final String SINGLE_CHAR; static final String WILDCARD; static final String SINGLE_PATTERN; static final String WILDCARD_PATTERN; }### Answer: @Test(expected = SigningPolicyException.class) public void testFileFailure() throws Exception { SigningPolicyParser parser = new SigningPolicyParser(); parser.parse("Foo"); }
### Question: SimpleMemoryCertStore extends CertStoreSpi { @Override public Collection<? extends CRL> engineGetCRLs(CRLSelector selector) throws CertStoreException { List<X509CRL> l = new LinkedList<X509CRL>(); for (X509CRL crl : crlStore) { if (selector.match(crl)) { l.add(crl); } } return l; } SimpleMemoryCertStore(CertStoreParameters params); @Override Collection<? extends CRL> engineGetCRLs(CRLSelector selector); @Override Collection<? extends Certificate> engineGetCertificates(CertSelector selector); }### Answer: @Test public void testEngineGetCRLsCRLSelector() throws Exception { SimpleMemoryCertStoreParams params = new SimpleMemoryCertStoreParams(null, null); store = new SimpleMemoryCertStore(params); assertEquals(0, store.engineGetCRLs(new X509CRLSelector()).size()); params = new SimpleMemoryCertStoreParams(new X509Certificate[] {cert}, new X509CRL[] {crl}); store = new SimpleMemoryCertStore(params); assertEquals(1, store.engineGetCRLs(new X509CRLSelector()).size()); X509CRLSelector crlSelector = new X509CRLSelector(); crlSelector.addIssuerName("CN=non-existent"); assertEquals(0, store.engineGetCRLs(crlSelector).size()); }
### Question: SimpleMemoryCertStore extends CertStoreSpi { @Override public Collection<? extends Certificate> engineGetCertificates(CertSelector selector) throws CertStoreException { List<X509Certificate> l = new LinkedList<X509Certificate>(); X509CertSelector select = (X509CertSelector) selector; for (X509Certificate cert : certStore) { if (selector.match(cert)) { l.add(cert); } } return l; } SimpleMemoryCertStore(CertStoreParameters params); @Override Collection<? extends CRL> engineGetCRLs(CRLSelector selector); @Override Collection<? extends Certificate> engineGetCertificates(CertSelector selector); }### Answer: @Test public void testEngineGetCertificatesCertSelector() throws Exception { SimpleMemoryCertStoreParams params = new SimpleMemoryCertStoreParams(null, null); store = new SimpleMemoryCertStore(params); assertEquals(0, store.engineGetCertificates(new X509CertSelector()).size()); params = new SimpleMemoryCertStoreParams(new X509Certificate[] {cert}, new X509CRL[] {crl}); store = new SimpleMemoryCertStore(params); assertEquals(1, store.engineGetCertificates(new X509CertSelector()).size()); params = new SimpleMemoryCertStoreParams(new X509Certificate[] {cert}, new X509CRL[] {crl}); store = new SimpleMemoryCertStore(params); X509CertSelector selector = new X509CertSelector(); selector.setSubject(cert.getSubjectX500Principal()); assertEquals(1, store.engineGetCertificates(selector).size()); X509CertSelector certSelector = new X509CertSelector(); certSelector.setSubject("CN=non-existent"); assertEquals(0, store.engineGetCertificates(certSelector).size()); }
### Question: SimpleMemoryKeyStore extends KeyStoreSpi { @Override public int engineSize() { return this.certMap.size(); } @Override void engineLoad(LoadStoreParameter params); @Override Enumeration<String> engineAliases(); @Override boolean engineContainsAlias(String alias); @Override void engineDeleteEntry(String alias); @Override Certificate engineGetCertificate(String alias); @Override boolean engineIsCertificateEntry(String alias); @Override boolean engineIsKeyEntry(String alias); @Override void engineSetCertificateEntry(String alias, Certificate cert); @Override int engineSize(); @Override void engineStore(OutputStream stream, char[] password); @Override void engineSetKeyEntry(String alias, byte[] key, Certificate[] chain); @Override void engineSetKeyEntry(String alias, Key key, char[] password, Certificate[] chain); @Override void engineLoad(InputStream stream, char[] password); @Override String engineGetCertificateAlias(Certificate cert); @Override Certificate[] engineGetCertificateChain(String alias); @Override Date engineGetCreationDate(String alias); @Override Key engineGetKey(String alias, char[] password); }### Answer: @Test public void testEngineSize() throws Exception { assertEquals(0, store.engineSize()); store.engineSetCertificateEntry(cert.getSubjectDN().getName(), cert); assertEquals(1, store.engineSize()); }
### Question: SimpleMemoryKeyStore extends KeyStoreSpi { @Override public Enumeration<String> engineAliases() { return Collections.enumeration(this.certMap.keySet()); } @Override void engineLoad(LoadStoreParameter params); @Override Enumeration<String> engineAliases(); @Override boolean engineContainsAlias(String alias); @Override void engineDeleteEntry(String alias); @Override Certificate engineGetCertificate(String alias); @Override boolean engineIsCertificateEntry(String alias); @Override boolean engineIsKeyEntry(String alias); @Override void engineSetCertificateEntry(String alias, Certificate cert); @Override int engineSize(); @Override void engineStore(OutputStream stream, char[] password); @Override void engineSetKeyEntry(String alias, byte[] key, Certificate[] chain); @Override void engineSetKeyEntry(String alias, Key key, char[] password, Certificate[] chain); @Override void engineLoad(InputStream stream, char[] password); @Override String engineGetCertificateAlias(Certificate cert); @Override Certificate[] engineGetCertificateChain(String alias); @Override Date engineGetCreationDate(String alias); @Override Key engineGetKey(String alias, char[] password); }### Answer: @Test public void testEngineAliases() throws Exception { assertFalse(store.engineAliases().hasMoreElements()); store.engineSetCertificateEntry(cert.getSubjectDN().getName(), cert); Enumeration e = store.engineAliases(); assertEquals(cert.getSubjectDN().getName(), e.nextElement()); assertFalse(e.hasMoreElements()); }
### Question: SimpleMemoryKeyStore extends KeyStoreSpi { @Override public void engineStore(OutputStream stream, char[] password) throws IOException, NoSuchAlgorithmException, CertificateException { throw new UnsupportedOperationException(); } @Override void engineLoad(LoadStoreParameter params); @Override Enumeration<String> engineAliases(); @Override boolean engineContainsAlias(String alias); @Override void engineDeleteEntry(String alias); @Override Certificate engineGetCertificate(String alias); @Override boolean engineIsCertificateEntry(String alias); @Override boolean engineIsKeyEntry(String alias); @Override void engineSetCertificateEntry(String alias, Certificate cert); @Override int engineSize(); @Override void engineStore(OutputStream stream, char[] password); @Override void engineSetKeyEntry(String alias, byte[] key, Certificate[] chain); @Override void engineSetKeyEntry(String alias, Key key, char[] password, Certificate[] chain); @Override void engineLoad(InputStream stream, char[] password); @Override String engineGetCertificateAlias(Certificate cert); @Override Certificate[] engineGetCertificateChain(String alias); @Override Date engineGetCreationDate(String alias); @Override Key engineGetKey(String alias, char[] password); }### Answer: @Test(expected = UnsupportedOperationException.class) public void testEngineStoreOutputStreamCharArray() throws Exception { store.engineStore(null); }
### Question: SimpleMemoryKeyStore extends KeyStoreSpi { @Override public void engineSetKeyEntry(String alias, byte[] key, Certificate[] chain) throws KeyStoreException { throw new UnsupportedOperationException(); } @Override void engineLoad(LoadStoreParameter params); @Override Enumeration<String> engineAliases(); @Override boolean engineContainsAlias(String alias); @Override void engineDeleteEntry(String alias); @Override Certificate engineGetCertificate(String alias); @Override boolean engineIsCertificateEntry(String alias); @Override boolean engineIsKeyEntry(String alias); @Override void engineSetCertificateEntry(String alias, Certificate cert); @Override int engineSize(); @Override void engineStore(OutputStream stream, char[] password); @Override void engineSetKeyEntry(String alias, byte[] key, Certificate[] chain); @Override void engineSetKeyEntry(String alias, Key key, char[] password, Certificate[] chain); @Override void engineLoad(InputStream stream, char[] password); @Override String engineGetCertificateAlias(Certificate cert); @Override Certificate[] engineGetCertificateChain(String alias); @Override Date engineGetCreationDate(String alias); @Override Key engineGetKey(String alias, char[] password); }### Answer: @Test(expected = UnsupportedOperationException.class) public void testEngineSetKeyEntryStringByteArrayCertificateArray() throws Exception { store.engineSetKeyEntry(null,null,null); } @Test(expected = UnsupportedOperationException.class) public void testEngineSetKeyEntryStringKeyCharArrayCertificateArray() throws Exception { store.engineSetKeyEntry(null, null, null); }
### Question: SimpleMemoryKeyStore extends KeyStoreSpi { @Override public void engineLoad(LoadStoreParameter params) throws IOException, NoSuchAlgorithmException, CertificateException { logger.debug("creating cert store."); if (params == null) { throw new IllegalArgumentException("parameter null"); } else if (!(params instanceof SimpleMemoryKeyStoreLoadStoreParameter)) { throw new IllegalArgumentException("Wrong parameter type"); } X509Certificate[] certs = ((SimpleMemoryKeyStoreLoadStoreParameter) params).getCerts(); this.certMap = new ConcurrentHashMap<String,X509Certificate>(); if (certs != null) { for (X509Certificate cert : certs) { if (cert != null) { logger.debug("adding cert " + cert.getSubjectDN().getName()); certMap.put(cert.getSubjectDN().getName(), cert); } } } } @Override void engineLoad(LoadStoreParameter params); @Override Enumeration<String> engineAliases(); @Override boolean engineContainsAlias(String alias); @Override void engineDeleteEntry(String alias); @Override Certificate engineGetCertificate(String alias); @Override boolean engineIsCertificateEntry(String alias); @Override boolean engineIsKeyEntry(String alias); @Override void engineSetCertificateEntry(String alias, Certificate cert); @Override int engineSize(); @Override void engineStore(OutputStream stream, char[] password); @Override void engineSetKeyEntry(String alias, byte[] key, Certificate[] chain); @Override void engineSetKeyEntry(String alias, Key key, char[] password, Certificate[] chain); @Override void engineLoad(InputStream stream, char[] password); @Override String engineGetCertificateAlias(Certificate cert); @Override Certificate[] engineGetCertificateChain(String alias); @Override Date engineGetCreationDate(String alias); @Override Key engineGetKey(String alias, char[] password); }### Answer: @Test(expected = UnsupportedOperationException.class) public void testEngineLoadInputStreamCharArray() throws Exception { store.engineLoad(null,new char[3]); }
### Question: SimpleMemoryKeyStore extends KeyStoreSpi { @Override public String engineGetCertificateAlias(Certificate cert) { throw new UnsupportedOperationException(); } @Override void engineLoad(LoadStoreParameter params); @Override Enumeration<String> engineAliases(); @Override boolean engineContainsAlias(String alias); @Override void engineDeleteEntry(String alias); @Override Certificate engineGetCertificate(String alias); @Override boolean engineIsCertificateEntry(String alias); @Override boolean engineIsKeyEntry(String alias); @Override void engineSetCertificateEntry(String alias, Certificate cert); @Override int engineSize(); @Override void engineStore(OutputStream stream, char[] password); @Override void engineSetKeyEntry(String alias, byte[] key, Certificate[] chain); @Override void engineSetKeyEntry(String alias, Key key, char[] password, Certificate[] chain); @Override void engineLoad(InputStream stream, char[] password); @Override String engineGetCertificateAlias(Certificate cert); @Override Certificate[] engineGetCertificateChain(String alias); @Override Date engineGetCreationDate(String alias); @Override Key engineGetKey(String alias, char[] password); }### Answer: @Test(expected = UnsupportedOperationException.class) public void testEngineGetCertificateAliasCertificate() throws Exception { store.engineGetCertificateAlias(cert); }
### Question: SimpleMemoryKeyStore extends KeyStoreSpi { @Override public Certificate[] engineGetCertificateChain(String alias) { throw new UnsupportedOperationException(); } @Override void engineLoad(LoadStoreParameter params); @Override Enumeration<String> engineAliases(); @Override boolean engineContainsAlias(String alias); @Override void engineDeleteEntry(String alias); @Override Certificate engineGetCertificate(String alias); @Override boolean engineIsCertificateEntry(String alias); @Override boolean engineIsKeyEntry(String alias); @Override void engineSetCertificateEntry(String alias, Certificate cert); @Override int engineSize(); @Override void engineStore(OutputStream stream, char[] password); @Override void engineSetKeyEntry(String alias, byte[] key, Certificate[] chain); @Override void engineSetKeyEntry(String alias, Key key, char[] password, Certificate[] chain); @Override void engineLoad(InputStream stream, char[] password); @Override String engineGetCertificateAlias(Certificate cert); @Override Certificate[] engineGetCertificateChain(String alias); @Override Date engineGetCreationDate(String alias); @Override Key engineGetKey(String alias, char[] password); }### Answer: @Test(expected = UnsupportedOperationException.class) public void testEngineGetCertificateChainString() throws Exception { store.engineGetCertificateChain("test"); }
### Question: SimpleMemoryKeyStore extends KeyStoreSpi { @Override public Date engineGetCreationDate(String alias) { throw new UnsupportedOperationException(); } @Override void engineLoad(LoadStoreParameter params); @Override Enumeration<String> engineAliases(); @Override boolean engineContainsAlias(String alias); @Override void engineDeleteEntry(String alias); @Override Certificate engineGetCertificate(String alias); @Override boolean engineIsCertificateEntry(String alias); @Override boolean engineIsKeyEntry(String alias); @Override void engineSetCertificateEntry(String alias, Certificate cert); @Override int engineSize(); @Override void engineStore(OutputStream stream, char[] password); @Override void engineSetKeyEntry(String alias, byte[] key, Certificate[] chain); @Override void engineSetKeyEntry(String alias, Key key, char[] password, Certificate[] chain); @Override void engineLoad(InputStream stream, char[] password); @Override String engineGetCertificateAlias(Certificate cert); @Override Certificate[] engineGetCertificateChain(String alias); @Override Date engineGetCreationDate(String alias); @Override Key engineGetKey(String alias, char[] password); }### Answer: @Test(expected = UnsupportedOperationException.class) public void testEngineGetCreationDateString() throws Exception { store.engineGetCreationDate("test"); }
### Question: SimpleMemoryKeyStore extends KeyStoreSpi { @Override public Key engineGetKey(String alias, char[] password) throws NoSuchAlgorithmException, UnrecoverableKeyException { throw new UnsupportedOperationException(); } @Override void engineLoad(LoadStoreParameter params); @Override Enumeration<String> engineAliases(); @Override boolean engineContainsAlias(String alias); @Override void engineDeleteEntry(String alias); @Override Certificate engineGetCertificate(String alias); @Override boolean engineIsCertificateEntry(String alias); @Override boolean engineIsKeyEntry(String alias); @Override void engineSetCertificateEntry(String alias, Certificate cert); @Override int engineSize(); @Override void engineStore(OutputStream stream, char[] password); @Override void engineSetKeyEntry(String alias, byte[] key, Certificate[] chain); @Override void engineSetKeyEntry(String alias, Key key, char[] password, Certificate[] chain); @Override void engineLoad(InputStream stream, char[] password); @Override String engineGetCertificateAlias(Certificate cert); @Override Certificate[] engineGetCertificateChain(String alias); @Override Date engineGetCreationDate(String alias); @Override Key engineGetKey(String alias, char[] password); }### Answer: @Test(expected = UnsupportedOperationException.class) public void testEngineGetKeyStringCharArray() throws Exception { store.engineGetKey("test", new char[] {'t'}); }
### Question: SimpleMemorySigningPolicyStore implements SigningPolicyStore { public SigningPolicy getSigningPolicy(X500Principal caPrincipal) throws SigningPolicyStoreException { SigningPolicy policy = store.get(caPrincipal.getName(X500Principal.RFC2253)); if (policy == null) { X509Name name = new X509Name(false, caPrincipal.getName(X500Principal.RFC2253)); logger.debug("Getting from policy store: " + X509NameHelper.toString(name)); policy = store.get(X509NameHelper.toString(name)); } return policy; } SimpleMemorySigningPolicyStore(SigningPolicy[] policies); SigningPolicy getSigningPolicy(X500Principal caPrincipal); }### Answer: @Test public void testGetSigningPolicy() throws Exception { SigningPolicyParser parser = new SigningPolicyParser(); Map<X500Principal, SigningPolicy> policies; policies = parser.parse(new InputStreamReader(new GlobusPathMatchingResourcePatternResolver().getResource("classpath:/org/globus/gsi/test/49f18420.signing_policy").getInputStream())); assertNotNull(policies); assertFalse(policies.isEmpty()); SimpleMemorySigningPolicyStore store = new SimpleMemorySigningPolicyStore(policies.values().toArray(new SigningPolicy[1])); for (X500Principal p : policies.keySet()) { assertNotNull(store.getSigningPolicy(p)); } }
### Question: StringUtils { @SuppressWarnings({"SameParameterValue"}) public static String prependEachLine(String s, String prependWith) { StringWriter sw = new StringWriter(s.length()+(prependWith.length()*20)); prependEachLine(new PrintWriter(sw), s, prependWith); return sw.toString(); } @SuppressWarnings({"SameParameterValue", "SameParameterValue"}) static String align(String s, int width, int alignment); static String align(String s, int width, char paddingChar, int alignment); static void align(PrintWriter output, String s, int width, int alignment); static void align(PrintWriter output, String s, int width, char paddingChar, int alignment); static String multiply(char c, int count); static String multiply(String s, int count); static void multiply(PrintWriter output, char c, int count); @SuppressWarnings({"SameParameterValue"}) static void multiply(PrintWriter output, String s, int count); @SuppressWarnings({"SameParameterValue"}) static String prependEachLine(String s, String prependWith); static void prependEachLine(PrintWriter output, String s, String prependWith); static final int ALIGN_LEFT; static final int ALIGN_CENTER; static final int ALIGN_RIGHT; }### Answer: @Test public void testPrependEachLine() throws Exception { Assert.assertEquals(" 1\n 2\n 3", StringUtils.prependEachLine("1\n2\n3", " ")); } @Test public void testPrependEachLineWithWriter() throws Exception { StringUtils.prependEachLine(getWriter(), "1\n2\n3", " "); assertWriter(" 1\n 2\n 3"); }
### Question: MarkdownTable { public int getNumberOfColumns() { int columns = 0; for(List<MarkdownTableCell> row : this.header) { columns = Math.max(columns, getNumberOfColumnsInRow(row)); } for(List<MarkdownTableCell> row : this.body) { columns = Math.max(columns, getNumberOfColumnsInRow(row)); } return columns; } MarkdownTable(); List<MarkdownTableCell> addHeaderRow(); List<MarkdownTableCell> addBodyRow(); void renderTable(PrintWriter output, boolean allowColspan, boolean renderAsCode); int getNumberOfColumns(); }### Answer: @Test public void testGetNumberOfColumns() throws Exception { MarkdownTable mt = new MarkdownTable(); for(int i=0; i<10; i++) { List<MarkdownTableCell> row = mt.addBodyRow(); for(int j=0; j <= i%5; j++) { row.add(new MarkdownTableCell("cell "+j)); } } Assert.assertEquals(5, mt.getNumberOfColumns()); }
### Question: TextCleaner { public String clean(Object input) { return clean(input, true); } TextCleaner(Options options); String clean(Object input); String cleanCode(Object input); String cleanInlineCode(Object input); String unescapeLeadingCharacters(String input); String cleanUrl(String input); }### Answer: @Test public void testCleanBasic() throws Exception { assertEqualsAndPrint(loadOut("cleanBasic"), BASIC.clean(loadBasicIn())); } @Test public void testCleanFull() throws Exception { assertEqualsAndPrint(loadOut("cleanFull"), FULL.clean(loadFullIn())); }
### Question: TextCleaner { public String cleanCode(Object input) { return clean(input, false); } TextCleaner(Options options); String clean(Object input); String cleanCode(Object input); String cleanInlineCode(Object input); String unescapeLeadingCharacters(String input); String cleanUrl(String input); }### Answer: @Test public void testCleanCodeBasic() throws Exception { assertEqualsAndPrint(loadOut("cleanCodeBasic"), BASIC.cleanCode(loadBasicIn())); } @Test public void testCleanCodeFull() throws Exception { assertEqualsAndPrint(loadOut("cleanCodeFull"), FULL.cleanCode(loadFullIn())); }
### Question: TextCleaner { public String cleanInlineCode(Object input) { String output = clean(input, false).replace('\n', ' '); if(output.indexOf('`') != -1) { String prepend = ""; if(output.charAt(0) == '`') { prepend = " "; } String append = ""; if(output.charAt(output.length()-1) == '`') { append = " "; } String delim = getDelimiter(output); output = String.format("%s%s%s%s%s", delim, prepend, output, append, delim); } else { output = String.format("`%s`", output); } return output; } TextCleaner(Options options); String clean(Object input); String cleanCode(Object input); String cleanInlineCode(Object input); String unescapeLeadingCharacters(String input); String cleanUrl(String input); }### Answer: @Test public void testCleanInlineCodeSimple() throws Exception { Assert.assertEquals("`hello & > world`", BASIC.cleanInlineCode("hello &amp; \n&gt; world")); } @Test public void testCleanInlineCodeLeadingTick() throws Exception { Assert.assertEquals("`` `tick``", BASIC.cleanInlineCode("`tick")); } @Test public void testCleanInlineCodeTrailingTick() throws Exception { Assert.assertEquals("``tick` ``", BASIC.cleanInlineCode("tick`")); } @Test public void testCleanInlineCodeInlineTick() throws Exception { Assert.assertEquals("``ti`ck``", BASIC.cleanInlineCode("ti`ck")); } @Test public void testCleanInlineCodeLotsOfTicks() throws Exception { Assert.assertEquals("```` ``t```i`ck` ````", BASIC.cleanInlineCode("``t`&#96;`i`ck`")); }
### Question: Strings { public static String replaceLast(String text, String regex, String replacement) { return text.replaceFirst("(?s)(.*)" + regex, "$1" + replacement); } private Strings(); static String replaceLast(String text, String regex, String replacement); static SpannableStringBuilder colorizeBackground(@NonNull String text, @NonNull String matchText, @ColorInt int color, boolean ignoreCase); static String EMPTY; static String NEW_LINE; }### Answer: @Test public void replaceLast() throws Exception { Assertions.assertThat("2017-02-14T13:54:04+0900") .isEqualTo(Strings.replaceLast("2017-02-14T13:54:04+09:00", ":", "")); }
### Question: StringUtils { public static String multiply(char c, int count) { return multiply(String.valueOf(c), count); } @SuppressWarnings({"SameParameterValue", "SameParameterValue"}) static String align(String s, int width, int alignment); static String align(String s, int width, char paddingChar, int alignment); static void align(PrintWriter output, String s, int width, int alignment); static void align(PrintWriter output, String s, int width, char paddingChar, int alignment); static String multiply(char c, int count); static String multiply(String s, int count); static void multiply(PrintWriter output, char c, int count); @SuppressWarnings({"SameParameterValue"}) static void multiply(PrintWriter output, String s, int count); @SuppressWarnings({"SameParameterValue"}) static String prependEachLine(String s, String prependWith); static void prependEachLine(PrintWriter output, String s, String prependWith); static final int ALIGN_LEFT; static final int ALIGN_CENTER; static final int ALIGN_RIGHT; }### Answer: @Test public void testMultiplyCharacter() throws Exception { Assert.assertEquals("", StringUtils.multiply('c', 0)); Assert.assertEquals("ccc", StringUtils.multiply('c', 3)); } @Test public void testMultiplyString() throws Exception { Assert.assertEquals("", StringUtils.multiply("str", 0)); Assert.assertEquals("strstrstrstr", StringUtils.multiply("str", 4)); } @Test public void testMultiplyCharacterWithWriter() throws Exception { StringUtils.multiply(getWriter(), 'c', 0); assertWriter(""); StringUtils.multiply(getWriter(), 'c', 3); assertWriter("ccc"); } @Test public void testMultiplyStringWithWriter() throws Exception { StringUtils.multiply(getWriter(), "str", 0); assertWriter(""); StringUtils.multiply(getWriter(), "str", 4); assertWriter("strstrstrstr"); }
### Question: TorqueDecoder implements Decoder<T> { public void update(T next) { counterBasedDecoder.update(next); } TorqueDecoder(FilteredBroadcastMessenger<TaggedTelemetryEvent> updateHub); void reset(); void update(T next); void invalidate(); }### Answer: @Test public void matchesKnownGood() { FilteredBroadcastMessenger<TaggedTelemetryEvent> bus = new FilteredBroadcastMessenger<TaggedTelemetryEvent>(); class PowerListener implements BroadcastListener<TaggedTelemetryEvent> { BigDecimal power; public void receiveMessage(TaggedTelemetryEvent telemetryEvent) { if (telemetryEvent instanceof TorquePowerUpdate) { TorquePowerUpdate up = (TorquePowerUpdate) telemetryEvent; power = up.getPower(); } } }; PowerListener powerListener = new PowerListener(); bus.addListener(TaggedTelemetryEvent.class, powerListener); BigDecimal speed = new BigDecimal(10.0); BigDecimal period = WHEEL_CIRCUM.multiply(new BigDecimal(Math.pow(10, -3))).divide(speed, 20, BigDecimal.ROUND_HALF_UP); int power = 200; int rotationsDelta = 10; int eventsDelta = 1; final byte[] data1 = new byte[8]; final byte[] data2 = new byte[8]; new TorqueData.TorqueDataPayload() .encode(data1); new TorqueData.TorqueDataPayload() .setEvents(eventsDelta) .updateTorqueSumFromPower(power, period) .setRotations(rotationsDelta) .encode(data2); TorqueData p1 = new TorqueData(data1); TorqueData p2 = new TorqueData(data2); TorqueDecoder<TorqueDecodable> dec = new TorqueDecoder<>(bus); dec.update(p1); dec.update(p2); assertEquals(new BigDecimal(power).setScale(0, RoundingMode.HALF_UP), powerListener.power.setScale(0, RoundingMode.HALF_UP)); }
### Question: RotationsToDistanceDecoder implements Decoder<T> { @Override public void update(T newPage) { decoder.update(newPage); } RotationsToDistanceDecoder(FilteredBroadcastMessenger<TaggedTelemetryEvent> updateHub, BigDecimal wheelCircumference); void reset(); @Override void update(T newPage); @Override void invalidate(); }### Answer: @Test public void matchesKnownGood() { FilteredBroadcastMessenger<TaggedTelemetryEvent> bus = new FilteredBroadcastMessenger<TaggedTelemetryEvent>(); class FreqListener implements BroadcastListener<TaggedTelemetryEvent> { private long rotations; public void receiveMessage(TaggedTelemetryEvent telemetryEvent) { if (telemetryEvent instanceof WheelRotationsUpdate) { WheelRotationsUpdate up = (WheelRotationsUpdate) telemetryEvent; rotations = up.getWheelRotations(); } } }; FreqListener freqListener = new FreqListener(); bus.addListener(TaggedTelemetryEvent.class, freqListener); BigDecimal speed = new BigDecimal(10.0); BigDecimal period = WHEEL_CIRCUM.divide(speed, 20, BigDecimal.ROUND_HALF_UP); int power = 200; int rotationsDelta = 10; int eventsDelta = 1; final byte[] data1 = new byte[8]; final byte[] data2 = new byte[8]; new TorqueData.TorqueDataPayload() .encode(data1); new TorqueData.TorqueDataPayload() .setEvents(eventsDelta) .updateTorqueSumFromPower(power, period) .setRotations(rotationsDelta) .encode(data2); TorqueData p1 = new TorqueData(data1); TorqueData p2 = new TorqueData(data2); RotationsToDistanceDecoder<RotationsToDistanceDecodable> dec = new RotationsToDistanceDecoder<>(bus, WHEEL_CIRCUM); dec.update(p1); dec.update(p2); assertEquals( rotationsDelta, freqListener.rotations ); }
### Question: CoastEventTrigger implements Decoder<T> { @Override @SuppressWarnings("unchecked") public void update(T newPage) { helper.update(newPage); } CoastEventTrigger(FilteredBroadcastMessenger<TaggedTelemetryEvent> updateHub); @Override @SuppressWarnings("unchecked") void update(T newPage); @Override void invalidate(); @Override void reset(); }### Answer: @Test public void testCoastTimeout() { class CoastHelper implements BroadcastListener<TaggedTelemetryEvent> { boolean coastDetected = false; public void receiveMessage(TaggedTelemetryEvent event) { if (!(event instanceof CoastDetectedEvent)) { return; } coastDetected = true; } } FilteredBroadcastMessenger<TaggedTelemetryEvent> bus = new FilteredBroadcastMessenger<TaggedTelemetryEvent>(); CoastEventTrigger<PowerOnlyDecodable> decoder = new CoastEventTrigger<>(bus); CoastHelper listener = new CoastHelper(); bus.addListener(TaggedTelemetryEvent.class, listener); decoder.update(new PowerOnlyDecodable() { public long getSumPowerDelta(PowerOnlyDecodable old) { return 0; } public long getEventCountDelta(CounterBasedDecodable old) { return 0; } public int getSumPower() { return 0; } public int getEventCount() { return 0; } public boolean isValidDelta(CounterBasedDecodable old) { return true; } public int getInstantPower() { return 0; } public long getTimestamp() { return 0; } }); decoder.update(new PowerOnlyDecodable() { public long getSumPowerDelta(PowerOnlyDecodable old) { return 0; } public long getEventCountDelta(CounterBasedDecodable old) { return 0; } public int getSumPower() { return 0; } public int getEventCount() { return 0; } public boolean isValidDelta(CounterBasedDecodable old) { return true; } public int getInstantPower() { return 0; } public long getTimestamp() { return CoastDetector.COAST_WINDOW; } }); assertTrue(listener.coastDetected); }
### Question: LapFlagDecoder implements Decoder<T> { @Override public void update(T newPage) { if (prev == null) {prev = newPage; return;} final boolean prevState = prev.isLapToggled(); final boolean state = newPage.isLapToggled(); prev = newPage; if (state == prevState) return; laps += 1; bus.send(new LapUpdate(newPage,laps)); } LapFlagDecoder(FilteredBroadcastMessenger<TaggedTelemetryEvent> bus); @Override void update(T newPage); @Override void invalidate(); @Override void reset(); }### Answer: @Test public void shouldIncrement() { final FilteredBroadcastMessenger<TaggedTelemetryEvent> bus = new FilteredBroadcastMessenger<>(); final LapFlagDecoder<LapFlagDecodable> decoder = new LapFlagDecoder<>(bus); final int[] res = new int[1]; bus.addListener(LapUpdate.class, new BroadcastListener<LapUpdate>() { @Override public void receiveMessage(LapUpdate lapUpdate) { res[0] = lapUpdate.getLaps(); } }); assertEquals(0, res[0]); decoder.update(toggled); assertEquals(0, res[0]); decoder.update(untoggled); assertEquals(1, res[0]); decoder.update(untoggled); assertEquals(1, res[0]); decoder.update(toggled); assertEquals(2, res[0]); }
### Question: LookupManagerImpl extends UniversalManagerImpl implements LookupManager { public List<LabelValue> getAllRoles() { List<Role> roles = dao.getRoles(); List<LabelValue> list = new ArrayList<LabelValue>(); for (Role role1 : roles) { list.add(new LabelValue(role1.getName(), role1.getName())); } return list; } void setLookupDao(LookupDao dao); List<LabelValue> getAllRoles(); }### Answer: @Test public void testGetAllRoles() { log.debug("entered 'testGetAllRoles' method"); Role role = new Role(Constants.ADMIN_ROLE); final List<Role> testData = new ArrayList<Role>(); testData.add(role); context.checking(new Expectations() {{ one(lookupDao).getRoles(); will(returnValue(testData)); }}); List<LabelValue> roles = mgr.getAllRoles(); assertTrue(roles.size() > 0); }
### Question: UserManagerImpl extends UniversalManagerImpl implements UserManager, UserService { public User getUser(String userId) { return dao.get(new Integer(userId)); } @Required void setPasswordEncoder(PasswordEncoder passwordEncoder); User getUser(String userId); List<User> getUsers(User user); String createSession(User user); User authenticate(String username, String password); User authenticate(String sessionKey); void logout(UserSession userSession); User saveUser(User user); void removeUser(String userId); User getUserByUsername(String username); UserSessionDao getUserSessionDao(); void setUserSessionDao(UserSessionDao userSessionDao); @Required void setUserDao(UserDao dao); }### Answer: @Test public void testGetUser() throws Exception { final User testData = new User("1"); testData.getRoles().add(new Role("user")); context.checking(new Expectations() {{ one(userDao).get(with(equal(1))); will(returnValue(testData)); }}); User user = userManager.getUser("1"); assertTrue(user != null); assert user != null; assertTrue(user.getRoles().size() == 1); }
### Question: LuaProfile extends ProfileDefinition { @Override public RulesProfile createProfile(ValidationMessages validation) { AnnotationBasedProfileBuilder annotationBasedProfileBuilder = new AnnotationBasedProfileBuilder(ruleFinder); return annotationBasedProfileBuilder.build( CheckList.REPOSITORY_KEY, CheckList.SONAR_WAY_PROFILE, Lua.KEY, CheckList.getChecks(), validation); } LuaProfile(RuleFinder ruleFinder); @Override RulesProfile createProfile(ValidationMessages validation); }### Answer: @Test public void should_create_sonar_way_profile() { ValidationMessages validation = ValidationMessages.create(); RuleFinder ruleFinder = ruleFinder(); LuaProfile definition = new LuaProfile(ruleFinder); RulesProfile profile = definition.createProfile(validation); assertThat(profile.getLanguage()).isEqualTo(Lua.KEY); assertThat(profile.getName()).isEqualTo(CheckList.SONAR_WAY_PROFILE); assertThat(profile.getActiveRulesByRepository(CheckList.REPOSITORY_KEY)).hasSize(15); assertThat(validation.hasErrors()).isFalse(); }
### Question: CoberturaSensor implements Sensor { @Override public void describe(SensorDescriptor descriptor) { descriptor .name("Lua Cobertura") .onlyOnFileType(InputFile.Type.MAIN) .onlyOnLanguage(Lua.KEY); } @Override void describe(SensorDescriptor descriptor); @Override void execute(SensorContext context); }### Answer: @Test public void testDescriptor() { DefaultSensorDescriptor descriptor = new DefaultSensorDescriptor(); sensor.describe(descriptor); assertThat(descriptor.name()).isEqualTo("Lua Cobertura"); assertThat(descriptor.languages()).containsOnly("lua"); }
### Question: LuaToolkit { @VisibleForTesting static List<Tokenizer> getTokenizers() { return ImmutableList.of( new StringTokenizer("<span class=\"s\">", "</span>"), new CDocTokenizer("<span class=\"cd\">", "</span>"), new JavadocTokenizer("<span class=\"cppd\">", "</span>"), new CppDocTokenizer("<span class=\"cppd\">", "</span>"), new KeywordsTokenizer("<span class=\"k\">", "</span>", LuaKeyword.keywordValues())); } private LuaToolkit(); static void main(String[] args); }### Answer: @Test public void test() { assertThat(LuaToolkit.getTokenizers().size()).isEqualTo(5); }
### Question: LuaCommentAnalyser extends CommentAnalyser { @Override public String getContents(String comment) { if (comment.startsWith("--[[")) { if (comment.endsWith("--]]")) { return comment.substring(4, comment.length() - 4); } return comment.substring(4); } else if (comment.startsWith("--")) { return comment.substring(2, comment.length()); } else{ throw new IllegalArgumentException(); } } @Override boolean isBlank(String line); @Override String getContents(String comment); }### Answer: @Test public void content() { assertThat(analyser.getContents("--[[comment1 \n comment2--]]")).isEqualTo("comment1 \n comment2"); assertThat(analyser.getContents("--comment")).isEqualTo("comment"); } @Test public void unknown_type_of_comment() { thrown.expect(IllegalArgumentException.class); analyser.getContents(""); }
### Question: LuaCommentAnalyser extends CommentAnalyser { @Override public boolean isBlank(String line) { for (int i = 0; i < line.length(); i++) { if (Character.isLetterOrDigit(line.charAt(i))) { return false; } } return true; } @Override boolean isBlank(String line); @Override String getContents(String comment); }### Answer: @Test public void blank() { assertThat(analyser.isBlank(" ")).isTrue(); assertThat(analyser.isBlank("comment")).isFalse(); }
### Question: FunctionCallComplexityCheck extends LuaCheck { public void setMaximumFunctionCallComplexityThreshold(int threshold) { this.maximumFunctionCallComplexityThreshold = threshold; } @Override void init(); @Override void leaveNode(AstNode node); void setMaximumFunctionCallComplexityThreshold(int threshold); }### Answer: @Test public void test() { FunctionCallComplexityCheck check = new FunctionCallComplexityCheck(); check.setMaximumFunctionCallComplexityThreshold(1); SourceFile file = LuaAstScanner.scanSingleFile(new File("src/test/resources/checks/functionCallComplexity.lua"), check); CheckMessagesVerifier.verify(file.getCheckMessages()) .next().atLine(1).withMessage("FunctionCall has a complexity of 5 which is greater than 1 authorized.") .noMore(); }
### Question: MethodComplexityCheck extends LuaCheck { public void setMaximumFunctionComplexityThreshold(int threshold) { this.maximumMethodComplexityThreshold = threshold; } @Override void init(); @Override void leaveNode(AstNode node); void setMaximumFunctionComplexityThreshold(int threshold); static final String CHECK_KEY; }### Answer: @Test public void test() { MethodComplexityCheck check = new MethodComplexityCheck(); check.setMaximumFunctionComplexityThreshold(0); SourceFile file = LuaAstScanner.scanSingleFile(new File("src/test/resources/checks/methodComplexity.lua"), check); CheckMessagesVerifier.verify(file.getCheckMessages()) .next().atLine(1).withMessage("Method has a complexity of 6 which is greater than 0 authorized.") .next().atLine(3).withMessage("Method has a complexity of 2 which is greater than 0 authorized.") .next().atLine(4).withMessage("Method has a complexity of 1 which is greater than 0 authorized.") .next().atLine(11).withMessage("Method has a complexity of 1 which is greater than 0 authorized.") .noMore(); }
### Question: FileComplexityCheck extends SquidCheck<LexerlessGrammar> { public void setMaximumFileComplexityThreshold(int threshold) { this.maximumFileComplexityThreshold = threshold; } @Override void leaveFile(AstNode astNode); void setMaximumFileComplexityThreshold(int threshold); static final String CHECK_KEY; }### Answer: @Test public void test() { check.setMaximumFileComplexityThreshold(0); SourceFile file = LuaAstScanner.scanSingleFile(new File("src/test/resources/checks/fileComplexity.lua"), check); CheckMessagesVerifier.verify(file.getCheckMessages()) .next().withMessage("File has a complexity of 1 which is greater than 0"+ " authorized.") .noMore(); }
### Question: LocalFunctionComplexityCheck extends LuaCheck { public void setMaximumFunctionComplexityThreshold(int threshold) { this.maximumLocalFunctionComplexityThreshold = threshold; } @Override void init(); @Override void leaveNode(AstNode node); void setMaximumFunctionComplexityThreshold(int threshold); static final String CHECK_KEY; }### Answer: @Test public void test() { LocalFunctionComplexityCheck check = new LocalFunctionComplexityCheck(); check.setMaximumFunctionComplexityThreshold(0); SourceFile file = LuaAstScanner.scanSingleFile(new File("src/test/resources/checks/localFunctionComplexity.lua"), check); CheckMessagesVerifier.verify(file.getCheckMessages()) .next().atLine(1).withMessage("LocalFunction has a complexity of 6 which is greater than 0 authorized.") .next().atLine(2).withMessage("LocalFunction has a complexity of 3 which is greater than 0 authorized.") .noMore(); }
### Question: FunctionComplexityCheck extends LuaCheck { public void setMaximumFunctionComplexityThreshold(int threshold) { this.maximumFunctionComplexityThreshold = threshold; } @Override void init(); @Override void leaveNode(AstNode node); void setMaximumFunctionComplexityThreshold(int threshold); static final String CHECK_KEY; }### Answer: @Test public void test() { FunctionComplexityCheck check = new FunctionComplexityCheck(); check.setMaximumFunctionComplexityThreshold(0); SourceFile file = LuaAstScanner.scanSingleFile(new File("src/test/resources/checks/functionComplexity.lua"), check); CheckMessagesVerifier.verify(file.getCheckMessages()) .next().atLine(1).withMessage("Function has a complexity of 4 which is greater than 0 authorized.") .noMore(); }
### Question: TableComplexityCheck extends LuaCheck { public void setMaximumTableComplexityThreshold(int threshold) { this.maximumTableComplexityThreshold = threshold; } @Override void init(); @Override void leaveNode(AstNode node); void setMaximumTableComplexityThreshold(int threshold); }### Answer: @Test public void test() { TableComplexityCheck check = new TableComplexityCheck(); check.setMaximumTableComplexityThreshold(0); SourceFile file = LuaAstScanner.scanSingleFile(new File("src/test/resources/checks/tableComplexity.lua"), check); CheckMessagesVerifier.verify(file.getCheckMessages()) .next().atLine(1).withMessage("Table has a complexity of 1 which is greater than 0 authorized.") .noMore(); }
### Question: LuaSquidSensor implements Sensor { @Override public void describe(SensorDescriptor descriptor) { descriptor .name("Lua") .onlyOnFileType(InputFile.Type.MAIN) .onlyOnLanguage(Lua.KEY); } LuaSquidSensor(CheckFactory checkFactory, FileLinesContextFactory fileLinesContextFactory); @Override void describe(SensorDescriptor descriptor); @Override void execute(SensorContext context); }### Answer: @Test public void testDescriptor() { DefaultSensorDescriptor descriptor = new DefaultSensorDescriptor(); sensor.describe(descriptor); assertThat(descriptor.name()).isEqualTo("Lua"); assertThat(descriptor.languages()).containsOnly("lua"); }
### Question: LuaRulesDefinition implements RulesDefinition { @Override public void define(Context context) { NewRepository repository = context .createRepository(CheckList.REPOSITORY_KEY, "lua") .setName(REPOSITORY_NAME); new AnnotationBasedRulesDefinition(repository, "lua").addRuleClasses(false, CheckList.getChecks()); repository.done(); } @Override void define(Context context); }### Answer: @Test public void test() { LuaRulesDefinition rulesDefinition = new LuaRulesDefinition(); RulesDefinition.Context context = new RulesDefinition.Context(); rulesDefinition.define(context); RulesDefinition.Repository repository = context.repository("lua"); assertThat(repository.name()).isEqualTo("SonarQube"); assertThat(repository.language()).isEqualTo("lua"); assertThat(repository.rules()).hasSize(CheckList.getChecks().size()); for (RulesDefinition.Rule rule : repository.rules()) { for (RulesDefinition.Param param : rule.params()) { assertThat(param.description()).as("description for " + param.key() + " of " + rule.key()).isNotEmpty(); } } }
### Question: Lua extends AbstractLanguage { @Override public String[] getFileSuffixes() { String[] suffixes = filterEmptyStrings(settings.getStringArray(LuaPlugin.FILE_SUFFIXES_KEY)); if (suffixes.length == 0) { suffixes = StringUtils.split(DEFAULT_FILE_SUFFIXES, ","); } return suffixes; } Lua(Settings settings); @Override String[] getFileSuffixes(); static final String NAME; static final String KEY; static final String DEFAULT_FILE_SUFFIXES; }### Answer: @Test public void testGetFileSuffixes() { Settings settings = new Settings(); Lua lua = new Lua(settings); assertThat(lua.getFileSuffixes()).isEqualTo(new String[] {"lua"}); settings.setProperty(LuaPlugin.FILE_SUFFIXES_KEY, ""); assertThat(lua.getFileSuffixes()).isEqualTo(new String[] {"lua"}); settings.setProperty(LuaPlugin.FILE_SUFFIXES_KEY, "lua"); assertThat(lua.getFileSuffixes()).isEqualTo(new String[] {"lua"}); }
### Question: LuaPlugin implements Plugin { @Override public void define(Context context) { context.addExtensions( Lua.class, LuaSquidSensor.class, CoberturaSensor.class, LuaRulesDefinition.class, LuaProfile.class, PropertyDefinition.builder(FILE_SUFFIXES_KEY) .defaultValue(Lua.DEFAULT_FILE_SUFFIXES) .name("File suffixes") .description("Comma-separated list of suffixes for files to analyze. To not filter, leave the list empty.") .onQualifiers(Qualifiers.MODULE, Qualifiers.PROJECT) .build(), PropertyDefinition.builder(COBERTURA_REPORT_PATH) .name("Cobertura xml report path") .description("Path to the Cobertura coverage report file. The path may be either absolute or relative to the project base directory.") .onQualifiers(Qualifiers.MODULE, Qualifiers.PROJECT) .build() ); } @Override void define(Context context); static final String FILE_SUFFIXES_KEY; static final String COBERTURA_REPORT_PATH; }### Answer: @Test public void testGetExtensions() throws Exception { Plugin.Context context = new Plugin.Context(Version.create(5, 6)); new LuaPlugin().define(context); assertThat(context.getExtensions()).isNotEmpty(); }
### Question: CoberturaReportParser { public static void parseReport(File xmlFile, final SensorContext context) { try { StaxParser parser = new StaxParser(rootCursor -> { rootCursor.advance(); collectPackageMeasures(rootCursor.descendantElementCursor("package"), context); }); parser.parse(xmlFile); } catch (XMLStreamException e) { throw new IllegalStateException(e); } } private CoberturaReportParser(); static void parseReport(File xmlFile, final SensorContext context); }### Answer: @Test(expected = IllegalStateException.class) public void invalidXmlFile() throws Exception { CoberturaReportParser.parseReport( TestUtils.getResource("org/sonar/plugins/lua/cobertura/coverage-invalid.xml"), SensorContextTester.create(new File(".")) ); }
### Question: SmartcarAuth { public void addClickHandler(final Context context, final View view) { addClickHandler(context, view, (new AuthUrlBuilder()).build()); } SmartcarAuth(String clientId, String redirectUri, String[] scope, SmartcarCallback callback); SmartcarAuth(String clientId, String redirectUri, String[] scope, boolean testMode, SmartcarCallback callback); AuthUrlBuilder authUrlBuilder(); void addClickHandler(final Context context, final View view); void addClickHandler(final Context context, final View view, final String authUrl); void launchAuthFlow(final Context context); void launchAuthFlow(final Context context, final String authUrl); }### Answer: @Test public void smartcarAuth_addClickHandler() { Context context = mock(Context.class); View view = mock(View.class); SmartcarAuth smartcarAuth = new SmartcarAuth( "client123", "scclient123: new String[] {"read_odometer", "read_vin"}, null ); smartcarAuth.addClickHandler(context, view); verify(view, times(1)) .setOnClickListener(Mockito.any(View.OnClickListener.class)); }
### Question: SmartcarAuth { public void launchAuthFlow(final Context context) { launchAuthFlow(context, (new AuthUrlBuilder()).build()); } SmartcarAuth(String clientId, String redirectUri, String[] scope, SmartcarCallback callback); SmartcarAuth(String clientId, String redirectUri, String[] scope, boolean testMode, SmartcarCallback callback); AuthUrlBuilder authUrlBuilder(); void addClickHandler(final Context context, final View view); void addClickHandler(final Context context, final View view, final String authUrl); void launchAuthFlow(final Context context); void launchAuthFlow(final Context context, final String authUrl); }### Answer: @Test public void smartcarAuth_launchAuthFlow() { Context context = mock(Context.class); SmartcarAuth smartcarAuth = new SmartcarAuth( "client123", "scclient123: new String[] {"read_odometer", "read_vin"}, null ); smartcarAuth.launchAuthFlow(context); }
### Question: ApduSessionParameter implements Serializable { public byte[] getValueAsBytes() { return Hex.decode(value); } ApduSessionParameter(); ApduSessionParameter(String name, String value); ApduSessionParameter(String name, byte[] value); String getName(); @Override boolean equals(Object o); @Override int hashCode(); void setName(String name); String getValue(); void setValue(String value); byte[] getValueAsBytes(); void setValue(byte[] value); void setValue(byte[] value, int index, int length); @Override String toString(); }### Answer: @Test public void getValueAsBytes() { ApduSessionParameter parameter = new ApduSessionParameter(); parameter.setName("Test Parameter"); parameter.setValue("0102030405"); byte[] value = parameter.getValueAsBytes(); Assert.assertArrayEquals( new byte[]{1, 2, 3, 4, 5}, value); }
### Question: KieWorkbenchEntryPoint extends DefaultWorkbenchEntryPoint { @PostConstruct public void init() { appFormerJsBridge.init("org.kie.bc.KIEWebapp"); homeConfiguration.setMonitoring(true); workbench.addStartupBlocker(KieWorkbenchEntryPoint.class); navigationExplorerScreen.getNavTreeEditor().setMaxLevels(NavTreeDefinitions.GROUP_WORKBENCH, 2); } @Inject KieWorkbenchEntryPoint(final Caller<AppConfigService> appConfigService, final ActivityBeansCache activityBeansCache, final DefaultWorkbenchFeaturesMenusHelper menusHelper, final ClientUserSystemManager userSystemManager, final WorkbenchMegaMenuPresenter menuBar, final Workbench workbench, final PermissionTreeSetup permissionTreeSetup, final DefaultAdminPageHelper adminPageHelper, final NavTreeDefinitions navTreeDefinitions, final NavigationManager navigationManager, final NavigationExplorerScreen navigationExplorerScreen, final DefaultWorkbenchErrorCallback defaultWorkbenchErrorCallback, final AppFormerJsBridge appFormerJsBridge, final HomeConfiguration homeConfiguration); @PostConstruct void init(); @Override void setupMenu(); void onNavTreeChanged(@Observes final NavTreeChangedEvent event); void onAuthzPolicyChanged(@Observes final SaveRoleEvent event); void onAuthzPolicyChanged(@Observes final SaveGroupEvent event); }### Answer: @Test public void initTest() { kieWorkbenchEntryPoint.init(); verify(workbench).addStartupBlocker(KieWorkbenchEntryPoint.class); verify(navTreeEditor).setMaxLevels(NavTreeDefinitions.GROUP_WORKBENCH, 2); }
### Question: KieWorkbenchEntryPoint extends DefaultWorkbenchEntryPoint { @Override protected void initializeWorkbench() { permissionTreeSetup.configureTree(); super.initializeWorkbench(); } @Inject KieWorkbenchEntryPoint(final Caller<AppConfigService> appConfigService, final ActivityBeansCache activityBeansCache, final DefaultWorkbenchFeaturesMenusHelper menusHelper, final ClientUserSystemManager userSystemManager, final WorkbenchMegaMenuPresenter menuBar, final Workbench workbench, final PermissionTreeSetup permissionTreeSetup, final DefaultAdminPageHelper adminPageHelper, final NavTreeDefinitions navTreeDefinitions, final NavigationManager navigationManager, final NavigationExplorerScreen navigationExplorerScreen, final DefaultWorkbenchErrorCallback defaultWorkbenchErrorCallback, final AppFormerJsBridge appFormerJsBridge, final HomeConfiguration homeConfiguration); @PostConstruct void init(); @Override void setupMenu(); void onNavTreeChanged(@Observes final NavTreeChangedEvent event); void onAuthzPolicyChanged(@Observes final SaveRoleEvent event); void onAuthzPolicyChanged(@Observes final SaveGroupEvent event); }### Answer: @Test public void testInitializeWorkbench() { kieWorkbenchEntryPoint.initializeWorkbench(); verify(permissionTreeSetup).configureTree(); }
### Question: KieWorkbenchEntryPoint extends DefaultWorkbenchEntryPoint { @Override protected void setupAdminPage() { adminPageHelper.setup(false, true, false); } @Inject KieWorkbenchEntryPoint(final Caller<AppConfigService> appConfigService, final ActivityBeansCache activityBeansCache, final DefaultWorkbenchFeaturesMenusHelper menusHelper, final ClientUserSystemManager userSystemManager, final WorkbenchMegaMenuPresenter menuBar, final Workbench workbench, final PermissionTreeSetup permissionTreeSetup, final DefaultAdminPageHelper adminPageHelper, final NavTreeDefinitions navTreeDefinitions, final NavigationManager navigationManager, final NavigationExplorerScreen navigationExplorerScreen, final DefaultWorkbenchErrorCallback defaultWorkbenchErrorCallback, final AppFormerJsBridge appFormerJsBridge, final HomeConfiguration homeConfiguration); @PostConstruct void init(); @Override void setupMenu(); void onNavTreeChanged(@Observes final NavTreeChangedEvent event); void onAuthzPolicyChanged(@Observes final SaveRoleEvent event); void onAuthzPolicyChanged(@Observes final SaveGroupEvent event); }### Answer: @Test public void testSetupAdminPage() { kieWorkbenchEntryPoint.setupAdminPage(); verify(adminPageHelper).setup(false, true, false); }
### Question: KieWorkbenchEntryPoint extends DefaultWorkbenchEntryPoint { @Override protected void initializeWorkbench() { permissionTreeSetup.configureTree(); super.initializeWorkbench(); } @Inject KieWorkbenchEntryPoint(final Caller<AppConfigService> appConfigService, final ActivityBeansCache activityBeansCache, final DefaultWorkbenchFeaturesMenusHelper menusHelper, final ClientUserSystemManager userSystemManager, final WorkbenchMegaMenuPresenter menuBar, final Workbench workbench, final PermissionTreeSetup permissionTreeSetup, final DefaultAdminPageHelper adminPageHelper, final NavTreeDefinitions navTreeDefinitions, final NavigationManager navigationManager, final NavigationExplorerScreen navigationExplorerScreen, final DefaultWorkbenchErrorCallback defaultWorkbenchErrorCallback, final ProfilePreferences profilePreferences, final Event<WorkbenchProfileCssClass> workbenchProfileCssClassEvent, final AppFormerJsBridge appFormerJsBridge); @PostConstruct void init(); @Override void setupMenu(); void onNavTreeChanged(@Observes final NavTreeChangedEvent event); void onAuthzPolicyChanged(@Observes final SaveRoleEvent event); void onAuthzPolicyChanged(@Observes final SaveGroupEvent event); void refreshMenuOnProfilesChange(@Observes PreferenceUpdatedEvent event); }### Answer: @Test public void testInitializeWorkbench() { kieWorkbenchEntryPoint.initializeWorkbench(); verify(permissionTreeSetup).configureTree(); }
### Question: AuthoringPerspective { @OnOpen public void onOpen() { placeManager.closeAllPlaces(); if (!projectPathString.isEmpty()) { vfsServices.call((RemoteCallback<Boolean>) isRegularFile -> { if (isRegularFile) { vfsServices.call((RemoteCallback<Path>) path -> { setWorkspaceContext(path, () -> placeManager.goTo(path)); }).get(projectPathString); } }).isRegularFile(projectPathString); } } @Inject AuthoringPerspective(final PlaceManager placeManager, final Caller<VFSService> vfsServices, final Event<WorkspaceProjectContextChangeEvent> workspaceProjectContextChangeEvent, final Caller<WorkspaceProjectService> workspaceProjectService, final ProjectController projectController, final Promises promises, final Event<NotificationEvent> notificationEvent); @PostConstruct void init(); @Perspective PerspectiveDefinition getPerspective(); @OnOpen void onOpen(); static final String IDENTIFIER; }### Answer: @Test public void onOpenTest() { final Path path = mock(Path.class); final WorkspaceProject workspaceProject = mock(WorkspaceProject.class); authoringPerspective.projectPathString = "git: doReturn(promises.resolve(true)).when(projectController).canReadBranch(workspaceProject); doReturn(true).when(vfsServices).isRegularFile(authoringPerspective.projectPathString); doReturn(path).when(vfsServices).get(authoringPerspective.projectPathString); doReturn(workspaceProject).when(workspaceProjectService).resolveProject(path); authoringPerspective.onOpen(); verify(placeManager).closeAllPlaces(); verify(workspaceProjectContextChangeEvent).fire(new WorkspaceProjectContextChangeEvent(workspaceProject)); verify(placeManager).goTo(same(path)); }
### Question: AreaController { @RequestMapping(value = "/get/{id}") public ActionResultObj get(@PathVariable Long id) { ActionResultObj result = new ActionResultObj(); try { if (id > 0) { EArea area = areaDao.fetch(id); if (area != null) { WMap map = new WMap(); map.put("data", area); result.ok(map); result.okMsg("查询成功!"); } else { result.errorMsg("查询失败!"); } } else { result.errorMsg("查询失败,链接不存在!"); } } catch (Exception e) { LOG.error("查询失败,原因:" + e.getMessage()); result.error(e); } return result; } @RequestMapping(value = "/list") ActionResultObj list(@RequestBody SearchQueryJS queryJs); @RequestMapping(value = "/allArea", method = RequestMethod.POST) ActionResultObj findAllArea(@RequestBody SearchQueryJS queryJs); @RequestMapping(value = "/save") ActionResultObj save(@RequestBody EArea area); @RequestMapping(value = "/get/{id}") ActionResultObj get(@PathVariable Long id); @RequestMapping(value = "/delete/{id}") ActionResultObj delete(@PathVariable Long id); @RequestMapping(value = "/kunMingArea") ActionResultObj getKunMingArea(); @Autowired public AreaService areaService; @Autowired public AreaDao areaDao; }### Answer: @Test public void get() throws Exception { MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.get("/area/delete/2").accept(MediaType.APPLICATION_JSON)).andReturn(); int status = mvcResult.getResponse().getStatus(); String content = mvcResult.getResponse().getContentAsString(); System.out.println(status + "--" + content); }
### Question: MoneyUtil { public static Double getWeightedAverage(Map<Double, Long> amounts) { Double totalAmount = 0d; Long quantity = 0L; if (amounts != null && amounts.size() > 0) { for (Double money : amounts.keySet()) { Double amount = ArithUtils.mul(money, amounts.get(money).doubleValue()); totalAmount = ArithUtils.add(totalAmount, amount); quantity += amounts.get(money); } } return ArithUtils.div(totalAmount, quantity.doubleValue()); } static boolean equals(Double money1, Double money2); static Double fixPrice(Double price); static Double fixDiscount(Double discount); static Double getWeightedAverage(Map<Double, Long> amounts); static Double getWeightedAverage(Double money1, Long quantity1, Double money2, Long quantity2); static String formatMoney(Object money, int bit); static Long parseLong(Object number); static Double parseDouble(Object number); static String numberFormat(Object object, String format); }### Answer: @Test() public void testGetWeightedAverage1() { Double d1 = 150d; Double d2 = 149d; Long q1 = 0L; Long q2 = 1L; Double result = MoneyUtil.getWeightedAverage(d1, q1, d2, q2); assertEquals(149d, result.doubleValue(), 2); }
### Question: OrgController { @RequestMapping(value = "/get/{id}") public ActionResultObj get(@PathVariable Long id) { ActionResultObj result = new ActionResultObj(); try { if (id != 0) { EOrg org = orgDao.fetch(id); if (org != null) { WMap map = new WMap(); map.put("data", org); result.ok(map); result.okMsg("查询成功!"); } else { result.errorMsg("查询失败!"); } } else { result.errorMsg("查询失败,链接不存在!"); } } catch (Exception e) { LOG.error("查询失败,原因:" + e.getMessage()); result.error(e); } return result; } @RequestMapping(value = "/list") ActionResultObj list(@RequestBody SearchQueryJS queryJs); @RequestMapping(value = "/get/{id}") ActionResultObj get(@PathVariable Long id); @RequestMapping(value = "/save") ActionResultObj save(@RequestBody EOrg org); @RequestMapping(value = "/delete/{id}") ActionResultObj delete(@PathVariable Long id); @RequestMapping(value = "/getOrgs/{type}") ActionResultObj getOrgsByListByType(@PathVariable String type); @Autowired public OrgService orgService; @Autowired public OrgDao orgDao; @Autowired public AreaDao areaDao; }### Answer: @Test public void get() throws Exception { MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.get("/org/3").accept(MediaType.APPLICATION_JSON)).andReturn(); int status = mvcResult.getResponse().getStatus(); String content = mvcResult.getResponse().getContentAsString(); System.out.println(status + "--" + content); }
### Question: DictController { @RequestMapping(value="/{id}") public ActionResultObj get(@PathVariable Long id){ ActionResultObj result = new ActionResultObj(); try{ if(id != 0){ EDict dict = dictDao.fetch(id); if(dict != null){ result.ok(dict); result.okMsg("查询成功!"); }else{ result.errorMsg("查询失败!"); } }else{ result.errorMsg("查询失败,链接不存在!"); } }catch(Exception e){ LOG.error("查询失败,原因:"+e.getMessage()); result.error(e); } return result; } @RequestMapping(value="list") ActionResultObj list(@RequestBody SearchQueryJS queryJs); @RequestMapping(value="type/{type}") ActionResultObj findByType(@PathVariable String type); @RequestMapping(value="/{id}") ActionResultObj get(@PathVariable Long id); @RequestMapping(value="save") ActionResultObj save(@RequestBody EDict dict); @RequestMapping(value="delete") ActionResultObj delete(@RequestBody Long id); @Autowired public DictService dictService; @Autowired public DictDao dictDao; }### Answer: @Test public void get() throws Exception { MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.get("/dict/3").accept(MediaType.APPLICATION_JSON)).andReturn(); int status = mvcResult.getResponse().getStatus(); String content = mvcResult.getResponse().getContentAsString(); System.out.println(status + "--" + content); }
### Question: Gsm7BitCharset extends Charset { public CharsetEncoder newEncoder() { return new Gsm7BitEncoder(this); } protected Gsm7BitCharset(String canonical, String[] aliases); CharsetEncoder newEncoder(); CharsetDecoder newDecoder(); boolean contains(Charset cs); }### Answer: @Test public void testEncoderOverflow() { assertEquals(CoderResult.OVERFLOW, charset.newEncoder().encode(CharBuffer.wrap("00"), ByteBuffer.wrap(new byte[1]), true)); }
### Question: ByteBuffer extends SmppObject { public void appendShort(short data) { byte[] shortBuf = new byte[SZ_SHORT]; shortBuf[1] = (byte) (data & 0xff); shortBuf[0] = (byte) ((data >>> 8) & 0xff); appendBytes0(shortBuf, SZ_SHORT); } ByteBuffer(); ByteBuffer(byte[] buffer); byte[] getBuffer(); void setBuffer(byte[] buffer); int length(); void appendByte(byte data); void appendShort(short data); void appendInt(int data); void appendCString(String string); void appendCString(String string, String encoding); void appendString(String string); void appendString(String string, String encoding); void appendString(String string, int count); void appendString(String string, int count, String encoding); void appendBuffer(ByteBuffer buf); void appendBytes(ByteBuffer bytes, int count); void appendBytes(byte[] bytes, int count); void appendBytes(byte[] bytes); byte removeByte(); short removeUnsignedByte(); short removeShort(); int removeInt(); int readInt(); String removeCString(); String removeCString(String encoding); String removeString(int size, String encoding); ByteBuffer removeBuffer(int count); ByteBuffer removeBytes(int count); void removeBytes0(int count); ByteBuffer readBytes(int count); String getHexDump(); }### Answer: @Test public void testAppendShort0() { buffer.appendShort(t_short); assertBufferMatches((byte) 0x02, (byte) 0x9a); }
### Question: ByteBuffer extends SmppObject { public void appendInt(int data) { byte[] intBuf = new byte[SZ_INT]; intBuf[3] = (byte) (data & 0xff); intBuf[2] = (byte) ((data >>> 8) & 0xff); intBuf[1] = (byte) ((data >>> 16) & 0xff); intBuf[0] = (byte) ((data >>> 24) & 0xff); appendBytes0(intBuf, SZ_INT); } ByteBuffer(); ByteBuffer(byte[] buffer); byte[] getBuffer(); void setBuffer(byte[] buffer); int length(); void appendByte(byte data); void appendShort(short data); void appendInt(int data); void appendCString(String string); void appendCString(String string, String encoding); void appendString(String string); void appendString(String string, String encoding); void appendString(String string, int count); void appendString(String string, int count, String encoding); void appendBuffer(ByteBuffer buf); void appendBytes(ByteBuffer bytes, int count); void appendBytes(byte[] bytes, int count); void appendBytes(byte[] bytes); byte removeByte(); short removeUnsignedByte(); short removeShort(); int removeInt(); int readInt(); String removeCString(); String removeCString(String encoding); String removeString(int size, String encoding); ByteBuffer removeBuffer(int count); ByteBuffer removeBytes(int count); void removeBytes0(int count); ByteBuffer readBytes(int count); String getHexDump(); }### Answer: @Test public void testAppendInt0() { buffer.appendInt(666); assertBufferMatches(NULL, NULL, (byte) 0x02, (byte) 0x9a); }
### Question: ByteBuffer extends SmppObject { public void appendCString(String string) { try { appendString0(string, true, Data.ENC_ASCII); } catch (UnsupportedEncodingException e) { } } ByteBuffer(); ByteBuffer(byte[] buffer); byte[] getBuffer(); void setBuffer(byte[] buffer); int length(); void appendByte(byte data); void appendShort(short data); void appendInt(int data); void appendCString(String string); void appendCString(String string, String encoding); void appendString(String string); void appendString(String string, String encoding); void appendString(String string, int count); void appendString(String string, int count, String encoding); void appendBuffer(ByteBuffer buf); void appendBytes(ByteBuffer bytes, int count); void appendBytes(byte[] bytes, int count); void appendBytes(byte[] bytes); byte removeByte(); short removeUnsignedByte(); short removeShort(); int removeInt(); int readInt(); String removeCString(); String removeCString(String encoding); String removeString(int size, String encoding); ByteBuffer removeBuffer(int count); ByteBuffer removeBytes(int count); void removeBytes0(int count); ByteBuffer readBytes(int count); String getHexDump(); }### Answer: @Test public void testAppendCString0() { buffer.appendCString(ABC); assertBufferMatches(A, B, C, NULL); } @Test public void testAppendCStringWithNullAppendsNull() { buffer.appendCString(null); assertBufferMatches(NULL); } @Test public void testAppendCStringWithInvalidEncodingThrowsException() throws Exception { thrown.expect(UnsupportedEncodingException.class); buffer.appendCString(ABC, INVALID); }
### Question: ByteBuffer extends SmppObject { public void appendString(String string) { try { appendString(string, Data.ENC_ASCII); } catch (UnsupportedEncodingException e) { } } ByteBuffer(); ByteBuffer(byte[] buffer); byte[] getBuffer(); void setBuffer(byte[] buffer); int length(); void appendByte(byte data); void appendShort(short data); void appendInt(int data); void appendCString(String string); void appendCString(String string, String encoding); void appendString(String string); void appendString(String string, String encoding); void appendString(String string, int count); void appendString(String string, int count, String encoding); void appendBuffer(ByteBuffer buf); void appendBytes(ByteBuffer bytes, int count); void appendBytes(byte[] bytes, int count); void appendBytes(byte[] bytes); byte removeByte(); short removeUnsignedByte(); short removeShort(); int removeInt(); int readInt(); String removeCString(); String removeCString(String encoding); String removeString(int size, String encoding); ByteBuffer removeBuffer(int count); ByteBuffer removeBytes(int count); void removeBytes0(int count); ByteBuffer readBytes(int count); String getHexDump(); }### Answer: @Test public void testAppendString() { buffer.appendString(ABC); assertBufferMatches(A, B, C); } @Test public void testAppendStringWithCount() { buffer.appendString(ABC, 2); assertBufferMatches(A, B); } @Test public void testAppendStringWithZeroCount() { buffer = new ByteBuffer(new byte[] { }); buffer.appendString(ABC, 0); assertBufferMatches(new byte[] { }); } @Test public void testAppendStringWithExcessiveCountThrowsException() throws Exception { thrown.expect(StringIndexOutOfBoundsException.class); buffer.appendString(ABC, 4); } @Test public void testAppenStringWithCountAndInvalidEncodingThrowsException() throws Exception { thrown.expect(UnsupportedEncodingException.class); buffer.appendString(ABC, 1, INVALID); }
### Question: Gsm7BitCharset extends Charset { public CharsetDecoder newDecoder() { return new Gsm7BitDecoder(this); } protected Gsm7BitCharset(String canonical, String[] aliases); CharsetEncoder newEncoder(); CharsetDecoder newDecoder(); boolean contains(Charset cs); }### Answer: @Test public void testDecoderOverflow() { assertEquals(CoderResult.OVERFLOW, charset.newDecoder().decode(ByteBuffer.wrap(new byte[] { 0x30, 0x30 }), CharBuffer.allocate(1), true)); }
### Question: ByteBuffer extends SmppObject { public void appendBuffer(ByteBuffer buf) { if (buf != null) { try { appendBytes(buf, buf.length()); } catch (NotEnoughDataInByteBufferException e) { } } } ByteBuffer(); ByteBuffer(byte[] buffer); byte[] getBuffer(); void setBuffer(byte[] buffer); int length(); void appendByte(byte data); void appendShort(short data); void appendInt(int data); void appendCString(String string); void appendCString(String string, String encoding); void appendString(String string); void appendString(String string, String encoding); void appendString(String string, int count); void appendString(String string, int count, String encoding); void appendBuffer(ByteBuffer buf); void appendBytes(ByteBuffer bytes, int count); void appendBytes(byte[] bytes, int count); void appendBytes(byte[] bytes); byte removeByte(); short removeUnsignedByte(); short removeShort(); int removeInt(); int readInt(); String removeCString(); String removeCString(String encoding); String removeString(int size, String encoding); ByteBuffer removeBuffer(int count); ByteBuffer removeBytes(int count); void removeBytes0(int count); ByteBuffer readBytes(int count); String getHexDump(); }### Answer: @Test public void testAppendBufferWithNullDoesNothing() { buffer = bufferOf(NULL); buffer.appendBuffer(null); assertBufferMatches(NULL); } @Test public void testAppendBuferAppendsAll() { buffer.appendBuffer(bufferOf(A, B, C)); assertBufferMatches(A, B, C); }
### Question: ByteBuffer extends SmppObject { public ByteBuffer readBytes(int count) throws NotEnoughDataInByteBufferException { int len = length(); ByteBuffer result = null; if (count > 0) { if (len >= count) { byte[] resBuf = new byte[count]; System.arraycopy(buffer, 0, resBuf, 0, count); result = new ByteBuffer(resBuf); return result; } else { throw new NotEnoughDataInByteBufferException(len, count); } } else { return result; } } ByteBuffer(); ByteBuffer(byte[] buffer); byte[] getBuffer(); void setBuffer(byte[] buffer); int length(); void appendByte(byte data); void appendShort(short data); void appendInt(int data); void appendCString(String string); void appendCString(String string, String encoding); void appendString(String string); void appendString(String string, String encoding); void appendString(String string, int count); void appendString(String string, int count, String encoding); void appendBuffer(ByteBuffer buf); void appendBytes(ByteBuffer bytes, int count); void appendBytes(byte[] bytes, int count); void appendBytes(byte[] bytes); byte removeByte(); short removeUnsignedByte(); short removeShort(); int removeInt(); int readInt(); String removeCString(); String removeCString(String encoding); String removeString(int size, String encoding); ByteBuffer removeBuffer(int count); ByteBuffer removeBytes(int count); void removeBytes0(int count); ByteBuffer readBytes(int count); String getHexDump(); }### Answer: @Test public void testReadBytesWithZeroCountReturnsNull() throws Exception { assertNull(buffer.readBytes(0)); } @Test public void testReadBytesWithExcessiveCountThrowsException() throws Exception { thrown.expect(NotEnoughDataInByteBufferException.class); thrown.expect(notEnoughData(1, 0)); buffer.readBytes(1); } @Test public void testRemoveBufferFromNullThrowsException() throws Exception { thrown.expect(NotEnoughDataInByteBufferException.class); thrown.expect(notEnoughData(1, 0)); buffer.readBytes(1); }
### Question: ByteBuffer extends SmppObject { public byte removeByte() throws NotEnoughDataInByteBufferException { byte result = 0; byte[] resBuff = removeBytes(SZ_BYTE).getBuffer(); result = resBuff[0]; return result; } ByteBuffer(); ByteBuffer(byte[] buffer); byte[] getBuffer(); void setBuffer(byte[] buffer); int length(); void appendByte(byte data); void appendShort(short data); void appendInt(int data); void appendCString(String string); void appendCString(String string, String encoding); void appendString(String string); void appendString(String string, String encoding); void appendString(String string, int count); void appendString(String string, int count, String encoding); void appendBuffer(ByteBuffer buf); void appendBytes(ByteBuffer bytes, int count); void appendBytes(byte[] bytes, int count); void appendBytes(byte[] bytes); byte removeByte(); short removeUnsignedByte(); short removeShort(); int removeInt(); int readInt(); String removeCString(); String removeCString(String encoding); String removeString(int size, String encoding); ByteBuffer removeBuffer(int count); ByteBuffer removeBytes(int count); void removeBytes0(int count); ByteBuffer readBytes(int count); String getHexDump(); }### Answer: @Test public void testRemoveByteFromNullThrowsException() throws Exception { thrown.expect(NotEnoughDataInByteBufferException.class); thrown.expect(notEnoughData(1, 0)); buffer.removeByte(); } @Test public void testRemoveByteFromEmptyThrowsException() throws Exception { thrown.expect(NotEnoughDataInByteBufferException.class); thrown.expect(notEnoughData(1, 0)); buffer = new ByteBuffer(new byte[] { }); buffer.removeByte(); } @Test public void testRemoveByteRemovesFirstByte() throws Exception { buffer = bufferOf(A, B, C); byte bite = buffer.removeByte(); assertEquals(A, bite); }
### Question: Gsm7BitCharsetProvider extends CharsetProvider { public Charset charsetForName (String charsetName) { if(charsetName.equalsIgnoreCase(CHARSET_NAME)) { return(gsm7Bit); } return(null); } Gsm7BitCharsetProvider(); Charset charsetForName(String charsetName); Iterator<Charset> charsets(); }### Answer: @Test public void testCharsetName() { Gsm7BitCharsetProvider provider = new Gsm7BitCharsetProvider(); Charset charset = provider.charsetForName("X-Gsm7Bit"); assertNotNull(charset); }
### Question: ByteBuffer extends SmppObject { public short removeShort() throws NotEnoughDataInByteBufferException { short result = 0; byte[] resBuff = removeBytes(SZ_SHORT).getBuffer(); result |= resBuff[0] & 0xff; result <<= 8; result |= resBuff[1] & 0xff; return result; } ByteBuffer(); ByteBuffer(byte[] buffer); byte[] getBuffer(); void setBuffer(byte[] buffer); int length(); void appendByte(byte data); void appendShort(short data); void appendInt(int data); void appendCString(String string); void appendCString(String string, String encoding); void appendString(String string); void appendString(String string, String encoding); void appendString(String string, int count); void appendString(String string, int count, String encoding); void appendBuffer(ByteBuffer buf); void appendBytes(ByteBuffer bytes, int count); void appendBytes(byte[] bytes, int count); void appendBytes(byte[] bytes); byte removeByte(); short removeUnsignedByte(); short removeShort(); int removeInt(); int readInt(); String removeCString(); String removeCString(String encoding); String removeString(int size, String encoding); ByteBuffer removeBuffer(int count); ByteBuffer removeBytes(int count); void removeBytes0(int count); ByteBuffer readBytes(int count); String getHexDump(); }### Answer: @Test public void testRemoveShortFromNullThrowsException() throws Exception { thrown.expect(NotEnoughDataInByteBufferException.class); thrown.expect(notEnoughData(2, 0)); buffer.removeShort(); } @Test public void testRemoveShortFromSmallBufferThrowsException() throws Exception { thrown.expect(NotEnoughDataInByteBufferException.class); thrown.expect(notEnoughData(2, 1)); buffer = bufferOf(NULL); buffer.removeShort(); } @Test public void testRemoveShortRemovesFirstShort() throws Exception { buffer = bufferOf((byte) 0x01, (byte) 0x02, (byte) 0x03, (byte) 0x04); short s = buffer.removeShort(); assertEquals((1 << 8) + 2, s); }
### Question: Queue extends SmppObject { public void enqueue(Object obj) throws IndexOutOfBoundsException { synchronized (mutex) { if ((maxQueueSize > 0) && (size() >= maxQueueSize)) { throw new IndexOutOfBoundsException("Queue is full. Element not added."); } queueData.add(obj); } } Queue(); Queue(int maxSize); int size(); boolean isEmpty(); Object dequeue(); Object dequeue(Object obj); void enqueue(Object obj); Object find(Object obj); }### Answer: @Test public void testConstructorLimitsSize() throws IndexOutOfBoundsException { thrown.expect(IndexOutOfBoundsException.class); queue = new Queue(10); for (int i = 0; i < 11; i++) { queue.enqueue(new Object()); } }
### Question: Queue extends SmppObject { public boolean isEmpty() { synchronized (mutex) { return queueData.isEmpty(); } } Queue(); Queue(int maxSize); int size(); boolean isEmpty(); Object dequeue(); Object dequeue(Object obj); void enqueue(Object obj); Object find(Object obj); }### Answer: @Test public void testIsEmpty() { assertTrue(queue.isEmpty()); queue.enqueue(new Object()); assertFalse(queue.isEmpty()); queue.dequeue(); assertTrue(queue.isEmpty()); }
### Question: ByteBuffer extends SmppObject { public ByteBuffer removeBuffer(int count) throws NotEnoughDataInByteBufferException { return removeBytes(count); } ByteBuffer(); ByteBuffer(byte[] buffer); byte[] getBuffer(); void setBuffer(byte[] buffer); int length(); void appendByte(byte data); void appendShort(short data); void appendInt(int data); void appendCString(String string); void appendCString(String string, String encoding); void appendString(String string); void appendString(String string, String encoding); void appendString(String string, int count); void appendString(String string, int count, String encoding); void appendBuffer(ByteBuffer buf); void appendBytes(ByteBuffer bytes, int count); void appendBytes(byte[] bytes, int count); void appendBytes(byte[] bytes); byte removeByte(); short removeUnsignedByte(); short removeShort(); int removeInt(); int readInt(); String removeCString(); String removeCString(String encoding); String removeString(int size, String encoding); ByteBuffer removeBuffer(int count); ByteBuffer removeBytes(int count); void removeBytes0(int count); ByteBuffer readBytes(int count); String getHexDump(); }### Answer: @Test public void testRemoveBufferWithExcessiveSizeThrowsException() throws Exception { thrown.expect(NotEnoughDataInByteBufferException.class); thrown.expect(notEnoughData(10, 1)); buffer = bufferOf(NULL); buffer.removeBuffer(10); }
### Question: ByteBuffer extends SmppObject { public String getHexDump() { StringBuffer dump = new StringBuffer(); try { int dataLen = length(); byte[] buffer = getBuffer(); for (int i=0; i<dataLen; i++) { dump.append(Character.forDigit((buffer[i] >> 4) & 0x0f, 16)); dump.append(Character.forDigit(buffer[i] & 0x0f, 16)); } } catch (Throwable t) { dump = new StringBuffer("Throwable caught when dumping = ").append(t); } return dump.toString(); } ByteBuffer(); ByteBuffer(byte[] buffer); byte[] getBuffer(); void setBuffer(byte[] buffer); int length(); void appendByte(byte data); void appendShort(short data); void appendInt(int data); void appendCString(String string); void appendCString(String string, String encoding); void appendString(String string); void appendString(String string, String encoding); void appendString(String string, int count); void appendString(String string, int count, String encoding); void appendBuffer(ByteBuffer buf); void appendBytes(ByteBuffer bytes, int count); void appendBytes(byte[] bytes, int count); void appendBytes(byte[] bytes); byte removeByte(); short removeUnsignedByte(); short removeShort(); int removeInt(); int readInt(); String removeCString(); String removeCString(String encoding); String removeString(int size, String encoding); ByteBuffer removeBuffer(int count); ByteBuffer removeBytes(int count); void removeBytes0(int count); ByteBuffer readBytes(int count); String getHexDump(); }### Answer: @Test public void testHexDump() { assertEquals("414243", bufferOf(A, B, C).getHexDump()); } @Test public void testHexDumpWithNullBuffer() { assertEquals("", buffer.getHexDump()); }
### Question: Unprocessed { public void reset() { hasUnprocessed = false; unprocessed.setBuffer(null); expected = 0; } void reset(); void check(); void setHasUnprocessed(boolean value); void setExpected(int value); void setLastTimeReceived(long value); void setLastTimeReceived(); ByteBuffer getUnprocessed(); boolean getHasUnprocessed(); int getExpected(); long getLastTimeReceived(); }### Answer: @Test public void testReset() { unprocessed.getUnprocessed().setBuffer(new byte[] { 0x00 }); unprocessed.setExpected(1); unprocessed.setHasUnprocessed(true); unprocessed.setLastTimeReceived(1); unprocessed.reset(); assertNull(unprocessed.getUnprocessed().getBuffer()); assertEquals(0, unprocessed.getExpected()); assertFalse(unprocessed.getHasUnprocessed()); assertEquals(1, unprocessed.getLastTimeReceived()); }
### Question: Unprocessed { public void setExpected(int value) { expected = value; } void reset(); void check(); void setHasUnprocessed(boolean value); void setExpected(int value); void setLastTimeReceived(long value); void setLastTimeReceived(); ByteBuffer getUnprocessed(); boolean getHasUnprocessed(); int getExpected(); long getLastTimeReceived(); }### Answer: @Test public void testSetExpected() { unprocessed.setExpected(1234); assertEquals(1234, unprocessed.getExpected()); }
### Question: DefaultEvent implements Event { public void write(String msg) { if (active) { System.out.println(msg); } } void write(String msg); void write(Exception e, String msg); void activate(); void deactivate(); }### Answer: @Test public void testInactiveByDefault() { event = new DefaultEvent(); event.write("HELLO"); assertEquals("", out.toString()); } @Test public void testWrite() { event.write("HELLO"); assertEquals("HELLO" + newLine, out.toString()); } @Test public void testWriteException() { try { throw new RuntimeException(); } catch (Exception ex) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ex.printStackTrace(new PrintStream(baos)); String expected = "Exception: " + baos.toString() + " END" + newLine; event.write(ex, "END"); assertEquals(expected, out.toString()); } }
### Question: Queue extends SmppObject { public int size() { synchronized (mutex) { return queueData.size(); } } Queue(); Queue(int maxSize); int size(); boolean isEmpty(); Object dequeue(); Object dequeue(Object obj); void enqueue(Object obj); Object find(Object obj); }### Answer: @Test public void testSize() { int size = 0; assertEquals(size, queue.size()); for (int i = 0; i < 10; i++) { queue.enqueue(size++); assertEquals(size, queue.size()); } }
### Question: DefaultEvent implements Event { public void deactivate() { active = false; } void write(String msg); void write(Exception e, String msg); void activate(); void deactivate(); }### Answer: @Test public void testDeactivate() { event.deactivate(); event.write("HELLO"); assertEquals("", out.toString()); }
### Question: DefaultDebug implements Debug { public void enter(int group, Object from, String name) { enter(from, name); } void enter(int group, Object from, String name); void enter(Object from, String name); void write(int group, String msg); void write(String msg); void exit(int group, Object from); void exit(Object from); void activate(); void activate(int group); void deactivate(); void deactivate(int group); boolean active(int group); }### Answer: @Test public void testEnterWithName() { debug.enter(0, OBJECT, NAME); assertEquals("-> OBJECT NAME" + newLine, out.toString()); } @Test public void testEnterWithoutName() { debug.enter(0, OBJECT, EMPTY); assertEquals("-> OBJECT" + newLine, out.toString()); } @Test public void testNestedEnter() { debug.enter(OBJECT, NAME); debug.enter(OBJECT, NAME); assertEquals("-> OBJECT NAME" + newLine + " -> OBJECT NAME" + newLine, out.toString()); }
### Question: DefaultDebug implements Debug { public void exit(int group, Object from) { exit(from); } void enter(int group, Object from, String name); void enter(Object from, String name); void write(int group, String msg); void write(String msg); void exit(int group, Object from); void exit(Object from); void activate(); void activate(int group); void deactivate(); void deactivate(int group); boolean active(int group); }### Answer: @Test public void testExit() { debug.exit(0, OBJECT); assertEquals("<- OBJECT" + newLine, out.toString()); }
### Question: DefaultDebug implements Debug { public void write(int group, String msg) { write(msg); } void enter(int group, Object from, String name); void enter(Object from, String name); void write(int group, String msg); void write(String msg); void exit(int group, Object from); void exit(Object from); void activate(); void activate(int group); void deactivate(); void deactivate(int group); boolean active(int group); }### Answer: @Test public void testWrite() { debug.write(0, "HELLO"); assertEquals(" HELLO" + newLine, out.toString()); }
### Question: DefaultDebug implements Debug { public void deactivate() { active = false; } void enter(int group, Object from, String name); void enter(Object from, String name); void write(int group, String msg); void write(String msg); void exit(int group, Object from); void exit(Object from); void activate(); void activate(int group); void deactivate(); void deactivate(int group); boolean active(int group); }### Answer: @Test public void testDeactivate() { debug.deactivate(); debug.write(0, "HELLO"); assertEquals("", out.toString()); }
### Question: Address extends ByteData { public String getAddress() { return address; } Address(); Address(int maxAddressLength); Address(byte ton, byte npi, int maxAddressLength); Address(String address); Address(String address, int maxAddressLength); Address(byte ton, byte npi, String address); Address(byte ton, byte npi, String address, int maxAddressLength); void setData(ByteBuffer buffer); ByteBuffer getData(); void setTon(byte ton); void setNpi(byte npi); void setAddress(String address); void setAddress(String address, int maxAddressLength); byte getTon(); byte getNpi(); String getAddress(); String getAddress(String encoding); String debugString(); }### Answer: @Test public void testConstructorStringSpecifiesAddress() throws Exception { assertEquals("1234", new Address("1234").getAddress()); }
### Question: Queue extends SmppObject { public Object find(Object obj) { synchronized (mutex) { Object current; ListIterator<Object> iter = queueData.listIterator(0); while (iter.hasNext()) { current = iter.next(); if (current.equals(obj)) { return current; } } } return null; } Queue(); Queue(int maxSize); int size(); boolean isEmpty(); Object dequeue(); Object dequeue(Object obj); void enqueue(Object obj); Object find(Object obj); }### Answer: @Test public void testFind() { Object a = new Object(); Object b = new Object(); Object c = new Object(); queue.enqueue(a); queue.enqueue(b); queue.enqueue(c); assertEquals(3, queue.size()); assertSame(a, queue.find(a)); assertSame(b, queue.find(b)); assertSame(c, queue.find(c)); assertEquals(3, queue.size()); }
### Question: Address extends ByteData { public Address() { this(Data.getDefaultTon(), Data.getDefaultNpi(), defaultMaxAddressLength); } Address(); Address(int maxAddressLength); Address(byte ton, byte npi, int maxAddressLength); Address(String address); Address(String address, int maxAddressLength); Address(byte ton, byte npi, String address); Address(byte ton, byte npi, String address, int maxAddressLength); void setData(ByteBuffer buffer); ByteBuffer getData(); void setTon(byte ton); void setNpi(byte npi); void setAddress(String address); void setAddress(String address, int maxAddressLength); byte getTon(); byte getNpi(); String getAddress(); String getAddress(String encoding); String debugString(); }### Answer: @Test(expected = WrongLengthOfStringException.class) public void testConstructorStringUsesDefaultMaxLength() throws Exception { new Address(address(21)); } @Test(expected = WrongLengthOfStringException.class) public void testConstructorStringIntSpecifiesAddressLength() throws Exception { new Address(address(5), 5); }
### Question: Address extends ByteData { public void setData(ByteBuffer buffer) throws NotEnoughDataInByteBufferException, TerminatingZeroNotFoundException, WrongLengthOfStringException { byte ton = buffer.removeByte(); byte npi = buffer.removeByte(); String address = buffer.removeCString(); setAddress(address); setTon(ton); setNpi(npi); } Address(); Address(int maxAddressLength); Address(byte ton, byte npi, int maxAddressLength); Address(String address); Address(String address, int maxAddressLength); Address(byte ton, byte npi, String address); Address(byte ton, byte npi, String address, int maxAddressLength); void setData(ByteBuffer buffer); ByteBuffer getData(); void setTon(byte ton); void setNpi(byte npi); void setAddress(String address); void setAddress(String address, int maxAddressLength); byte getTon(); byte getNpi(); String getAddress(); String getAddress(String encoding); String debugString(); }### Answer: @Test public void testSetData() throws Exception { ByteBuffer buffer = mock(ByteBuffer.class); when(buffer.removeByte()).thenReturn((byte) 0x01, (byte) 0x02); when(buffer.removeCString()).thenReturn("1234567890"); address.setData(buffer); assertEquals(0x01, address.getTon()); assertEquals(0x02, address.getNpi()); assertEquals("1234567890", address.getAddress()); }
### Question: Address extends ByteData { public ByteBuffer getData() { ByteBuffer addressBuf = new ByteBuffer(); addressBuf.appendByte(getTon()); addressBuf.appendByte(getNpi()); try { addressBuf.appendCString(getAddress(), Data.ENC_ASCII); } catch(UnsupportedEncodingException e) { } return addressBuf; } Address(); Address(int maxAddressLength); Address(byte ton, byte npi, int maxAddressLength); Address(String address); Address(String address, int maxAddressLength); Address(byte ton, byte npi, String address); Address(byte ton, byte npi, String address, int maxAddressLength); void setData(ByteBuffer buffer); ByteBuffer getData(); void setTon(byte ton); void setNpi(byte npi); void setAddress(String address); void setAddress(String address, int maxAddressLength); byte getTon(); byte getNpi(); String getAddress(); String getAddress(String encoding); String debugString(); }### Answer: @Test public void testGetData() throws Exception { for (byte ton : TONS) { for (byte npi : NPIS) { for (int len = 1; len <= MAX_ADDRESS_LENGTH; len++) { String a = address(len); address = new Address(ton, npi, a, len + 1); ByteBuffer buffer = address.getData(); assertEquals(ton, buffer.removeByte()); assertEquals(npi, buffer.removeByte()); assertEquals(a, buffer.removeCString()); } } } }
### Question: Address extends ByteData { public void setTon(byte ton) { this.ton = ton; } Address(); Address(int maxAddressLength); Address(byte ton, byte npi, int maxAddressLength); Address(String address); Address(String address, int maxAddressLength); Address(byte ton, byte npi, String address); Address(byte ton, byte npi, String address, int maxAddressLength); void setData(ByteBuffer buffer); ByteBuffer getData(); void setTon(byte ton); void setNpi(byte npi); void setAddress(String address); void setAddress(String address, int maxAddressLength); byte getTon(); byte getNpi(); String getAddress(); String getAddress(String encoding); String debugString(); }### Answer: @Test public void testSetTon() { for (byte ton : TONS) { address.setTon(ton); assertEquals(ton, address.getTon()); } }
### Question: Address extends ByteData { public void setNpi(byte npi) { this.npi = npi; } Address(); Address(int maxAddressLength); Address(byte ton, byte npi, int maxAddressLength); Address(String address); Address(String address, int maxAddressLength); Address(byte ton, byte npi, String address); Address(byte ton, byte npi, String address, int maxAddressLength); void setData(ByteBuffer buffer); ByteBuffer getData(); void setTon(byte ton); void setNpi(byte npi); void setAddress(String address); void setAddress(String address, int maxAddressLength); byte getTon(); byte getNpi(); String getAddress(); String getAddress(String encoding); String debugString(); }### Answer: @Test public void testSetNpi() { for (byte npi : NPIS) { address.setNpi(npi); assertEquals(npi, address.getNpi()); } }
### Question: Address extends ByteData { public String debugString() { String dbgs = "(addr: "; dbgs += super.debugString(); dbgs += Integer.toString(getTon()); dbgs += " "; dbgs += Integer.toString(getNpi()); dbgs += " "; dbgs += getAddress(); dbgs += ") "; return dbgs; } Address(); Address(int maxAddressLength); Address(byte ton, byte npi, int maxAddressLength); Address(String address); Address(String address, int maxAddressLength); Address(byte ton, byte npi, String address); Address(byte ton, byte npi, String address, int maxAddressLength); void setData(ByteBuffer buffer); ByteBuffer getData(); void setTon(byte ton); void setNpi(byte npi); void setAddress(String address); void setAddress(String address, int maxAddressLength); byte getTon(); byte getNpi(); String getAddress(); String getAddress(String encoding); String debugString(); }### Answer: @Test public void testDebugString() throws Exception { for (byte ton : TONS) { for (byte npi : NPIS) { for (int len = 1; len <= MAX_ADDRESS_LENGTH; len++) { String a = address(len); address = new Address(ton, npi, a, len + 1); String s = "(addr: " + Integer.toString(ton) + " " + Integer.toString(npi) + " " + a + ") "; assertEquals(s, address.debugString()); } } } }
### Question: ByteData extends SmppObject { protected static void checkString(String string, int max) throws WrongLengthOfStringException { checkString(string, 0, max); } ByteData(); abstract void setData(ByteBuffer buffer); abstract ByteBuffer getData(); String debugString(); }### Answer: @Test public void testCheckStringEqualZero() throws Exception { checkString("", 0); } @Test public void testCheckStringNonZero() throws Exception { checkString(" ", 1); } @Test public void testCheckStringOneZero() throws Exception { thrown.expect(stringLengthException(0, 0, 1)); checkString(" ", 0); } @Test public void testCheckStringUTF16() throws Exception { thrown.expect(stringLengthException(0, 1, 4)); checkString(" ", 1, "UTF-16"); } @Test public void testCheckStringInvalidEncoding() throws Exception { thrown.expect(UnsupportedEncodingException.class); checkString(" ", 1, "UTF-17"); }
### Question: Queue extends SmppObject { public Object dequeue() { synchronized (mutex) { Object first = null; if (size() > 0) { first = queueData.removeFirst(); } return first; } } Queue(); Queue(int maxSize); int size(); boolean isEmpty(); Object dequeue(); Object dequeue(Object obj); void enqueue(Object obj); Object find(Object obj); }### Answer: @Test public void testDequeueReturnsNullWhenEmpty() { assertNull(queue.dequeue()); }
### Question: ByteData extends SmppObject { protected static void checkCString(String string, int max) throws WrongLengthOfStringException { checkCString(string, 1, max); } ByteData(); abstract void setData(ByteBuffer buffer); abstract ByteBuffer getData(); String debugString(); }### Answer: @Test public void testCheckCString() throws Exception { thrown.expect(stringLengthException(0, 0, 1)); invokeMethod(CLAZZ, "checkCString", (String) null, 0, 0); }
### Question: ByteData extends SmppObject { protected static void checkRange(int min, int val, int max) throws IntegerOutOfRangeException { if ((val < min) || (val > max)) { throw new IntegerOutOfRangeException(min, max, val); } } ByteData(); abstract void setData(ByteBuffer buffer); abstract ByteBuffer getData(); String debugString(); }### Answer: @Test public void testCheckRange() throws Exception { checkRange(0, 0, 0); checkRange(0, 10, 100); } @Test public void testCheckRangeBelow() throws Exception { thrown.expect(integerOutOfRange(5, 10, 1)); checkRange(5, 1, 10); } @Test public void testCheckRangeAbove() throws Exception { thrown.expect(integerOutOfRange(5, 10, 11)); checkRange(5, 11, 10); }
### Question: ByteData extends SmppObject { protected static short decodeUnsigned(byte signed) { if (signed >= 0) { return signed; } else { return (short) (256 + (short) signed); } } ByteData(); abstract void setData(ByteBuffer buffer); abstract ByteBuffer getData(); String debugString(); }### Answer: @Test public void testDecodeUnsignedByte() throws Exception { assertEquals(0, decodeUnsigned((byte) 0x00)); assertEquals(127, decodeUnsigned((byte) 0x7f)); assertEquals(255, decodeUnsigned((byte) 0xff)); } @Test public void testDecodeUnsignedShort() throws Exception { assertEquals(0, decodeUnsigned((short) 0)); assertEquals(32768, decodeUnsigned((short) 32768)); }
### Question: ByteData extends SmppObject { protected static byte encodeUnsigned(short positive) { if (positive < 128) { return (byte) positive; } else { return (byte) (- (256 - positive)); } } ByteData(); abstract void setData(ByteBuffer buffer); abstract ByteBuffer getData(); String debugString(); }### Answer: @Test public void testEncodeUnsignedShort() throws Exception { assertEquals((byte) 0x00, encodeUnsigned((short) 0)); assertEquals((byte) 0xff, encodeUnsigned((short) 255)); } @Test public void testEncodeUnsignedInt() throws Exception { assertEquals((short) 0, encodeUnsigned((int) 0)); assertEquals((short) 32768, encodeUnsigned((int) 32768)); }
### Question: ByteBuffer extends SmppObject { public void appendByte(byte data) { byte[] byteBuf = new byte[SZ_BYTE]; byteBuf[0] = data; appendBytes0(byteBuf, SZ_BYTE); } ByteBuffer(); ByteBuffer(byte[] buffer); byte[] getBuffer(); void setBuffer(byte[] buffer); int length(); void appendByte(byte data); void appendShort(short data); void appendInt(int data); void appendCString(String string); void appendCString(String string, String encoding); void appendString(String string); void appendString(String string, String encoding); void appendString(String string, int count); void appendString(String string, int count, String encoding); void appendBuffer(ByteBuffer buf); void appendBytes(ByteBuffer bytes, int count); void appendBytes(byte[] bytes, int count); void appendBytes(byte[] bytes); byte removeByte(); short removeUnsignedByte(); short removeShort(); int removeInt(); int readInt(); String removeCString(); String removeCString(String encoding); String removeString(int size, String encoding); ByteBuffer removeBuffer(int count); ByteBuffer removeBytes(int count); void removeBytes0(int count); ByteBuffer readBytes(int count); String getHexDump(); }### Answer: @Test public void testAppendByte0() { buffer.appendByte(t_bite); assertBufferMatches(t_bite); } @Test public void testAppendByte1() { buffer = new ByteBuffer(new byte[] {}); buffer.appendByte(t_bite); assertBufferMatches(t_bite); }
### Question: SmppObject { static public Debug getDebug() { return debug; } static void setDebug(Debug dbg); static void setEvent(Event evt); static Debug getDebug(); static Event getEvent(); static final int DRXTX; static final int DRXTXD; static final int DRXTXD2; static final int DSESS; static final int DPDU; static final int DPDUD; static final int DCOM; static final int DCOMD; static final int DUTL; static final int DUTLD; }### Answer: @Test public void testDefaultDebug() { assertEquals(DefaultDebug.class, SmppObject.getDebug().getClass()); }
### Question: SmppObject { static public Event getEvent() { return event; } static void setDebug(Debug dbg); static void setEvent(Event evt); static Debug getDebug(); static Event getEvent(); static final int DRXTX; static final int DRXTXD; static final int DRXTXD2; static final int DSESS; static final int DPDU; static final int DPDUD; static final int DCOM; static final int DCOMD; static final int DUTL; static final int DUTLD; }### Answer: @Test public void testDefaultEvent() { assertEquals(DefaultEvent.class, SmppObject.getEvent().getClass()); }
### Question: SmppObject { static public void setDebug(Debug dbg) { debug = dbg; } static void setDebug(Debug dbg); static void setEvent(Event evt); static Debug getDebug(); static Event getEvent(); static final int DRXTX; static final int DRXTXD; static final int DRXTXD2; static final int DSESS; static final int DPDU; static final int DPDUD; static final int DCOM; static final int DCOMD; static final int DUTL; static final int DUTLD; }### Answer: @Test public void testSetDebug() { Debug debug = mock(Debug.class); SmppObject.setDebug(debug); assertEquals(debug, SmppObject.getDebug()); }
### Question: SmppObject { static public void setEvent(Event evt) { event = evt; } static void setDebug(Debug dbg); static void setEvent(Event evt); static Debug getDebug(); static Event getEvent(); static final int DRXTX; static final int DRXTXD; static final int DRXTXD2; static final int DSESS; static final int DPDU; static final int DPDUD; static final int DCOM; static final int DCOMD; static final int DUTL; static final int DUTLD; }### Answer: @Test public void testSetEvent() { Event event = mock(Event.class); SmppObject.setEvent(event); assertEquals(event, SmppObject.getEvent()); }
### Question: RequestReader { public Request read() throws IOException { final String line = this.reader.readLine(); if (line == null) { throw new CloseException("exception while reading line (null)"); } return mapper.readValue(line, Request.class); } RequestReader(final InputStream in); Request read(); }### Answer: @Test public void throwOnClosed() throws IOException { final InputStream in = new ByteArrayInputStream(new byte[]{}) { @Override public int read(byte[] var1) throws IOException { throw new IOException("closed"); } }; final RequestReader reader = new RequestReader(in); boolean thrown = false; try { reader.read(); } catch (IOException ex) { thrown = true; } assertThat(thrown).isTrue(); } @Test public void twoValid() throws IOException { final String input = "{\"content\":\"package foo;\"}\n{\"content\":\"package bar;\"}\n"; final InputStream in = new ByteArrayInputStream(input.getBytes()); final RequestReader reader = new RequestReader(in); Request request = reader.read(); Request expected = new Request(); expected.content = "package foo;"; assertThat(request.content).isEqualTo(expected.content); assertThat(request).isEqualTo(expected); request = reader.read(); expected = new Request(); expected.content = "package bar;"; assertThat(request.content).isEqualTo(expected.content); assertThat(request).isEqualTo(expected); } @Test public void oneMalformedOnValid() throws IOException { final String input = "foo\n{\"content\":\"package foo;\"}\n"; final InputStream in = new ByteArrayInputStream(input.getBytes()); final RequestReader reader = new RequestReader(in); boolean thrown = false; try { reader.read(); } catch (IOException ex) { thrown = true; } assertThat(thrown).isTrue(); Request request = reader.read(); Request expected = new Request(); expected.content = "package foo;"; assertThat(request.content).isEqualTo(expected.content); assertThat(request).isEqualTo(expected); }
### Question: Driver { public void run() throws DriverException, CloseException { while (true) { this.processOne(); } } Driver(final RequestReader reader, final ResponseWriter writer); void run(); void processOne(); }### Answer: @Test public void exitOnCloseIn() throws DriverException, CloseException { final String input = "{\"content\":\"package foo;\"}\n{\"content\":\"package bar;\"}\n"; final InputStream in = new ByteArrayInputStream(input.getBytes()); final RequestReader reader = new RequestReader(in); final ByteArrayOutputStream out = new ByteArrayOutputStream(); final ResponseWriter writer = new ResponseWriter(out); final Driver driver = new Driver(reader, writer); try { driver.run(); } catch (CloseException ex) { } }