src_fm_fc_ms_ff stringlengths 43 86.8k | target stringlengths 20 276k |
|---|---|
SnapshotPostProcessor { @VisibleForTesting static long updateVersionAndCheckConsistency(long localVersion, long newVersion, String errorMessage) { if (localVersion == -1) { return newVersion; } else { if (localVersion != newVersion) { throw new UnrecoverableStoreException(errorMessage, args -> args.add("localVersion", ... | @Test public void shouldSucceedWhenInitializionSnapshotToAppModelVersion() { assertThat(updateVersionAndCheckConsistency(-1L, 5L, "shouldSucceed because the applicationVersion was not yet initialized")) .as("Whenever the Version is not initialized we can set it").isEqualTo(5L); }
@Test(expectedExceptions = Unrecoverabl... |
SnapshotPostProcessor { long getConsistentApplicationModelVersion() { long applicationModelVersion = 0; if (m_beforePostProcessingVersion > 0) { applicationModelVersion = m_beforePostProcessingVersion; } if (m_afterPostProcessingVersion > 0) { applicationModelVersion = m_afterPostProcessingVersion; } return application... | @Test public void shouldReturn0WhenNoApplicationVersionDefined() { SnapshotPostProcessor snapshotPostProcessor = new SnapshotPostProcessor((snapshot, storeName) -> snapshot); assertThat(snapshotPostProcessor.getConsistentApplicationModelVersion()).isEqualTo(0L); } |
SnapshotPostProcessor { SerializableSnapshot apply(String storeName, SerializableSnapshot serializableSnapshot) { m_beforePostProcessingVersion = updateVersionAndCheckConsistency(m_beforePostProcessingVersion, serializableSnapshot.getApplicationModelVersion(), "Snapshot serializable application model version differs am... | @Test(expectedExceptions = UnrecoverableStoreException.class) public void shouldFailWhenValidatingPostProcessingUpdatingApplicationModelVersion() { SerializableSnapshot initialSnapshot = new SerializableSnapshot(); long initialSnapshotModelVersion = 10L; long finalSnapshotModelVersion = 9L; initialSnapshot.setApplicati... |
OAuthAsyncCompletionHandler extends AsyncCompletionHandler<T> { @Override public T onCompleted(com.ning.http.client.Response ningResponse) { try { final Map<String, String> headersMap = new HashMap<>(); for (Map.Entry<String, List<String>> header : ningResponse.getHeaders().entrySet()) { final StringBuilder value = new... | @Test public void shouldReleaseLatchOnSuccess() throws Exception { handler = new OAuthAsyncCompletionHandler<>(callback, ALL_GOOD_RESPONSE_CONVERTER); final com.ning.http.client.Response response = new MockResponse(200, "ok", new FluentCaseInsensitiveStringsMap(), new byte[0]); handler.onCompleted(response); assertNotN... |
HMACSha1SignatureService implements SignatureService { @Override public String getSignature(String baseString, String apiSecret, String tokenSecret) { try { Preconditions.checkEmptyString(baseString, "Base string cant be null or empty string"); Preconditions.checkEmptyString(apiSecret, "Api secret cant be null or empty... | @Test(expected = OAuthException.class) public void shouldThrowExceptionIfBaseStringIsEmpty() { service.getSignature(" ", "apiSecret", "tokenSecret"); }
@Test(expected = OAuthException.class) public void shouldThrowExceptionIfApiSecretIsNull() { service.getSignature("base string", null, "tokenSecret"); }
@Test(expected ... |
RSASha1SignatureService implements SignatureService { @Override public String getSignatureMethod() { return METHOD; } RSASha1SignatureService(PrivateKey privateKey); @Override String getSignature(String baseString, String apiSecret, String tokenSecret); @Override String getSignatureMethod(); } | @Test public void shouldReturnSignatureMethodString() { final String expected = "RSA-SHA1"; assertEquals(expected, service.getSignatureMethod()); } |
RSASha1SignatureService implements SignatureService { @Override public String getSignature(String baseString, String apiSecret, String tokenSecret) { try { final Signature signature = Signature.getInstance(RSA_SHA1); signature.initSign(privateKey); signature.update(baseString.getBytes(UTF8)); return BASE_64_ENCODER.enc... | @Test public void shouldReturnSignature() { final String apiSecret = "api secret"; final String tokenSecret = "token secret"; final String baseString = "base string"; final String signature = "LUNRzQAlpdNyM9mLXm96Va6g/qVNnEAb7p7K1KM0g8IopOFQJPoOO7cvppgt7w3QyhijWJnCmvqXaaIAGrqvd" + "yr3fIzBULh8D/iZQUNLMi08GCOA34P81XBvsc... |
ParameterList { public String appendTo(String url) { Preconditions.checkNotNull(url, "Cannot append to null URL"); final String queryString = asFormUrlEncodedString(); if (queryString.equals(EMPTY_STRING)) { return url; } else { return url + (url.indexOf(QUERY_STRING_SEPARATOR) == -1 ? QUERY_STRING_SEPARATOR : PARAM_SE... | @Test(expected = IllegalArgumentException.class) public void shouldThrowExceptionWhenAppendingNullMapToQuerystring() { params.appendTo(null); }
@Test public void shouldAppendNothingToQuerystringIfGivenEmptyMap() { final String url = "http: Assert.assertEquals(url, params.appendTo(url)); } |
Token implements Serializable { public String getParameter(String parameter) { String value = null; for (String str : rawResponse.split("&")) { if (str.startsWith(parameter + '=')) { final String[] part = str.split("="); if (part.length > 1) { value = part[1].trim(); } break; } } return value; } protected Token(String... | @Test public void shouldReturnUrlParam() { final Token actual = new OAuth1AccessToken("acccess", "secret", "user_id=3107154759&screen_name=someuser&empty=&="); assertEquals("someuser", actual.getParameter("screen_name")); assertEquals("3107154759", actual.getParameter("user_id")); assertEquals(null, actual.getParameter... |
OAuthRequest { public void addOAuthParameter(String key, String value) { oauthParameters.put(checkKey(key), value); } OAuthRequest(Verb verb, String url); void addOAuthParameter(String key, String value); Map<String, String> getOauthParameters(); void setRealm(String realm); String getRealm(); String getCompleteUrl(); ... | @Test(expected = IllegalArgumentException.class) public void shouldThrowExceptionIfParameterIsNotOAuth() { request.addOAuthParameter("otherParam", "value"); } |
MultipartUtils { public static ByteArrayOutputStream getPayload(MultipartPayload multipartPayload) throws IOException { final ByteArrayOutputStream os = new ByteArrayOutputStream(); final String preamble = multipartPayload.getPreamble(); if (preamble != null) { os.write((preamble + "\r\n").getBytes()); } final List<Bod... | @Test public void testEmptyMultipartPayload() throws IOException { final MultipartPayload mP = new MultipartPayload(); final StringBuilder headersString = new StringBuilder(); for (Map.Entry<String, String> header : mP.getHeaders().entrySet()) { headersString.append(header.getKey()) .append(": ") .append(header.getValu... |
MultipartUtils { public static String parseBoundaryFromHeader(String contentTypeHeader) { if (contentTypeHeader == null) { return null; } final Matcher matcher = BOUNDARY_FROM_HEADER_REGEXP.matcher(contentTypeHeader); return matcher.find() ? matcher.group(1) : null; } private MultipartUtils(); static void checkBoundar... | @Test public void testParseBoundaryFromHeader() { assertNull(MultipartUtils.parseBoundaryFromHeader(null)); assertEquals("0aA'()+_,-./:=?", MultipartUtils.parseBoundaryFromHeader("multipart/subtype; boundary=\"0aA'()+_,-./:=?\"")); assertEquals("0aA'()+_, -./:=?", MultipartUtils.parseBoundaryFromHeader("multipart/subty... |
MultipartUtils { public static void checkBoundarySyntax(String boundary) { if (boundary == null || !BOUNDARY_REGEXP.matcher(boundary).matches()) { throw new IllegalArgumentException("{'boundary'='" + boundary + "'} has invalid syntax. Should be '" + BOUNDARY_PATTERN + "'."); } } private MultipartUtils(); static void c... | @Test public void testValidCheckBoundarySyntax() { MultipartUtils.checkBoundarySyntax("0aA'()+_,-./:=?"); MultipartUtils.checkBoundarySyntax("0aA'()+_,- ./:=?"); MultipartUtils.checkBoundarySyntax(" 0aA'()+_,-./:=?"); MultipartUtils.checkBoundarySyntax("123456789012345678901234567890123456789012345678901234567890123456... |
Preconditions { public static void checkNotNull(Object object, String errorMsg) { check(object != null, errorMsg); } static void checkNotNull(Object object, String errorMsg); static void checkEmptyString(String string, String errorMsg); static boolean hasText(String str); } | @Test(expected = IllegalArgumentException.class) public void shouldThrowExceptionForNullObjects() { Preconditions.checkNotNull(null, ERROR_MSG); } |
Preconditions { public static void checkEmptyString(String string, String errorMsg) { check(hasText(string), errorMsg); } static void checkNotNull(Object object, String errorMsg); static void checkEmptyString(String string, String errorMsg); static boolean hasText(String str); } | @Test(expected = IllegalArgumentException.class) public void shouldThrowExceptionForNullStrings() { Preconditions.checkEmptyString(null, ERROR_MSG); }
@Test(expected = IllegalArgumentException.class) public void shouldThrowExceptionForEmptyStrings() { Preconditions.checkEmptyString("", ERROR_MSG); }
@Test(expected = Il... |
FitBitJsonTokenExtractor extends OAuth2AccessTokenJsonExtractor { @Override public void generateError(String rawResponse) throws IOException { final JsonNode errorNode = OAuth2AccessTokenJsonExtractor.OBJECT_MAPPER.readTree(rawResponse) .get("errors").get(0); OAuth2Error errorCode; try { errorCode = OAuth2Error.parseFr... | @Test public void testErrorExtraction() throws IOException { final FitBitJsonTokenExtractor extractor = new FitBitJsonTokenExtractor(); final OAuth2AccessTokenErrorResponse thrown = assertThrows(OAuth2AccessTokenErrorResponse.class, new ThrowingRunnable() { @Override public void run() throws Throwable { extractor.gener... |
OAuthEncoder { public static String encode(String plain) { Preconditions.checkNotNull(plain, "Cannot encode null object"); String encoded; try { encoded = URLEncoder.encode(plain, CHARSET); } catch (UnsupportedEncodingException uee) { throw new OAuthException("Charset not found while encoding string: " + CHARSET, uee);... | @Test public void shouldPercentEncodeString() { final String plain = "this is a test &^"; final String encoded = "this%20is%20a%20test%20%26%5E"; assertEquals(encoded, OAuthEncoder.encode(plain)); }
@Test public void shouldNotPercentEncodeReservedCharacters() { final String plain = "abcde123456-._~"; final String encod... |
OAuthEncoder { public static String decode(String encoded) { Preconditions.checkNotNull(encoded, "Cannot decode null object"); try { return URLDecoder.decode(encoded, CHARSET); } catch (UnsupportedEncodingException uee) { throw new OAuthException("Charset not found while decoding string: " + CHARSET, uee); } } static ... | @Test public void shouldFormURLDecodeString() { final String encoded = "this+is+a+test+%26%5E"; final String plain = "this is a test &^"; assertEquals(plain, OAuthEncoder.decode(encoded)); }
@Test(expected = IllegalArgumentException.class) public void shouldThrowExceptionIfStringToDecodeIsNull() { OAuthEncoder.decode(n... |
StreamUtils { public static String getStreamContents(InputStream is) throws IOException { Preconditions.checkNotNull(is, "Cannot get String from a null object"); final char[] buffer = new char[0x10000]; final StringBuilder out = new StringBuilder(); try (Reader in = new InputStreamReader(is, "UTF-8")) { int read; do { ... | @Test public void shouldCorrectlyDecodeAStream() throws IOException { final String value = "expected"; final InputStream is = new ByteArrayInputStream(value.getBytes()); final String decoded = StreamUtils.getStreamContents(is); assertEquals("expected", decoded); }
@Test(expected = IllegalArgumentException.class) public... |
OAuth2AccessTokenExtractor implements TokenExtractor<OAuth2AccessToken> { @Override public OAuth2AccessToken extract(Response response) throws IOException { if (response.getCode() != 200) { throw new OAuthException("Response code is not 200 but '" + response.getCode() + '\''); } final String body = response.getBody(); ... | @Test public void shouldExtractTokenFromOAuthStandardResponse() throws IOException { final String responseBody = "access_token=166942940015970|2.2ltzWXYNDjCtg5ZDVVJJeg__.3600.1295816400-548517159" + "|RsXNdKrpxg8L6QNLWcs2TVTmcaE"; final OAuth2AccessToken extracted; try (Response response = ok(responseBody)) { extracted... |
OAuthAsyncCompletionHandler implements Callback { @Override public void onResponse(Call call, okhttp3.Response okHttpResponse) { try { final Response response = OkHttpHttpClient.convertResponse(okHttpResponse); try { @SuppressWarnings("unchecked") final T t = converter == null ? (T) response : converter.convert(respons... | @Test public void shouldReleaseLatchOnSuccess() throws Exception { handler = new OAuthAsyncCompletionHandler<>(callback, ALL_GOOD_RESPONSE_CONVERTER, future); call.enqueue(handler); final Request request = new Request.Builder().url("http: final okhttp3.Response response = new okhttp3.Response.Builder() .request(request... |
OAuth2AccessTokenJsonExtractor implements TokenExtractor<OAuth2AccessToken> { @Override public OAuth2AccessToken extract(Response response) throws IOException { final String body = response.getBody(); Preconditions.checkEmptyString(body, "Response body is incorrect. Can't extract a token from an empty string"); if (res... | @Test public void shouldParseResponse() throws IOException { final String responseBody = "{ \"access_token\":\"I0122HHJKLEM21F3WLPYHDKGKZULAUO4SGMV3ABKFTDT3T3X\", " + "\"token_type\":\"example\"}"; final OAuth2AccessToken token; try (Response response = ok(responseBody)) { token = extractor.extract(response); } assertE... |
OAuth20Service extends OAuthService { public OAuth2AccessToken getAccessTokenPasswordGrant(String username, String password) throws IOException, InterruptedException, ExecutionException { final OAuthRequest request = createAccessTokenPasswordGrantRequest(username, password, null); return sendAccessTokenRequestSync(requ... | @Test public void shouldProduceCorrectRequestSync() throws IOException, InterruptedException, ExecutionException { final OAuth20Service service = new ServiceBuilder("your_api_key") .apiSecret("your_api_secret") .build(new OAuth20ApiUnit()); final OAuth2AccessToken token = service.getAccessTokenPasswordGrant("user1", "p... |
OAuth20Service extends OAuthService { public Future<OAuth2AccessToken> getAccessTokenPasswordGrantAsync(String username, String password) { return getAccessTokenPasswordGrantAsync(username, password, (OAuthAsyncRequestCallback<OAuth2AccessToken>) null); } OAuth20Service(DefaultApi20 api, String apiKey, String apiSecret... | @Test public void shouldProduceCorrectRequestAsync() throws ExecutionException, InterruptedException, IOException { final OAuth20Service service = new ServiceBuilder("your_api_key") .apiSecret("your_api_secret") .build(new OAuth20ApiUnit()); final OAuth2AccessToken token = service.getAccessTokenPasswordGrantAsync("user... |
OAuth20Service extends OAuthService { public OAuth2Authorization extractAuthorization(String redirectLocation) { final OAuth2Authorization authorization = new OAuth2Authorization(); int end = redirectLocation.indexOf('#'); if (end == -1) { end = redirectLocation.length(); } for (String param : redirectLocation.substrin... | @Test public void testOAuthExtractAuthorization() { final OAuth20Service service = new ServiceBuilder("your_api_key") .apiSecret("your_api_secret") .build(new OAuth20ApiUnit()); OAuth2Authorization authorization = service.extractAuthorization("https: assertEquals("SplxlOB", authorization.getCode()); assertEquals("xyz",... |
OAuthAsyncCompletionHandler implements Callback { @Override public void onFailure(Call call, IOException exception) { try { okHttpFuture.setException(exception); if (callback != null) { callback.onThrowable(exception); } } finally { okHttpFuture.finish(); } } OAuthAsyncCompletionHandler(OAuthAsyncRequestCallback<T> cal... | @Test public void shouldReleaseLatchOnFailure() throws Exception { handler = new OAuthAsyncCompletionHandler<>(callback, ALL_GOOD_RESPONSE_CONVERTER, future); call.enqueue(handler); handler.onFailure(call, new IOException()); assertNull(callback.getResponse()); assertNotNull(callback.getThrowable()); assertTrue(callbac... |
HMACSha1SignatureService implements SignatureService { @Override public String getSignatureMethod() { return METHOD; } @Override String getSignature(String baseString, String apiSecret, String tokenSecret); @Override String getSignatureMethod(); } | @Test public void shouldReturnSignatureMethodString() { final String expected = "HMAC-SHA1"; assertEquals(expected, service.getSignatureMethod()); } |
CSRFToken implements Serializable { public String getParameterName() { return parameterName; } CSRFToken(String token); CSRFToken(String headerName, String parameterName, String token); String getHeaderName(); String getParameterName(); String getToken(); } | @Test public void testPOSTRequestsWithWrongToken() throws Exception { this.mockMvc.perform(post("/test/csrf").param(TEST_TOKEN.getParameterName(), "WRONG_TOKEN")).andExpect( status().isBadRequest()); }
@Test public void testPUTRequestsWithWrongToken() throws Exception { this.mockMvc.perform(put("/test/csrf").param(TEST... |
FileSystemLogRepository implements ExecutionLogRepository { @Override public void update(ExecutionLog log) { store(log, readJson(logFileFor(log.getTaskName(), log.getId())).map(obj -> obj.getAsJsonPrimitive("previous")).map( JsonPrimitive::getAsString)); } FileSystemLogRepository(String basePath, int dispersionFactor);... | @Test public void testUpdate() { ExecutionLog original = ExecutionLog.newExecutionFor(TASK_NAME); repository.newExecution(original); assertEquals(original, repository.getLog(original.getTaskName(), original.getId()).get()); ExecutionLog log = original.withSuccess(); repository.update(log); assertEquals(log, repository.... |
FileSystemLogRepository implements ExecutionLogRepository { @Override public Stream<ExecutionLog> executionsFor(String taskName, Optional<String> start, int max) { String id; if (start.isPresent()) { id = start.get(); } else { JsonObject index = readIndexJson(); if (!index.has(taskName)) { return Stream.empty(); } id =... | @Test public void testExecutionsFor() { ExecutionLog original = ExecutionLog.newExecutionFor(TASK_NAME); repository.newExecution(original); ExecutionLog newLog = ExecutionLog.newExecutionFor(TASK_NAME); repository.newExecution(newLog); assertTrue(repository.executionsFor(original.getTaskName(), Optional.empty(), Intege... |
ExecutionLog { public static ExecutionLog newExecutionFor(String taskName) { return new ExecutionLog(UUID.randomUUID().toString().replace("-", ""), DateTime.now(), Optional.empty(), TaskState.RUNNING, Objects.requireNonNull(taskName), Optional.empty(), Collections.emptySet(), computeHostName(), Optional.empty(), Option... | @Test(expected = NullPointerException.class) public void testNullTaskName() { ExecutionLog.newExecutionFor(null); } |
ExecutionLog { public static ExecutionLog newCustomExecution(String taskName, String code, String user) { return new ExecutionLog(UUID.randomUUID().toString().replace("-", ""), DateTime.now(), Optional.empty(), TaskState.RUNNING, Objects.requireNonNull(taskName), Optional.empty(), Collections.emptySet(), computeHostNam... | @Test(expected = NullPointerException.class) public void testNullTaskNameOnCustomTask() { ExecutionLog.newCustomExecution(null, "code", "myself"); }
@Test(expected = NullPointerException.class) public void testNullCode() { ExecutionLog.newCustomExecution(TASK_NAME, null, "myself"); }
@Test(expected = NullPointerExcepti... |
ExecutionLog { @Override public boolean equals(Object obj) { if (obj instanceof ExecutionLog) { ExecutionLog other = (ExecutionLog) obj; return Objects.equals(id, other.id) && Objects.equals(start, other.start) && Objects.equals(end, other.end) && Objects.equals(state, other.state) && Objects.equals(taskName, other.tas... | @Test public void testEquals() { ExecutionLog log = ExecutionLog.newExecutionFor(TASK_NAME); ExecutionLog custom = ExecutionLog.newCustomExecution(TASK_NAME, "mycode", "myself"); assertEquals(log, log); assertNotEquals(log, log.withSuccess()); assertNotEquals(log, log.withFile("xpto")); assertNotEquals(log, log.withErr... |
GuitarString { public void tic() { double newAveragedDouble = DECAY * (buffer.dequeue() + buffer.peek()) / 2; buffer.enqueue(newAveragedDouble); } GuitarString(double frequency); void pluck(); void tic(); double sample(); } | @Test public void testTic() { GuitarString s = new GuitarString(11025); s.pluck(); double s1 = s.sample(); s.tic(); double s2 = s.sample(); s.tic(); double s3 = s.sample(); s.tic(); double s4 = s.sample(); s.tic(); double s5 = s.sample(); double expected = 0.996 * 0.5 * (s1 + s2); assertEquals(expected, s5, 0.001); } |
Plip extends Creature { public Action chooseAction(Map<Direction, Occupant> neighbors) { List<Direction> emptySpaces = getNeighborsOfType(neighbors, "empty"); List<Direction> cloruses = getNeighborsOfType(neighbors, "clorus"); if (emptySpaces.isEmpty()) { return new Action(Action.ActionType.STAY); } if (energy > 1) { D... | @Test public void testChoose() { Plip p = new Plip(1.2); HashMap<Direction, Occupant> surrounded = new HashMap<Direction, Occupant>(); surrounded.put(Direction.TOP, new Impassible()); surrounded.put(Direction.BOTTOM, new Impassible()); surrounded.put(Direction.LEFT, new Impassible()); surrounded.put(Direction.RIGHT, ne... |
Board implements WorldState { public int tileAt(int i, int j) { if (i < 0 || i >= N || j < 0 || j >= N) { throw new IndexOutOfBoundsException("Invalid row and/or column"); } return tiles[i][j]; } Board(int[][] tiles); int tileAt(int i, int j); int size(); int hamming(); int manhattan(); int hashCode(); boolean equals(O... | @Test public void verifyImmutability() { int r = 2; int c = 2; int[][] x = new int[r][c]; int cnt = 0; for (int i = 0; i < r; i += 1) { for (int j = 0; j < c; j += 1) { x[i][j] = cnt; cnt += 1; } } Board b = new Board(x); assertEquals("Your Board class is not being initialized with the right values.", 0, b.tileAt(0, 0)... |
IntList { public static IntList list(Integer... args) { IntList result, p; if (args.length > 0) { result = new IntList(args[0], null); } else { return null; } int k; for (k = 1, p = result; k < args.length; k += 1, p = p.rest) { p.rest = new IntList(args[k], null); } return result; } IntList(int first0, IntList rest0);... | @Test public void testList() { IntList one = new IntList(1, null); IntList twoOne = new IntList(2, one); IntList threeTwoOne = new IntList(3, twoOne); IntList x = IntList.list(3, 2, 1); assertEquals(threeTwoOne, x); } |
IntList { public static void dSquareList(IntList L) { while (L != null) { L.first = L.first * L.first; L = L.rest; } } IntList(int first0, IntList rest0); IntList(); static void dSquareList(IntList L); static IntList squareListIterative(IntList L); static IntList squareListRecursive(IntList L); static IntList dcatenat... | @Test public void testdSquareList() { IntList L = IntList.list(1, 2, 3); IntList.dSquareList(L); assertEquals(IntList.list(1, 4, 9), L); } |
IntList { public static IntList squareListRecursive(IntList L) { if (L == null) { return null; } return new IntList(L.first * L.first, squareListRecursive(L.rest)); } IntList(int first0, IntList rest0); IntList(); static void dSquareList(IntList L); static IntList squareListIterative(IntList L); static IntList squareL... | @Test public void testSquareListRecursive() { IntList L = IntList.list(1, 2, 3); IntList res = IntList.squareListRecursive(L); assertEquals(IntList.list(1, 2, 3), L); assertEquals(IntList.list(1, 4, 9), res); } |
IntList { public static IntList dcatenate(IntList A, IntList B) { return null; } IntList(int first0, IntList rest0); IntList(); static void dSquareList(IntList L); static IntList squareListIterative(IntList L); static IntList squareListRecursive(IntList L); static IntList dcatenate(IntList A, IntList B); static IntLis... | @Test public void testDcatenate() { IntList A = IntList.list(1, 2, 3); IntList B = IntList.list(4, 5, 6); IntList exp = IntList.list(1, 2, 3, 4, 5, 6); assertEquals(exp, IntList.dcatenate(A, B)); assertEquals(IntList.list(1, 2, 3, 4, 5, 6), A); } |
IntList { public static IntList catenate(IntList A, IntList B) { return null; } IntList(int first0, IntList rest0); IntList(); static void dSquareList(IntList L); static IntList squareListIterative(IntList L); static IntList squareListRecursive(IntList L); static IntList dcatenate(IntList A, IntList B); static IntList... | @Test public void testCatenate() { IntList A = IntList.list(1, 2, 3); IntList B = IntList.list(4, 5, 6); IntList exp = IntList.list(1, 2, 3, 4, 5, 6); assertEquals(exp, IntList.catenate(A, B)); assertEquals(IntList.list(1, 2, 3), A); } |
Boggle { public static String answerString(List<String> answers, int numberOfAnswers) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < answers.size() && i < numberOfAnswers; i++) { sb.append(answers.get(i)).append('\n'); } sb.setLength(sb.length() - 1); return sb.toString(); } static void main(String[] ar... | @Test public void solveBoard() { List<String> boardLines = null; List<String> dictionaryWords = null; try { boardLines = Files.readAllLines(Paths.get("testBoggle")); dictionaryWords = Files.readAllLines(Paths.get("words")); } catch (IOException e) { e.printStackTrace(); } Board board = new Board(boardLines, dictionaryW... |
Arithmetic { public static int product(int a, int b) { return a * b; } static int product(int a, int b); static int sum(int a, int b); } | @Test public void testProduct() { assertEquals(30, Arithmetic.product(5, 6)); assertEquals(-30, Arithmetic.product(5, -6)); assertEquals(0, Arithmetic.product(0, -6)); } |
Arithmetic { public static int sum(int a, int b) { return a * b; } static int product(int a, int b); static int sum(int a, int b); } | @Test public void testSum() { assertEquals(11, Arithmetic.sum(5, 6)); assertEquals(-1, Arithmetic.sum(5, -6)); assertEquals(-6, Arithmetic.sum(0, -6)); assertEquals(0, Arithmetic.sum(6, -6)); } |
Trie { public List<String> getWordsContainingPrefix(String prefix) { LinkedList<String> words = new LinkedList<>(); Node pointer = root; for (int i = 0; i < prefix.length(); i++) { char currentChar = prefix.charAt(i); if (!pointer.children.containsKey(currentChar)) { return words; } pointer = pointer.children.get(curre... | @Test public void getWordsContainingPrefix() { Trie trie = new Trie(); trie.add("app"); trie.add("appearance"); trie.add("apple"); trie.add("appliance"); trie.add("application"); trie.add("montclair"); trie.add("mountain"); List<String> wordsContainingPrefix = trie.getWordsContainingPrefix("foster"); assertEquals(0, wo... |
BinaryTrie implements Serializable { public Match longestPrefixMatch(BitSequence querySequence) { StringBuilder currentBitSeq = new StringBuilder(); Node pointer = root; for (int i = 0; i < querySequence.length(); i++) { if (querySequence.bitAt(i) == 0 && pointer.leftChild != null) { currentBitSeq.append('0'); pointer ... | @Test public void bestPrefixMatchWithExactMatches() { System.out.println("Testing that bestPrefixMatch works with exact matches."); Map<Character, Integer> frequencyTable = new HashMap<Character, Integer>(); frequencyTable.put('a', 1); frequencyTable.put('b', 2); frequencyTable.put('c', 4); frequencyTable.put('d', 5); ... |
BinaryTrie implements Serializable { public Map<Character, BitSequence> buildLookupTable() { Map<Character, BitSequence> lookupTable = new HashMap<>(); Map<Node, String> nodeBitPrefixTable = new HashMap<>(); nodeBitPrefixTable.put(root, ""); Stack<Node> nodeStack = new Stack<>(); nodeStack.push(root); while (!nodeStack... | @Test public void testYourLookupTable() { System.out.println("Testing that your code outputs the right lookup table."); Map<Character, Integer> frequencyTable = new HashMap<Character, Integer>(); frequencyTable.put('a', 1); frequencyTable.put('b', 2); frequencyTable.put('c', 4); frequencyTable.put('d', 5); frequencyTab... |
Dog { public String noise() { if (size < 10) { return "yip"; } return "bark"; } Dog(int s); String noise(); } | @Test public void testSmall() { Dog d = new Dog(3); assertEquals("yip", d.noise()); }
@Test public void testLarge() { Dog d = new Dog(20); assertEquals("bark", d.noise()); } |
SimpleOomage implements Oomage { @Override public boolean equals(Object o) { if (o == null || getClass() != o.getClass()) { return false; } if (this == o || this.hashCode() == o.hashCode()) { return true; } return false; } SimpleOomage(int r, int g, int b); @Override boolean equals(Object o); @Override int hashCode(); ... | @Test public void testEquals() { SimpleOomage ooA = new SimpleOomage(5, 10, 20); SimpleOomage ooA2 = new SimpleOomage(5, 10, 20); SimpleOomage ooB = new SimpleOomage(50, 50, 50); assertEquals(ooA, ooA2); assertNotEquals(ooA, ooB); assertNotEquals(ooA2, ooB); assertNotEquals(ooA, "ketchup"); } |
SimpleOomage implements Oomage { public static SimpleOomage randomSimpleOomage() { int red = StdRandom.uniform(0, 51) * 5; int green = StdRandom.uniform(0, 51) * 5; int blue = StdRandom.uniform(0, 51) * 5; return new SimpleOomage(red, green, blue); } SimpleOomage(int r, int g, int b); @Override boolean equals(Object o)... | @Test public void testRandomOomagesHashCodeSpread() { List<Oomage> oomages = new ArrayList<>(); int N = 10000; for (int i = 0; i < N; i += 1) { oomages.add(SimpleOomage.randomSimpleOomage()); } assertTrue(OomageTestUtility.haveNiceHashCodeSpread(oomages, 10)); } |
Clorus extends Creature { @Override public Clorus replicate() { energy /= 2; return new Clorus(energy); } Clorus(double energy); @Override void move(); @Override void attack(Creature c); @Override Clorus replicate(); @Override void stay(); @Override Action chooseAction(Map<Direction, Occupant> neighbors); @Override Col... | @Test public void testReplicate() { Clorus c = new Clorus(2); Clorus offspring = c.replicate(); assertEquals(1, c.energy(), 0.01); assertEquals(1, offspring.energy(), 0.01); assertNotSame(c, offspring); } |
Clorus extends Creature { @Override public Action chooseAction(Map<Direction, Occupant> neighbors) { List<Direction> emptySpaces = getNeighborsOfType(neighbors, "empty"); List<Direction> plips = getNeighborsOfType(neighbors, "plip"); if (emptySpaces.isEmpty()) { return new Action(Action.ActionType.STAY); } if (!plips.i... | @Test public void testChoose() { Clorus c = new Clorus(5); HashMap<Direction, Occupant> noEmptySpaces = new HashMap<Direction, Occupant>(); noEmptySpaces.put(Direction.TOP, new Plip()); noEmptySpaces.put(Direction.BOTTOM, new Impassible()); noEmptySpaces.put(Direction.LEFT, new Plip()); noEmptySpaces.put(Direction.RIGH... |
Plip extends Creature { public Plip replicate() { energy /= 2; return new Plip(energy); } Plip(double e); Plip(); Color color(); void attack(Creature c); void move(); void stay(); Plip replicate(); Action chooseAction(Map<Direction, Occupant> neighbors); } | @Test public void testReplicate() { Plip p = new Plip(2); Plip offspring = p.replicate(); assertEquals(1, p.energy(), 0.01); assertEquals(1, offspring.energy(), 0.01); assertNotSame(p, offspring); } |
StringWritableCsv { public static StringBuffer writeTo(StringBuffer sb, StringWritable... values) throws IllegalArgumentException { checkNotNull(sb, "sb"); if(null == values || values.length == 0) { return sb; } writeStringWritableToStringBuffer(values[0], sb); int i = 1; while (i < values.length) { sb.append(','); wri... | @Test public void writeToNullOrEmpty() { assertTrue(StringWritableCsv.writeTo(new StringBuffer()).length() == 0); assertTrue(StringWritableCsv.writeTo(new StringBuffer(), new CharAttributeValue[]{}).length() == 0); }
@Test public void writeToOneArg() { CharAttributeValue[] pairs = new CharAttributeValue[] { new ScramAt... |
UsAsciiUtils { public static String toPrintable(String value) throws IllegalArgumentException { checkNotNull(value, "value"); char[] printable = new char[value.length()]; int i = 0; for(char chr : value.toCharArray()) { int c = (int) chr; if (c < 0 || c >= 127) { throw new IllegalArgumentException("value contains chara... | @Test public void toPrintableNonASCII() { String[] nonASCIIStrings = new String[] { "abcdé", "ñ", "€", "Наташа", (char) 127 + "" }; int n = 0; for(String s : nonASCIIStrings) { try { UsAsciiUtils.toPrintable(s); } catch(IllegalArgumentException ex) { n++; } } assertTrue( "String(s) with non-ASCII characters not throwin... |
ServerFirstMessage implements StringWritable { @Override public String toString() { return writeTo(new StringBuffer()).toString(); } ServerFirstMessage(
String clientNonce, String serverNonce, String salt, int iteration
); String getClientNonce(); String getServerNonce(); String getNonce(); String getSa... | @Test public void validConstructor() { ServerFirstMessage serverFirstMessage = new ServerFirstMessage( CLIENT_NONCE, "3rfcNHYJY1ZVvWVs7j", "QSXCR+Q6sek8bf92", 4096 ); assertEquals(SERVER_FIRST_MESSAGE, serverFirstMessage.toString()); } |
ClientFirstMessage implements StringWritable { public static ClientFirstMessage parseFrom(String clientFirstMessage) throws ScramParseException, IllegalArgumentException { checkNotEmpty(clientFirstMessage, "clientFirstMessage"); Gs2Header gs2Header = Gs2Header.parseFrom(clientFirstMessage); String[] userNonceString; tr... | @Test public void parseFromInvalidValues() { String[] invalidValues = new String[] { "n,,r=user,r=" + CLIENT_NONCE, "n,,z=user,r=" + CLIENT_NONCE, "n,,n=user", "n,", "n,,", "n,,n=user,r", "n,,n=user,r=" }; int n = 0; for(String s : invalidValues) { try { assertNotNull(ClientFirstMessage.parseFrom(s)); } catch (ScramPar... |
ScramStringFormatting { public static String toSaslName(String value) { if(null == value || value.isEmpty()) { return value; } int nComma = 0, nEqual = 0; char[] originalChars = value.toCharArray(); for(char c : originalChars) { if(',' == c) { nComma++; } else if('=' == c) { nEqual++; } } if(nComma == 0 && nEqual == 0)... | @Test public void toSaslNameNoCharactersToBeEscaped() { for(String s : VALUES_NO_CHARS_TO_BE_ESCAPED) { assertEquals(s, ScramStringFormatting.toSaslName(s)); } }
@Test public void toSaslNameWithCharactersToBeEscaped() { for(int i = 0; i < VALUES_TO_BE_ESCAPED.length; i++) { assertEquals(ESCAPED_VALUES[i], ScramStringFo... |
ScramStringFormatting { public static String fromSaslName(String value) throws IllegalArgumentException { if(null == value || value.isEmpty()) { return value; } int nEqual = 0; char[] orig = value.toCharArray(); for(int i = 0; i < orig.length; i++) { if(orig[i] == ',') { throw new IllegalArgumentException("Invalid ',' ... | @Test public void fromSaslNameNoCharactersToBeEscaped() { for(String s : VALUES_NO_CHARS_TO_BE_ESCAPED) { assertEquals(s, ScramStringFormatting.fromSaslName(s)); } }
@Test public void fromSaslNameWithCharactersToBeUnescaped() { for(int i = 0; i < ESCAPED_VALUES.length; i++) { assertEquals(VALUES_TO_BE_ESCAPED[i], Scram... |
ScramFunctions { public static byte[] hmac(ScramMechanism scramMechanism, byte[] message, byte[] key) { return CryptoUtil.hmac(scramMechanism.secretKeySpec(key), scramMechanism.getMacInstance(), message); } static byte[] saltedPassword(
ScramMechanism scramMechanism, StringPreparation stringPreparation, St... | @Test public void hmac() throws UnsupportedEncodingException { String message = "The quick brown fox jumps over the lazy dog"; byte[] key = "key".getBytes(StandardCharsets.UTF_8); assertBytesEqualsBase64( "3nybhbi3iqa8ino29wqQcBydtNk=", ScramFunctions.hmac(ScramMechanisms.SCRAM_SHA_1, message.getBytes(StandardCharsets.... |
ScramFunctions { public static byte[] saltedPassword( ScramMechanism scramMechanism, StringPreparation stringPreparation, String password, byte[] salt, int iteration ) { return CryptoUtil.hi( scramMechanism.secretKeyFactory(), scramMechanism.algorithmKeyLength(), stringPreparation.normalize(password), salt, iteration )... | @Test public void saltedPassword() { assertBytesEqualsBase64("HZbuOlKbWl+eR8AfIposuKbhX30=", generateSaltedPassword()); } |
ScramFunctions { public static byte[] clientKey(ScramMechanism scramMechanism, byte[] saltedPassword) { return hmac(scramMechanism, CLIENT_KEY_HMAC_KEY, saltedPassword); } static byte[] saltedPassword(
ScramMechanism scramMechanism, StringPreparation stringPreparation, String password, byte[] salt,
... | @Test public void clientKey() { assertBytesEqualsBase64("4jTEe/bDZpbdbYUrmaqiuiZVVyg=", generateClientKey()); } |
ScramFunctions { public static byte[] storedKey(ScramMechanism scramMechanism, byte[] clientKey) { return hash(scramMechanism, clientKey); } static byte[] saltedPassword(
ScramMechanism scramMechanism, StringPreparation stringPreparation, String password, byte[] salt,
int iteration
); stati... | @Test public void storedKey() { assertBytesEqualsBase64("6dlGYMOdZcOPutkcNY8U2g7vK9Y=", generateStoredKey()); } |
ScramFunctions { public static byte[] serverKey(ScramMechanism scramMechanism, byte[] saltedPassword) { return hmac(scramMechanism, SERVER_KEY_HMAC_KEY, saltedPassword); } static byte[] saltedPassword(
ScramMechanism scramMechanism, StringPreparation stringPreparation, String password, byte[] salt,
... | @Test public void serverKey() { assertBytesEqualsBase64("D+CSWLOshSulAsxiupA+qs2/fTE=", generateServerKey()); } |
ScramFunctions { public static byte[] clientSignature(ScramMechanism scramMechanism, byte[] storedKey, String authMessage) { return hmac(scramMechanism, authMessage.getBytes(StandardCharsets.UTF_8), storedKey); } static byte[] saltedPassword(
ScramMechanism scramMechanism, StringPreparation stringPreparati... | @Test public void clientSignature() { assertBytesEqualsBase64("XXE4xIawv6vfSePi2ovW5cedthM=", generateClientSignature()); } |
ScramFunctions { public static byte[] clientProof(byte[] clientKey, byte[] clientSignature) { return CryptoUtil.xor(clientKey, clientSignature); } static byte[] saltedPassword(
ScramMechanism scramMechanism, StringPreparation stringPreparation, String password, byte[] salt,
int iteration
);... | @Test public void clientProof() { assertBytesEqualsBase64("v0X8v3Bz2T0CJGbJQyF0X+HI4Ts=", generateClientProof()); } |
ScramFunctions { public static byte[] serverSignature(ScramMechanism scramMechanism, byte[] serverKey, String authMessage) { return clientSignature(scramMechanism, serverKey, authMessage); } static byte[] saltedPassword(
ScramMechanism scramMechanism, StringPreparation stringPreparation, String password, b... | @Test public void serverSignature() { assertBytesEqualsBase64("rmF9pqV8S7suAoZWja4dJRkFsKQ=", generateServerSignature()); } |
ScramFunctions { public static boolean verifyClientProof( ScramMechanism scramMechanism, byte[] clientProof, byte[] storedKey, String authMessage ) { byte[] clientSignature = clientSignature(scramMechanism, storedKey, authMessage); byte[] clientKey = CryptoUtil.xor(clientSignature, clientProof); byte[] computedStoredKe... | @Test public void verifyClientProof() { assertTrue( ScramFunctions.verifyClientProof( ScramMechanisms.SCRAM_SHA_1, generateClientProof(), generateStoredKey(), AUTH_MESSAGE ) ); } |
ScramFunctions { public static boolean verifyServerSignature( ScramMechanism scramMechanism, byte[] serverKey, String authMessage, byte[] serverSignature ) { return Arrays.equals(serverSignature(scramMechanism, serverKey, authMessage), serverSignature); } static byte[] saltedPassword(
ScramMechanism scramM... | @Test public void verifyServerSignature() { assertTrue( ScramFunctions.verifyServerSignature( ScramMechanisms.SCRAM_SHA_1, generateServerKey(), AUTH_MESSAGE, generateServerSignature() ) ); } |
ScramAttributeValue extends AbstractCharAttributeValue { public static ScramAttributeValue parse(String value) throws ScramParseException { if(null == value || value.length() < 3 || value.charAt(1) != '=') { throw new ScramParseException("Invalid ScramAttributeValue '" + value + "'"); } return new ScramAttributeValue(S... | @Test public void parseIllegalValuesStructure() { String[] values = new String[] { null, "", "asdf", "asdf=a", CLIENT_PROOF.getChar() + "=", CLIENT_PROOF.getChar() + ",a" }; int n = 0; for(String value : values) { try { assertNotNull(ScramAttributeValue.parse(value)); } catch(ScramParseException e) { n++; } } assertEqu... |
Gs2AttributeValue extends AbstractCharAttributeValue { public static Gs2AttributeValue parse(String value) throws IllegalArgumentException { if(null == value) { return null; } if(value.length() < 1 || value.length() == 2 || (value.length() > 2 && value.charAt(1) != '=')) { throw new IllegalArgumentException("Invalid Gs... | @Test public void parseNullValue() { assertNull(Gs2AttributeValue.parse(null)); }
@Test public void parseIllegalValuesStructure() { String[] values = new String[] { "", "as", "asdfjkl", Gs2Attributes.CHANNEL_BINDING_REQUIRED.getChar() + "=" }; int n = 0; for(String value : values) { try { assertNotNull(Gs2AttributeValu... |
Gs2Header extends AbstractStringWritable { public static Gs2Header parseFrom(String message) throws IllegalArgumentException { checkNotNull(message, "Null message"); String[] gs2HeaderSplit = StringWritableCsv.parseFrom(message, 2); if(gs2HeaderSplit.length == 0) { throw new IllegalArgumentException("Invalid number of ... | @Test public void parseFromInvalid() { String[] invalids = new String[] { "Z,", "n,Z=blah", "p,", "n=a," }; int n = 0; for(String invalid : invalids) { try { Gs2Header.parseFrom(invalid); System.out.println(invalid); } catch (IllegalArgumentException e) { n++; } } assertEquals(invalids.length, n); } |
ScramClient { public static PreBuilder1 channelBinding(ChannelBinding channelBinding) throws IllegalArgumentException { return new PreBuilder1(checkNotNull(channelBinding, "channelBinding")); } private ScramClient(
ChannelBinding channelBinding, StringPreparation stringPreparation,
Optional<Scr... | @Test public void getValid() { ScramClient client1 = ScramClient .channelBinding(ScramClient.ChannelBinding.NO) .stringPreparation(StringPreparations.NO_PREPARATION) .selectMechanismBasedOnServerAdvertised("SCRAM-SHA-1") .setup(); ScramClient client2 = ScramClient .channelBinding(ScramClient.ChannelBinding.YES) .string... |
StringWritableCsv { public static String[] parseFrom(String value, int n, int offset) throws IllegalArgumentException { checkNotNull(value, "value"); if(n < 0 || offset < 0) { throw new IllegalArgumentException("Limit and offset have to be >= 0"); } if(value.isEmpty()) { return new String[0]; } String[] split = value.s... | @Test public void parseFromEmpty() { assertArrayEquals(new String[]{}, StringWritableCsv.parseFrom("")); }
@Test public void parseFromOneArgWithLimitsOffsets() { for(String s : ONE_ARG_VALUES) { assertArrayEquals(new String[] {s}, StringWritableCsv.parseFrom(s)); } int[] numberEntries = new int[] { 0, 1 }; for(int n : ... |
ScramClient { public static List<String> supportedMechanisms() { return Arrays.stream(ScramMechanisms.values()).map(m -> m.getName()).collect(Collectors.toList()); } private ScramClient(
ChannelBinding channelBinding, StringPreparation stringPreparation,
Optional<ScramMechanism> nonChannelBindi... | @Test public void supportedMechanismsTestAll() { assertArrayEquals( Arrays.stream( new String[] { "SCRAM-SHA-1", "SCRAM-SHA-1-PLUS", "SCRAM-SHA-256", "SCRAM-SHA-256-PLUS" } ).sorted().toArray(), ScramClient.supportedMechanisms().stream().sorted().toArray() ); } |
CryptoUtil { public static String nonce(int size, SecureRandom random) { if(size <= 0) { throw new IllegalArgumentException("Size must be positive"); } char[] chars = new char[size]; int r; for(int i = 0; i < size;) { r = random.nextInt(MAX_ASCII_PRINTABLE_RANGE - MIN_ASCII_PRINTABLE_RANGE + 1) + MIN_ASCII_PRINTABLE_RA... | @Test(expected = IllegalArgumentException.class) public void nonceInvalidSize1() { CryptoUtil.nonce(0, SECURE_RANDOM); }
@Test(expected = IllegalArgumentException.class) public void nonceInvalidSize2() { CryptoUtil.nonce(-1, SECURE_RANDOM); }
@Test public void nonceValid() { int nNonces = 1000; int nonceMaxSize = 100; ... |
YAMLFileParameterizer { protected static String normalizeFilename(String filename) { return StringUtils.trimToEmpty(filename).replaceAll("\\\\|/", "\\"+File.separator); } static void rewriteAll(String dir, Map<String, Any> generateEnvVars); static void rewriteAll(String srcLocation, String destDir, Map<String, Any> ge... | @Test public void testNormalizeFilename() { String s1="/a/b/c\\d.txt"; String s2="\\a\\b\\c\\d.txt"; String expected = String.format("%sa%sb%sc%sd.txt", File.separator, File.separator, File.separator, File.separator); String ns1 = YAMLFileParameterizer.normalizeFilename(s1); String ns2 = YAMLFileParameterizer.normalize... |
HybridServiceGenerator implements Generator { @Override public String getFramework() { return "light-hybrid-4j-service"; } @Override String getFramework(); @Override void generate(String targetPath, Object model, Any config); } | @Test public void testGetFramework() { HybridServiceGenerator generator = new HybridServiceGenerator(); Assert.assertEquals("light-hybrid-4j-service", generator.getFramework()); } |
HybridServerGenerator implements Generator { @Override public void generate(String targetPath, Object model, Any config) throws IOException { String rootPackage = config.get("rootPackage").toString(); String modelPackage = config.get("modelPackage").toString(); String handlerPackage = config.get("handlerPackage").toStr... | @Test public void testGenerator() throws IOException { Any anyConfig = JsonIterator.parse(HybridServerGeneratorTest.class.getResourceAsStream(configName), 1024).readAny(); HybridServerGenerator generator = new HybridServerGenerator(); generator.generate(targetPath, null, anyConfig); } |
HybridServerGenerator implements Generator { @Override public String getFramework() { return "light-hybrid-4j-server"; } @Override String getFramework(); @Override void generate(String targetPath, Object model, Any config); } | @Test public void testGetFramework() { HybridServerGenerator generator = new HybridServerGenerator(); Assert.assertEquals("light-hybrid-4j-server", generator.getFramework()); } |
GraphqlGenerator implements Generator { @Override public void generate(String targetPath, Object model, Any config) throws IOException { String schemaPackage = config.get("schemaPackage").toString(); String schemaClass = config.get("schemaClass").toString(); boolean overwriteSchemaClass = config.toBoolean("overwriteSch... | @Test public void testGeneratorWithSchema() throws IOException { Any anyConfig = JsonIterator.parse(GraphqlGeneratorTest.class.getResourceAsStream(configName), 1024).readAny(); try(InputStream is = GraphqlGenerator.class.getResourceAsStream(schemaName)) { String schema = convertStreamToString(is); GraphqlGenerator gene... |
GraphqlGenerator implements Generator { @Override public String getFramework() { return "light-graphql-4j"; } @Override String getFramework(); @Override void generate(String targetPath, Object model, Any config); } | @Test public void testGetFramework() { GraphqlGenerator generator = new GraphqlGenerator(); Assert.assertEquals("light-graphql-4j", generator.getFramework()); } |
YAMLFileParameterizer { protected static Set<String> buildFileExcludeSet(String sourceDir, Map<String, Any> generateEnvVars) { if (generateEnvVars.containsKey(KEY_EXCLUDE)) { return buildFileExcludeSet(sourceDir, generateEnvVars.get(KEY_EXCLUDE).asList()); } return Collections.emptySet(); } static void rewriteAll(Stri... | @Test public void testFileExcludeSet() { List<Any> excludes = Arrays.asList(Any.wrap("/a/b/c\\d.txt"), Any.wrap("2.yml"), Any.wrap("\\a\\b\\c\\d.txt"), Any.wrap("")); Set<String> excludeSet = YAMLFileParameterizer.buildFileExcludeSet(".",excludes); assertTrue(2==excludeSet.size()); } |
YAMLFileParameterizer { protected static Set<String> buildResourceExcludeSet(String resourceLocation, Map<String, Any> generateEnvVars) { if (generateEnvVars.containsKey(KEY_EXCLUDE)) { return buildResourceExcludeSet(resourceLocation, generateEnvVars.get(KEY_EXCLUDE).asList()); } return Collections.emptySet(); } stati... | @Test public void testResourceExcludeSet() { List<Any> excludes = Arrays.asList(Any.wrap("audit.yml"), Any.wrap("body.yml")); Set<String> excludeSet = YAMLFileParameterizer.buildResourceExcludeSet("handlerconfig/", excludes); assertTrue(2==excludeSet.size()); } |
OpenApiSpecGenerator implements Generator { @SuppressWarnings("rawtypes") @Override public void generate(String targetPath, Object model, Any config) throws IOException { if (StringUtils.isBlank(targetPath)) { logger.error("Output location is not specified."); return; } if (!config.keys().contains(CONFIG_SPECGENERATION... | @Test public void test() throws IOException { Any anyConfig = JsonIterator.parse(OpenApiGeneratorTest.class.getResourceAsStream(configName), 1024).readAny(); OpenApiSpecGenerator generator = new OpenApiSpecGenerator(); generator.generate(outputDir, null, anyConfig); } |
Utils { public static String camelize(String word) { return camelize(word, false); } static String camelize(String word); static String camelize(String word, boolean lowercaseFirstLetter); static boolean isUrl(String location); static byte[] urlToByteArray(URL url); } | @Test public void testUnderscoreToLowerCamel() { for (Map.Entry<String, String> entry : underscoreToLowerCamel_.entrySet()) { Assert.assertEquals(entry.getValue(), Utils.camelize(entry.getKey(), true)); } }
@Test public void testUnderscoreToCamel() { for (Map.Entry<String, String> entry : underscoreToCamel_.entrySet())... |
HybridServiceGenerator implements Generator { @Override public void generate(String targetPath, Object model, Any config) throws IOException { String handlerPackage = config.get("handlerPackage").toString(); boolean overwriteHandler = config.toBoolean("overwriteHandler"); boolean overwriteHandlerTest = config.toBoolean... | @Test public void testGenerator() throws IOException { Any anyConfig = JsonIterator.parse(HybridServiceGeneratorTest.class.getResourceAsStream(configName), 1024).readAny(); Any anyModel = JsonIterator.parse(HybridServiceGeneratorTest.class.getResourceAsStream(schemaName), 1024).readAny(); HybridServiceGenerator generat... |
Token { public static boolean isValid(final String token) { if (token == null || token.length() == 0) { return false; } final int len = token.length(); for (int i = 0; i < len; ++i) { if (isSeparator(token.charAt(i))) { return false; } } return true; } static boolean isSeparator(final char ch); static boolean isValid(... | @Test public void test004() { isValid("abc"); } |
Accept extends AbstractFrameFilter implements FrameFilter { @Override public boolean process(TransactionContext context) { if (expression != null) { String resolvedExpression = Template.preProcess(expression, getContext().getSymbols()); try { if (evaluator.evaluateBoolean(resolvedExpression)) { if (Log.isLogging(Log.DE... | @Test public void testAcceptContext() { Accept filter = new Accept(); String expression = "match( Working.Record Type , PO )"; filter.setCondition(expression); filter.open(transformContext); assertFalse(filter.process(context)); assertNotNull(context.getWorkingFrame()); } |
TransformContext extends OperationalContext { public Object resolveFieldValue(final String token) { Object retval = null; if (token.startsWith(WORKING)) { final String name = token.substring(WORKING.length()); if ((transactionContext != null) && (transactionContext.getWorkingFrame() != null)) { retval = transactionCont... | @Test public void resolveFieldValue() { assertNull(transformContext.resolveFieldValue("one")); assertNotNull(transformContext.resolveFieldValue("Source.Field2")); assertNotNull(transformContext.resolveFieldValue("Working.Field4")); assertNotNull(transformContext.resolveFieldValue("Target.Field6")); assertNull(transform... |
TransformContext extends OperationalContext { public Object resolveToValue(final String token) { Object retval = null; if (StringUtil.isNotEmpty(token)) { final Object value = resolveFieldValue(token); if (value != null) { retval = value; } else { final Object obj = searchForValue(token); if (obj != null) { retval = ob... | @Test public void resolveToValue() { assertNull(transformContext.resolveFieldValue("one")); assertNotNull(transformContext.resolveFieldValue("Source.Field2")); assertNotNull(transformContext.resolveFieldValue("Working.Field4")); assertNotNull(transformContext.resolveFieldValue("Target.Field6")); assertNull(transformCon... |
FileContext extends PersistentContext { public FileContext() { } FileContext(); @Override void open(); @Override void close(); } | @Test public void fileContext() { String jobName = "ContextTest"; DataFrame config = new DataFrame().set("fields", new DataFrame().set("SomeKey", "SomeValue").set("AnotherKey", "AnotherValue")); TransformEngine engine = new DefaultTransformEngine(); engine.setName(jobName); TransformContext context = new FileContext();... |
NotEmpty extends AbstractValidator implements FrameValidator { @Override public boolean process(TransactionContext context) throws ValidationException { boolean retval = true; DataFrame frame = context.getWorkingFrame(); if (frame != null) { DataField field = frame.getField(fieldName); if (field != null) { String value... | @Test public void test() { String cfgData = "{ \"field\" : \"model\", \"desc\" : \"Model cannot be empty\" }"; Config configuration = parseConfiguration(cfgData); TransactionContext context = createTransactionContext(); DataFrame sourceFrame = new DataFrame(); sourceFrame.put("model", "PT4500"); context.setSourceFrame(... |
NotNull extends AbstractValidator implements FrameValidator { @Override public boolean process(TransactionContext context) throws ValidationException { boolean retval = true; DataFrame frame = context.getWorkingFrame(); if (frame != null) { DataField field = frame.getField(fieldName); if (field != null) { if (field.isN... | @Test public void test() { String cfgData = "{ \"field\" : \"model\", \"desc\" : \"Model cannot be empty\" }"; Config configuration = parseConfiguration(cfgData); FrameValidator validator = new NotNull(); try { validator.setConfiguration(configuration); } catch (ConfigurationException e) { e.printStackTrace(); fail(e.g... |
Pagination { public synchronized void step() { offset += step; } Pagination(long step); Pagination(long start, long step); Pagination(String name, long step); Pagination(String name, long start, long step); long getOffset(); synchronized void setOffset(long offset); String getName(); long getStep(); long getStart();... | @Test public void testStep() { Pagination page = new Pagination(5); assertEquals("page", page.getName()); assertTrue(page.getStep() == 5); assertTrue(page.getOffset() == 0); page.step(); assertTrue(page.getOffset() == 5); } |
Pagination { public synchronized void reset() { this.offset = start; } Pagination(long step); Pagination(long start, long step); Pagination(String name, long step); Pagination(String name, long start, long step); long getOffset(); synchronized void setOffset(long offset); String getName(); long getStep(); long getSt... | @Test public void testReset() { final String NAME = "offset"; Pagination page = new Pagination(NAME, 5); assertEquals(NAME, page.getName()); assertTrue(page.getStep() == 5); assertTrue(page.getOffset() == 0); page.step(); page.step(); page.step(); page.step(); page.step(); page.step(); assertTrue(page.getOffset() == 30... |
Pagination { @SuppressWarnings("unchecked") public synchronized SymbolTable toSymbolTable() { SymbolTable retval = new SymbolTable(); retval.put(name + ".start", getOffset()); retval.put(name + ".size", getStep()); retval.put(name + ".end", getEnd()); return retval; } Pagination(long step); Pagination(long start, long... | @Test public void testToSymbolTable() { final String NAME = "offset"; Pagination page = new Pagination(NAME, 0, 5); assertEquals(NAME, page.getName()); assertTrue(page.getStep() == 5); assertTrue(page.getOffset() == 0); page.step(); assertTrue(page.getOffset() == 5); SymbolTable symbols = page.toSymbolTable(); assertNo... |
Pagination { public String getName() { return name; } Pagination(long step); Pagination(long start, long step); Pagination(String name, long step); Pagination(String name, long start, long step); long getOffset(); synchronized void setOffset(long offset); String getName(); long getStep(); long getStart(); long getEn... | @Test public void blankName() { Pagination page = new Pagination("", 0, 5); assertEquals(Pagination.DEFAULT_NAME, page.getName()); page = new Pagination(" ", 0, 5); assertEquals(Pagination.DEFAULT_NAME, page.getName()); page = new Pagination(null, 0, 5); assertEquals(Pagination.DEFAULT_NAME, page.getName()); } |
Token { public static String unquote(String text) { if (text == null) { return null; } final int len = text.length(); if (len < 2 || text.charAt(0) != '"' || text.charAt(len - 1) != '"') { return text; } text = text.substring(1, len - 1); return unescape(text); } static boolean isSeparator(final char ch); static boole... | @Test public void test014() { unquote("abc", "\"abc\""); }
@Test public void test015() { unquote("\"abc", "\"abc"); }
@Test public void test016() { unquote("abc\"", "abc\""); }
@Test public void test017() { unquote("abc", "\"ab\\c\""); }
@Test public void test018() { unquote("ab\\c", "\"ab\\\\c\""); }
@Test public void... |
Pagination { @Override public String toString() { StringBuilder b = new StringBuilder("Pagination: '"); b.append(getName()); b.append("' start:").append(getStart()); b.append(" step:").append(getStep()); return b.toString(); } Pagination(long step); Pagination(long start, long step); Pagination(String name, long step... | @Test public void toStringTest() { final String expected = "Pagination: 'offset' start:0 step:5"; final String NAME = "offset"; Pagination page = new Pagination(NAME, 0, 5); assertEquals(expected, page.toString()); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.