src_fm_fc_ms_ff
stringlengths
43
86.8k
target
stringlengths
20
276k
QuestionRepository implements QuestionDataSource { @Override public void addQuestion(Question question) { throw new UnsupportedOperationException("Unsupported operation"); } @Inject QuestionRepository(@Local QuestionDataSource localDataSource, @Remote QuestionDataSource remoteDataSource); @Override Flowable<List<Question>> loadQuestions(boolean forceRemote); Flowable<Question> getQuestion(long questionId); @Override void addQuestion(Question question); @Override void clearData(); }
@Test(expected = UnsupportedOperationException.class) public void addQuestion_ShouldThrowException() { repository.addQuestion(question1); }
QuestionLocalDataSource implements QuestionDataSource { @Override public Flowable<List<Question>> loadQuestions(boolean forceRemote) { return questionDao.getAllQuestions(); } @Inject QuestionLocalDataSource(QuestionDao questionDao); @Override Flowable<List<Question>> loadQuestions(boolean forceRemote); @Override void addQuestion(Question question); @Override void clearData(); }
@Test public void loadQuestions_ShouldReturnFromDatabase() { List<Question> questions = Arrays.asList(new Question(), new Question()); TestSubscriber<List<Question>> subscriber = new TestSubscriber<>(); given(questionDao.getAllQuestions()).willReturn(Flowable.just(questions)); localDataSource.loadQuestions(false).subscribe(subscriber); then(questionDao).should().getAllQuestions(); }
QuestionLocalDataSource implements QuestionDataSource { @Override public void addQuestion(Question question) { questionDao.insert(question); } @Inject QuestionLocalDataSource(QuestionDao questionDao); @Override Flowable<List<Question>> loadQuestions(boolean forceRemote); @Override void addQuestion(Question question); @Override void clearData(); }
@Test public void addQuestion_ShouldInsertToDatabase() { Question question = new Question(); localDataSource.addQuestion(question); then(questionDao).should().insert(question); }
QuestionLocalDataSource implements QuestionDataSource { @Override public void clearData() { questionDao.deleteAll(); } @Inject QuestionLocalDataSource(QuestionDao questionDao); @Override Flowable<List<Question>> loadQuestions(boolean forceRemote); @Override void addQuestion(Question question); @Override void clearData(); }
@Test public void clearData_ShouldDeleteAllDataInDatabase() { localDataSource.clearData(); then(questionDao).should().deleteAll(); }
QuestionRemoteDataSource implements QuestionDataSource { @Override public Flowable<List<Question>> loadQuestions(boolean forceRemote) { return questionService.loadQuestionsByTag(Config.ANDROID_QUESTION_TAG).map(QuestionResponse::getQuestions); } @Inject QuestionRemoteDataSource(QuestionService questionService); @Override Flowable<List<Question>> loadQuestions(boolean forceRemote); @Override void addQuestion(Question question); @Override void clearData(); }
@Test public void loadQuestions_ShouldReturnFromRemoteService() { QuestionResponse questionResponse = new QuestionResponse(); TestSubscriber<List<Question>> subscriber = new TestSubscriber<>(); given(questionService.loadQuestionsByTag(Config.ANDROID_QUESTION_TAG)).willReturn(Flowable.just(questionResponse)); remoteDataSource.loadQuestions(anyBoolean()).subscribe(subscriber); then(questionService).should().loadQuestionsByTag(Config.ANDROID_QUESTION_TAG); }
QuestionRemoteDataSource implements QuestionDataSource { @Override public void addQuestion(Question question) { throw new UnsupportedOperationException("Unsupported operation"); } @Inject QuestionRemoteDataSource(QuestionService questionService); @Override Flowable<List<Question>> loadQuestions(boolean forceRemote); @Override void addQuestion(Question question); @Override void clearData(); }
@Test(expected = UnsupportedOperationException.class) public void addQuestion_NoThingToDoWithRemoteService() { Question question = mock(Question.class); remoteDataSource.addQuestion(question); then(questionService).shouldHaveZeroInteractions(); }
PathUtil { static String getRelativeFileInternal(File canonicalBaseFile, File canonicalFileToRelativize) { ArrayList<String> basePath = getPathComponents(canonicalBaseFile); ArrayList<String> pathToRelativize = getPathComponents(canonicalFileToRelativize); if (!basePath.get(0).equals(pathToRelativize.get(0))) { return canonicalFileToRelativize.getPath(); } int commonDirs; StringBuilder sb = new StringBuilder(); for (commonDirs=1; commonDirs<basePath.size() && commonDirs<pathToRelativize.size(); commonDirs++) { if (!basePath.get(commonDirs).equals(pathToRelativize.get(commonDirs))) { break; } } boolean first = true; for (int i=commonDirs; i<basePath.size(); i++) { if (!first) { sb.append(File.separatorChar); } else { first = false; } sb.append(".."); } first = true; for (int i=commonDirs; i<pathToRelativize.size(); i++) { if (first) { if (sb.length() != 0) { sb.append(File.separatorChar); } first = false; } else { sb.append(File.separatorChar); } sb.append(pathToRelativize.get(i)); } if (sb.length() == 0) { return "."; } return sb.toString(); } private PathUtil(); static File getRelativeFile(File baseFile, File fileToRelativize); static String getRelativePath(String basePath, String pathToRelativize); }
@Test public void pathUtilTest1() { File[] roots = File.listRoots(); if (roots.length > 1) { File basePath = new File(roots[0] + "some" + File.separatorChar + "dir" + File.separatorChar + "test.txt"); File relativePath = new File(roots[1] + "some" + File.separatorChar + "dir" + File.separatorChar + "test.txt"); String path = PathUtil.getRelativeFileInternal(basePath, relativePath); Assert.assertEquals(path, relativePath.getPath()); } } @Test public void pathUtilTest11() { File[] roots = File.listRoots(); File basePath = new File(roots[0] + "some"); File relativePath = new File(roots[0] + "some" + File.separatorChar + "dir" + File.separatorChar + "dir2"); String path = PathUtil.getRelativeFileInternal(basePath, relativePath); Assert.assertEquals(path, "dir" + File.separatorChar + "dir2"); } @Test public void pathUtilTest12() { File[] roots = File.listRoots(); File basePath = new File(roots[0] + "some" + File.separatorChar); File relativePath = new File(roots[0] + "some" + File.separatorChar + "dir" + File.separatorChar + "dir2" + File.separatorChar); String path = PathUtil.getRelativeFileInternal(basePath, relativePath); Assert.assertEquals(path, "dir" + File.separatorChar + "dir2"); } @Test public void pathUtilTest13() { File[] roots = File.listRoots(); File basePath = new File(roots[0] + "some"); File relativePath = new File(roots[0] + "some" + File.separatorChar + "dir" + File.separatorChar + "dir2" + File.separatorChar); String path = PathUtil.getRelativeFileInternal(basePath, relativePath); Assert.assertEquals(path, "dir" + File.separatorChar + "dir2"); } @Test public void pathUtilTest14() { File[] roots = File.listRoots(); File basePath = new File(roots[0] + "some" + File.separatorChar); File relativePath = new File(roots[0] + "some" + File.separatorChar + "dir" + File.separatorChar + "dir2"); String path = PathUtil.getRelativeFileInternal(basePath, relativePath); Assert.assertEquals(path, "dir" + File.separatorChar + "dir2"); } @Test public void pathUtilTest15() { File[] roots = File.listRoots(); File basePath = new File(roots[0] + "some" + File.separatorChar + "dir3"); File relativePath = new File(roots[0] + "some" + File.separatorChar + "dir" + File.separatorChar + "dir2"); String path = PathUtil.getRelativeFileInternal(basePath, relativePath); Assert.assertEquals(path, ".." + File.separatorChar + "dir" + File.separatorChar + "dir2"); } @Test public void pathUtilTest16() { File[] roots = File.listRoots(); File basePath = new File(roots[0] + "some2" + File.separatorChar + "dir3"); File relativePath = new File(roots[0] + "some" + File.separatorChar + "dir" + File.separatorChar + "dir2"); String path = PathUtil.getRelativeFileInternal(basePath, relativePath); Assert.assertEquals(path, ".." + File.separatorChar + ".." + File.separatorChar + "some" + File.separatorChar + "dir" + File.separatorChar + "dir2"); } @Test public void pathUtilTest17() { File[] roots = File.listRoots(); File basePath = new File(roots[0].getPath()); File relativePath = new File(roots[0] + "some" + File.separatorChar + "dir" + File.separatorChar + "dir2"); String path = PathUtil.getRelativeFileInternal(basePath, relativePath); Assert.assertEquals(path, "some" + File.separatorChar + "dir" + File.separatorChar + "dir2"); } @Test public void pathUtilTest18() { File[] roots = File.listRoots(); File basePath = new File(roots[0] + "some" + File.separatorChar + "dir"); File relativePath = new File(roots[0] + "some"); String path = PathUtil.getRelativeFileInternal(basePath, relativePath); Assert.assertEquals(path, ".."); } @Test public void pathUtilTest19() { File[] roots = File.listRoots(); File basePath = new File(roots[0] + "some" + File.separatorChar + "dir" + File.separatorChar + "dir2"); File relativePath = new File(roots[0] + "some"); String path = PathUtil.getRelativeFileInternal(basePath, relativePath); Assert.assertEquals(path, ".." + File.separatorChar + ".."); } @Test public void pathUtilTest2() { File[] roots = File.listRoots(); File basePath = new File(roots[0] + "some" + File.separatorChar + "dir" + File.separatorChar + "test.txt"); File relativePath = new File(roots[0] + "some" + File.separatorChar + "dir" + File.separatorChar + "test.txt"); String path = PathUtil.getRelativeFileInternal(basePath, relativePath); Assert.assertEquals(path, "."); } @Test public void pathUtilTest3() { File[] roots = File.listRoots(); File basePath = new File(roots[0] + "some" + File.separatorChar + "dir" + File.separatorChar); File relativePath = new File(roots[0] + "some" + File.separatorChar + "dir" + File.separatorChar); String path = PathUtil.getRelativeFileInternal(basePath, relativePath); Assert.assertEquals(path, "."); } @Test public void pathUtilTest4() { File[] roots = File.listRoots(); File basePath = new File(roots[0] + "some" + File.separatorChar + "dir"); File relativePath = new File(roots[0] + "some" + File.separatorChar + "dir"); String path = PathUtil.getRelativeFileInternal(basePath, relativePath); Assert.assertEquals(path, "."); } @Test public void pathUtilTest5() { File[] roots = File.listRoots(); File basePath = new File(roots[0] + "some" + File.separatorChar + "dir"); File relativePath = new File(roots[0] + "some" + File.separatorChar + "dir" + File.separatorChar); String path = PathUtil.getRelativeFileInternal(basePath, relativePath); Assert.assertEquals(path, "."); } @Test public void pathUtilTest6() { File[] roots = File.listRoots(); File basePath = new File(roots[0] + "some" + File.separatorChar + "dir" + File.separatorChar); File relativePath = new File(roots[0] + "some" + File.separatorChar + "dir"); String path = PathUtil.getRelativeFileInternal(basePath, relativePath); Assert.assertEquals(path, "."); } @Test public void pathUtilTest7() { File[] roots = File.listRoots(); File basePath = new File(roots[0] + "some"); File relativePath = new File(roots[0] + "some" + File.separatorChar + "dir"); String path = PathUtil.getRelativeFileInternal(basePath, relativePath); Assert.assertEquals(path, "dir"); } @Test public void pathUtilTest8() { File[] roots = File.listRoots(); File basePath = new File(roots[0] + "some" + File.separatorChar); File relativePath = new File(roots[0] + "some" + File.separatorChar + "dir" + File.separatorChar); String path = PathUtil.getRelativeFileInternal(basePath, relativePath); Assert.assertEquals(path, "dir"); } @Test public void pathUtilTest9() { File[] roots = File.listRoots(); File basePath = new File(roots[0] + "some"); File relativePath = new File(roots[0] + "some" + File.separatorChar + "dir" + File.separatorChar); String path = PathUtil.getRelativeFileInternal(basePath, relativePath); Assert.assertEquals(path, "dir"); } @Test public void pathUtilTest10() { File[] roots = File.listRoots(); File basePath = new File(roots[0] + "some" + File.separatorChar); File relativePath = new File(roots[0] + "some" + File.separatorChar + "dir"); String path = PathUtil.getRelativeFileInternal(basePath, relativePath); Assert.assertEquals(path, "dir"); }
BytecodeAdapterService implements SourceAdapterService<String, CtMethod, CtField, Annotation> { @Override public IsClass toClass(String binaryName) { int arrayCount = 0; while (binaryName.matches(".*" + X_Util.arrayRegex)) { arrayCount += 1; binaryName = binaryName.replaceFirst(X_Util.arrayRegex, ""); } IsClass cls = classes.get(binaryName); return cls.toArray(arrayCount); } BytecodeAdapterService(); BytecodeAdapterService(ClassPool pool); @Override IsClass toClass(String binaryName); @Override IsMethod toMethod(CtMethod type); @Override IsField toField(CtField type); @Override IsAnnotation toAnnotation(Annotation type); IsType[] toTypes(CtClass[] parameterTypes); static MappedIterable<Method> getMethodsInDeclaredOrder(Class<?> type); }
@Test public void testArrayParser() { IsClass clsArray = service.toClass("java.lang.Class[]"); Assert.assertNotNull(clsArray); } @Test public void testAnnoNoArgs() { IsClass asClass = service.toClass(OuterTestClass.NoTargetAnno.class.getName()); IsAnnotation anno = asClass.getAnnotation(Target.class.getName()); IsAnnotationValue empty = anno.getValue(anno.getMethod("value")); Assert.assertTrue(empty.isArray()); Assert.assertEquals(0, Array.getLength(empty.getRawValue())); } @Test public void testTestClass() { Class<?> cls = getTestClass(); IsClass asClass = service.toClass(cls.getName()); Assert.assertEquals(asClass.getPackage(), cls.getPackage().getName()); Assert.assertEquals(asClass.getEnclosedName(), X_Source.classToEnclosedSourceName(cls)); Assert.assertEquals(asClass.getModifier(), cls.getModifiers()); testAnnos(cls.getDeclaredAnnotations(), asClass); } @Test public void testTestClass_Methods() { Class<?> cls = getTestClass(); IsClass asClass = service.toClass(cls.getName()); for (Method method : cls.getMethods()) { IsMethod imethod = asClass.getMethod(method.getName(), true, method.getParameterTypes()); String testCase = imethod.getQualifiedName() +" != "+method.getName(); Assert.assertNotNull(testCase, imethod); Assert.assertEquals(testCase, method.getName(), imethod.getName()); Assert.assertEquals(testCase, method.getModifiers(), imethod.getModifier()); Assert.assertEquals(testCase, imethod.getReturnType().getQualifiedName(), method.getReturnType().getCanonicalName()); Assert.assertTrue(testCase, BytecodeUtil.typesEqual(imethod.getParameters(), method.getParameterTypes())); Assert.assertTrue(testCase, BytecodeUtil.typesEqual(imethod.getExceptions(), method.getExceptionTypes())); testAnnos(method.getDeclaredAnnotations(), imethod); } } @Test public void testTestClass_Fields() { Class<?> cls = getTestClass(); IsClass asClass = service.toClass(cls.getName()); for (Field field : cls.getFields()) { IsField ifield = asClass.getField(field.getName()); Assert.assertNotNull(field.getName(), ifield); Assert.assertEquals(field.getName(), ifield.getName()); Assert.assertEquals(field.getModifiers(), ifield.getModifier()); testAnnos(field.getDeclaredAnnotations(), ifield); } }
ToStringUserInterface extends AbstractUserInterface implements Appendable { @Override public String toString() { return b.toString(); } @Override int hashCode(); @Override String toString(); @Override boolean equals(Object obj); @Override Appendable append(CharSequence csq); @Override Appendable append(CharSequence csq, int start, int end); @Override Appendable append(char c); }
@Test public void testUserToStringNamed() { ToStringUserInterface ui = X_AutoUi.makeUi(MODEL, UserViewNamed.class, ToStringUserInterface.class); Assert.assertEquals("email: email,\nname: name,\nid: id", ui.toString()); } @Test public void testUserToStringWrapped() { UserInterface<User> ui = X_AutoUi.makeUi(MODEL, UserViewWrapped.class, ToStringUserInterface.class); Assert.assertEquals("email: email,\nname: name,\nid: id,\n", ui.toString()); }
JavaLexer { public static <R> int visitAnnotation (final AnnotationVisitor<R> visitor, final R receiver, final CharSequence chars, int pos) { pos = eatWhitespace(chars, pos); if (pos == chars.length()) { return pos; } int start = pos; try { while(chars.charAt(pos) == '@') { pos = eatJavaname(chars, pos + 1); final String annoName = chars.subSequence(start + 1, pos).toString(); String annoBody = ""; pos = eatWhitespace(chars, pos); if (pos < chars.length() && chars.charAt(pos) == '(') { final int bodyStart = pos+1; pos = eatAnnotationBody(visitor, receiver, chars, pos); annoBody = chars.subSequence(bodyStart, pos).toString(); pos ++; } final AnnotationMemberVisitor<R> bodyVisitor = visitor.visitAnnotation(annoName, annoBody, receiver); if (bodyVisitor != null && annoBody.length() > 0) { visitAnnotationMembers(bodyVisitor, receiver, annoBody, 0); } start = pos = eatWhitespace(chars, pos); if (pos == chars.length()) { break; } } } catch (final IndexOutOfBoundsException e) { error( e, "Error parsing annotation on: " + chars.subSequence(start, chars.length())); } return pos; } JavaLexer(String definition); static int visitJavadoc(final JavadocVisitor<R> visitor, final R receiver, final CharSequence chars, int pos); static int visitAnnotation(final AnnotationVisitor<R> visitor, final R receiver, final CharSequence chars, int pos); static int visitAnnotationMembers(final AnnotationMemberVisitor<R> visitor, final R receiver, final CharSequence chars, int pos); static int visitModifier(final ModifierVisitor<R> visitor, final R receiver, final CharSequence chars, int pos); static int visitGeneric(final GenericVisitor<R> visitor, final R receiver, final CharSequence chars, int pos); static int visitMethodSignature(final MethodVisitor<R> visitor, final R receiver, final CharSequence chars, int pos); static TypeDef extractType(final CharSequence chars, int pos); static SimpleStack<IsGeneric> extractGenerics(final CharSequence chars, final int pos); String getClassName(); int getPrivacy(); int getModifier(); String getSuperClass(); String[] getGenerics(); String[] getImports(); String[] getInterfaces(); boolean isPublic(); boolean isPrivate(); boolean isProtected(); boolean isStatic(); boolean isFinal(); boolean isAbstract(); boolean isNative(); boolean isClass(); boolean isAnnotation(); boolean isEnum(); boolean hasGenerics(); static Iterable<String> findImportsInGeneric(final String generic); static IsParameter lexParam(final CharSequence chars); static int visitClassFile(final ClassVisitor<Param> extractor, final Param receiver, final CharSequence chars, int pos); }
@Test public void testAnnotationLexer() { final short[] success = new short[1]; final String annoBody = "name=\"one \\\"\\\"two\\\"\\\" three\\\\\", " + "{1, 2.0, false}, values={1, \"string\", com.test.Class.class}"; JavaLexer.visitAnnotation(new AnnotationVisitor<Void>(){ @Override public AnnotationMemberVisitor<Void> visitAnnotation(String annoName, String annoContent, Void receiver) { success[0] = 1; Assert.assertEquals(annoName, "java.lang.Annotation"); Assert.assertEquals(annoContent, annoBody); return null; } }, null, "@java.lang.Annotation(" + annoBody + ")" , 0); Assert.assertEquals(success[0], 1); }
JavaLexer { public static TypeDef extractType(final CharSequence chars, int pos) { int start = pos = eatWhitespace(chars, pos); int lastPeriod = -1; final int max = chars.length()-1; boolean doneParsing = false; final StringBuilder pkg = new StringBuilder(); package_loop: if (Character.isLowerCase(chars.charAt(pos))) { while(true) { pos = eatWhitespace(chars, pos); while(Character.isJavaIdentifierPart(chars.charAt(++pos))){ if (pos == max){ if (lastPeriod == -1) { doneParsing = true; } else { start = pos = lastPeriod + 1; } break package_loop; } } final int whitespace = eatWhitespace(chars, pos); final int next = chars.charAt(whitespace); if (next == '.') { if (whitespace > pos && chars.charAt(whitespace+1)=='.') { break package_loop; } if (lastPeriod != -1) { pkg.append('.'); } lastPeriod = pos = whitespace; pkg.append(chars.subSequence(start, pos).toString().trim()); pos = start = eatWhitespace(chars, pos+1); if (Character.isUpperCase(chars.charAt(start))) { break package_loop; } } else { if (whitespace > pos || next == '[' || next == '<') { doneParsing = true; break package_loop; } } } } TypeDef def; if (doneParsing){ if (pos == max) { return new TypeDef(chars.subSequence(start, pos+1).toString(), pos); } def = new TypeDef(chars.subSequence(start, pos).toString()); } else { final StringBuilder typeName = new StringBuilder(); lastPeriod = -1; typeloop: while (true) { pos = eatWhitespace(chars, pos); if (!Character.isJavaIdentifierStart(chars.charAt(pos))){ if (pos > start) { if (lastPeriod != -1) { typeName.append('.'); } typeName.append(chars.subSequence(start, pos).toString().trim()); } break; } while(Character.isJavaIdentifierPart(chars.charAt(++pos))) { if (pos == max) { if (lastPeriod != -1) { typeName.append('.'); } typeName.append(chars.subSequence(start, pos+1).toString().trim()); break typeloop; } } final int whitespace = eatWhitespace(chars, pos); if (chars.charAt(whitespace) == '.') { if (lastPeriod != -1) { typeName.append('.'); } if (pos != whitespace && chars.charAt(whitespace + 1) == '.') { typeName.append(chars.subSequence(start, pos).toString().trim()); break; } lastPeriod = pos = whitespace; typeName.append(chars.subSequence(start, pos).toString()); start = pos = eatWhitespace(chars, pos+1); } else { if (whitespace > pos) { if (lastPeriod != -1) { typeName.append('.'); } typeName.append(chars.subSequence(start, pos).toString().trim()); break; } } } def = new TypeDef(typeName.toString()); if (pos == max) { pos++; } } def.pkgName = pkg.toString(); start = pos = eatWhitespace(chars, pos); if (pos < chars.length()) { pos = eatGeneric(chars, pos); if (pos != start) { def.generics = chars.subSequence(start, ++pos).toString(); } } pos = eatWhitespace(chars, pos); while (pos < max && chars.charAt(pos) == '[') { def.arrayDepth ++; while (chars.charAt(++pos)!=']') { ; } pos = eatWhitespace(chars, pos+1); } if (pos < chars.length() && chars.charAt(pos) == '.') { assert chars.charAt(pos+1) == '.'; assert chars.charAt(pos+2) == '.'; def.arrayDepth++; def.varargs = true; pos = eatWhitespace(chars, pos+3); } def.index = pos; return def; } JavaLexer(String definition); static int visitJavadoc(final JavadocVisitor<R> visitor, final R receiver, final CharSequence chars, int pos); static int visitAnnotation(final AnnotationVisitor<R> visitor, final R receiver, final CharSequence chars, int pos); static int visitAnnotationMembers(final AnnotationMemberVisitor<R> visitor, final R receiver, final CharSequence chars, int pos); static int visitModifier(final ModifierVisitor<R> visitor, final R receiver, final CharSequence chars, int pos); static int visitGeneric(final GenericVisitor<R> visitor, final R receiver, final CharSequence chars, int pos); static int visitMethodSignature(final MethodVisitor<R> visitor, final R receiver, final CharSequence chars, int pos); static TypeDef extractType(final CharSequence chars, int pos); static SimpleStack<IsGeneric> extractGenerics(final CharSequence chars, final int pos); String getClassName(); int getPrivacy(); int getModifier(); String getSuperClass(); String[] getGenerics(); String[] getImports(); String[] getInterfaces(); boolean isPublic(); boolean isPrivate(); boolean isProtected(); boolean isStatic(); boolean isFinal(); boolean isAbstract(); boolean isNative(); boolean isClass(); boolean isAnnotation(); boolean isEnum(); boolean hasGenerics(); static Iterable<String> findImportsInGeneric(final String generic); static IsParameter lexParam(final CharSequence chars); static int visitClassFile(final ClassVisitor<Param> extractor, final Param receiver, final CharSequence chars, int pos); }
@Test public void testTypeLexer() { String type = "java.lang.Class"; TypeData data = JavaLexer.extractType(type, 0); Assert.assertEquals("java.lang", data.pkgName); Assert.assertEquals("Class", data.clsName); Assert.assertEquals("Class", data.simpleName); Assert.assertEquals(type, data.toString()); String generics = "<SomeGenerics<With, Generics, In<Them>>>"; type = "com.foo.Outer.Inner" + generics + " [] [][ ]"; data = JavaLexer.extractType(type, 0); Assert.assertEquals("com.foo", data.pkgName); Assert.assertEquals("Outer.Inner", data.clsName); Assert.assertEquals("Inner", data.simpleName); Assert.assertEquals(3, data.arrayDepth); Assert.assertEquals(generics, data.generics); }
JavaLexer { public static <R> int visitMethodSignature (final MethodVisitor<R> visitor, final R receiver, final CharSequence chars, int pos) { pos = eatWhitespace(chars, pos); if (pos == chars.length()) { return pos; } pos = visitAnnotation(visitor, receiver, chars, pos); pos = visitModifier(visitor, receiver, chars, pos); pos = visitGeneric(visitor, receiver, chars, pos); final TypeDef returnType = extractType(chars, pos); visitor.visitReturnType(returnType, receiver); int start = pos = eatWhitespace(chars, returnType.index); if (chars.charAt(pos) == '.' && chars.charAt(pos+1) == '.') { pos = eatWhitespace(chars, pos+3); returnType.arrayDepth++; } pos = eatJavaname(chars, pos); visitor.visitName(chars.subSequence(start, pos).toString(), receiver); pos = eatWhitespace(chars, pos); if (pos == chars.length()) { return pos; } if (chars.charAt(pos) == '(') { pos = eatWhitespace(chars, pos + 1); while (chars.charAt(pos) != ')') { int initial = pos; final ParameterVisitor<R> param = visitor.visitParameter(); pos = visitAnnotation(param, receiver, chars, pos); pos = visitModifier(param, receiver, chars, pos); final TypeDef def = extractType(chars, pos); start = pos = eatWhitespace(chars, def.index); boolean varargs = false; if (chars.charAt(pos) == '.') { assert chars.charAt(pos+1)=='.'; assert chars.charAt(pos+2)=='.'; def.arrayDepth ++; start = pos = eatWhitespace(chars, pos+3); pos = eatJavaname(chars, start); varargs = true; } else { pos = eatJavaname(chars, start); } param.visitType(def, chars.subSequence(start, pos).toString(), varargs, receiver); pos = eatWhitespace(chars, pos); if (chars.charAt(pos) == ',') { pos++; } if (initial == pos) { throw new IllegalArgumentException("Bad signature " + chars); } } } if (pos == chars.length()) { return pos; } pos = eatWhitespace(chars, pos+1); if (pos == chars.length()) { return pos; } if (chars.charAt(pos) == 't') { if (chars.subSequence(pos, pos+6).equals("throws")) { pos = eatWhitespace(chars, pos+7); while (pos < chars.length()) { if (chars.charAt(pos)=='{' || chars.charAt(pos) == ';') { return pos; } start = pos; pos = eatJavaname(chars, pos); visitor.visitException(chars.subSequence(start, pos).toString(), receiver); pos = eatWhitespace(chars, pos); if (pos == chars.length()) { return pos; } if (chars.charAt(pos) == ',') { pos = eatWhitespace(chars, pos+1); } } } } return eatWhitespace(chars, pos); } JavaLexer(String definition); static int visitJavadoc(final JavadocVisitor<R> visitor, final R receiver, final CharSequence chars, int pos); static int visitAnnotation(final AnnotationVisitor<R> visitor, final R receiver, final CharSequence chars, int pos); static int visitAnnotationMembers(final AnnotationMemberVisitor<R> visitor, final R receiver, final CharSequence chars, int pos); static int visitModifier(final ModifierVisitor<R> visitor, final R receiver, final CharSequence chars, int pos); static int visitGeneric(final GenericVisitor<R> visitor, final R receiver, final CharSequence chars, int pos); static int visitMethodSignature(final MethodVisitor<R> visitor, final R receiver, final CharSequence chars, int pos); static TypeDef extractType(final CharSequence chars, int pos); static SimpleStack<IsGeneric> extractGenerics(final CharSequence chars, final int pos); String getClassName(); int getPrivacy(); int getModifier(); String getSuperClass(); String[] getGenerics(); String[] getImports(); String[] getInterfaces(); boolean isPublic(); boolean isPrivate(); boolean isProtected(); boolean isStatic(); boolean isFinal(); boolean isAbstract(); boolean isNative(); boolean isClass(); boolean isAnnotation(); boolean isEnum(); boolean hasGenerics(); static Iterable<String> findImportsInGeneric(final String generic); static IsParameter lexParam(final CharSequence chars); static int visitClassFile(final ClassVisitor<Param> extractor, final Param receiver, final CharSequence chars, int pos); }
@Test public void testMethodLexer() { final String methodGeneric = "<Complex, Generic extends Signature & More<Stuff>>"; final String modifiers = "public static final"; final String returnType = "Type"; final String returnGeneric = "<With<Generics>>"; final String methodName = "methodName"; final String paramGeneric = "<? extends Generic<int[]>>"; String params = "String[] i, java . lang . Class" +paramGeneric+ " cls"; String exceptions = "java.lang.RuntimeException, ClassCastException "; String method = modifiers + " "+methodGeneric +" "+ returnType+returnGeneric+"[][] " + methodName+ "(" + params+") throws "+exceptions; final int[] success = new int[8]; JavaLexer.visitMethodSignature(new MethodVisitor<Void>() { @Override public AnnotationMemberVisitor<Void> visitAnnotation(String annoName, String annoBody, Void receiver) { Assert.fail("No annotations"); return null; } @Override public void visitJavadoc(String javadoc, Void receiver) { Assert.fail("No javadoc"); } @Override public void visitModifier(int modifier, Void receiver) { switch(modifier) { case Modifier.PUBLIC: case Modifier.STATIC: case Modifier.FINAL: success[0] = success[0] | modifier; break; default: Assert.fail("Illegal modifier: "+Integer.toHexString(modifier)); } } @Override public void visitGeneric(String generic, Void receiver) { Assert.assertEquals(generic, methodGeneric); success[1] = 1; } @Override public void visitReturnType(TypeData returnedType, Void receiver) { Assert.assertEquals(returnedType.clsName, returnType); Assert.assertEquals(returnedType.generics, returnGeneric); Assert.assertEquals(returnedType.arrayDepth, 2); success[2] = 1; } @Override public void visitName(String name, Void receiver) { Assert.assertEquals(name, methodName); success[3] = 1; } @Override public ParameterVisitor<Void> visitParameter() { return new ParameterVisitor<Void>() { @Override public AnnotationMemberVisitor<Void> visitAnnotation(String annoName, String annoBody, Void receiver) { return null; } @Override public void visitModifier(int modifier, Void receiver) { } @Override public void visitType(TypeData type, String name, boolean varargs, Void receiver) { if ("i".equals(name)) { success[4] = 1; Assert.assertEquals("String", type.clsName); Assert.assertEquals(1, type.arrayDepth); } else if ("cls".equals(name)){ success[5] = 1; Assert.assertEquals("java.lang", type.pkgName); Assert.assertEquals("Class", type.clsName); Assert.assertEquals(0, type.arrayDepth); Assert.assertEquals(paramGeneric, type.generics); } else { Assert.fail("Unrecognized name: "+name+"; type: "+type); } } }; } @Override public void visitException(String type, Void receiver) { if ("java.lang.RuntimeException".equals(type)) { success[6] = 1; } else if ("ClassCastException".equals(type)) { success[7] = 1; } else { Assert.fail("Unrecognized exception type: "+type); } } }, null, method, 0); Assert.assertArrayEquals(success, new int[]{ Modifier.PUBLIC|Modifier.STATIC|Modifier.FINAL ,1,1,1, 1,1,1,1 }); }
LogInjector { public Log defaultLogger() { return (level, debug) -> (level == LogLevel.ERROR ? SYS_ERR : SYS_OUT) .print(level, debug); } Log defaultLogger(); }
@Test public void testDefaultLogging() throws Throwable { final String msg = "Success! " + hashCode(); borrowSout( ()-> LogInjector.DEFAULT.log(LogLevel.INFO, msg) , lines-> Assert.assertEquals("[INFO] " + msg, lines.first()) ); assertTrue("Failed", !failed); Log.defaultLogger().log(LogInjectorTest.class, "Default Logging Works!"); }
SlideRenderer { public void renderSlide(DomBuffer into, UiContainerExpr slide) { final DomBuffer out; if ("xapi-slide".equals(into.getTagName())) { out = into; } else { out = into.makeTag("xapi-slide"); } slide.getAttribute("id") .mapNullSafe(UiAttrExpr::getExpression) .mapNullSafe(ASTHelper::extractStringValue) .readIfPresent(out::setId); final ComposableXapiVisitor<DomBuffer> visitor = new ComposableXapiVisitor<>(); visitor .withUiContainerExpr((tag, buffer)->{ renderSlideChild(out, tag, visitor, slide); return false; }) .visit(slide.getBody(), out); } void renderSlide(DomBuffer into, UiContainerExpr slide); }
@Test public void testAllSlidesCanRender() throws IOException, ParseException { items.forAll(item->{ SlideRenderer renderer = new SlideRenderer(); final DomBuffer into = new DomBuffer() .setNewLine(true) .setTrimWhitespace(false); renderer.renderSlide(into, item.out2()); X_Log.info(X_Source.pathToLogLink(item.out1().getResourceName()), "\n", item.out2(), "\nRenders:", into, "\n\n" ); }); }
RangePool { public boolean insert(Coord coord, T value) { ReservedNode<T> newNode = new ReservedNode<>(coord, value); if (highest.getRange().contains(coord)) { if (highest.getRange().getX() == coord.getX()) { highest.attachBelow(newNode); } else { final UnreservedNode<T> newSpace = highest.split(newNode, RangeDirection.Higher); if (lowest == highest) { lowest = newSpace; } } return true; } else if (lowest.getRange().contains(coord)) { if (lowest.getRange().getY() == coord.getY()) { lowest.attachAbove(newNode); } else { final UnreservedNode<T> newSpace = lowest.split(newNode, RangeDirection.Lower); if (lowest == highest) { highest = newSpace; } } return true; } else { double toHighest = highest.getRange().getX() - coord.getY(); double toLowest = coord.getX() - lowest.getRange().getY(); final UnreservedNode<T> searchFrom; if (toHighest > toLowest) { searchFrom = lowest; } else { searchFrom = highest; } Maybe<UnreservedNode<T>> into = searchFrom.findUnreserved(coord); if (into.isPresent()) { final UnreservedNode<T> space = into.get(); final Coord unreserved = space.getRange(); if (unreserved.contains(coord)) { if (unreserved.equals(coord)) { space.replaceWith(newNode); } else if (unreserved.getY() == coord.getY()) { space.attachAbove(newNode); } else if (unreserved.getX() == coord.getX()) { space.attachBelow(newNode); } else { space.split(newNode, RangeDirection.Higher); } return true; } else { } } } return false; } RangePool(); boolean insert(Coord coord, T value); Maybe<Coord> reserveSpace(Coord point, T value); boolean isValid(); MappedIterable<UnreservedNode<T>> forUnreservedAsc(); MappedIterable<UnreservedNode<T>> forUnreservedDesc(); MappedIterable<ReservedNode<T>> forReservedAsc(); MappedIterable<ReservedNode<T>> forReservedDesc(); }
@Test public void testInsertAtEdges() { int cnt = 0; RangePool<Integer> pool = new RangePool<>(); assertPoolStructure(pool, new Coord[]{coord(Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY)} ); pool.insert(coord(-2, 2), cnt++); assertPoolStructure(pool, new Coord[]{coord(Double.NEGATIVE_INFINITY, -2), coord(2, Double.POSITIVE_INFINITY)}, coord(-2, 2) ); pool.insert(coord(2, 4), cnt++); assertPoolStructure(pool, new Coord[]{ coord(Double.NEGATIVE_INFINITY, -2), coord(4, Double.POSITIVE_INFINITY) }, coord(-2, 2), coord(2, 4) ); pool.insert(coord(-4, -2), cnt++); assertPoolStructure(pool, new Coord[]{coord(Double.NEGATIVE_INFINITY, -4), coord(4, Double.POSITIVE_INFINITY)}, coord(-4, -2), coord(-2, 2), coord(2, 4) ); pool = new RangePool<>(); assertPoolStructure(pool, new Coord[]{coord(Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY)} ); pool.insert(coord(-2, 2), cnt++); assertPoolStructure(pool, new Coord[]{coord(Double.NEGATIVE_INFINITY, -2), coord(2, Double.POSITIVE_INFINITY)}, coord(-2, 2) ); pool.insert(coord(-4, -2), cnt++); assertPoolStructure(pool, new Coord[]{ coord(Double.NEGATIVE_INFINITY, -4), coord(2, Double.POSITIVE_INFINITY) }, coord(-4, -2), coord(-2, 2) ); pool.insert(coord(2, 4), cnt++); assertPoolStructure(pool, new Coord[]{ coord(Double.NEGATIVE_INFINITY, -4), coord(4, Double.POSITIVE_INFINITY) }, coord(-4, -2), coord(-2, 2), coord(2, 4) ); } @Test public void testInsertAtContainedEdges() { int cnt = 0; RangePool<Integer> pool = new RangePool<>(); assertPoolStructure(pool, new Coord[]{coord(Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY)} ); pool.insert(coord(8, 16), cnt++); assertPoolStructure(pool, new Coord[]{ coord(Double.NEGATIVE_INFINITY, 8), coord(16, Double.POSITIVE_INFINITY) }, coord(8, 16) ); pool.insert(coord(-16, -8), cnt++); assertPoolStructure(pool, new Coord[]{ coord(Double.NEGATIVE_INFINITY, -16), coord(-8, 8), coord(16, Double.POSITIVE_INFINITY) }, coord(-16, -8), coord(8, 16) ); pool.insert(coord(-1, 1), cnt++); assertPoolStructure(pool, new Coord[]{ coord(Double.NEGATIVE_INFINITY, -16), coord(-8, -1), coord(1, 8), coord(16, Double.POSITIVE_INFINITY) }, coord(-16, -8), coord(-1, 1), coord(8, 16) ); pool.insert(coord(-2, -1), cnt++); assertPoolStructure(pool, new Coord[]{ coord(Double.NEGATIVE_INFINITY, -16), coord(-8, -2), coord(1, 8), coord(16, Double.POSITIVE_INFINITY) }, coord(-16, -8), coord(-2, -1), coord(-1, 1), coord(8, 16) ); pool.insert(coord(1, 2), cnt++); assertPoolStructure(pool, new Coord[]{ coord(Double.NEGATIVE_INFINITY, -16), coord(-8, -2), coord(2, 8), coord(16, Double.POSITIVE_INFINITY) }, coord(-16, -8), coord(-2, -1), coord(-1, 1), coord(1, 2), coord(8, 16) ); pool.insert(coord(-8, -2), cnt++); assertPoolStructure(pool, new Coord[]{ coord(Double.NEGATIVE_INFINITY, -16), coord(2, 8), coord(16, Double.POSITIVE_INFINITY) }, coord(-16, -8), coord(-8, -2), coord(-2, -1), coord(-1, 1), coord(1, 2), coord(8, 16) ); pool.insert(coord(2, 8), cnt++); assertPoolStructure(pool, new Coord[]{ coord(Double.NEGATIVE_INFINITY, -16), coord(16, Double.POSITIVE_INFINITY) }, coord(-16, -8), coord(-8, -2), coord(-2, -1), coord(-1, 1), coord(1, 2), coord(2, 8), coord(8, 16) ); } @Test public void testRangeSplit() { int cnt = 0; RangePool<Integer> pool = new RangePool<>(); assertPoolStructure(pool, new Coord[]{coord(Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY)} ); pool.insert(coord(8, 16), cnt++); assertPoolStructure(pool, new Coord[]{coord(Double.NEGATIVE_INFINITY, 8), coord(16, Double.POSITIVE_INFINITY)}, coord(8, 16) ); pool.insert(coord(-16, -8), cnt++); assertPoolStructure(pool, new Coord[]{ coord(Double.NEGATIVE_INFINITY, -16), coord(-8, 8), coord(16, Double.POSITIVE_INFINITY) }, coord(-16, -8), coord(8, 16) ); pool.insert(coord(-2, 2), cnt++); assertPoolStructure(pool, new Coord[]{ coord(Double.NEGATIVE_INFINITY, -16), coord(-8, -2), coord(2, 8), coord(16, Double.POSITIVE_INFINITY) }, coord(-16, -8), coord(-2, 2), coord(8, 16) ); pool = new RangePool<>(); assertPoolStructure(pool, new Coord[]{coord(Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY)} ); pool.insert(coord(-16, -8), cnt++); assertPoolStructure(pool, new Coord[]{coord(Double.NEGATIVE_INFINITY, -16), coord(-8, Double.POSITIVE_INFINITY)}, coord(-16, -8) ); pool.insert(coord(8, 16), cnt++); assertPoolStructure(pool, new Coord[]{ coord(Double.NEGATIVE_INFINITY, -16), coord(-8, 8), coord(16, Double.POSITIVE_INFINITY) }, coord(-16, -8), coord(8, 16) ); pool.insert(coord(-2, 2), cnt++); assertPoolStructure(pool, new Coord[]{ coord(Double.NEGATIVE_INFINITY, -16), coord(-8, -2), coord(2, 8), coord(16, Double.POSITIVE_INFINITY) }, coord(-16, -8), coord(-2, 2), coord(8, 16) ); }
CacheUtils { public byte[] getBytes(@NonNull String key) { return getBytes(key, null); } private CacheUtils(@NonNull File cacheDir, long maxSize, int maxCount); static CacheUtils getInstance(); static CacheUtils getInstance(String cacheName); static CacheUtils getInstance(long maxSize, int maxCount); static CacheUtils getInstance(String cacheName, long maxSize, int maxCount); static CacheUtils getInstance(@NonNull File cacheDir); static CacheUtils getInstance(@NonNull File cacheDir, long maxSize, int maxCount); void put(@NonNull String key, @NonNull byte[] value); void put(@NonNull String key, @NonNull byte[] value, int saveTime); byte[] getBytes(@NonNull String key); byte[] getBytes(@NonNull String key, byte[] defaultValue); void put(@NonNull String key, @NonNull String value); void put(@NonNull String key, @NonNull String value, int saveTime); String getString(@NonNull String key); String getString(@NonNull String key, String defaultValue); void put(@NonNull String key, @NonNull JSONObject value); void put(@NonNull String key, @NonNull JSONObject value, int saveTime); JSONObject getJSONObject(@NonNull String key); JSONObject getJSONObject(@NonNull String key, JSONObject defaultValue); void put(@NonNull String key, @NonNull JSONArray value); void put(@NonNull String key, @NonNull JSONArray value, int saveTime); JSONArray getJSONArray(@NonNull String key); JSONArray getJSONArray(@NonNull String key, JSONArray defaultValue); void put(@NonNull String key, @NonNull Bitmap value); void put(@NonNull String key, @NonNull Bitmap value, int saveTime); Bitmap getBitmap(@NonNull String key); Bitmap getBitmap(@NonNull String key, Bitmap defaultValue); void put(@NonNull String key, @NonNull Drawable value); void put(@NonNull String key, @NonNull Drawable value, int saveTime); Drawable getDrawable(@NonNull String key); Drawable getDrawable(@NonNull String key, Drawable defaultValue); void put(@NonNull String key, @NonNull Parcelable value); void put(@NonNull String key, @NonNull Parcelable value, int saveTime); T getParcelable(@NonNull String key, @NonNull Parcelable.Creator<T> creator); T getParcelable(@NonNull String key, @NonNull Parcelable.Creator<T> creator, T defaultValue); void put(@NonNull String key, @NonNull Serializable value); void put(@NonNull String key, @NonNull Serializable value, int saveTime); Object getSerializable(@NonNull String key); Object getSerializable(@NonNull String key, Object defaultValue); long getCacheSize(); int getCacheCount(); boolean remove(@NonNull String key); boolean clear(); static final int SEC; static final int MIN; static final int HOUR; static final int DAY; }
@Test public void getBytes() throws Exception { Assert.assertEquals(mString, new String(mCacheUtils1.getBytes("bytes1"))); Assert.assertEquals(mString, new String(mCacheUtils1.getBytes("bytes1", null))); Assert.assertNull(mCacheUtils1.getBytes("bytes2", null)); Assert.assertEquals(mString, new String(mCacheUtils2.getBytes("bytes2"))); Assert.assertEquals(mString, new String(mCacheUtils2.getBytes("bytes2", null))); Assert.assertNull(mCacheUtils2.getBytes("bytes1", null)); }
CacheUtils { public String getString(@NonNull String key) { return getString(key, null); } private CacheUtils(@NonNull File cacheDir, long maxSize, int maxCount); static CacheUtils getInstance(); static CacheUtils getInstance(String cacheName); static CacheUtils getInstance(long maxSize, int maxCount); static CacheUtils getInstance(String cacheName, long maxSize, int maxCount); static CacheUtils getInstance(@NonNull File cacheDir); static CacheUtils getInstance(@NonNull File cacheDir, long maxSize, int maxCount); void put(@NonNull String key, @NonNull byte[] value); void put(@NonNull String key, @NonNull byte[] value, int saveTime); byte[] getBytes(@NonNull String key); byte[] getBytes(@NonNull String key, byte[] defaultValue); void put(@NonNull String key, @NonNull String value); void put(@NonNull String key, @NonNull String value, int saveTime); String getString(@NonNull String key); String getString(@NonNull String key, String defaultValue); void put(@NonNull String key, @NonNull JSONObject value); void put(@NonNull String key, @NonNull JSONObject value, int saveTime); JSONObject getJSONObject(@NonNull String key); JSONObject getJSONObject(@NonNull String key, JSONObject defaultValue); void put(@NonNull String key, @NonNull JSONArray value); void put(@NonNull String key, @NonNull JSONArray value, int saveTime); JSONArray getJSONArray(@NonNull String key); JSONArray getJSONArray(@NonNull String key, JSONArray defaultValue); void put(@NonNull String key, @NonNull Bitmap value); void put(@NonNull String key, @NonNull Bitmap value, int saveTime); Bitmap getBitmap(@NonNull String key); Bitmap getBitmap(@NonNull String key, Bitmap defaultValue); void put(@NonNull String key, @NonNull Drawable value); void put(@NonNull String key, @NonNull Drawable value, int saveTime); Drawable getDrawable(@NonNull String key); Drawable getDrawable(@NonNull String key, Drawable defaultValue); void put(@NonNull String key, @NonNull Parcelable value); void put(@NonNull String key, @NonNull Parcelable value, int saveTime); T getParcelable(@NonNull String key, @NonNull Parcelable.Creator<T> creator); T getParcelable(@NonNull String key, @NonNull Parcelable.Creator<T> creator, T defaultValue); void put(@NonNull String key, @NonNull Serializable value); void put(@NonNull String key, @NonNull Serializable value, int saveTime); Object getSerializable(@NonNull String key); Object getSerializable(@NonNull String key, Object defaultValue); long getCacheSize(); int getCacheCount(); boolean remove(@NonNull String key); boolean clear(); static final int SEC; static final int MIN; static final int HOUR; static final int DAY; }
@Test public void getString() throws Exception { Assert.assertEquals(mString, mCacheUtils1.getString("string1")); Assert.assertEquals(mString, mCacheUtils1.getString("string1", null)); Assert.assertNull(mCacheUtils1.getString("string2", null)); Assert.assertEquals(mString, mCacheUtils2.getString("string2")); Assert.assertEquals(mString, mCacheUtils2.getString("string2", null)); Assert.assertNull(mCacheUtils2.getString("string1", null)); }
CacheUtils { public JSONObject getJSONObject(@NonNull String key) { return getJSONObject(key, null); } private CacheUtils(@NonNull File cacheDir, long maxSize, int maxCount); static CacheUtils getInstance(); static CacheUtils getInstance(String cacheName); static CacheUtils getInstance(long maxSize, int maxCount); static CacheUtils getInstance(String cacheName, long maxSize, int maxCount); static CacheUtils getInstance(@NonNull File cacheDir); static CacheUtils getInstance(@NonNull File cacheDir, long maxSize, int maxCount); void put(@NonNull String key, @NonNull byte[] value); void put(@NonNull String key, @NonNull byte[] value, int saveTime); byte[] getBytes(@NonNull String key); byte[] getBytes(@NonNull String key, byte[] defaultValue); void put(@NonNull String key, @NonNull String value); void put(@NonNull String key, @NonNull String value, int saveTime); String getString(@NonNull String key); String getString(@NonNull String key, String defaultValue); void put(@NonNull String key, @NonNull JSONObject value); void put(@NonNull String key, @NonNull JSONObject value, int saveTime); JSONObject getJSONObject(@NonNull String key); JSONObject getJSONObject(@NonNull String key, JSONObject defaultValue); void put(@NonNull String key, @NonNull JSONArray value); void put(@NonNull String key, @NonNull JSONArray value, int saveTime); JSONArray getJSONArray(@NonNull String key); JSONArray getJSONArray(@NonNull String key, JSONArray defaultValue); void put(@NonNull String key, @NonNull Bitmap value); void put(@NonNull String key, @NonNull Bitmap value, int saveTime); Bitmap getBitmap(@NonNull String key); Bitmap getBitmap(@NonNull String key, Bitmap defaultValue); void put(@NonNull String key, @NonNull Drawable value); void put(@NonNull String key, @NonNull Drawable value, int saveTime); Drawable getDrawable(@NonNull String key); Drawable getDrawable(@NonNull String key, Drawable defaultValue); void put(@NonNull String key, @NonNull Parcelable value); void put(@NonNull String key, @NonNull Parcelable value, int saveTime); T getParcelable(@NonNull String key, @NonNull Parcelable.Creator<T> creator); T getParcelable(@NonNull String key, @NonNull Parcelable.Creator<T> creator, T defaultValue); void put(@NonNull String key, @NonNull Serializable value); void put(@NonNull String key, @NonNull Serializable value, int saveTime); Object getSerializable(@NonNull String key); Object getSerializable(@NonNull String key, Object defaultValue); long getCacheSize(); int getCacheCount(); boolean remove(@NonNull String key); boolean clear(); static final int SEC; static final int MIN; static final int HOUR; static final int DAY; }
@Test public void getJSONObject() throws Exception { Assert.assertEquals(mJSONObject.toString(), mCacheUtils1.getJSONObject("jsonObject1").toString()); Assert.assertEquals(mJSONObject.toString(), mCacheUtils1.getJSONObject("jsonObject1", null).toString()); Assert.assertNull(mCacheUtils1.getJSONObject("jsonObject2", null)); Assert.assertEquals(mJSONObject.toString(), mCacheUtils2.getJSONObject("jsonObject2").toString()); Assert.assertEquals(mJSONObject.toString(), mCacheUtils2.getJSONObject("jsonObject2", null).toString()); Assert.assertNull(mCacheUtils2.getJSONObject("jsonObject1", null)); }
CacheUtils { public JSONArray getJSONArray(@NonNull String key) { return getJSONArray(key, null); } private CacheUtils(@NonNull File cacheDir, long maxSize, int maxCount); static CacheUtils getInstance(); static CacheUtils getInstance(String cacheName); static CacheUtils getInstance(long maxSize, int maxCount); static CacheUtils getInstance(String cacheName, long maxSize, int maxCount); static CacheUtils getInstance(@NonNull File cacheDir); static CacheUtils getInstance(@NonNull File cacheDir, long maxSize, int maxCount); void put(@NonNull String key, @NonNull byte[] value); void put(@NonNull String key, @NonNull byte[] value, int saveTime); byte[] getBytes(@NonNull String key); byte[] getBytes(@NonNull String key, byte[] defaultValue); void put(@NonNull String key, @NonNull String value); void put(@NonNull String key, @NonNull String value, int saveTime); String getString(@NonNull String key); String getString(@NonNull String key, String defaultValue); void put(@NonNull String key, @NonNull JSONObject value); void put(@NonNull String key, @NonNull JSONObject value, int saveTime); JSONObject getJSONObject(@NonNull String key); JSONObject getJSONObject(@NonNull String key, JSONObject defaultValue); void put(@NonNull String key, @NonNull JSONArray value); void put(@NonNull String key, @NonNull JSONArray value, int saveTime); JSONArray getJSONArray(@NonNull String key); JSONArray getJSONArray(@NonNull String key, JSONArray defaultValue); void put(@NonNull String key, @NonNull Bitmap value); void put(@NonNull String key, @NonNull Bitmap value, int saveTime); Bitmap getBitmap(@NonNull String key); Bitmap getBitmap(@NonNull String key, Bitmap defaultValue); void put(@NonNull String key, @NonNull Drawable value); void put(@NonNull String key, @NonNull Drawable value, int saveTime); Drawable getDrawable(@NonNull String key); Drawable getDrawable(@NonNull String key, Drawable defaultValue); void put(@NonNull String key, @NonNull Parcelable value); void put(@NonNull String key, @NonNull Parcelable value, int saveTime); T getParcelable(@NonNull String key, @NonNull Parcelable.Creator<T> creator); T getParcelable(@NonNull String key, @NonNull Parcelable.Creator<T> creator, T defaultValue); void put(@NonNull String key, @NonNull Serializable value); void put(@NonNull String key, @NonNull Serializable value, int saveTime); Object getSerializable(@NonNull String key); Object getSerializable(@NonNull String key, Object defaultValue); long getCacheSize(); int getCacheCount(); boolean remove(@NonNull String key); boolean clear(); static final int SEC; static final int MIN; static final int HOUR; static final int DAY; }
@Test public void getJSONArray() throws Exception { Assert.assertEquals(mJSONArray.toString(), mCacheUtils1.getJSONArray("jsonArray1").toString()); Assert.assertEquals(mJSONArray.toString(), mCacheUtils1.getJSONArray("jsonArray1", null).toString()); Assert.assertNull(mCacheUtils1.getJSONArray("jsonArray2", null)); Assert.assertEquals(mJSONArray.toString(), mCacheUtils2.getJSONArray("jsonArray2").toString()); Assert.assertEquals(mJSONArray.toString(), mCacheUtils2.getJSONArray("jsonArray2", null).toString()); Assert.assertNull(mCacheUtils2.getJSONArray("jsonArray1", null)); }
CacheUtils { public Bitmap getBitmap(@NonNull String key) { return getBitmap(key, null); } private CacheUtils(@NonNull File cacheDir, long maxSize, int maxCount); static CacheUtils getInstance(); static CacheUtils getInstance(String cacheName); static CacheUtils getInstance(long maxSize, int maxCount); static CacheUtils getInstance(String cacheName, long maxSize, int maxCount); static CacheUtils getInstance(@NonNull File cacheDir); static CacheUtils getInstance(@NonNull File cacheDir, long maxSize, int maxCount); void put(@NonNull String key, @NonNull byte[] value); void put(@NonNull String key, @NonNull byte[] value, int saveTime); byte[] getBytes(@NonNull String key); byte[] getBytes(@NonNull String key, byte[] defaultValue); void put(@NonNull String key, @NonNull String value); void put(@NonNull String key, @NonNull String value, int saveTime); String getString(@NonNull String key); String getString(@NonNull String key, String defaultValue); void put(@NonNull String key, @NonNull JSONObject value); void put(@NonNull String key, @NonNull JSONObject value, int saveTime); JSONObject getJSONObject(@NonNull String key); JSONObject getJSONObject(@NonNull String key, JSONObject defaultValue); void put(@NonNull String key, @NonNull JSONArray value); void put(@NonNull String key, @NonNull JSONArray value, int saveTime); JSONArray getJSONArray(@NonNull String key); JSONArray getJSONArray(@NonNull String key, JSONArray defaultValue); void put(@NonNull String key, @NonNull Bitmap value); void put(@NonNull String key, @NonNull Bitmap value, int saveTime); Bitmap getBitmap(@NonNull String key); Bitmap getBitmap(@NonNull String key, Bitmap defaultValue); void put(@NonNull String key, @NonNull Drawable value); void put(@NonNull String key, @NonNull Drawable value, int saveTime); Drawable getDrawable(@NonNull String key); Drawable getDrawable(@NonNull String key, Drawable defaultValue); void put(@NonNull String key, @NonNull Parcelable value); void put(@NonNull String key, @NonNull Parcelable value, int saveTime); T getParcelable(@NonNull String key, @NonNull Parcelable.Creator<T> creator); T getParcelable(@NonNull String key, @NonNull Parcelable.Creator<T> creator, T defaultValue); void put(@NonNull String key, @NonNull Serializable value); void put(@NonNull String key, @NonNull Serializable value, int saveTime); Object getSerializable(@NonNull String key); Object getSerializable(@NonNull String key, Object defaultValue); long getCacheSize(); int getCacheCount(); boolean remove(@NonNull String key); boolean clear(); static final int SEC; static final int MIN; static final int HOUR; static final int DAY; }
@Test public void getBitmap() throws Exception { Assert.assertTrue(mCacheUtils1.getString("bitmap1").equals("Bitmap (100 x 100) compressed as PNG with quality 100")); Assert.assertTrue(mCacheUtils1.getString("bitmap1", null).equals("Bitmap (100 x 100) compressed as PNG with quality 100")); Assert.assertNull(mCacheUtils1.getString("bitmap2", null)); Assert.assertTrue(mCacheUtils2.getString("bitmap2").equals("Bitmap (100 x 100) compressed as PNG with quality 100")); Assert.assertTrue(mCacheUtils2.getString("bitmap2", null).equals("Bitmap (100 x 100) compressed as PNG with quality 100")); Assert.assertNull(mCacheUtils2.getString("bitmap1", null)); }
CacheUtils { public Drawable getDrawable(@NonNull String key) { return getDrawable(key, null); } private CacheUtils(@NonNull File cacheDir, long maxSize, int maxCount); static CacheUtils getInstance(); static CacheUtils getInstance(String cacheName); static CacheUtils getInstance(long maxSize, int maxCount); static CacheUtils getInstance(String cacheName, long maxSize, int maxCount); static CacheUtils getInstance(@NonNull File cacheDir); static CacheUtils getInstance(@NonNull File cacheDir, long maxSize, int maxCount); void put(@NonNull String key, @NonNull byte[] value); void put(@NonNull String key, @NonNull byte[] value, int saveTime); byte[] getBytes(@NonNull String key); byte[] getBytes(@NonNull String key, byte[] defaultValue); void put(@NonNull String key, @NonNull String value); void put(@NonNull String key, @NonNull String value, int saveTime); String getString(@NonNull String key); String getString(@NonNull String key, String defaultValue); void put(@NonNull String key, @NonNull JSONObject value); void put(@NonNull String key, @NonNull JSONObject value, int saveTime); JSONObject getJSONObject(@NonNull String key); JSONObject getJSONObject(@NonNull String key, JSONObject defaultValue); void put(@NonNull String key, @NonNull JSONArray value); void put(@NonNull String key, @NonNull JSONArray value, int saveTime); JSONArray getJSONArray(@NonNull String key); JSONArray getJSONArray(@NonNull String key, JSONArray defaultValue); void put(@NonNull String key, @NonNull Bitmap value); void put(@NonNull String key, @NonNull Bitmap value, int saveTime); Bitmap getBitmap(@NonNull String key); Bitmap getBitmap(@NonNull String key, Bitmap defaultValue); void put(@NonNull String key, @NonNull Drawable value); void put(@NonNull String key, @NonNull Drawable value, int saveTime); Drawable getDrawable(@NonNull String key); Drawable getDrawable(@NonNull String key, Drawable defaultValue); void put(@NonNull String key, @NonNull Parcelable value); void put(@NonNull String key, @NonNull Parcelable value, int saveTime); T getParcelable(@NonNull String key, @NonNull Parcelable.Creator<T> creator); T getParcelable(@NonNull String key, @NonNull Parcelable.Creator<T> creator, T defaultValue); void put(@NonNull String key, @NonNull Serializable value); void put(@NonNull String key, @NonNull Serializable value, int saveTime); Object getSerializable(@NonNull String key); Object getSerializable(@NonNull String key, Object defaultValue); long getCacheSize(); int getCacheCount(); boolean remove(@NonNull String key); boolean clear(); static final int SEC; static final int MIN; static final int HOUR; static final int DAY; }
@Test public void getDrawable() throws Exception { Assert.assertTrue(mCacheUtils1.getString("drawable1").equals("Bitmap (100 x 100) compressed as PNG with quality 100")); Assert.assertTrue(mCacheUtils1.getString("drawable1", null).equals("Bitmap (100 x 100) compressed as PNG with quality 100")); Assert.assertNull(mCacheUtils1.getString("drawable2", null)); Assert.assertTrue(mCacheUtils2.getString("drawable2").equals("Bitmap (100 x 100) compressed as PNG with quality 100")); Assert.assertTrue(mCacheUtils2.getString("drawable2", null).equals("Bitmap (100 x 100) compressed as PNG with quality 100")); Assert.assertNull(mCacheUtils2.getString("drawable1", null)); }
CacheUtils { public <T> T getParcelable(@NonNull String key, @NonNull Parcelable.Creator<T> creator) { return getParcelable(key, creator, null); } private CacheUtils(@NonNull File cacheDir, long maxSize, int maxCount); static CacheUtils getInstance(); static CacheUtils getInstance(String cacheName); static CacheUtils getInstance(long maxSize, int maxCount); static CacheUtils getInstance(String cacheName, long maxSize, int maxCount); static CacheUtils getInstance(@NonNull File cacheDir); static CacheUtils getInstance(@NonNull File cacheDir, long maxSize, int maxCount); void put(@NonNull String key, @NonNull byte[] value); void put(@NonNull String key, @NonNull byte[] value, int saveTime); byte[] getBytes(@NonNull String key); byte[] getBytes(@NonNull String key, byte[] defaultValue); void put(@NonNull String key, @NonNull String value); void put(@NonNull String key, @NonNull String value, int saveTime); String getString(@NonNull String key); String getString(@NonNull String key, String defaultValue); void put(@NonNull String key, @NonNull JSONObject value); void put(@NonNull String key, @NonNull JSONObject value, int saveTime); JSONObject getJSONObject(@NonNull String key); JSONObject getJSONObject(@NonNull String key, JSONObject defaultValue); void put(@NonNull String key, @NonNull JSONArray value); void put(@NonNull String key, @NonNull JSONArray value, int saveTime); JSONArray getJSONArray(@NonNull String key); JSONArray getJSONArray(@NonNull String key, JSONArray defaultValue); void put(@NonNull String key, @NonNull Bitmap value); void put(@NonNull String key, @NonNull Bitmap value, int saveTime); Bitmap getBitmap(@NonNull String key); Bitmap getBitmap(@NonNull String key, Bitmap defaultValue); void put(@NonNull String key, @NonNull Drawable value); void put(@NonNull String key, @NonNull Drawable value, int saveTime); Drawable getDrawable(@NonNull String key); Drawable getDrawable(@NonNull String key, Drawable defaultValue); void put(@NonNull String key, @NonNull Parcelable value); void put(@NonNull String key, @NonNull Parcelable value, int saveTime); T getParcelable(@NonNull String key, @NonNull Parcelable.Creator<T> creator); T getParcelable(@NonNull String key, @NonNull Parcelable.Creator<T> creator, T defaultValue); void put(@NonNull String key, @NonNull Serializable value); void put(@NonNull String key, @NonNull Serializable value, int saveTime); Object getSerializable(@NonNull String key); Object getSerializable(@NonNull String key, Object defaultValue); long getCacheSize(); int getCacheCount(); boolean remove(@NonNull String key); boolean clear(); static final int SEC; static final int MIN; static final int HOUR; static final int DAY; }
@Test public void getParcel() throws Exception { Assert.assertTrue(mCacheUtils1.getParcelable("parcelable1", ParcelableTest.CREATOR).equals(mParcelableTest)); Assert.assertTrue(mCacheUtils1.getParcelable("parcelable1", ParcelableTest.CREATOR, null).equals(mParcelableTest)); Assert.assertNull(mCacheUtils1.getParcelable("parcelable2", ParcelableTest.CREATOR, null)); Assert.assertTrue(mCacheUtils2.getParcelable("parcelable2", ParcelableTest.CREATOR).equals(mParcelableTest)); Assert.assertTrue(mCacheUtils2.getParcelable("parcelable2", ParcelableTest.CREATOR, null).equals(mParcelableTest)); Assert.assertNull(mCacheUtils2.getParcelable("parcelable1", ParcelableTest.CREATOR, null)); }
CacheUtils { public Object getSerializable(@NonNull String key) { return getSerializable(key, null); } private CacheUtils(@NonNull File cacheDir, long maxSize, int maxCount); static CacheUtils getInstance(); static CacheUtils getInstance(String cacheName); static CacheUtils getInstance(long maxSize, int maxCount); static CacheUtils getInstance(String cacheName, long maxSize, int maxCount); static CacheUtils getInstance(@NonNull File cacheDir); static CacheUtils getInstance(@NonNull File cacheDir, long maxSize, int maxCount); void put(@NonNull String key, @NonNull byte[] value); void put(@NonNull String key, @NonNull byte[] value, int saveTime); byte[] getBytes(@NonNull String key); byte[] getBytes(@NonNull String key, byte[] defaultValue); void put(@NonNull String key, @NonNull String value); void put(@NonNull String key, @NonNull String value, int saveTime); String getString(@NonNull String key); String getString(@NonNull String key, String defaultValue); void put(@NonNull String key, @NonNull JSONObject value); void put(@NonNull String key, @NonNull JSONObject value, int saveTime); JSONObject getJSONObject(@NonNull String key); JSONObject getJSONObject(@NonNull String key, JSONObject defaultValue); void put(@NonNull String key, @NonNull JSONArray value); void put(@NonNull String key, @NonNull JSONArray value, int saveTime); JSONArray getJSONArray(@NonNull String key); JSONArray getJSONArray(@NonNull String key, JSONArray defaultValue); void put(@NonNull String key, @NonNull Bitmap value); void put(@NonNull String key, @NonNull Bitmap value, int saveTime); Bitmap getBitmap(@NonNull String key); Bitmap getBitmap(@NonNull String key, Bitmap defaultValue); void put(@NonNull String key, @NonNull Drawable value); void put(@NonNull String key, @NonNull Drawable value, int saveTime); Drawable getDrawable(@NonNull String key); Drawable getDrawable(@NonNull String key, Drawable defaultValue); void put(@NonNull String key, @NonNull Parcelable value); void put(@NonNull String key, @NonNull Parcelable value, int saveTime); T getParcelable(@NonNull String key, @NonNull Parcelable.Creator<T> creator); T getParcelable(@NonNull String key, @NonNull Parcelable.Creator<T> creator, T defaultValue); void put(@NonNull String key, @NonNull Serializable value); void put(@NonNull String key, @NonNull Serializable value, int saveTime); Object getSerializable(@NonNull String key); Object getSerializable(@NonNull String key, Object defaultValue); long getCacheSize(); int getCacheCount(); boolean remove(@NonNull String key); boolean clear(); static final int SEC; static final int MIN; static final int HOUR; static final int DAY; }
@Test public void getSerializable() throws Exception { Assert.assertTrue(mCacheUtils1.getSerializable("serializable1").equals(mSerializableTest)); Assert.assertTrue(mCacheUtils1.getSerializable("serializable1", null).equals(mSerializableTest)); Assert.assertNull(mCacheUtils1.getSerializable("parcelable2", null)); Assert.assertTrue(mCacheUtils2.getSerializable("serializable2").equals(mSerializableTest)); Assert.assertTrue(mCacheUtils2.getSerializable("serializable2", null).equals(mSerializableTest)); Assert.assertNull(mCacheUtils2.getSerializable("parcelable1", null)); }
CacheUtils { public long getCacheSize() { return mCacheManager.getCacheSize(); } private CacheUtils(@NonNull File cacheDir, long maxSize, int maxCount); static CacheUtils getInstance(); static CacheUtils getInstance(String cacheName); static CacheUtils getInstance(long maxSize, int maxCount); static CacheUtils getInstance(String cacheName, long maxSize, int maxCount); static CacheUtils getInstance(@NonNull File cacheDir); static CacheUtils getInstance(@NonNull File cacheDir, long maxSize, int maxCount); void put(@NonNull String key, @NonNull byte[] value); void put(@NonNull String key, @NonNull byte[] value, int saveTime); byte[] getBytes(@NonNull String key); byte[] getBytes(@NonNull String key, byte[] defaultValue); void put(@NonNull String key, @NonNull String value); void put(@NonNull String key, @NonNull String value, int saveTime); String getString(@NonNull String key); String getString(@NonNull String key, String defaultValue); void put(@NonNull String key, @NonNull JSONObject value); void put(@NonNull String key, @NonNull JSONObject value, int saveTime); JSONObject getJSONObject(@NonNull String key); JSONObject getJSONObject(@NonNull String key, JSONObject defaultValue); void put(@NonNull String key, @NonNull JSONArray value); void put(@NonNull String key, @NonNull JSONArray value, int saveTime); JSONArray getJSONArray(@NonNull String key); JSONArray getJSONArray(@NonNull String key, JSONArray defaultValue); void put(@NonNull String key, @NonNull Bitmap value); void put(@NonNull String key, @NonNull Bitmap value, int saveTime); Bitmap getBitmap(@NonNull String key); Bitmap getBitmap(@NonNull String key, Bitmap defaultValue); void put(@NonNull String key, @NonNull Drawable value); void put(@NonNull String key, @NonNull Drawable value, int saveTime); Drawable getDrawable(@NonNull String key); Drawable getDrawable(@NonNull String key, Drawable defaultValue); void put(@NonNull String key, @NonNull Parcelable value); void put(@NonNull String key, @NonNull Parcelable value, int saveTime); T getParcelable(@NonNull String key, @NonNull Parcelable.Creator<T> creator); T getParcelable(@NonNull String key, @NonNull Parcelable.Creator<T> creator, T defaultValue); void put(@NonNull String key, @NonNull Serializable value); void put(@NonNull String key, @NonNull Serializable value, int saveTime); Object getSerializable(@NonNull String key); Object getSerializable(@NonNull String key, Object defaultValue); long getCacheSize(); int getCacheCount(); boolean remove(@NonNull String key); boolean clear(); static final int SEC; static final int MIN; static final int HOUR; static final int DAY; }
@Test public void getCacheSize() throws Exception { Assert.assertEquals(FileUtils.getDirLength(file1), mCacheUtils1.getCacheSize()); Assert.assertEquals(FileUtils.getDirLength(file2), mCacheUtils2.getCacheSize()); }
CacheUtils { public int getCacheCount() { return mCacheManager.getCacheCount(); } private CacheUtils(@NonNull File cacheDir, long maxSize, int maxCount); static CacheUtils getInstance(); static CacheUtils getInstance(String cacheName); static CacheUtils getInstance(long maxSize, int maxCount); static CacheUtils getInstance(String cacheName, long maxSize, int maxCount); static CacheUtils getInstance(@NonNull File cacheDir); static CacheUtils getInstance(@NonNull File cacheDir, long maxSize, int maxCount); void put(@NonNull String key, @NonNull byte[] value); void put(@NonNull String key, @NonNull byte[] value, int saveTime); byte[] getBytes(@NonNull String key); byte[] getBytes(@NonNull String key, byte[] defaultValue); void put(@NonNull String key, @NonNull String value); void put(@NonNull String key, @NonNull String value, int saveTime); String getString(@NonNull String key); String getString(@NonNull String key, String defaultValue); void put(@NonNull String key, @NonNull JSONObject value); void put(@NonNull String key, @NonNull JSONObject value, int saveTime); JSONObject getJSONObject(@NonNull String key); JSONObject getJSONObject(@NonNull String key, JSONObject defaultValue); void put(@NonNull String key, @NonNull JSONArray value); void put(@NonNull String key, @NonNull JSONArray value, int saveTime); JSONArray getJSONArray(@NonNull String key); JSONArray getJSONArray(@NonNull String key, JSONArray defaultValue); void put(@NonNull String key, @NonNull Bitmap value); void put(@NonNull String key, @NonNull Bitmap value, int saveTime); Bitmap getBitmap(@NonNull String key); Bitmap getBitmap(@NonNull String key, Bitmap defaultValue); void put(@NonNull String key, @NonNull Drawable value); void put(@NonNull String key, @NonNull Drawable value, int saveTime); Drawable getDrawable(@NonNull String key); Drawable getDrawable(@NonNull String key, Drawable defaultValue); void put(@NonNull String key, @NonNull Parcelable value); void put(@NonNull String key, @NonNull Parcelable value, int saveTime); T getParcelable(@NonNull String key, @NonNull Parcelable.Creator<T> creator); T getParcelable(@NonNull String key, @NonNull Parcelable.Creator<T> creator, T defaultValue); void put(@NonNull String key, @NonNull Serializable value); void put(@NonNull String key, @NonNull Serializable value, int saveTime); Object getSerializable(@NonNull String key); Object getSerializable(@NonNull String key, Object defaultValue); long getCacheSize(); int getCacheCount(); boolean remove(@NonNull String key); boolean clear(); static final int SEC; static final int MIN; static final int HOUR; static final int DAY; }
@Test public void getCacheCount() throws Exception { Assert.assertEquals(8, mCacheUtils1.getCacheCount()); Assert.assertEquals(8, mCacheUtils2.getCacheCount()); }
CacheUtils { public boolean remove(@NonNull String key) { return mCacheManager.removeByKey(key); } private CacheUtils(@NonNull File cacheDir, long maxSize, int maxCount); static CacheUtils getInstance(); static CacheUtils getInstance(String cacheName); static CacheUtils getInstance(long maxSize, int maxCount); static CacheUtils getInstance(String cacheName, long maxSize, int maxCount); static CacheUtils getInstance(@NonNull File cacheDir); static CacheUtils getInstance(@NonNull File cacheDir, long maxSize, int maxCount); void put(@NonNull String key, @NonNull byte[] value); void put(@NonNull String key, @NonNull byte[] value, int saveTime); byte[] getBytes(@NonNull String key); byte[] getBytes(@NonNull String key, byte[] defaultValue); void put(@NonNull String key, @NonNull String value); void put(@NonNull String key, @NonNull String value, int saveTime); String getString(@NonNull String key); String getString(@NonNull String key, String defaultValue); void put(@NonNull String key, @NonNull JSONObject value); void put(@NonNull String key, @NonNull JSONObject value, int saveTime); JSONObject getJSONObject(@NonNull String key); JSONObject getJSONObject(@NonNull String key, JSONObject defaultValue); void put(@NonNull String key, @NonNull JSONArray value); void put(@NonNull String key, @NonNull JSONArray value, int saveTime); JSONArray getJSONArray(@NonNull String key); JSONArray getJSONArray(@NonNull String key, JSONArray defaultValue); void put(@NonNull String key, @NonNull Bitmap value); void put(@NonNull String key, @NonNull Bitmap value, int saveTime); Bitmap getBitmap(@NonNull String key); Bitmap getBitmap(@NonNull String key, Bitmap defaultValue); void put(@NonNull String key, @NonNull Drawable value); void put(@NonNull String key, @NonNull Drawable value, int saveTime); Drawable getDrawable(@NonNull String key); Drawable getDrawable(@NonNull String key, Drawable defaultValue); void put(@NonNull String key, @NonNull Parcelable value); void put(@NonNull String key, @NonNull Parcelable value, int saveTime); T getParcelable(@NonNull String key, @NonNull Parcelable.Creator<T> creator); T getParcelable(@NonNull String key, @NonNull Parcelable.Creator<T> creator, T defaultValue); void put(@NonNull String key, @NonNull Serializable value); void put(@NonNull String key, @NonNull Serializable value, int saveTime); Object getSerializable(@NonNull String key); Object getSerializable(@NonNull String key, Object defaultValue); long getCacheSize(); int getCacheCount(); boolean remove(@NonNull String key); boolean clear(); static final int SEC; static final int MIN; static final int HOUR; static final int DAY; }
@Test public void remove() throws Exception { Assert.assertNotNull(mCacheUtils1.getString("string1")); mCacheUtils1.remove("string1"); Assert.assertNull(mCacheUtils1.getString("string1")); Assert.assertNotNull(mCacheUtils2.getString("string2")); mCacheUtils2.remove("string2"); Assert.assertNull(mCacheUtils2.getString("string2")); }
CacheUtils { public boolean clear() { return mCacheManager.clear(); } private CacheUtils(@NonNull File cacheDir, long maxSize, int maxCount); static CacheUtils getInstance(); static CacheUtils getInstance(String cacheName); static CacheUtils getInstance(long maxSize, int maxCount); static CacheUtils getInstance(String cacheName, long maxSize, int maxCount); static CacheUtils getInstance(@NonNull File cacheDir); static CacheUtils getInstance(@NonNull File cacheDir, long maxSize, int maxCount); void put(@NonNull String key, @NonNull byte[] value); void put(@NonNull String key, @NonNull byte[] value, int saveTime); byte[] getBytes(@NonNull String key); byte[] getBytes(@NonNull String key, byte[] defaultValue); void put(@NonNull String key, @NonNull String value); void put(@NonNull String key, @NonNull String value, int saveTime); String getString(@NonNull String key); String getString(@NonNull String key, String defaultValue); void put(@NonNull String key, @NonNull JSONObject value); void put(@NonNull String key, @NonNull JSONObject value, int saveTime); JSONObject getJSONObject(@NonNull String key); JSONObject getJSONObject(@NonNull String key, JSONObject defaultValue); void put(@NonNull String key, @NonNull JSONArray value); void put(@NonNull String key, @NonNull JSONArray value, int saveTime); JSONArray getJSONArray(@NonNull String key); JSONArray getJSONArray(@NonNull String key, JSONArray defaultValue); void put(@NonNull String key, @NonNull Bitmap value); void put(@NonNull String key, @NonNull Bitmap value, int saveTime); Bitmap getBitmap(@NonNull String key); Bitmap getBitmap(@NonNull String key, Bitmap defaultValue); void put(@NonNull String key, @NonNull Drawable value); void put(@NonNull String key, @NonNull Drawable value, int saveTime); Drawable getDrawable(@NonNull String key); Drawable getDrawable(@NonNull String key, Drawable defaultValue); void put(@NonNull String key, @NonNull Parcelable value); void put(@NonNull String key, @NonNull Parcelable value, int saveTime); T getParcelable(@NonNull String key, @NonNull Parcelable.Creator<T> creator); T getParcelable(@NonNull String key, @NonNull Parcelable.Creator<T> creator, T defaultValue); void put(@NonNull String key, @NonNull Serializable value); void put(@NonNull String key, @NonNull Serializable value, int saveTime); Object getSerializable(@NonNull String key); Object getSerializable(@NonNull String key, Object defaultValue); long getCacheSize(); int getCacheCount(); boolean remove(@NonNull String key); boolean clear(); static final int SEC; static final int MIN; static final int HOUR; static final int DAY; }
@Test public void clear() throws Exception { Assert.assertNotNull(mCacheUtils1.getBytes("bytes1")); Assert.assertNotNull(mCacheUtils1.getString("string1")); Assert.assertNotNull(mCacheUtils1.getJSONObject("jsonObject1")); Assert.assertNotNull(mCacheUtils1.getJSONArray("jsonArray1")); Assert.assertNotNull(mCacheUtils1.getString("bitmap1")); Assert.assertNotNull(mCacheUtils1.getString("drawable1")); Assert.assertNotNull(mCacheUtils1.getParcelable("parcelable1", ParcelableTest.CREATOR)); Assert.assertNotNull(mCacheUtils1.getSerializable("serializable1")); mCacheUtils1.clear(); Assert.assertNull(mCacheUtils1.getBytes("bytes1")); Assert.assertNull(mCacheUtils1.getString("string1")); Assert.assertNull(mCacheUtils1.getJSONObject("jsonObject1")); Assert.assertNull(mCacheUtils1.getJSONArray("jsonArray1")); Assert.assertNull(mCacheUtils1.getString("bitmap1")); Assert.assertNull(mCacheUtils1.getString("drawable1")); Assert.assertNull(mCacheUtils1.getParcelable("parcelable1", ParcelableTest.CREATOR)); Assert.assertNull(mCacheUtils1.getSerializable("serializable1")); Assert.assertNotNull(mCacheUtils2.getBytes("bytes2")); Assert.assertNotNull(mCacheUtils2.getString("string2")); Assert.assertNotNull(mCacheUtils2.getJSONObject("jsonObject2")); Assert.assertNotNull(mCacheUtils2.getJSONArray("jsonArray2")); Assert.assertNotNull(mCacheUtils2.getString("bitmap2")); Assert.assertNotNull(mCacheUtils2.getString("drawable2")); Assert.assertNotNull(mCacheUtils2.getParcelable("parcelable2", ParcelableTest.CREATOR)); Assert.assertNotNull(mCacheUtils2.getSerializable("serializable2")); mCacheUtils2.clear(); Assert.assertNull(mCacheUtils2.getBytes("bytes2")); Assert.assertNull(mCacheUtils2.getString("string2")); Assert.assertNull(mCacheUtils2.getJSONObject("jsonObject2")); Assert.assertNull(mCacheUtils2.getJSONArray("jsonArray2")); Assert.assertNull(mCacheUtils2.getString("bitmap2")); Assert.assertNull(mCacheUtils2.getString("drawable2")); Assert.assertNull(mCacheUtils2.getParcelable("parcelable2", ParcelableTest.CREATOR)); Assert.assertNull(mCacheUtils2.getSerializable("serializable2")); }
SPUtils { public String getString(@NonNull String key) { return getString(key, ""); } private SPUtils(String spName); static SPUtils getInstance(); static SPUtils getInstance(String spName); void put(@NonNull String key, @NonNull String value); String getString(@NonNull String key); String getString(@NonNull String key, @NonNull String defaultValue); void put(@NonNull String key, int value); int getInt(@NonNull String key); int getInt(@NonNull String key, int defaultValue); void put(@NonNull String key, long value); long getLong(@NonNull String key); long getLong(@NonNull String key, long defaultValue); void put(@NonNull String key, float value); float getFloat(@NonNull String key); float getFloat(@NonNull String key, float defaultValue); void put(@NonNull String key, boolean value); boolean getBoolean(@NonNull String key); boolean getBoolean(@NonNull String key, boolean defaultValue); void put(@NonNull String key, @NonNull Set<String> values); Set<String> getStringSet(@NonNull String key); Set<String> getStringSet(@NonNull String key, @NonNull Set<String> defaultValue); Map<String, ?> getAll(); boolean contains(@NonNull String key); void remove(@NonNull String key); void clear(); }
@Test public void getString() throws Exception { Assert.assertEquals("stringVal1", spUtils1.getString("stringKey1")); Assert.assertEquals("stringVal", spUtils1.getString("stringKey", "stringVal")); Assert.assertEquals("", spUtils1.getString("stringKey")); Assert.assertEquals("stringVal2", spUtils2.getString("stringKey2")); Assert.assertEquals("stringVal", spUtils2.getString("stringKey", "stringVal")); Assert.assertEquals("", spUtils2.getString("stringKey")); }
SPUtils { public int getInt(@NonNull String key) { return getInt(key, -1); } private SPUtils(String spName); static SPUtils getInstance(); static SPUtils getInstance(String spName); void put(@NonNull String key, @NonNull String value); String getString(@NonNull String key); String getString(@NonNull String key, @NonNull String defaultValue); void put(@NonNull String key, int value); int getInt(@NonNull String key); int getInt(@NonNull String key, int defaultValue); void put(@NonNull String key, long value); long getLong(@NonNull String key); long getLong(@NonNull String key, long defaultValue); void put(@NonNull String key, float value); float getFloat(@NonNull String key); float getFloat(@NonNull String key, float defaultValue); void put(@NonNull String key, boolean value); boolean getBoolean(@NonNull String key); boolean getBoolean(@NonNull String key, boolean defaultValue); void put(@NonNull String key, @NonNull Set<String> values); Set<String> getStringSet(@NonNull String key); Set<String> getStringSet(@NonNull String key, @NonNull Set<String> defaultValue); Map<String, ?> getAll(); boolean contains(@NonNull String key); void remove(@NonNull String key); void clear(); }
@Test public void getInt() throws Exception { Assert.assertEquals(1, spUtils1.getInt("intKey1")); Assert.assertEquals(2048, spUtils1.getInt("intKey", 2048)); Assert.assertEquals(-1, spUtils1.getInt("intKey")); Assert.assertEquals(2, spUtils2.getInt("intKey2")); Assert.assertEquals(2048, spUtils2.getInt("intKey", 2048)); Assert.assertEquals(-1, spUtils2.getInt("intKey")); }
SPUtils { public long getLong(@NonNull String key) { return getLong(key, -1L); } private SPUtils(String spName); static SPUtils getInstance(); static SPUtils getInstance(String spName); void put(@NonNull String key, @NonNull String value); String getString(@NonNull String key); String getString(@NonNull String key, @NonNull String defaultValue); void put(@NonNull String key, int value); int getInt(@NonNull String key); int getInt(@NonNull String key, int defaultValue); void put(@NonNull String key, long value); long getLong(@NonNull String key); long getLong(@NonNull String key, long defaultValue); void put(@NonNull String key, float value); float getFloat(@NonNull String key); float getFloat(@NonNull String key, float defaultValue); void put(@NonNull String key, boolean value); boolean getBoolean(@NonNull String key); boolean getBoolean(@NonNull String key, boolean defaultValue); void put(@NonNull String key, @NonNull Set<String> values); Set<String> getStringSet(@NonNull String key); Set<String> getStringSet(@NonNull String key, @NonNull Set<String> defaultValue); Map<String, ?> getAll(); boolean contains(@NonNull String key); void remove(@NonNull String key); void clear(); }
@Test public void getLong() throws Exception { Assert.assertEquals(1L, spUtils1.getLong("longKey1")); Assert.assertEquals(2048L, spUtils1.getLong("longKey", 2048)); Assert.assertEquals(-1L, spUtils1.getLong("longKey")); Assert.assertEquals(2L, spUtils2.getLong("longKey2")); Assert.assertEquals(2048L, spUtils2.getLong("longKey", 2048)); Assert.assertEquals(-1L, spUtils2.getLong("longKey")); }
SPUtils { public float getFloat(@NonNull String key) { return getFloat(key, -1f); } private SPUtils(String spName); static SPUtils getInstance(); static SPUtils getInstance(String spName); void put(@NonNull String key, @NonNull String value); String getString(@NonNull String key); String getString(@NonNull String key, @NonNull String defaultValue); void put(@NonNull String key, int value); int getInt(@NonNull String key); int getInt(@NonNull String key, int defaultValue); void put(@NonNull String key, long value); long getLong(@NonNull String key); long getLong(@NonNull String key, long defaultValue); void put(@NonNull String key, float value); float getFloat(@NonNull String key); float getFloat(@NonNull String key, float defaultValue); void put(@NonNull String key, boolean value); boolean getBoolean(@NonNull String key); boolean getBoolean(@NonNull String key, boolean defaultValue); void put(@NonNull String key, @NonNull Set<String> values); Set<String> getStringSet(@NonNull String key); Set<String> getStringSet(@NonNull String key, @NonNull Set<String> defaultValue); Map<String, ?> getAll(); boolean contains(@NonNull String key); void remove(@NonNull String key); void clear(); }
@Test public void getFloat() throws Exception { Assert.assertEquals(1f, spUtils1.getFloat("floatKey1"), 0f); Assert.assertEquals(2048f, spUtils1.getFloat("floatKey", 2048f), 0f); Assert.assertEquals(-1f, spUtils1.getFloat("floatKey"), 0f); Assert.assertEquals(2f, spUtils2.getFloat("floatKey2"), 0f); Assert.assertEquals(2048f, spUtils2.getFloat("floatKey", 2048f), 0f); Assert.assertEquals(-1f, spUtils2.getFloat("floatKey"), 0f); }
SPUtils { public boolean getBoolean(@NonNull String key) { return getBoolean(key, false); } private SPUtils(String spName); static SPUtils getInstance(); static SPUtils getInstance(String spName); void put(@NonNull String key, @NonNull String value); String getString(@NonNull String key); String getString(@NonNull String key, @NonNull String defaultValue); void put(@NonNull String key, int value); int getInt(@NonNull String key); int getInt(@NonNull String key, int defaultValue); void put(@NonNull String key, long value); long getLong(@NonNull String key); long getLong(@NonNull String key, long defaultValue); void put(@NonNull String key, float value); float getFloat(@NonNull String key); float getFloat(@NonNull String key, float defaultValue); void put(@NonNull String key, boolean value); boolean getBoolean(@NonNull String key); boolean getBoolean(@NonNull String key, boolean defaultValue); void put(@NonNull String key, @NonNull Set<String> values); Set<String> getStringSet(@NonNull String key); Set<String> getStringSet(@NonNull String key, @NonNull Set<String> defaultValue); Map<String, ?> getAll(); boolean contains(@NonNull String key); void remove(@NonNull String key); void clear(); }
@Test public void getBoolean() throws Exception { Assert.assertTrue(spUtils1.getBoolean("booleanKey1")); Assert.assertTrue(spUtils1.getBoolean("booleanKey", true)); Assert.assertFalse(spUtils1.getBoolean("booleanKey")); Assert.assertTrue(spUtils2.getBoolean("booleanKey2")); Assert.assertTrue(spUtils2.getBoolean("booleanKey", true)); Assert.assertFalse(spUtils2.getBoolean("booleanKey")); }
SPUtils { public Map<String, ?> getAll() { return sp.getAll(); } private SPUtils(String spName); static SPUtils getInstance(); static SPUtils getInstance(String spName); void put(@NonNull String key, @NonNull String value); String getString(@NonNull String key); String getString(@NonNull String key, @NonNull String defaultValue); void put(@NonNull String key, int value); int getInt(@NonNull String key); int getInt(@NonNull String key, int defaultValue); void put(@NonNull String key, long value); long getLong(@NonNull String key); long getLong(@NonNull String key, long defaultValue); void put(@NonNull String key, float value); float getFloat(@NonNull String key); float getFloat(@NonNull String key, float defaultValue); void put(@NonNull String key, boolean value); boolean getBoolean(@NonNull String key); boolean getBoolean(@NonNull String key, boolean defaultValue); void put(@NonNull String key, @NonNull Set<String> values); Set<String> getStringSet(@NonNull String key); Set<String> getStringSet(@NonNull String key, @NonNull Set<String> defaultValue); Map<String, ?> getAll(); boolean contains(@NonNull String key); void remove(@NonNull String key); void clear(); }
@Test public void getAll() throws Exception { Map<String, ?> map; System.out.println("sp1 {"); map = spUtils1.getAll(); for (Map.Entry<String, ?> entry : map.entrySet()) { System.out.println(" " + entry.getKey() + ": " + entry.getValue()); } System.out.println("}"); System.out.println("sp2 {"); map = spUtils2.getAll(); for (Map.Entry<String, ?> entry : map.entrySet()) { System.out.println(" " + entry.getKey() + ": " + entry.getValue()); } System.out.println("}"); }
SPUtils { public void remove(@NonNull String key) { sp.edit().remove(key).apply(); } private SPUtils(String spName); static SPUtils getInstance(); static SPUtils getInstance(String spName); void put(@NonNull String key, @NonNull String value); String getString(@NonNull String key); String getString(@NonNull String key, @NonNull String defaultValue); void put(@NonNull String key, int value); int getInt(@NonNull String key); int getInt(@NonNull String key, int defaultValue); void put(@NonNull String key, long value); long getLong(@NonNull String key); long getLong(@NonNull String key, long defaultValue); void put(@NonNull String key, float value); float getFloat(@NonNull String key); float getFloat(@NonNull String key, float defaultValue); void put(@NonNull String key, boolean value); boolean getBoolean(@NonNull String key); boolean getBoolean(@NonNull String key, boolean defaultValue); void put(@NonNull String key, @NonNull Set<String> values); Set<String> getStringSet(@NonNull String key); Set<String> getStringSet(@NonNull String key, @NonNull Set<String> defaultValue); Map<String, ?> getAll(); boolean contains(@NonNull String key); void remove(@NonNull String key); void clear(); }
@Test public void testRemove() throws Exception { Assert.assertEquals("stringVal1", spUtils1.getString("stringKey1")); spUtils1.remove("stringKey1"); Assert.assertEquals("", spUtils1.getString("stringKey1")); Assert.assertEquals("stringVal2", spUtils2.getString("stringKey2")); spUtils2.remove("stringKey2"); Assert.assertEquals("", spUtils2.getString("stringKey2")); }
SPUtils { public boolean contains(@NonNull String key) { return sp.contains(key); } private SPUtils(String spName); static SPUtils getInstance(); static SPUtils getInstance(String spName); void put(@NonNull String key, @NonNull String value); String getString(@NonNull String key); String getString(@NonNull String key, @NonNull String defaultValue); void put(@NonNull String key, int value); int getInt(@NonNull String key); int getInt(@NonNull String key, int defaultValue); void put(@NonNull String key, long value); long getLong(@NonNull String key); long getLong(@NonNull String key, long defaultValue); void put(@NonNull String key, float value); float getFloat(@NonNull String key); float getFloat(@NonNull String key, float defaultValue); void put(@NonNull String key, boolean value); boolean getBoolean(@NonNull String key); boolean getBoolean(@NonNull String key, boolean defaultValue); void put(@NonNull String key, @NonNull Set<String> values); Set<String> getStringSet(@NonNull String key); Set<String> getStringSet(@NonNull String key, @NonNull Set<String> defaultValue); Map<String, ?> getAll(); boolean contains(@NonNull String key); void remove(@NonNull String key); void clear(); }
@Test public void testContains() throws Exception { Assert.assertTrue(spUtils1.contains("stringKey1")); Assert.assertFalse(spUtils1.contains("stringKey")); Assert.assertTrue(spUtils2.contains("stringKey2")); Assert.assertFalse(spUtils2.contains("stringKey")); }
SPUtils { public void clear() { sp.edit().clear().apply(); } private SPUtils(String spName); static SPUtils getInstance(); static SPUtils getInstance(String spName); void put(@NonNull String key, @NonNull String value); String getString(@NonNull String key); String getString(@NonNull String key, @NonNull String defaultValue); void put(@NonNull String key, int value); int getInt(@NonNull String key); int getInt(@NonNull String key, int defaultValue); void put(@NonNull String key, long value); long getLong(@NonNull String key); long getLong(@NonNull String key, long defaultValue); void put(@NonNull String key, float value); float getFloat(@NonNull String key); float getFloat(@NonNull String key, float defaultValue); void put(@NonNull String key, boolean value); boolean getBoolean(@NonNull String key); boolean getBoolean(@NonNull String key, boolean defaultValue); void put(@NonNull String key, @NonNull Set<String> values); Set<String> getStringSet(@NonNull String key); Set<String> getStringSet(@NonNull String key, @NonNull Set<String> defaultValue); Map<String, ?> getAll(); boolean contains(@NonNull String key); void remove(@NonNull String key); void clear(); }
@Test public void clear() throws Exception { spUtils1.clear(); Assert.assertEquals("", spUtils1.getString("stringKey1")); Assert.assertEquals(-1, spUtils1.getInt("intKey1")); Assert.assertEquals(-1L, spUtils1.getLong("longKey1")); Assert.assertEquals(-1f, spUtils1.getFloat("floatKey1"), 0f); Assert.assertFalse(spUtils1.getBoolean("booleanKey1")); spUtils2.clear(); Assert.assertEquals("", spUtils2.getString("stringKey2")); Assert.assertEquals(-1, spUtils2.getInt("intKey2")); Assert.assertEquals(-1L, spUtils2.getLong("longKey1")); Assert.assertEquals(-1f, spUtils2.getFloat("floatKey1"), 0f); Assert.assertFalse(spUtils2.getBoolean("booleanKey1")); }
ProxyConfig { public String getProxyHost() { return proxyHost; } ProxyConfig(PropertyLoader propertyLoader); boolean isProxyRequired(); String getProxyType(); String getProxyHost(); int getProxyPort(); String getProxyAddress(); String getProxyUsername(); String getProxyPassword(); String getNonProxyHosts(); }
@Test public void proxySettingsObtainedInOrder() { Properties properties = givenDefaultProperties(); environmentVariables.set("HTTP_PROXY", "http: ProxyConfig proxyConfig = new ProxyConfig(new DefaultPropertyLoader(properties)); assertThat(proxyConfig.getProxyHost(), is("proxyhost3")); System.setProperty("http.proxyHost", "proxyhost2"); proxyConfig = new ProxyConfig(new DefaultPropertyLoader(properties)); assertThat(proxyConfig.getProxyHost(), is("proxyhost2")); given(properties.getProperty("proxy.host")).willReturn("proxyhost1"); proxyConfig = new ProxyConfig(new DefaultPropertyLoader(properties)); assertThat(proxyConfig.getProxyHost(), is("proxyhost1")); }
ConcordionBrowserFixture extends ConcordionFixture implements BrowserBasedTest { @Override public Browser getBrowser() { return getBrowser(threadBrowserId.get()); } static void setScreenshotTakerClass(Class<? extends ScreenshotTaker> screenshotTaker); @Override Browser getBrowser(); Browser getBrowser(String key); Browser getBrowser(String key, BrowserProvider browserProvider); void switchBrowser(String key); void switchBrowser(String key, BrowserProvider browserProvider); @AfterSuite void resetThreadBrowsers(); }
@Test public void closesMultipleDriversForSingleBrowserProvider() throws IOException { BrowserProvider mockProvider = mock(BrowserProvider.class); WebDriver mockDriver = mock(WebDriver.class); when(mockProvider.createDriver()).thenReturn(mockDriver); Browser browser1 = test1.getBrowser("A", mockProvider); browser1.getDriver(); Browser browser2 = test1.getBrowser("B", mockProvider); browser2.getDriver(); test1.closeSuiteResources(); verify(mockProvider, times(1)).close(); verify(mockDriver, times(2)).quit(); } @Test public void closesMultipleDriversAndBrowserProviders() throws IOException { BrowserProvider mockProvider1 = mock(BrowserProvider.class); WebDriver mockDriver1 = mock(WebDriver.class); when(mockProvider1.createDriver()).thenReturn(mockDriver1); BrowserProvider mockProvider2 = mock(BrowserProvider.class); WebDriver mockDriver2 = mock(WebDriver.class); when(mockProvider2.createDriver()).thenReturn(mockDriver2); Browser browser1 = test1.getBrowser("E", mockProvider1); browser1.getDriver(); Browser browser2 = test1.getBrowser("F", mockProvider1); browser2.getDriver(); Browser browser3 = test1.getBrowser("G", mockProvider2); browser3.getDriver(); test1.closeSuiteResources(); verify(mockProvider1, times(1)).close(); verify(mockDriver1, times(2)).quit(); verify(mockProvider2, times(1)).close(); verify(mockDriver2, times(1)).quit(); } @Test public void runningTestsAsSeparateSuites_browsersAreNotReused() { BrowserProvider mockProvider = mock(BrowserProvider.class); ConcordionBrowserFixture test = this.test1; Browser browser1 = test.getBrowser("X", mockProvider); afterSuite(test); ConcordionBrowserFixture test2 = new ConcordionBrowserFixture() {}; Browser browser2 = test2.getBrowser("X", mockProvider); afterSuite(test2); assertThat(browser1, is(not(browser2))); } @Test public void reusesBrowsersForSameKey() { BrowserProvider mockProvider = mock(BrowserProvider.class); Browser browser1 = test1.getBrowser("X", mockProvider); Browser browser2 = test1.getBrowser("X", mockProvider); assertThat(browser1, is(browser2)); }
PageHelper { public <P extends BasePageObject<P>> P newInstance(Class<P> expectedPage, Object... params) { try { if (params.length > 0) { Class<?>[] constructorArguments = new Class<?>[2]; constructorArguments[0] = BrowserBasedTest.class; constructorArguments[1] = Object[].class; return expectedPage.getDeclaredConstructor(constructorArguments).newInstance(getTest(), params); } else { return expectedPage.getDeclaredConstructor(BrowserBasedTest.class).newInstance(getTest()); } } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e) { if (e.getMessage() == null && e.getCause() != null) { throw new RuntimeException(e.getCause()); } else { throw new RuntimeException(e); } } } PageHelper(BasePageObject<?> pageObject); PageHelper(BasePageObject<?> pageObject, Class<?> logLocation); void triggerCheckPage(WebElement triggerElement, String tag); void checkWindow(String tag); void checkRegion(WebElement region, String tag); boolean isElementPresent(WebElement element); boolean isElementVisible(WebElement element); static boolean isElementPresent(WebDriver driver, By by); static boolean isElementVisible(WebDriver driver, By by); void capturePage(WebElement element); void capturePage(WebElement element, String description); void capturePage(ScreenshotTaker screenshotTaker, String description); void capturePage(WebElement element, String description, CardResult result); P capturePageAndClick(WebElement element, Class<P> expectedPage, Object... params); P capturePageAndClick(WebElement element, String description, Class<P> expectedPage, Object... params); P capturePageAndClick(WebElement element, int timeoutSeconds, String description, Class<P> expectedPage, Object... params); void waitForElementToClickable(WebElement webElement, int timeOutInSeconds); P newInstance(Class<P> expectedPage, Object... params); WebElement getFirstVisibleElement(List<WebElement> webElements); String getCurrentFrameNameOrId(); static String getCurrentFrameNameOrId(WebDriver driver); static WebElement getCurrentFrame(WebDriver driver); void switchToMainDocument(); static void switchToMainDocument(WebDriver driver); void acceptAlertIfPresent(); static void acceptAlertIfPresent(WebDriver driver); static void waitUntil(WebDriver driver, ExpectedCondition<?> condition, int timeOutInSeconds); }
@Test public void canCreateInstanceOfPageObjectUsingBBTOnly() { PageHelper tpo = setUpMocks(); TestPageObject testPageObject = tpo.newInstance(TestPageObject.class); assertNotNull("Should not be null when constructing instance of " + TestPageObject.class.getName(), testPageObject); } @Test public void canCreateInstanceOfPageObjectUsingBBTPlusMultipleParams() { PageHelper tpo = setUpMocks(); TestPageObject testPageObject = tpo.newInstance(TestPageObject.class, "HelloWorld", 1); assertNotNull("Should not be null when constructing instance of " + TestPageObject.class.getName() + " and optional parameters", testPageObject); } @Test public void shouldFailAsNoParamsConstructorForPageObject() { PageHelper tpo = setUpMocks(); thrown.expect(RuntimeException.class); thrown.expectCause(allOf( instanceOf(NoSuchMethodException.class), hasProperty("message", is("org.concordion.cubano.driver.web.TestPageObjectNoParams.<init>(org.concordion.cubano.driver.BrowserBasedTest, [Ljava.lang.Object;)")))); tpo.newInstance(TestPageObjectNoParams.class, "ShouldFailAsNoParamsConstructor"); } @Test public void canCreateInstanceOfPageObjectWhichOnlyHasBBTConstructor() { PageHelper tpo = setUpMocks(); TestPageObjectNoParams testPageObjectNoParams = tpo.newInstance(TestPageObjectNoParams.class); assertNotNull("Should not be null when constructing instance of " + TestPageObjectNoParams.class.getName() + " and class has Browser Based Test Constructor Only", testPageObjectNoParams); }
CaselessProperties extends Properties { @Override public synchronized Object put(Object key, Object value) { lookup.put(((String) key), (String) key); return super.put(key, value); } @Override synchronized Object put(Object key, Object value); @Override String getProperty(String key); @Override String getProperty(String key, String defaultValue); }
@Test public void propertyKeyOriginalCaseIsAvailalbe() { Properties properties = new CaselessProperties(); properties.put("a.SETTING", "value"); @SuppressWarnings("unchecked") Enumeration<String> en = (Enumeration<String>) properties.propertyNames(); String propName = en.nextElement(); assertThat(propName, is("a.SETTING")); }
DefaultPropertyLoader implements PropertyLoader { @Override public String getProperty(String key) { String value = retrieveProperty(key); if (value.isEmpty()) { throw new IllegalArgumentException(String.format("Unable to find property %s", key)); } return value; } DefaultPropertyLoader(Properties properties); String getEnvironment(); @Override String getProperty(String key); @Override String getProperty(String key, String defaultValue); @Override boolean getPropertyAsBoolean(String key, String defaultValue); @Override int getPropertyAsInteger(String key, String defaultValue); @Override Map<String, String> getPropertiesStartingWith(String keyPrefix); @Override Map<String, String> getPropertiesStartingWith(String keyPrefix, boolean trimPrefix); }
@Test public void environmentPropertiesOverrideDefaultProperties() { Properties properties = givenDefaultProperties(); given(properties.getProperty("a.setting")).willReturn("false"); given(properties.getProperty("SIT.a.setting")).willReturn("true"); DefaultPropertyLoader loader = new DefaultPropertyLoader(properties); assertThat(loader.getProperty("a.setting"), is("false")); given(properties.getProperty(eq("environment"), any())).willReturn("SIT"); loader = new DefaultPropertyLoader(properties); assertThat(loader.getProperty("a.setting"), is("true")); }
DefaultPropertyLoader implements PropertyLoader { public String getEnvironment() { return environment; } DefaultPropertyLoader(Properties properties); String getEnvironment(); @Override String getProperty(String key); @Override String getProperty(String key, String defaultValue); @Override boolean getPropertyAsBoolean(String key, String defaultValue); @Override int getPropertyAsInteger(String key, String defaultValue); @Override Map<String, String> getPropertiesStartingWith(String keyPrefix); @Override Map<String, String> getPropertiesStartingWith(String keyPrefix, boolean trimPrefix); }
@Test public void systemPropertyWillOverrideEnvironment() throws Exception { Properties properties = givenDefaultProperties(); System.setProperty("environment", "SIT"); DefaultPropertyLoader loader = new DefaultPropertyLoader(properties); assertThat(loader.getEnvironment(), is("SIT")); }
DefaultPropertyLoader implements PropertyLoader { @Override public Map<String, String> getPropertiesStartingWith(String keyPrefix) { return getPropertiesStartingWith(keyPrefix, false); } DefaultPropertyLoader(Properties properties); String getEnvironment(); @Override String getProperty(String key); @Override String getProperty(String key, String defaultValue); @Override boolean getPropertyAsBoolean(String key, String defaultValue); @Override int getPropertyAsInteger(String key, String defaultValue); @Override Map<String, String> getPropertiesStartingWith(String keyPrefix); @Override Map<String, String> getPropertiesStartingWith(String keyPrefix, boolean trimPrefix); }
@Test public void canSearchForPopertiesWithPrefixMatchingCase() throws IOException { Properties properties = givenDefaultSearchProperties(); DefaultPropertyLoader loader = new DefaultPropertyLoader(properties); Map<String, String> found = loader.getPropertiesStartingWith("a.setting."); assertThat(found.values().size(), is(1)); assertThat(found.keySet().iterator().next(), is("a.setting.2")); } @Test public void canSearchForPopertiesAngGetOriginalPropertyCase() throws IOException { Properties properties = givenDefaultSearchProperties(); DefaultPropertyLoader loader = new DefaultPropertyLoader(properties); Map<String, String> found = loader.getPropertiesStartingWith("a."); assertThat(found.values().size(), is(2)); assertThat(found.keySet().iterator().next(), is("a.SETTING.1")); } @Test public void canSearchForPopertiesAngGetKeysWithoutPrefix() throws IOException { Properties properties = givenDefaultSearchProperties(); DefaultPropertyLoader loader = new DefaultPropertyLoader(properties); Map<String, String> found = loader.getPropertiesStartingWith("a.setting.", true); assertThat(found.values().size(), is(1)); assertThat(found.keySet().iterator().next(), is("2")); }
DefaultPropertiesLoader implements PropertiesLoader { @Override public Properties getProperties() { return properties; } protected DefaultPropertiesLoader(String properties, String userProperties); private DefaultPropertiesLoader(); static DefaultPropertiesLoader getInstance(); @Override Properties getProperties(); }
@Test public void userPropertiesOverrideConfigProperties() { String defaultProperties = "a.setting=false"; String userProperties = "a.setting=true"; Properties properties = new DefaultPropertiesLoader(defaultProperties, "").getProperties(); assertThat(properties.getProperty("a.setting"), is("false")); properties = new DefaultPropertiesLoader(defaultProperties, userProperties).getProperties(); assertThat(properties.getProperty("a.setting"), is("true")); }
ConcordionBase implements ResourceRegistry { @Override public boolean isRegistered(Closeable resource, ResourceScope scope) { return getResourcePairFromScope(resource, scope).isPresent(); } @Override void registerCloseableResource(Closeable resource, ResourceScope scope); @Override void registerCloseableResource(Closeable resource, ResourceScope scope, CloseListener listener); @Override boolean isRegistered(Closeable resource, ResourceScope scope); @Override void closeResource(Closeable resource); }
@Test public void isRegisteredReturnsFalseIfNotRegistered() { assertFalse(test1.isRegistered(resource0, ResourceScope.SPECIFICATION)); }
PrometheusMetricsReporter extends AbstractMetricsReporter implements MetricsReporter { @Override public void reportSpan(SpanData spanData) { String[] labelValues = getLabelValues(spanData); if (labelValues != null) { this.histogram.labels(labelValues).observe(spanData.getDuration() / (double)1000000); } } private PrometheusMetricsReporter(String name, CollectorRegistry registry, List<MetricLabel> labels); @Override void reportSpan(SpanData spanData); static Builder newMetricsReporter(); }
@Test public void testReportSpan() { PrometheusMetricsReporter reporter = PrometheusMetricsReporter.newMetricsReporter() .withCollectorRegistry(collectorRegistry) .withConstLabel("span.kind", Tags.SPAN_KIND_CLIENT) .build(); Map<String,Object> spanTags = new HashMap<String,Object>(); spanTags.put(Tags.SPAN_KIND.getKey(), Tags.SPAN_KIND_CLIENT); SpanData spanData = mock(SpanData.class); when(spanData.getOperationName()).thenReturn("testop"); when(spanData.getTags()).thenReturn(spanTags); when(spanData.getDuration()).thenReturn(100000L); reporter.reportSpan(spanData); List<MetricFamilySamples> samples = reporter.getHistogram().collect(); assertEquals(1, samples.size()); assertEquals(17, samples.get(0).samples.size()); for (int i=0; i < samples.get(0).samples.size(); i++) { Sample sample = samples.get(0).samples.get(i); assertEquals("testop", sample.labelValues.get(0)); List<String> labelNames = new ArrayList<String>(sample.labelNames); if (labelNames.get(labelNames.size()-1).equals("le")) { labelNames.remove(labelNames.size()-1); if (sample.labelValues.get(sample.labelNames.size()-1).equals("+Inf")) { assertEquals(1, (int)sample.value); } } assertEquals(Arrays.asList(reporter.getLabelNames()), labelNames); } }
Metrics { public static Tracer decorate(Tracer tracer, MetricsReporter reporter) { return decorate(tracer, Collections.singleton(reporter)); } static Tracer decorate(Tracer tracer, MetricsReporter reporter); static Tracer decorate(Tracer tracer, Set<MetricsReporter> reporters); }
@Test public void testAsChildOf() { MetricsReporter reporter = Mockito.mock(MetricsReporter.class); MockTracer tracer = new MockTracer(); Tracer metricsTracer = Metrics.decorate(tracer, reporter); Scope parentSpan = metricsTracer.buildSpan("parent") .withTag("spanName","parent") .startActive(true); parentSpan.span().setTag("additionalTag", "parent"); Scope childSpan = metricsTracer.buildSpan("child") .asChildOf(parentSpan.span()) .withTag("spanName","child") .startActive(true); childSpan.span().setTag("additionalTag", "child"); childSpan.close(); parentSpan.close(); List<MockSpan> spans = tracer.finishedSpans(); assertEquals(2, spans.size()); MockSpan span1 = spans.get(0); MockSpan span2 = spans.get(1); MockSpan parent, child; if (span1.operationName().equals("parent")) { parent = span1; child = span2; } else { parent = span2; child = span1; } assertEquals("Child's parent id should be spanId of parent", child.parentId(), parent.context().spanId()); assertEquals(0, parent.parentId()); } @Test public void testStandardUsage() { Map<String,Object> sysTags = new HashMap<String,Object>(); sysTags.put("service", "TestService"); MetricsReporter reporter = Mockito.mock(MetricsReporter.class); MockTracer tracer = new MockTracer(); Tracer metricsTracer = Metrics.decorate(tracer, reporter); Scope parent = metricsTracer.buildSpan("parent").withTag("spanName","parent").startActive(true); parent.span().setTag("additionalTag", "parent"); Scope child = metricsTracer.buildSpan("child").withTag("spanName","child").startActive(true); child.span().setTag("additionalTag", "child"); assertEquals(0, tracer.finishedSpans().size()); child.close(); assertEquals(1, tracer.finishedSpans().size()); parent.close(); List<MockSpan> spans = tracer.finishedSpans(); assertEquals(2, spans.size()); Mockito.verify(reporter, Mockito.times(2)).reportSpan(spanDataCaptor.capture()); List<SpanData> captured = spanDataCaptor.getAllValues(); assertEquals(captured.size(), spans.size()); for (int i=0; i < spans.size(); i++) { MockSpan span = spans.get(i); assertEquals(span.operationName(), span.tags().get("spanName")); assertEquals(span.operationName(), span.tags().get("additionalTag")); } assertTrue(captured.get(0).getDuration() < captured.get(1).getDuration()); assertEquals("child", captured.get(0).getOperationName()); assertEquals("parent", captured.get(1).getOperationName()); assertEquals(tracer.finishedSpans().get(0).tags(), captured.get(0).getTags()); assertEquals(tracer.finishedSpans().get(1).tags(), captured.get(1).getTags()); } @Test public void testWithTags() { MetricsReporter reporter = Mockito.mock(MetricsReporter.class); MockTracer tracer = new MockTracer(); Tracer metricsTracer = Metrics.decorate(tracer, reporter); Scope parent = metricsTracer.buildSpan("parent") .withTag("booleanTag", true) .withTag("numericTag", new Integer(100)) .startActive(true); parent.close(); List<MockSpan> spans = tracer.finishedSpans(); assertEquals(1, spans.size()); MockSpan span = spans.get(0); Map<String, Object> tags = span.tags(); Object booleanTag = tags.get("booleanTag"); assertNotNull("Expected a tag named 'booleanTag'", booleanTag); assertTrue("booleanTag should be a Boolean", booleanTag instanceof Boolean); assertEquals("booleanTag should be true", true, booleanTag); Object numericTag = tags.get("numericTag"); assertNotNull("Expected a tag named 'numericTag'", numericTag); assertTrue("numericTag should be a Number", numericTag instanceof Number); assertEquals("numericTag should be 100", 100, numericTag); } @Test public void testWithStartTimestamp() throws InterruptedException { MetricsReporter reporter = Mockito.mock(MetricsReporter.class); MockTracer tracer = new MockTracer(); Tracer metricsTracer = Metrics.decorate(tracer, reporter); long start = System.currentTimeMillis() * 687; Thread.sleep(100); Scope parent = metricsTracer.buildSpan("parent") .withStartTimestamp(start) .startActive(true); parent.close(); List<MockSpan> spans = tracer.finishedSpans(); assertEquals(1, spans.size()); MockSpan span = spans.get(0); long started = span.startMicros(); assertEquals(start, started); }
MicrometerMetricsReporter extends AbstractMetricsReporter implements MetricsReporter { @Override public void reportSpan(SpanData spanData) { boolean skip = Arrays.stream(this.metricLabels).anyMatch(m -> m.value(spanData) == null); if (skip) { return; } List<Tag> tags = Arrays.stream(this.metricLabels) .map(m -> new ImmutableTag(m.name(), m.value(spanData).toString())) .collect(Collectors.toList()); Timer timer = this.registry.find(this.name).tags(tags).timer(); if (null != timer) { timer.record(spanData.getDuration(), TimeUnit.MICROSECONDS); return; } Timer.Builder builder = Timer.builder(this.name).tags(tags); if (publishPercentileHistogram) { builder.publishPercentileHistogram(); } if (null != percentiles) { builder.publishPercentiles(percentiles); } if (null != sla) { builder.sla(sla); } if (null != minimumExpectedValue) { builder.minimumExpectedValue(minimumExpectedValue); } if (null != maximumExpectedValue) { builder.maximumExpectedValue(maximumExpectedValue); } builder.register(this.registry).record(spanData.getDuration(), TimeUnit.MICROSECONDS); } protected MicrometerMetricsReporter(String name, List<MetricLabel> labels, MeterRegistry registry, Duration sla, Duration minimumExpectedValue, Duration maximumExpectedValue, boolean publishPercentileHistogram, double... percentiles); @Override void reportSpan(SpanData spanData); static Builder newMetricsReporter(); }
@Test public void testReportSpan() { SpanData spanData = defaultMockSpanData(); when(spanData.getTags()).thenReturn(Collections.singletonMap(Tags.SPAN_KIND.getKey(), Tags.SPAN_KIND_CLIENT)); MicrometerMetricsReporter reporter = MicrometerMetricsReporter.newMetricsReporter() .withConstLabel("span.kind", Tags.SPAN_KIND_CLIENT) .build(); reporter.reportSpan(spanData); List<Tag> tags = defaultTags(); assertEquals(100, (long) registry.find("span").timer().totalTime(TimeUnit.MILLISECONDS)); assertEquals(1, Metrics.timer("span", tags).count()); }
PrometheusMetricsReporter extends AbstractMetricsReporter implements MetricsReporter { protected static String convertLabel(String label) { StringBuilder builder = new StringBuilder(label); for (int i=0; i < builder.length(); i++) { char ch = builder.charAt(i); if (!(ch == '_' || ch == ':' || Character.isLetter(ch) || (i > 0 && Character.isDigit(ch)))) { builder.setCharAt(i, '_'); } } return builder.toString(); } private PrometheusMetricsReporter(String name, CollectorRegistry registry, List<MetricLabel> labels); @Override void reportSpan(SpanData spanData); static Builder newMetricsReporter(); }
@Test public void testConvertLabel() { assertEquals("Hello9", PrometheusMetricsReporter.convertLabel("Hello9")); assertEquals("Hello_there", PrometheusMetricsReporter.convertLabel("Hello there")); assertEquals("_tag1", PrometheusMetricsReporter.convertLabel("1tag1")); assertEquals("tag_:_", PrometheusMetricsReporter.convertLabel("tag£:%")); }
TagMetricLabel implements MetricLabel { @Override public Object value(SpanData spanData) { Object ret = spanData.getTags().get(name()); return ret == null ? defaultValue : ret; } TagMetricLabel(String name, Object defaultValue); @Override String name(); @Override Object defaultValue(); @Override Object value(SpanData spanData); }
@Test public void testLabelFromTagWithValue() { MetricLabel label = new TagMetricLabel(TEST_LABEL, TEST_LABEL_DEFAULT); Map<String,Object> tags = new HashMap<String,Object>(); tags.put(TEST_LABEL, "TagValue"); SpanData spanData = mock(SpanData.class); when(spanData.getTags()).thenReturn(tags); assertEquals("TagValue", label.value(spanData)); } @Test public void testLabelFromTagWithNull() { MetricLabel label = new TagMetricLabel(TEST_LABEL, TEST_LABEL_DEFAULT); Map<String,Object> tags = new HashMap<String,Object>(); tags.put(TEST_LABEL, null); SpanData spanData = mock(SpanData.class); when(spanData.getTags()).thenReturn(tags); assertEquals(TEST_LABEL_DEFAULT, label.value(spanData)); }
BaggageMetricLabel implements MetricLabel { @Override public Object value(SpanData spanData) { Object ret = spanData.getBaggageItem(name()); return ret == null ? defaultValue : ret; } BaggageMetricLabel(String name, Object defaultValue); @Override String name(); @Override Object defaultValue(); @Override Object value(SpanData spanData); }
@Test public void testLabelFromBaggage() { MetricLabel label = new BaggageMetricLabel(TEST_LABEL, TEST_LABEL_DEFAULT); SpanData spanData = mock(SpanData.class); when(spanData.getBaggageItem(anyString())).thenReturn("BaggageValue"); assertEquals("BaggageValue", label.value(spanData)); verify(spanData, times(1)).getBaggageItem(TEST_LABEL); }
AbstractMetricsReporter implements MetricsReporter { protected String[] getLabelValues(SpanData spanData) { String[] values = new String[metricLabels.length]; for (int i=0; i < values.length; i++) { Object value = metricLabels[i].value(spanData); if (value == null) { return null; } values[i] = value.toString(); } return values; } protected AbstractMetricsReporter(List<MetricLabel> labels); }
@Test public void testWithSpecifiedTagValues() { AbstractMetricsReporter reporter = new AbstractMetricsReporter( Collections.<MetricLabel>emptyList()) { @Override public void reportSpan(SpanData spanData) { } }; Map<String,Object> spanTags = new HashMap<String,Object>(); spanTags.put(Tags.SPAN_KIND.getKey(), Tags.SPAN_KIND_SERVER); spanTags.put(Tags.ERROR.getKey(), true); SpanData spanData = mock(SpanData.class); when(spanData.getOperationName()).thenReturn("testop"); when(spanData.getTags()).thenReturn(spanTags); String[] labelValues = reporter.getLabelValues(spanData); assertEquals(3, labelValues.length); assertEquals(Tags.SPAN_KIND_SERVER, labelValues[1]); assertEquals(Boolean.toString(true), labelValues[2]); } @Test public void testWithSpecifiedOverriddenTagValue() { MetricLabel errorMetricTag = new MetricLabel() { @Override public String name() { return Tags.ERROR.getKey(); } @Override public Object defaultValue() { return null; } @Override public Object value(SpanData spanData) { Object error = spanData.getTags().containsKey(name()) ? spanData.getTags().get(name()) : false; if (spanData.getTags().containsKey(Tags.HTTP_STATUS.getKey())) { int status = (int)spanData.getTags().get(Tags.HTTP_STATUS.getKey()); if (status > 400) { error = "4xx"; } else if (status > 500) { error = "5xx"; } } return error; } }; AbstractMetricsReporter reporter = new AbstractMetricsReporter( Arrays.<MetricLabel>asList(new ConstMetricLabel("service", "TestService"), errorMetricTag)) { @Override public void reportSpan(SpanData spanData) { } }; Map<String,Object> spanTags = new HashMap<String,Object>(); spanTags.put(Tags.ERROR.getKey(), true); spanTags.put(Tags.HTTP_STATUS.getKey(), 401); spanTags.put(Tags.SPAN_KIND.getKey(), Tags.SPAN_KIND_CLIENT); SpanData spanData = mock(SpanData.class); when(spanData.getOperationName()).thenReturn("testop"); when(spanData.getTags()).thenReturn(spanTags); String[] labelValues = reporter.getLabelValues(spanData); assertEquals(4, labelValues.length); assertEquals("TestService", labelValues[0]); assertEquals("testop", labelValues[1]); assertEquals(Tags.SPAN_KIND_CLIENT, labelValues[2]); assertEquals("4xx", labelValues[3]); }
NumberPadTimePickerPresenter implements INumberPadTimePicker.Presenter, DigitwiseTimeModel.OnInputChangeListener { @Override public void presentState(@NonNull INumberPadTimePicker.State state) { initialize(state); if (!mIs24HourMode) { mView.setAmPmDisplayIndex(mLocaleModel.isAmPmWrittenBeforeTime() ? 0 : 1); final CharSequence amPmDisplayText; switch (state.getAmPmState()) { case AM: amPmDisplayText = mAltTexts[0]; break; case PM: amPmDisplayText = mAltTexts[1]; break; default: amPmDisplayText = null; break; } mView.updateAmPmDisplay(amPmDisplayText); } mView.setAmPmDisplayVisible(!mIs24HourMode); setAltKeysTexts(); updateViewEnabledStates(); } NumberPadTimePickerPresenter(@NonNull INumberPadTimePicker.View view, @NonNull LocaleModel localeModel, boolean is24HourMode); @Override void onNumberKeyClick(CharSequence numberKeyText); @Override void onAltKeyClick(CharSequence altKeyText); @Override void onBackspaceClick(); @Override boolean onBackspaceLongClick(); @Override boolean onOkButtonClick(); @Override void onShow(); @Override void onSetOkButtonCallbacks(); @Override void presentState(@NonNull INumberPadTimePicker.State state); @Override void detachView(); @Override INumberPadTimePicker.State getState(); @Override void onDigitStored(int digit); @Override void onDigitRemoved(int digit); @Override void onDigitsCleared(); }
@Test public void verifyViewEnabledStatesForEmptyState() { createNewViewAndPresenter(MODE_12HR); mPresenters[MODE_12HR].presentState(NumberPadTimePickerState.EMPTY); verifyInitialization(MODE_12HR); verify(mViews[MODE_12HR]).setOkButtonEnabled(false); createNewViewAndPresenter(MODE_24HR); mPresenters[MODE_24HR].presentState(NumberPadTimePickerState.EMPTY); verifyInitialization(MODE_24HR); verify(mViews[MODE_24HR]).setOkButtonEnabled(false); }
NumberPadTimePickerPresenter implements INumberPadTimePicker.Presenter, DigitwiseTimeModel.OnInputChangeListener { @Override public void onAltKeyClick(CharSequence altKeyText) { final String altKeyString = altKeyText.toString(); final int[] altDigits = mTextModel.altDigits(altKeyString); if (count() <= 2) { insertDigits(altDigits); } if (!is24HourFormat()) { mAmPmState = altKeyString.equalsIgnoreCase(mAltTexts[0]) ? AM : PM; mView.updateAmPmDisplay(altKeyString); } else { mAmPmState = HRS_24; } updateViewEnabledStates(); } NumberPadTimePickerPresenter(@NonNull INumberPadTimePicker.View view, @NonNull LocaleModel localeModel, boolean is24HourMode); @Override void onNumberKeyClick(CharSequence numberKeyText); @Override void onAltKeyClick(CharSequence altKeyText); @Override void onBackspaceClick(); @Override boolean onBackspaceLongClick(); @Override boolean onOkButtonClick(); @Override void onShow(); @Override void onSetOkButtonCallbacks(); @Override void presentState(@NonNull INumberPadTimePicker.State state); @Override void detachView(); @Override INumberPadTimePicker.State getState(); @Override void onDigitStored(int digit); @Override void onDigitRemoved(int digit); @Override void onDigitsCleared(); }
@Test public void mode12Hr_VerifyOnTimeSetCallback() { for (int time = 100; time <= 1259; time++) { if (time % 100 > 59) { System.out.println("Skipping invalid time " + time); continue; } System.out.println("Testing time " + time); for (int amOrPm = 0; amOrPm < 2; amOrPm++) { createNewViewAndPresenter(MODE_12HR); if (time <= 959) { inputThreeDigitTime(time, MODE_12HR); } else { inputFourDigitTime(time, MODE_12HR); } mPresenters[MODE_12HR].onAltKeyClick(altText(amOrPm, MODE_12HR)); final int hour = (time >= 1200 ? 0 : time / 100) + (amOrPm == 1 ? 12 : 0); final int minute = time % 100; confirmTimeSelection(mPresenters[MODE_12HR], MODE_12HR, hour, minute); } } }
InsertOrReplaceProxy implements MethodInterceptor { @Override public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable { if (method.getName().equals("toString") && args.length == 0) { String sql = toString((String) proxy.invoke(realInsert, args)); return sql; } return proxy.invoke(realInsert, args); } Insert getInstance(Class<Insert> clazz, Insert realInsert); @Override Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy); String toString(String sql); }
@Test public void intercept() throws Exception { String sql = "INSERT INTO person (id, name) VALUES (1, 'KK')"; CCJSqlParserManager pm = new CCJSqlParserManager(); Insert insert = (Insert) pm.parse(new StringReader(sql)); Insert insertProxy = new InsertOrReplaceProxy().getInstance(Insert.class, insert); Table table = insertProxy.getTable(); Assert.assertEquals("person", table.getName()); String string = insertProxy.toString(); Assert.assertEquals("INSERT OR REPLACE INTO person (id, name) VALUES (1, 'KK')", string); }
ShadowResources { public String getString(@StringRes int id) throws NotFoundException { return getText(id).toString(); } ShadowResources(); String getString(@StringRes int id); @NonNull String[] getStringArray(@ArrayRes int id); @NonNull int[] getIntArray(@ArrayRes int id); String getPackageName(); }
@Test public void getString() throws Exception { Assert.assertEquals("KBUnitTest", resources.getString(R.string.test_string)); }
ShadowResources { @NonNull public String[] getStringArray(@ArrayRes int id) throws NotFoundException { Map<Integer, String> idNameMap = getArrayIdTable(); Map<String, List<String>> stringArrayMap = getResourceStringArrayMap(); if (idNameMap.containsKey(id)) { String name = idNameMap.get(id); if (stringArrayMap.containsKey(name)) { List<String> stringList = stringArrayMap.get(name); return stringList.toArray(new String[0]); } } throw new Resources.NotFoundException("String array resource ID #0x" + Integer.toHexString(id)); } ShadowResources(); String getString(@StringRes int id); @NonNull String[] getStringArray(@ArrayRes int id); @NonNull int[] getIntArray(@ArrayRes int id); String getPackageName(); }
@Test public void getStringArray() throws Exception { String[] array = resources.getStringArray(R.array.arrayName); Assert.assertEquals("item0", array[0]); Assert.assertEquals("item1", array[1]); }
ShadowResources { @NonNull public int[] getIntArray(@ArrayRes int id) throws NotFoundException { Map<Integer, String> idNameMap = getArrayIdTable(); Map<String, List<Integer>> intArrayMap = getResourceIntArrayMap(); if (idNameMap.containsKey(id)) { String name = idNameMap.get(id); if (intArrayMap.containsKey(name)) { List<Integer> intList = intArrayMap.get(name); int[] intArray = new int[intList.size()]; for (int i = 0; i < intList.size(); i++) { intArray[i] = intList.get(i); } return intArray; } } return new int[0]; } ShadowResources(); String getString(@StringRes int id); @NonNull String[] getStringArray(@ArrayRes int id); @NonNull int[] getIntArray(@ArrayRes int id); String getPackageName(); }
@Test public void getIntArray() { int[] intArray = resources.getIntArray(R.array.intArray); Assert.assertEquals(0, intArray[0]); Assert.assertEquals(1, intArray[1]); int[] intArrayNoItem = resources.getIntArray(R.array.intArrayNoItem); Assert.assertEquals(0, intArrayNoItem.length); }
ShadowResources { public String getPackageName() { if (!TextUtils.isEmpty(mPackageName)) { return mPackageName; } String manifestPath = "build/intermediates/bundles/debug/AndroidManifest.xml"; if (!new File(manifestPath).exists()) { manifestPath = "build/intermediates/bundles/release/AndroidManifest.xml"; } FileReader reader = new FileReader(); if (new File(manifestPath).exists()) { String manifest = reader.readString(manifestPath); Element body = Jsoup.parse(manifest).body(); String packageName = body.childNode(0).attr("package"); return mPackageName = packageName; } else { manifestPath = "build/intermediates/manifest/androidTest/debug/AndroidManifest.xml"; String manifest = reader.readString(manifestPath); Element body = Jsoup.parse(manifest).body(); String packageName = body.childNode(0).attr("package"); packageName = packageName.substring(0, packageName.length() - ".test".length()); return mPackageName = packageName; } } ShadowResources(); String getString(@StringRes int id); @NonNull String[] getStringArray(@ArrayRes int id); @NonNull int[] getIntArray(@ArrayRes int id); String getPackageName(); }
@Test public void getPackageName() throws Exception { Assert.assertEquals("net.kb.test.library", resources.getPackageName()); }
KbSqlParserManager { public Statement parse(String sql) throws JSQLParserException { sql = sql.trim(); boolean isInsertOrReplace = false; if (sql.toUpperCase().startsWith("INSERT OR REPLACE")) { isInsertOrReplace = true; String[] sqlParts = new String[2]; sqlParts[0] = sql.substring(0, "INSERT OR REPLACE".length()); sqlParts[1] = sql.substring("INSERT OR REPLACE".length(), sql.length()); sqlParts[0] = sqlParts[0].toUpperCase().replace("INSERT OR REPLACE", "INSERT"); sql = sqlParts[0] + sqlParts[1]; } CCJSqlParser parser = new CCJSqlParser(new StringReader(sql)); try { Statement statement = parser.Statement(); if (isInsertOrReplace && statement instanceof Insert) { statement = new InsertOrReplaceProxy().getInstance(Insert.class, (Insert) statement); } return statement; } catch (Exception ex) { throw new JSQLParserException(ex); } } Statement parse(String sql); }
@Test public void parse() throws Exception { String sql = "INSERT or replace INTO person (id, name) VALUES (?, ?)"; Insert insert = (Insert) new KbSqlParserManager().parse(sql); Assert.assertEquals("INSERT OR REPLACE INTO person (id, name) VALUES (?, ?)", insert.toString()); }
ShadowCursor implements Cursor { @Override public String getString(int columnIndex) { Object obj = getObject(columnIndex); return obj == null ? null : obj.toString(); } ShadowCursor(List<String> columns, List<List<Object>> datas); @Override int getCount(); @Override int getPosition(); @Override boolean move(int offset); @Override boolean moveToPosition(int position); @Override boolean moveToFirst(); @Override boolean moveToLast(); @Override boolean moveToNext(); @Override boolean moveToPrevious(); @Override boolean isFirst(); @Override boolean isLast(); @Override boolean isBeforeFirst(); @Override boolean isAfterLast(); @Override int getColumnIndex(String columnName); @Override int getColumnIndexOrThrow(String columnName); @Override String getColumnName(int columnIndex); @Override String[] getColumnNames(); @Override int getColumnCount(); @Override byte[] getBlob(int columnIndex); @Override String getString(int columnIndex); @Override void copyStringToBuffer(int columnIndex, CharArrayBuffer buffer); @Override short getShort(int columnIndex); @Override int getInt(int columnIndex); @Override long getLong(int columnIndex); @Override float getFloat(int columnIndex); @Override double getDouble(int columnIndex); @Override int getType(int columnIndex); @Override boolean isNull(int columnIndex); @Override void deactivate(); @Override boolean requery(); @Override void close(); @Override boolean isClosed(); @Override void registerContentObserver(ContentObserver observer); @Override void unregisterContentObserver(ContentObserver observer); @Override void registerDataSetObserver(DataSetObserver observer); @Override void unregisterDataSetObserver(DataSetObserver observer); @Override void setNotificationUri(ContentResolver cr, Uri uri); @Override Uri getNotificationUri(); @Override boolean getWantsAllOnMoveCalls(); @Override void setExtras(Bundle extras); @Override Bundle getExtras(); @Override Bundle respond(Bundle extras); }
@Test public void getString() throws Exception { List<String> columns = Arrays.asList("first", "second", "third"); List<Object> datas = Arrays.asList("test", null, new Object()); ShadowCursor cursor = new ShadowCursor(columns, Arrays.asList(datas)); cursor.moveToNext(); Assert.assertEquals("test", cursor.getString(0)); Assert.assertEquals(null, cursor.getString(1)); }
KbSqlParser { public static String bindArgs(String sql, @Nullable Object[] bindArgs) { if (bindArgs == null || bindArgs.length == 0 || sql.startsWith("PRAGMA")) { return sql; } bindArgs = replaceBoolean(bindArgs); try { KbSqlParserManager pm = new KbSqlParserManager(); Statement statement = pm.parse(sql); Set<Expression> expressionSet = findBindArgsExpressions(statement); Iterator<Object> iterator = Arrays.asList(bindArgs).iterator(); bindExpressionArgs(expressionSet, iterator); return statement.toString(); } catch (Exception e) { e.printStackTrace(); } return sql; } static String bindArgs(String sql, @Nullable Object[] bindArgs); static Object[] replaceBoolean(Object[] bindArgs); }
@Test public void bindSelectArgs() throws Exception { Object[] args = new Object[]{1, 10, 20, "test"}; String sql = "select * from person where id=? and (uid BETWEEN ? and ?) and test LIKE ? order by id"; String boundSql = KbSqlParser.bindArgs(sql, args); System.out.println(boundSql); Assert.assertEquals("SELECT * FROM person WHERE id = 1 AND (uid BETWEEN 10 AND 20) AND test LIKE 'test' ORDER BY id", boundSql); } @Test public void bindInsertArgs() { Object[] args = new Object[]{1, "kk"}; String sql = "INSERT INTO person (id, name) VALUES (?, ?)"; String boundSql = KbSqlParser.bindArgs(sql, args); Assert.assertEquals("INSERT INTO person (id, name) VALUES (1, 'kk')", boundSql); } @Test public void bindDeleteArgs() { Object[] args = new Object[]{1}; String sql = "DELETE FROM person WHERE id = ?"; String boundSql = KbSqlParser.bindArgs(sql, args); Assert.assertEquals("DELETE FROM person WHERE id = 1", boundSql); } @Test public void bindUpdateArgs() { Object[] args = new Object[]{"kk", 1}; String sql = "UPDATE person SET name = ? WHERE id = ?"; String boundSql = KbSqlParser.bindArgs(sql, args); Assert.assertEquals("UPDATE person SET name = 'kk' WHERE id = 1", boundSql); }
KbSqlParser { protected static int getBindArgsCount(String sql) { Set<Expression> expressionSet = findBindArgsExpressions(sql); int count = 0; for (Expression expression : expressionSet) { count += getBindArgsCount(expression); } return count; } static String bindArgs(String sql, @Nullable Object[] bindArgs); static Object[] replaceBoolean(Object[] bindArgs); }
@Test public void getBindArgsCount() throws Exception { String sql0 = "select * from person where id=? and (uid BETWEEN ? and ?) and test LIKE ? order by id"; String sql1 = "INSERT INTO person (id, name) VALUES (?, ?)"; String sql2 = "DELETE FROM person WHERE id in (?,?)"; String sql3 = "UPDATE person SET name = ? WHERE id = ?"; Assert.assertEquals(4, KbSqlParser.getBindArgsCount(sql0)); Assert.assertEquals(2, KbSqlParser.getBindArgsCount(sql1)); Assert.assertEquals(2, KbSqlParser.getBindArgsCount(sql2)); Assert.assertEquals(2, KbSqlParser.getBindArgsCount(sql3)); }
KbSqlParser { protected static Set<Expression> findBindArgsExpressions(String sql) { if (sql == null || sql.startsWith("PRAGMA") || !sql.contains("?")) { return new LinkedHashSet<>(); } KbSqlParserManager pm = new KbSqlParserManager(); try { Statement statement = pm.parse(sql); Set<Expression> expressionSet = findBindArgsExpressions(statement); return expressionSet; } catch (JSQLParserException e) { e.printStackTrace(); } return new LinkedHashSet<>(); } static String bindArgs(String sql, @Nullable Object[] bindArgs); static Object[] replaceBoolean(Object[] bindArgs); }
@Test public void findJdbcParamExpressions() throws Exception { String sql = "DELETE FROM person WHERE id = ?"; Set<Expression> expressionSet = KbSqlParser.findBindArgsExpressions(sql); System.out.println(); }
ShadowContext implements Shadow { public static void deleteAllTempDir() { FileUtils.deletePath(DB_PATH); FileUtils.deletePath(DATA_DIR); FileUtils.deletePath(EXT_DIR); } ShadowContext(Resources resources); @NonNull final String getString(@StringRes int resId); Resources getResources(); SharedPreferences getSharedPreferences(String name, int mode); Context getApplicationContext(); AssetManager getAssets(); File getDatabasePath(String name); String[] databaseList(); static String getDbDir(); File getDataDir(); File getFilesDir(); File getFileStreamPath(String name); File getCacheDir(); File getCodeCacheDir(); File getNoBackupFilesDir(); File getExtDir(); File getExternalCacheDir(); @Nullable File getExternalFilesDir(@Nullable String type); String[] fileList(); String getPackageResourcePath(); String getPackageCodePath(); static void deleteAllTempDir(); void putSQLiteDatabase(String name, SQLiteDatabase db); SQLiteDatabase openOrCreateDatabase(String name, int mode, SQLiteDatabase.CursorFactory factory); @TargetApi(Build.VERSION_CODES.JELLY_BEAN) SQLiteDatabase openOrCreateDatabase(String name, int mode, SQLiteDatabase.CursorFactory factory, DatabaseErrorHandler errorHandler); boolean deleteDatabase(String name); Map<String, SQLiteDatabase> getDbMap(); @Override String toString(); @Override void setProxyObject(Object proxyObject); static final String DB_PATH; }
@Test public void deleteAllTempDir() throws Exception { ShadowContext.deleteAllTempDir(); }
NoOpWorkflowImpl implements NoOpWorkflow { @Override public void run() { System.out.println("Run called"); run(0); } @Override void run(); }
@Test public void testRun() { context.checking( new Expectations() { { exactly(3).of(control).createDatabaseName("test"); will(returnValue("bbb")); } }); new NoOpWorkflowClientFactoryImpl().getClient("test").run(); }
JobWorkflowImpl implements JobWorkflow { @Override public void executeCommand(final RunJobRequest request) { this.request = request; this.workflowId = contextProvider .getDecisionContext() .getWorkflowContext() .getWorkflowExecution() .getWorkflowId(); final String masterRoleName = "dm-master-role-" + workflowId; final String agentProfileName = "dm-profile-" + workflowId; new TryFinally() { @Override protected void doFinally() { Promise<Void> done = Promise.Void(); if (workerId != null) { done = ec2Activities.terminateInstance(workerId, request.getIdentity()); } done = ec2Activities.deleteInstanceProfile(agentProfileName, request.getIdentity(), done); controlActivities.deleteRole(masterRoleName, done); } @Override protected void doTry() { String taskListName = "dm-agent-tl-" + workflowId; Promise<String> masterRoleArn = controlActivities.createAgentControllerRole( masterRoleName, taskListName, request.getIdentity()); Promise<Void> profileCreated = ec2Activities.createAgentInstanceProfile( Promise.asPromise(agentProfileName), masterRoleArn, Promise.asPromise(request.getIdentity())); Promise<String> userData = controlActivities.createAgentUserData(masterRoleArn, Promise.asPromise(taskListName)); Promise<String> workerId = launchInstances(agentProfileName, userData, profileCreated); Promise<Void> set = setWorkerId(workerId); Promise<Void> ready = waitUntilWorkerReady(workerId, set); Promise<String> actionId = controlActivities.notifyActionStarted( "AgentActivities.runJob", "Start running command on instance", ready); Promise<JobResult> result = agentActivities.runJob( request.getJob(), new ActivitySchedulingOptions() .withTaskList(taskListName) .withStartToCloseTimeoutSeconds( request.getWorkerOptions().getJobTimeoutSeconds()), actionId); reportResult(actionId, result); } }; } @Override void executeCommand(final RunJobRequest request); }
@Test public void testRun() { final Identity identity = Identity.of("a", "b", "c"); WorkerOptions workerOptions = new WorkerOptions(); RunJobRequest request = new RunJobRequest(); request.setWorkerOptions(workerOptions); final Job job = new CommandLineJob(); request.setIdentity(identity); request.setJob(job); final CreateInstanceOptions options = new CreateInstanceOptions(); options.setWorkerOptions(workerOptions); options.setInstanceProfileName("dm-profile-test"); options.setUserData("test-data"); final JobResult result = new JobResult(); result.setStandardOutput("something"); result.setElapsedMillis(1000); context.checking( new Expectations() { { one(controlActivities) .createAgentControllerRole("dm-master-role-test", "dm-agent-tl-test", identity); will(returnValue("aws:test:arn")); one(ec2Activities) .createAgentInstanceProfile("dm-profile-test", "aws:test:arn", identity); one(controlActivities).createAgentUserData("aws:test:arn", "dm-agent-tl-test"); will(returnValue("test-data")); one(ec2Activities).launchInstance(options, identity); will(returnValue("dmw-test")); one(ec2Activities).describeInstance("dmw-test", identity); will(returnValue(new WorkerInstance().withInstanceStatus("running"))); one(controlActivities) .notifyActionStarted("AgentActivities.runJob", "Start running command on instance"); will(returnValue("action-id")); one(agentActivities).runJob(job); will(returnValue(result)); one(controlActivities) .notifyActionCompleted( with(equal("action-id")), with(aNonNull(String.class)), with(equal(1000L))); one(ec2Activities).terminateInstance("dmw-test", identity); one(ec2Activities).deleteInstanceProfile("dm-profile-test", identity); one(controlActivities).deleteRole("dm-master-role-test"); } }); new JobWorkflowClientFactoryImpl().getClient("test").executeCommand(request); }
UriBuilderImpl extends UriBuilder { @Override public UriBuilder replaceQueryParam(String name, Object... values) { checkSsp(); if (queryParams == null) { queryParams = UriComponent.decodeQuery(query.toString(), false); query.setLength(0); } name = encode(name, UriComponent.Type.QUERY_PARAM); queryParams.remove(name); if (values == null) { return this; } for (Object value : values) { if (value == null) { throw new IllegalArgumentException("One or more of query value parameters are null"); } queryParams.add(name, encode(value.toString(), UriComponent.Type.QUERY_PARAM)); } return this; } UriBuilderImpl(); private UriBuilderImpl(UriBuilderImpl that); @Override UriBuilder clone(); @Override UriBuilder uri(URI uri); @Override UriBuilder scheme(String scheme); @Override UriBuilder schemeSpecificPart(String ssp); @Override UriBuilder userInfo(String ui); @Override UriBuilder host(String host); @Override UriBuilder port(int port); @Override UriBuilder replacePath(String path); @Override UriBuilder path(String path); @Override UriBuilder path(Class resource); @Override UriBuilder path(Class resource, String methodName); @Override UriBuilder path(Method method); @Override UriBuilder segment(String... segments); @Override UriBuilder replaceMatrix(String matrix); @Override UriBuilder matrixParam(String name, Object... values); @Override UriBuilder replaceMatrixParam(String name, Object... values); @Override UriBuilder replaceQuery(String query); @Override UriBuilder queryParam(String name, Object... values); @Override UriBuilder replaceQueryParam(String name, Object... values); @Override UriBuilder fragment(String fragment); @Override URI buildFromMap(Map<String, ? extends Object> values); @Override URI buildFromEncodedMap(Map<String, ? extends Object> values); @Override URI build(Object... values); @Override URI buildFromEncoded(Object... values); }
@Test public void testReplaceQueryParam() { URI uri = new UriBuilderImpl().path("http: assertEquals("http: }
DemoAO { public void hello(String name) throws FileNotFoundException { System.out.println(demoService.sayHello(name)); } void hello(String name); }
@Test public void testHello() throws FileNotFoundException { demoAO.hello("抠逼阵儿"); }
StackTraceHelper { public static StackFrame[] convertJsStackTrace(@Nullable ReadableArray stack) { int size = stack != null ? stack.size() : 0; StackFrame[] result = new StackFrame[size]; for (int i = 0; i < size; i++) { ReadableMap frame = stack.getMap(i); String methodName = frame.getString("methodName"); String fileName = frame.getString("file"); int lineNumber = -1; if (frame.hasKey(LINE_NUMBER_KEY) && !frame.isNull(LINE_NUMBER_KEY)) { lineNumber = frame.getInt(LINE_NUMBER_KEY); } int columnNumber = -1; if (frame.hasKey(COLUMN_KEY) && !frame.isNull(COLUMN_KEY)) { columnNumber = frame.getInt(COLUMN_KEY); } result[i] = new StackFrameImpl(fileName, methodName, lineNumber, columnNumber); } return result; } static StackFrame[] convertJsStackTrace(@Nullable ReadableArray stack); static StackFrame[] convertJsStackTrace(JSONArray stack); static StackFrame[] convertJsStackTrace(String stack); static StackFrame[] convertJavaStackTrace(Throwable exception); static String formatFrameSource(StackFrame frame); static String formatStackTrace(String title, StackFrame[] stack); static final java.lang.String COLUMN_KEY; static final java.lang.String LINE_NUMBER_KEY; }
@Test public void testParseStackFrameWithMethod() { final StackFrame frame = StackTraceHelper.convertJsStackTrace( "[email protected]:1:2000")[0]; assertThat(frame.getMethod()).isEqualTo("render"); assertThat(frame.getFileName()).isEqualTo("Test.bundle"); assertThat(frame.getLine()).isEqualTo(1); assertThat(frame.getColumn()).isEqualTo(2000); } @Test public void testParseStackFrameWithoutMethod() { final StackFrame frame = StackTraceHelper.convertJsStackTrace( "Test.bundle:1:2000")[0]; assertThat(frame.getMethod()).isEqualTo("(unknown)"); assertThat(frame.getFileName()).isEqualTo("Test.bundle"); assertThat(frame.getLine()).isEqualTo(1); assertThat(frame.getColumn()).isEqualTo(2000); } @Test public void testParseStackFrameWithInvalidFrame() { try { StackTraceHelper.convertJsStackTrace("Test.bundle:ten:twenty"); failBecauseExceptionWasNotThrown(IllegalArgumentException.class); } catch (Exception e) { assertThat(e).isInstanceOf(IllegalArgumentException.class); } }
MultipartStreamReader { public boolean readAllParts(ChunkCallback callback) throws IOException { ByteString delimiter = ByteString.encodeUtf8(CRLF + "--" + mBoundary + CRLF); ByteString closeDelimiter = ByteString.encodeUtf8(CRLF + "--" + mBoundary + "--" + CRLF); int bufferLen = 4 * 1024; long chunkStart = 0; long bytesSeen = 0; Buffer content = new Buffer(); while (true) { boolean isCloseDelimiter = false; long searchStart = Math.max(bytesSeen - closeDelimiter.size(), chunkStart); long indexOfDelimiter = content.indexOf(delimiter, searchStart); if (indexOfDelimiter == -1) { isCloseDelimiter = true; indexOfDelimiter = content.indexOf(closeDelimiter, searchStart); } if (indexOfDelimiter == -1) { bytesSeen = content.size(); long bytesRead = mSource.read(content, bufferLen); if (bytesRead <= 0) { return false; } continue; } long chunkEnd = indexOfDelimiter; long length = chunkEnd - chunkStart; if (chunkStart > 0) { Buffer chunk = new Buffer(); content.skip(chunkStart); content.read(chunk, length); emitChunk(chunk, isCloseDelimiter, callback); } else { content.skip(chunkEnd); } if (isCloseDelimiter) { return true; } bytesSeen = chunkStart = delimiter.size(); } } MultipartStreamReader(BufferedSource source, String boundary); boolean readAllParts(ChunkCallback callback); }
@Test public void testSimpleCase() throws IOException { ByteString response = ByteString.encodeUtf8( "preable, should be ignored\r\n" + "--sample_boundary\r\n" + "Content-Type: application/json; charset=utf-8\r\n" + "Content-Length: 2\r\n\r\n" + "{}\r\n" + "--sample_boundary--\r\n" + "epilogue, should be ignored"); Buffer source = new Buffer(); source.write(response); MultipartStreamReader reader = new MultipartStreamReader(source, "sample_boundary"); CallCountTrackingChunkCallback callback = new CallCountTrackingChunkCallback() { @Override public void execute(Map<String, String> headers, Buffer body, boolean done) throws IOException { super.execute(headers, body, done); assertThat(done).isTrue(); assertThat(headers.get("Content-Type")).isEqualTo("application/json; charset=utf-8"); assertThat(body.readUtf8()).isEqualTo("{}"); } }; boolean success = reader.readAllParts(callback); assertThat(callback.getCallCount()).isEqualTo(1); assertThat(success).isTrue(); } @Test public void testMultipleParts() throws IOException { ByteString response = ByteString.encodeUtf8( "preable, should be ignored\r\n" + "--sample_boundary\r\n" + "1\r\n" + "--sample_boundary\r\n" + "2\r\n" + "--sample_boundary\r\n" + "3\r\n" + "--sample_boundary--\r\n" + "epilogue, should be ignored"); Buffer source = new Buffer(); source.write(response); MultipartStreamReader reader = new MultipartStreamReader(source, "sample_boundary"); CallCountTrackingChunkCallback callback = new CallCountTrackingChunkCallback() { @Override public void execute(Map<String, String> headers, Buffer body, boolean done) throws IOException { super.execute(headers, body, done); assertThat(done).isEqualTo(getCallCount() == 3); assertThat(body.readUtf8()).isEqualTo(String.valueOf(getCallCount())); } }; boolean success = reader.readAllParts(callback); assertThat(callback.getCallCount()).isEqualTo(3); assertThat(success).isTrue(); } @Test public void testNoDelimiter() throws IOException { ByteString response = ByteString.encodeUtf8("Yolo"); Buffer source = new Buffer(); source.write(response); MultipartStreamReader reader = new MultipartStreamReader(source, "sample_boundary"); CallCountTrackingChunkCallback callback = new CallCountTrackingChunkCallback(); boolean success = reader.readAllParts(callback); assertThat(callback.getCallCount()).isEqualTo(0); assertThat(success).isFalse(); } @Test public void testNoCloseDelimiter() throws IOException { ByteString response = ByteString.encodeUtf8( "preable, should be ignored\r\n" + "--sample_boundary\r\n" + "Content-Type: application/json; charset=utf-8\r\n" + "Content-Length: 2\r\n\r\n" + "{}\r\n" + "--sample_boundary\r\n" + "incomplete message..."); Buffer source = new Buffer(); source.write(response); MultipartStreamReader reader = new MultipartStreamReader(source, "sample_boundary"); CallCountTrackingChunkCallback callback = new CallCountTrackingChunkCallback(); boolean success = reader.readAllParts(callback); assertThat(callback.getCallCount()).isEqualTo(1); assertThat(success).isFalse(); }
ClipboardModule extends ContextBaseJavaModule { @SuppressLint("DeprecatedMethod") @ReactMethod public void setString(String text) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { ClipData clipdata = ClipData.newPlainText(null, text); ClipboardManager clipboard = getClipboardService(); clipboard.setPrimaryClip(clipdata); } else { ClipboardManager clipboard = getClipboardService(); clipboard.setText(text); } } ClipboardModule(Context context); @Override String getName(); @ReactMethod void getString(Promise promise); @SuppressLint("DeprecatedMethod") @ReactMethod void setString(String text); }
@Test public void testSetString() { mClipboardModule.setString(TEST_CONTENT); assertTrue(mClipboardManager.getText().equals(TEST_CONTENT)); mClipboardModule.setString(null); assertFalse(mClipboardManager.hasText()); mClipboardModule.setString(""); assertFalse(mClipboardManager.hasText()); mClipboardModule.setString(" "); assertTrue(mClipboardManager.hasText()); }
NetworkingModule extends ReactContextBaseJavaModule { @ReactMethod public void sendRequest( String method, String url, final int requestId, ReadableArray headers, ReadableMap data, final String responseType, final boolean useIncrementalUpdates, int timeout, boolean withCredentials) { Request.Builder requestBuilder = new Request.Builder().url(url); if (requestId != 0) { requestBuilder.tag(requestId); } final RCTDeviceEventEmitter eventEmitter = getEventEmitter(); OkHttpClient.Builder clientBuilder = mClient.newBuilder(); if (!withCredentials) { clientBuilder.cookieJar(CookieJar.NO_COOKIES); } if (useIncrementalUpdates) { clientBuilder.addNetworkInterceptor(new Interceptor() { @Override public Response intercept(Interceptor.Chain chain) throws IOException { Response originalResponse = chain.proceed(chain.request()); ProgressResponseBody responseBody = new ProgressResponseBody( originalResponse.body(), new ProgressListener() { long last = System.nanoTime(); @Override public void onProgress(long bytesWritten, long contentLength, boolean done) { long now = System.nanoTime(); if (!done && !shouldDispatch(now, last)) { return; } if (responseType.equals("text")) { return; } ResponseUtil.onDataReceivedProgress( eventEmitter, requestId, bytesWritten, contentLength); last = now; } }); return originalResponse.newBuilder().body(responseBody).build(); } }); } if (timeout != mClient.connectTimeoutMillis()) { clientBuilder.readTimeout(timeout, TimeUnit.MILLISECONDS); } OkHttpClient client = clientBuilder.build(); Headers requestHeaders = extractHeaders(headers, data); if (requestHeaders == null) { ResponseUtil.onRequestError(eventEmitter, requestId, "Unrecognized headers format", null); return; } String contentType = requestHeaders.get(CONTENT_TYPE_HEADER_NAME); String contentEncoding = requestHeaders.get(CONTENT_ENCODING_HEADER_NAME); requestBuilder.headers(requestHeaders); if (data == null) { requestBuilder.method(method, RequestBodyUtil.getEmptyBody(method)); } else if (data.hasKey(REQUEST_BODY_KEY_STRING)) { if (contentType == null) { ResponseUtil.onRequestError( eventEmitter, requestId, "Payload is set but no content-type header specified", null); return; } String body = data.getString(REQUEST_BODY_KEY_STRING); MediaType contentMediaType = MediaType.parse(contentType); if (RequestBodyUtil.isGzipEncoding(contentEncoding)) { RequestBody requestBody = RequestBodyUtil.createGzip(contentMediaType, body); if (requestBody == null) { ResponseUtil.onRequestError(eventEmitter, requestId, "Failed to gzip request body", null); return; } requestBuilder.method(method, requestBody); } else { requestBuilder.method(method, RequestBody.create(contentMediaType, body)); } } else if (data.hasKey(REQUEST_BODY_KEY_BASE64)) { if (contentType == null) { ResponseUtil.onRequestError( eventEmitter, requestId, "Payload is set but no content-type header specified", null); return; } String base64String = data.getString(REQUEST_BODY_KEY_BASE64); MediaType contentMediaType = MediaType.parse(contentType); requestBuilder.method( method, RequestBody.create(contentMediaType, ByteString.decodeBase64(base64String))); } else if (data.hasKey(REQUEST_BODY_KEY_URI)) { if (contentType == null) { ResponseUtil.onRequestError( eventEmitter, requestId, "Payload is set but no content-type header specified", null); return; } String uri = data.getString(REQUEST_BODY_KEY_URI); InputStream fileInputStream = RequestBodyUtil.getFileInputStream(getReactApplicationContext(), uri); if (fileInputStream == null) { ResponseUtil.onRequestError( eventEmitter, requestId, "Could not retrieve file for uri " + uri, null); return; } requestBuilder.method( method, RequestBodyUtil.create(MediaType.parse(contentType), fileInputStream)); } else if (data.hasKey(REQUEST_BODY_KEY_FORMDATA)) { if (contentType == null) { contentType = "multipart/form-data"; } ReadableArray parts = data.getArray(REQUEST_BODY_KEY_FORMDATA); MultipartBody.Builder multipartBuilder = constructMultipartBody(parts, contentType, requestId); if (multipartBuilder == null) { return; } requestBuilder.method( method, RequestBodyUtil.createProgressRequest( multipartBuilder.build(), new ProgressListener() { long last = System.nanoTime(); @Override public void onProgress(long bytesWritten, long contentLength, boolean done) { long now = System.nanoTime(); if (done || shouldDispatch(now, last)) { ResponseUtil.onDataSend(eventEmitter, requestId, bytesWritten, contentLength); last = now; } } })); } else { requestBuilder.method(method, RequestBodyUtil.getEmptyBody(method)); } addRequest(requestId); client.newCall(requestBuilder.build()).enqueue( new Callback() { @Override public void onFailure(Call call, IOException e) { if (mShuttingDown) { return; } removeRequest(requestId); String errorMessage = e.getMessage() != null ? e.getMessage() : "Error while executing request: " + e.getClass().getSimpleName(); ResponseUtil.onRequestError(eventEmitter, requestId, errorMessage, e); } @Override public void onResponse(Call call, Response response) throws IOException { if (mShuttingDown) { return; } removeRequest(requestId); ResponseUtil.onResponseReceived( eventEmitter, requestId, response.code(), translateHeaders(response.headers()), response.request().url().toString()); ResponseBody responseBody = response.body(); try { if (useIncrementalUpdates && responseType.equals("text")) { readWithProgress(eventEmitter, requestId, responseBody); ResponseUtil.onRequestSuccess(eventEmitter, requestId); return; } String responseString = ""; if (responseType.equals("text")) { responseString = responseBody.string(); } else if (responseType.equals("base64")) { responseString = Base64.encodeToString(responseBody.bytes(), Base64.NO_WRAP); } ResponseUtil.onDataReceived(eventEmitter, requestId, responseString); ResponseUtil.onRequestSuccess(eventEmitter, requestId); } catch (IOException e) { ResponseUtil.onRequestError(eventEmitter, requestId, e.getMessage(), e); } } }); } NetworkingModule( ReactApplicationContext reactContext, @Nullable String defaultUserAgent, OkHttpClient client, @Nullable List<NetworkInterceptorCreator> networkInterceptorCreators); NetworkingModule( ReactApplicationContext context, @Nullable String defaultUserAgent, OkHttpClient client); NetworkingModule(final ReactApplicationContext context); NetworkingModule( ReactApplicationContext context, List<NetworkInterceptorCreator> networkInterceptorCreators); NetworkingModule(ReactApplicationContext context, String defaultUserAgent); @Override void initialize(); @Override String getName(); @Override void onCatalystInstanceDestroy(); @ReactMethod /** * @param timeout value of 0 results in no timeout */ void sendRequest( String method, String url, final int requestId, ReadableArray headers, ReadableMap data, final String responseType, final boolean useIncrementalUpdates, int timeout, boolean withCredentials); @ReactMethod void abortRequest(final int requestId); @ReactMethod void clearCookies(com.facebook.react.bridge.Callback callback); }
@Test public void testGetWithoutHeaders() throws Exception { OkHttpClient httpClient = mock(OkHttpClient.class); when(httpClient.newCall(any(Request.class))).thenAnswer(new Answer<Object>() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { Call callMock = mock(Call.class); return callMock; } }); OkHttpClient.Builder clientBuilder = mock(OkHttpClient.Builder.class); when(clientBuilder.build()).thenReturn(httpClient); when(httpClient.newBuilder()).thenReturn(clientBuilder); NetworkingModule networkingModule = new NetworkingModule(mock(ReactApplicationContext.class), "", httpClient); networkingModule.sendRequest( "GET", "http: 0, JavaOnlyArray.of(), null, "text", true, 0, false); ArgumentCaptor<Request> argumentCaptor = ArgumentCaptor.forClass(Request.class); verify(httpClient).newCall(argumentCaptor.capture()); assertThat(argumentCaptor.getValue().url().toString()).isEqualTo("http: assertThat(argumentCaptor.getValue().headers().size()).isEqualTo(1); assertThat(argumentCaptor.getValue().method()).isEqualTo("GET"); } @Test public void testFailGetWithInvalidHeadersStruct() throws Exception { RCTDeviceEventEmitter emitter = mock(RCTDeviceEventEmitter.class); ReactApplicationContext context = mock(ReactApplicationContext.class); when(context.getJSModule(any(Class.class))).thenReturn(emitter); OkHttpClient httpClient = mock(OkHttpClient.class); OkHttpClient.Builder clientBuilder = mock(OkHttpClient.Builder.class); when(clientBuilder.build()).thenReturn(httpClient); when(httpClient.newBuilder()).thenReturn(clientBuilder); NetworkingModule networkingModule = new NetworkingModule(context, "", httpClient); List<JavaOnlyArray> invalidHeaders = Arrays.asList(JavaOnlyArray.of("foo")); mockEvents(); networkingModule.sendRequest( "GET", "http: 0, JavaOnlyArray.from(invalidHeaders), null, "text", true, 0, false); verifyErrorEmit(emitter, 0); } @Test public void testFailPostWithoutContentType() throws Exception { RCTDeviceEventEmitter emitter = mock(RCTDeviceEventEmitter.class); ReactApplicationContext context = mock(ReactApplicationContext.class); when(context.getJSModule(any(Class.class))).thenReturn(emitter); OkHttpClient httpClient = mock(OkHttpClient.class); OkHttpClient.Builder clientBuilder = mock(OkHttpClient.Builder.class); when(clientBuilder.build()).thenReturn(httpClient); when(httpClient.newBuilder()).thenReturn(clientBuilder); NetworkingModule networkingModule = new NetworkingModule(context, "", httpClient); JavaOnlyMap body = new JavaOnlyMap(); body.putString("string", "This is request body"); mockEvents(); networkingModule.sendRequest( "POST", "http: 0, JavaOnlyArray.of(), body, "text", true, 0, false); verifyErrorEmit(emitter, 0); } @Test public void testSuccessfulPostRequest() throws Exception { OkHttpClient httpClient = mock(OkHttpClient.class); when(httpClient.newCall(any(Request.class))).thenAnswer(new Answer<Object>() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { Call callMock = mock(Call.class); return callMock; } }); OkHttpClient.Builder clientBuilder = mock(OkHttpClient.Builder.class); when(clientBuilder.build()).thenReturn(httpClient); when(httpClient.newBuilder()).thenReturn(clientBuilder); NetworkingModule networkingModule = new NetworkingModule(mock(ReactApplicationContext.class), "", httpClient); JavaOnlyMap body = new JavaOnlyMap(); body.putString("string", "This is request body"); networkingModule.sendRequest( "POST", "http: 0, JavaOnlyArray.of(JavaOnlyArray.of("Content-Type", "text/plain")), body, "text", true, 0, false); ArgumentCaptor<Request> argumentCaptor = ArgumentCaptor.forClass(Request.class); verify(httpClient).newCall(argumentCaptor.capture()); assertThat(argumentCaptor.getValue().url().toString()).isEqualTo("http: assertThat(argumentCaptor.getValue().headers().size()).isEqualTo(2); assertThat(argumentCaptor.getValue().method()).isEqualTo("POST"); assertThat(argumentCaptor.getValue().body().contentType().type()).isEqualTo("text"); assertThat(argumentCaptor.getValue().body().contentType().subtype()).isEqualTo("plain"); Buffer contentBuffer = new Buffer(); argumentCaptor.getValue().body().writeTo(contentBuffer); assertThat(contentBuffer.readUtf8()).isEqualTo("This is request body"); } @Test public void testHeaders() throws Exception { OkHttpClient httpClient = mock(OkHttpClient.class); when(httpClient.newCall(any(Request.class))).thenAnswer(new Answer<Object>() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { Call callMock = mock(Call.class); return callMock; } }); OkHttpClient.Builder clientBuilder = mock(OkHttpClient.Builder.class); when(clientBuilder.build()).thenReturn(httpClient); when(httpClient.newBuilder()).thenReturn(clientBuilder); NetworkingModule networkingModule = new NetworkingModule(mock(ReactApplicationContext.class), "", httpClient); List<JavaOnlyArray> headers = Arrays.asList( JavaOnlyArray.of("Accept", "text/plain"), JavaOnlyArray.of("User-Agent", "React test agent/1.0")); networkingModule.sendRequest( "GET", "http: 0, JavaOnlyArray.from(headers), null, "text", true, 0, false); ArgumentCaptor<Request> argumentCaptor = ArgumentCaptor.forClass(Request.class); verify(httpClient).newCall(argumentCaptor.capture()); Headers requestHeaders = argumentCaptor.getValue().headers(); assertThat(requestHeaders.size()).isEqualTo(2); assertThat(requestHeaders.get("Accept")).isEqualTo("text/plain"); assertThat(requestHeaders.get("User-Agent")).isEqualTo("React test agent/1.0"); } @Test public void testMultipartPostRequestSimple() throws Exception { PowerMockito.mockStatic(RequestBodyUtil.class); when(RequestBodyUtil.getFileInputStream(any(ReactContext.class), any(String.class))) .thenReturn(mock(InputStream.class)); when(RequestBodyUtil.create(any(MediaType.class), any(InputStream.class))) .thenReturn(mock(RequestBody.class)); when(RequestBodyUtil.createProgressRequest(any(RequestBody.class), any(ProgressListener.class))) .thenCallRealMethod(); JavaOnlyMap body = new JavaOnlyMap(); JavaOnlyArray formData = new JavaOnlyArray(); JavaOnlyMap bodyPart = new JavaOnlyMap(); bodyPart.putString("string", "value"); bodyPart.putArray( "headers", JavaOnlyArray.from( Arrays.asList( JavaOnlyArray.of("content-disposition", "name")))); formData.pushMap(bodyPart); body.putArray("formData", formData); OkHttpClient httpClient = mock(OkHttpClient.class); when(httpClient.newCall(any(Request.class))).thenAnswer( new Answer<Object>() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { Call callMock = mock(Call.class); return callMock; } }); OkHttpClient.Builder clientBuilder = mock(OkHttpClient.Builder.class); when(clientBuilder.build()).thenReturn(httpClient); when(httpClient.newBuilder()).thenReturn(clientBuilder); NetworkingModule networkingModule = new NetworkingModule(mock(ReactApplicationContext.class), "", httpClient); networkingModule.sendRequest( "POST", "http: 0, new JavaOnlyArray(), body, "text", true, 0, false); ArgumentCaptor<Request> argumentCaptor = ArgumentCaptor.forClass(Request.class); verify(httpClient).newCall(argumentCaptor.capture()); assertThat(argumentCaptor.getValue().url().toString()).isEqualTo("http: assertThat(argumentCaptor.getValue().method()).isEqualTo("POST"); assertThat(argumentCaptor.getValue().body().contentType().type()). isEqualTo(MultipartBody.FORM.type()); assertThat(argumentCaptor.getValue().body().contentType().subtype()). isEqualTo(MultipartBody.FORM.subtype()); Headers requestHeaders = argumentCaptor.getValue().headers(); assertThat(requestHeaders.size()).isEqualTo(1); } @Test public void testMultipartPostRequestHeaders() throws Exception { PowerMockito.mockStatic(RequestBodyUtil.class); when(RequestBodyUtil.getFileInputStream(any(ReactContext.class), any(String.class))) .thenReturn(mock(InputStream.class)); when(RequestBodyUtil.create(any(MediaType.class), any(InputStream.class))) .thenReturn(mock(RequestBody.class)); when(RequestBodyUtil.createProgressRequest(any(RequestBody.class), any(ProgressListener.class))) .thenCallRealMethod(); List<JavaOnlyArray> headers = Arrays.asList( JavaOnlyArray.of("Accept", "text/plain"), JavaOnlyArray.of("User-Agent", "React test agent/1.0"), JavaOnlyArray.of("content-type", "multipart/form-data")); JavaOnlyMap body = new JavaOnlyMap(); JavaOnlyArray formData = new JavaOnlyArray(); JavaOnlyMap bodyPart = new JavaOnlyMap(); bodyPart.putString("string", "value"); bodyPart.putArray( "headers", JavaOnlyArray.from( Arrays.asList( JavaOnlyArray.of("content-disposition", "name")))); formData.pushMap(bodyPart); body.putArray("formData", formData); OkHttpClient httpClient = mock(OkHttpClient.class); when(httpClient.newCall(any(Request.class))).thenAnswer( new Answer<Object>() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { Call callMock = mock(Call.class); return callMock; } }); OkHttpClient.Builder clientBuilder = mock(OkHttpClient.Builder.class); when(clientBuilder.build()).thenReturn(httpClient); when(httpClient.newBuilder()).thenReturn(clientBuilder); NetworkingModule networkingModule = new NetworkingModule(mock(ReactApplicationContext.class), "", httpClient); networkingModule.sendRequest( "POST", "http: 0, JavaOnlyArray.from(headers), body, "text", true, 0, false); ArgumentCaptor<Request> argumentCaptor = ArgumentCaptor.forClass(Request.class); verify(httpClient).newCall(argumentCaptor.capture()); assertThat(argumentCaptor.getValue().url().toString()).isEqualTo("http: assertThat(argumentCaptor.getValue().method()).isEqualTo("POST"); assertThat(argumentCaptor.getValue().body().contentType().type()). isEqualTo(MultipartBody.FORM.type()); assertThat(argumentCaptor.getValue().body().contentType().subtype()). isEqualTo(MultipartBody.FORM.subtype()); Headers requestHeaders = argumentCaptor.getValue().headers(); assertThat(requestHeaders.size()).isEqualTo(3); assertThat(requestHeaders.get("Accept")).isEqualTo("text/plain"); assertThat(requestHeaders.get("User-Agent")).isEqualTo("React test agent/1.0"); assertThat(requestHeaders.get("content-type")).isEqualTo("multipart/form-data"); } @Test public void testMultipartPostRequestBody() throws Exception { InputStream inputStream = mock(InputStream.class); PowerMockito.mockStatic(RequestBodyUtil.class); when(RequestBodyUtil.getFileInputStream(any(ReactContext.class), any(String.class))) .thenReturn(inputStream); when(RequestBodyUtil.create(any(MediaType.class), any(InputStream.class))).thenCallRealMethod(); when(RequestBodyUtil.createProgressRequest(any(RequestBody.class), any(ProgressListener.class))) .thenCallRealMethod(); when(inputStream.available()).thenReturn("imageUri".length()); final MultipartBody.Builder multipartBuilder = mock(MultipartBody.Builder.class); PowerMockito.whenNew(MultipartBody.Builder.class).withNoArguments().thenReturn(multipartBuilder); when(multipartBuilder.setType(any(MediaType.class))).thenAnswer( new Answer<Object>() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { return multipartBuilder; } }); when(multipartBuilder.addPart(any(Headers.class), any(RequestBody.class))).thenAnswer( new Answer<Object>() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { return multipartBuilder; } }); when(multipartBuilder.build()).thenAnswer( new Answer<Object>() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { return mock(MultipartBody.class); } }); List<JavaOnlyArray> headers = Arrays.asList( JavaOnlyArray.of("content-type", "multipart/form-data")); JavaOnlyMap body = new JavaOnlyMap(); JavaOnlyArray formData = new JavaOnlyArray(); body.putArray("formData", formData); JavaOnlyMap bodyPart = new JavaOnlyMap(); bodyPart.putString("string", "locale"); bodyPart.putArray( "headers", JavaOnlyArray.from( Arrays.asList( JavaOnlyArray.of("content-disposition", "user")))); formData.pushMap(bodyPart); JavaOnlyMap imageBodyPart = new JavaOnlyMap(); imageBodyPart.putString("uri", "imageUri"); imageBodyPart.putArray( "headers", JavaOnlyArray.from( Arrays.asList( JavaOnlyArray.of("content-type", "image/jpg"), JavaOnlyArray.of("content-disposition", "filename=photo.jpg")))); formData.pushMap(imageBodyPart); OkHttpClient httpClient = mock(OkHttpClient.class); when(httpClient.newCall(any(Request.class))).thenAnswer( new Answer<Object>() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { Call callMock = mock(Call.class); return callMock; } }); OkHttpClient.Builder clientBuilder = mock(OkHttpClient.Builder.class); when(clientBuilder.build()).thenReturn(httpClient); when(httpClient.newBuilder()).thenReturn(clientBuilder); NetworkingModule networkingModule = new NetworkingModule(mock(ReactApplicationContext.class), "", httpClient); networkingModule.sendRequest( "POST", "http: 0, JavaOnlyArray.from(headers), body, "text", true, 0, false); PowerMockito.verifyStatic(times(1)); RequestBodyUtil.getFileInputStream(any(ReactContext.class), eq("imageUri")); PowerMockito.verifyStatic(times(1)); RequestBodyUtil.create(MediaType.parse("image/jpg"), inputStream); verify(multipartBuilder).build(); verify(multipartBuilder).setType(MultipartBody.FORM); ArgumentCaptor<Headers> headersArgumentCaptor = ArgumentCaptor.forClass(Headers.class); ArgumentCaptor<RequestBody> bodyArgumentCaptor = ArgumentCaptor.forClass(RequestBody.class); verify(multipartBuilder, times(2)). addPart(headersArgumentCaptor.capture(), bodyArgumentCaptor.capture()); List<Headers> bodyHeaders = headersArgumentCaptor.getAllValues(); assertThat(bodyHeaders.size()).isEqualTo(2); List<RequestBody> bodyRequestBody = bodyArgumentCaptor.getAllValues(); assertThat(bodyRequestBody.size()).isEqualTo(2); assertThat(bodyHeaders.get(0).get("content-disposition")).isEqualTo("user"); assertThat(bodyRequestBody.get(0).contentType()).isNull(); assertThat(bodyRequestBody.get(0).contentLength()).isEqualTo("locale".getBytes().length); assertThat(bodyHeaders.get(1).get("content-disposition")).isEqualTo("filename=photo.jpg"); assertThat(bodyRequestBody.get(1).contentType()).isEqualTo(MediaType.parse("image/jpg")); assertThat(bodyRequestBody.get(1).contentLength()).isEqualTo("imageUri".getBytes().length); }
UIManagerModuleConstants { public static Map<String, Object> getConstants() { HashMap<String, Object> constants = new HashMap<String, Object>(); constants.put( "UIView", MapBuilder.of( "ContentMode", MapBuilder.of( "ScaleAspectFit", ImageView.ScaleType.FIT_CENTER.ordinal(), "ScaleAspectFill", ImageView.ScaleType.CENTER_CROP.ordinal(), "ScaleAspectCenter", ImageView.ScaleType.CENTER_INSIDE.ordinal()))); constants.put( "StyleConstants", MapBuilder.of( "PointerEventsValues", MapBuilder.of( "none", PointerEvents.NONE.ordinal(), "boxNone", PointerEvents.BOX_NONE.ordinal(), "boxOnly", PointerEvents.BOX_ONLY.ordinal(), "unspecified", PointerEvents.AUTO.ordinal()))); constants.put( "PopupMenu", MapBuilder.of( ACTION_DISMISSED, ACTION_DISMISSED, ACTION_ITEM_SELECTED, ACTION_ITEM_SELECTED)); constants.put( "AccessibilityEventTypes", MapBuilder.of( "typeWindowStateChanged", AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED, "typeViewClicked", AccessibilityEvent.TYPE_VIEW_CLICKED)); return constants; } static Map<String, Object> getConstants(); static final String ACTION_DISMISSED; static final String ACTION_ITEM_SELECTED; }
@Test public void testNoCustomConstants() { List<ViewManager> viewManagers = Arrays.asList(mock(ViewManager.class)); UIManagerModule uiManagerModule = new UIManagerModule( mReactContext, viewManagers, mUIImplementationProvider, false); Map<String, Object> constants = uiManagerModule.getConstants(); assertThat(constants) .containsKey(CUSTOM_BUBBLING_EVENT_TYPES) .containsKey(CUSTOM_DIRECT_EVENT_TYPES) .containsKey("Dimensions"); } @Test public void testCustomBubblingEvents() { ViewManager mockViewManager = mock(ViewManager.class); List<ViewManager> viewManagers = Arrays.asList(mockViewManager); when(mockViewManager.getExportedCustomBubblingEventTypeConstants()) .thenReturn(MapBuilder.of("onTwirl", TWIRL_BUBBLING_EVENT_MAP)); UIManagerModule uiManagerModule = new UIManagerModule( mReactContext, viewManagers, mUIImplementationProvider, false); Map<String, Object> constants = uiManagerModule.getConstants(); assertThat((Map) constants.get(CUSTOM_BUBBLING_EVENT_TYPES)) .contains(MapEntry.entry("onTwirl", TWIRL_BUBBLING_EVENT_MAP)) .containsKey("topChange"); } @Test public void testCustomDirectEvents() { ViewManager mockViewManager = mock(ViewManager.class); List<ViewManager> viewManagers = Arrays.asList(mockViewManager); when(mockViewManager.getExportedCustomDirectEventTypeConstants()) .thenReturn(MapBuilder.of("onTwirl", TWIRL_DIRECT_EVENT_MAP)); UIManagerModule uiManagerModule = new UIManagerModule( mReactContext, viewManagers, mUIImplementationProvider, false); Map<String, Object> constants = uiManagerModule.getConstants(); assertThat((Map) constants.get(CUSTOM_DIRECT_EVENT_TYPES)) .contains(MapEntry.entry("onTwirl", TWIRL_DIRECT_EVENT_MAP)) .containsKey("topLoadingStart"); } @Test public void testCustomViewConstants() { ViewManager mockViewManager = mock(ViewManager.class); List<ViewManager> viewManagers = Arrays.asList(mockViewManager); when(mockViewManager.getName()).thenReturn("RedPandaPhotoOfTheDayView"); when(mockViewManager.getExportedViewConstants()) .thenReturn(MapBuilder.of("PhotoSizeType", MapBuilder.of("Small", 1, "Large", 2))); UIManagerModule uiManagerModule = new UIManagerModule( mReactContext, viewManagers, mUIImplementationProvider, false); Map<String, Object> constants = uiManagerModule.getConstants(); assertThat(constants).containsKey("RedPandaPhotoOfTheDayView"); assertThat((Map) constants.get("RedPandaPhotoOfTheDayView")).containsKey("Constants"); assertThat((Map) valueAtPath(constants, "RedPandaPhotoOfTheDayView", "Constants")) .containsKey("PhotoSizeType"); } @Test public void testNativeProps() { ViewManager mockViewManager = mock(ViewManager.class); List<ViewManager> viewManagers = Arrays.asList(mockViewManager); when(mockViewManager.getName()).thenReturn("SomeView"); when(mockViewManager.getNativeProps()) .thenReturn(MapBuilder.of("fooProp", "number")); UIManagerModule uiManagerModule = new UIManagerModule( mReactContext, viewManagers, mUIImplementationProvider, false); Map<String, Object> constants = uiManagerModule.getConstants(); assertThat((String) valueAtPath(constants, "SomeView", "NativeProps", "fooProp")) .isEqualTo("number"); } @Test public void testMergeConstants() { ViewManager managerX = mock(ViewManager.class); when(managerX.getExportedCustomDirectEventTypeConstants()).thenReturn(MapBuilder.of( "onTwirl", MapBuilder.of( "registrationName", "onTwirl", "keyToOverride", "valueX", "mapToMerge", MapBuilder.of("keyToOverride", "innerValueX", "anotherKey", "valueX")))); ViewManager managerY = mock(ViewManager.class); when(managerY.getExportedCustomDirectEventTypeConstants()).thenReturn(MapBuilder.of( "onTwirl", MapBuilder.of( "extraKey", "extraValue", "keyToOverride", "valueY", "mapToMerge", MapBuilder.of("keyToOverride", "innerValueY", "extraKey", "valueY")))); List<ViewManager> viewManagers = Arrays.asList(managerX, managerY); UIManagerModule uiManagerModule = new UIManagerModule( mReactContext, viewManagers, mUIImplementationProvider, false); Map<String, Object> constants = uiManagerModule.getConstants(); assertThat((Map) constants.get(CUSTOM_DIRECT_EVENT_TYPES)).containsKey("onTwirl"); Map twirlMap = (Map) valueAtPath(constants, CUSTOM_DIRECT_EVENT_TYPES, "onTwirl"); assertThat(twirlMap) .contains(MapEntry.entry("registrationName", "onTwirl")) .contains(MapEntry.entry("keyToOverride", "valueY")) .contains(MapEntry.entry("extraKey", "extraValue")) .containsKey("mapToMerge"); Map mapToMerge = (Map) valueAtPath(twirlMap, "mapToMerge"); assertThat(mapToMerge) .contains(MapEntry.entry("keyToOverride", "innerValueY")) .contains(MapEntry.entry("anotherKey", "valueX")) .contains(MapEntry.entry("extraKey", "valueY")); }
UIManagerModule extends ReactContextBaseJavaModule implements OnBatchCompleteListener, LifecycleEventListener, PerformanceCounter { @ReactMethod public void replaceExistingNonRootView(int oldTag, int newTag) { mUIImplementation.replaceExistingNonRootView(oldTag, newTag); } UIManagerModule( ReactApplicationContext reactContext, List<ViewManager> viewManagerList, UIImplementationProvider uiImplementationProvider, boolean lazyViewManagersEnabled); UIImplementation getUIImplementation(); @Override String getName(); @Override Map<String, Object> getConstants(); @Override void initialize(); @Override void onHostResume(); @Override void onHostPause(); @Override void onHostDestroy(); @Override void onCatalystInstanceDestroy(); Map<String,Double> getPerformanceCounters(); int addMeasuredRootView(final SizeMonitoringFrameLayout rootView); @ReactMethod void removeRootView(int rootViewTag); void updateNodeSize(int nodeViewTag, int newWidth, int newHeight); @ReactMethod void createView(int tag, String className, int rootViewTag, ReadableMap props); @ReactMethod void updateView(int tag, String className, ReadableMap props); @ReactMethod void manageChildren( int viewTag, @Nullable ReadableArray moveFrom, @Nullable ReadableArray moveTo, @Nullable ReadableArray addChildTags, @Nullable ReadableArray addAtIndices, @Nullable ReadableArray removeFrom); @ReactMethod void setChildren( int viewTag, ReadableArray childrenTags); @ReactMethod void replaceExistingNonRootView(int oldTag, int newTag); @ReactMethod void removeSubviewsFromContainerWithID(int containerTag); @ReactMethod void measure(int reactTag, Callback callback); @ReactMethod void measureInWindow(int reactTag, Callback callback); @ReactMethod void measureLayout( int tag, int ancestorTag, Callback errorCallback, Callback successCallback); @ReactMethod void measureLayoutRelativeToParent( int tag, Callback errorCallback, Callback successCallback); @ReactMethod void findSubviewIn( final int reactTag, final ReadableArray point, final Callback callback); void registerAnimation(Animation animation); void addAnimation(int reactTag, int animationID, Callback onSuccess); void removeAnimation(int reactTag, int animationID); @ReactMethod void setJSResponder(int reactTag, boolean blockNativeResponder); @ReactMethod void clearJSResponder(); @ReactMethod void dispatchViewManagerCommand(int reactTag, int commandId, ReadableArray commandArgs); @ReactMethod void showPopupMenu(int reactTag, ReadableArray items, Callback error, Callback success); @ReactMethod void setLayoutAnimationEnabledExperimental(boolean enabled); @ReactMethod void configureNextLayoutAnimation( ReadableMap config, Callback success, Callback error); @Override void onBatchComplete(); void setViewHierarchyUpdateDebugListener( @Nullable NotThreadSafeViewHierarchyUpdateDebugListener listener); EventDispatcher getEventDispatcher(); @ReactMethod void sendAccessibilityEvent(int tag, int eventType); void addUIBlock(UIBlock block); int resolveRootTagFromReactTag(int reactTag); }
@Test public void testReplaceExistingNonRootView() { UIManagerModule uiManager = getUIManagerModule(); TestMoveDeleteHierarchy hierarchy = createMoveDeleteHierarchy(uiManager); int newViewTag = 1234; uiManager.createView( newViewTag, ReactViewManager.REACT_CLASS, hierarchy.rootView, JavaOnlyMap.of("backgroundColor", Color.RED)); uiManager.replaceExistingNonRootView(hierarchy.view2, newViewTag); uiManager.onBatchComplete(); executePendingFrameCallbacks(); assertThat(hierarchy.nativeRootView.getChildCount()).isEqualTo(4); assertThat(hierarchy.nativeRootView.getChildAt(2)).isInstanceOf(ReactViewGroup.class); ReactViewGroup view = (ReactViewGroup) hierarchy.nativeRootView.getChildAt(2); assertThat(view.getBackgroundColor()).isEqualTo(Color.RED); }
UIManagerModule extends ReactContextBaseJavaModule implements OnBatchCompleteListener, LifecycleEventListener, PerformanceCounter { @ReactMethod public void removeSubviewsFromContainerWithID(int containerTag) { mUIImplementation.removeSubviewsFromContainerWithID(containerTag); } UIManagerModule( ReactApplicationContext reactContext, List<ViewManager> viewManagerList, UIImplementationProvider uiImplementationProvider, boolean lazyViewManagersEnabled); UIImplementation getUIImplementation(); @Override String getName(); @Override Map<String, Object> getConstants(); @Override void initialize(); @Override void onHostResume(); @Override void onHostPause(); @Override void onHostDestroy(); @Override void onCatalystInstanceDestroy(); Map<String,Double> getPerformanceCounters(); int addMeasuredRootView(final SizeMonitoringFrameLayout rootView); @ReactMethod void removeRootView(int rootViewTag); void updateNodeSize(int nodeViewTag, int newWidth, int newHeight); @ReactMethod void createView(int tag, String className, int rootViewTag, ReadableMap props); @ReactMethod void updateView(int tag, String className, ReadableMap props); @ReactMethod void manageChildren( int viewTag, @Nullable ReadableArray moveFrom, @Nullable ReadableArray moveTo, @Nullable ReadableArray addChildTags, @Nullable ReadableArray addAtIndices, @Nullable ReadableArray removeFrom); @ReactMethod void setChildren( int viewTag, ReadableArray childrenTags); @ReactMethod void replaceExistingNonRootView(int oldTag, int newTag); @ReactMethod void removeSubviewsFromContainerWithID(int containerTag); @ReactMethod void measure(int reactTag, Callback callback); @ReactMethod void measureInWindow(int reactTag, Callback callback); @ReactMethod void measureLayout( int tag, int ancestorTag, Callback errorCallback, Callback successCallback); @ReactMethod void measureLayoutRelativeToParent( int tag, Callback errorCallback, Callback successCallback); @ReactMethod void findSubviewIn( final int reactTag, final ReadableArray point, final Callback callback); void registerAnimation(Animation animation); void addAnimation(int reactTag, int animationID, Callback onSuccess); void removeAnimation(int reactTag, int animationID); @ReactMethod void setJSResponder(int reactTag, boolean blockNativeResponder); @ReactMethod void clearJSResponder(); @ReactMethod void dispatchViewManagerCommand(int reactTag, int commandId, ReadableArray commandArgs); @ReactMethod void showPopupMenu(int reactTag, ReadableArray items, Callback error, Callback success); @ReactMethod void setLayoutAnimationEnabledExperimental(boolean enabled); @ReactMethod void configureNextLayoutAnimation( ReadableMap config, Callback success, Callback error); @Override void onBatchComplete(); void setViewHierarchyUpdateDebugListener( @Nullable NotThreadSafeViewHierarchyUpdateDebugListener listener); EventDispatcher getEventDispatcher(); @ReactMethod void sendAccessibilityEvent(int tag, int eventType); void addUIBlock(UIBlock block); int resolveRootTagFromReactTag(int reactTag); }
@Test public void testRemoveSubviewsFromContainerWithID() { UIManagerModule uiManager = getUIManagerModule(); ReactRootView rootView = new ReactRootView(RuntimeEnvironment.application.getApplicationContext()); int rootTag = uiManager.addMeasuredRootView(rootView); final int containerTag = rootTag + 1; final int containerSiblingTag = containerTag + 1; uiManager.createView( containerTag, ReactViewManager.REACT_CLASS, rootTag, JavaOnlyMap.of("collapsable", false)); uiManager.createView( containerSiblingTag, ReactViewManager.REACT_CLASS, rootTag, JavaOnlyMap.of("collapsable", false)); addChild(uiManager, rootTag, containerTag, 0); addChild(uiManager, rootTag, containerSiblingTag, 1); uiManager.createView( containerTag + 2, ReactTextViewManager.REACT_CLASS, rootTag, JavaOnlyMap.of("collapsable", false)); uiManager.createView( containerTag + 3, ReactTextViewManager.REACT_CLASS, rootTag, JavaOnlyMap.of("collapsable", false)); addChild(uiManager, containerTag, containerTag + 2, 0); addChild(uiManager, containerTag, containerTag + 3, 1); uiManager.onBatchComplete(); executePendingFrameCallbacks(); assertThat(rootView.getChildCount()).isEqualTo(2); assertThat(((ViewGroup) rootView.getChildAt(0)).getChildCount()).isEqualTo(2); uiManager.removeSubviewsFromContainerWithID(containerTag); uiManager.onBatchComplete(); executePendingFrameCallbacks(); assertThat(rootView.getChildCount()).isEqualTo(2); assertThat(((ViewGroup) rootView.getChildAt(0)).getChildCount()).isEqualTo(0); }
CompositeReactPackage extends ReactInstancePackage { @Override public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) { final Map<String, NativeModule> moduleMap = new HashMap<>(); for (ReactPackage reactPackage: mChildReactPackages) { for (NativeModule nativeModule: reactPackage.createNativeModules(reactContext)) { moduleMap.put(nativeModule.getName(), nativeModule); } } return new ArrayList(moduleMap.values()); } CompositeReactPackage(ReactPackage arg1, ReactPackage arg2, ReactPackage... args); @Override List<NativeModule> createNativeModules(ReactApplicationContext reactContext); @Override List<NativeModule> createNativeModules( ReactApplicationContext reactContext, ReactInstanceManager reactInstanceManager); @Override List<Class<? extends JavaScriptModule>> createJSModules(); @Override List<ViewManager> createViewManagers(ReactApplicationContext reactContext); }
@Test public void testThatCreateNativeModulesIsCalledOnAllPackages() { CompositeReactPackage composite = new CompositeReactPackage(packageNo1, packageNo2, packageNo3); composite.createNativeModules(reactContext); verify(packageNo1).createNativeModules(reactContext); verify(packageNo2).createNativeModules(reactContext); verify(packageNo3).createNativeModules(reactContext); } @Test public void testThatCompositeReturnsASumOfNativeModules() { CompositeReactPackage composite = new CompositeReactPackage(packageNo1, packageNo2); NativeModule moduleNo1 = mock(NativeModule.class); when(moduleNo1.getName()).thenReturn("ModuleNo1"); final String sameModuleName = "SameModuleName"; NativeModule moduleNo2 = mock(NativeModule.class); when(moduleNo2.getName()).thenReturn(sameModuleName); NativeModule moduleNo3 = mock(NativeModule.class); when(moduleNo3.getName()).thenReturn(sameModuleName); NativeModule moduleNo4 = mock(NativeModule.class); when(moduleNo4.getName()).thenReturn("ModuleNo4"); when(packageNo1.createNativeModules(reactContext)).thenReturn( Arrays.asList(new NativeModule[]{moduleNo1, moduleNo2})); when(packageNo2.createNativeModules(reactContext)).thenReturn( Arrays.asList(new NativeModule[]{moduleNo3, moduleNo4})); List<NativeModule> compositeModules = composite.createNativeModules(reactContext); Set<NativeModule> expected = new HashSet<>( Arrays.asList(new NativeModule[]{moduleNo1, moduleNo3, moduleNo4})); Set<NativeModule> actual = new HashSet<>(compositeModules); assertEquals(expected, actual); }
CompositeReactPackage extends ReactInstancePackage { @Override public List<Class<? extends JavaScriptModule>> createJSModules() { final Set<Class<? extends JavaScriptModule>> moduleSet = new HashSet<>(); for (ReactPackage reactPackage: mChildReactPackages) { for (Class<? extends JavaScriptModule> jsModule: reactPackage.createJSModules()) { moduleSet.add(jsModule); } } return new ArrayList(moduleSet); } CompositeReactPackage(ReactPackage arg1, ReactPackage arg2, ReactPackage... args); @Override List<NativeModule> createNativeModules(ReactApplicationContext reactContext); @Override List<NativeModule> createNativeModules( ReactApplicationContext reactContext, ReactInstanceManager reactInstanceManager); @Override List<Class<? extends JavaScriptModule>> createJSModules(); @Override List<ViewManager> createViewManagers(ReactApplicationContext reactContext); }
@Test public void testThatCreateJSModulesIsCalledOnAllPackages() { CompositeReactPackage composite = new CompositeReactPackage(packageNo1, packageNo2, packageNo3); composite.createJSModules(); verify(packageNo1).createJSModules(); verify(packageNo2).createJSModules(); verify(packageNo3).createJSModules(); } @Test public void testThatCompositeReturnsASumOfJSModules() { CompositeReactPackage composite = new CompositeReactPackage(packageNo1, packageNo2); Class<? extends JavaScriptModule> moduleNo1 = mock(JavaScriptModuleNo1.class).getClass(); Class<? extends JavaScriptModule> moduleNo2 = mock(JavaScriptModuleNo2.class).getClass(); Class<? extends JavaScriptModule> moduleNo3 = mock(JavaScriptModuleNo3.class).getClass(); List<Class<? extends JavaScriptModule>> l1 = new ArrayList<>(); l1.add(moduleNo1); when(packageNo1.createJSModules()).thenReturn(l1); List<Class<? extends JavaScriptModule>> l2 = new ArrayList<>(); l2.add(moduleNo2); l2.add(moduleNo3); when(packageNo2.createJSModules()).thenReturn(l2); List<Class<? extends JavaScriptModule>> compositeModules = composite.createJSModules(); List<Class<? extends JavaScriptModule>> l3 = new ArrayList<>(); l3.add(moduleNo1); l3.add(moduleNo2); l3.add(moduleNo3); Set<Class<? extends JavaScriptModule>> expected = new HashSet<>(l3); Set<Class<? extends JavaScriptModule>> actual = new HashSet<>(compositeModules); assertEquals(expected, actual); }
CompositeReactPackage extends ReactInstancePackage { @Override public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) { final Map<String, ViewManager> viewManagerMap = new HashMap<>(); for (ReactPackage reactPackage: mChildReactPackages) { for (ViewManager viewManager: reactPackage.createViewManagers(reactContext)) { viewManagerMap.put(viewManager.getName(), viewManager); } } return new ArrayList(viewManagerMap.values()); } CompositeReactPackage(ReactPackage arg1, ReactPackage arg2, ReactPackage... args); @Override List<NativeModule> createNativeModules(ReactApplicationContext reactContext); @Override List<NativeModule> createNativeModules( ReactApplicationContext reactContext, ReactInstanceManager reactInstanceManager); @Override List<Class<? extends JavaScriptModule>> createJSModules(); @Override List<ViewManager> createViewManagers(ReactApplicationContext reactContext); }
@Test public void testThatCreateViewManagersIsCalledOnAllPackages() { CompositeReactPackage composite = new CompositeReactPackage(packageNo1, packageNo2, packageNo3); composite.createViewManagers(reactContext); verify(packageNo1).createViewManagers(reactContext); verify(packageNo2).createViewManagers(reactContext); verify(packageNo3).createViewManagers(reactContext); } @Test public void testThatCompositeReturnsASumOfViewManagers() { CompositeReactPackage composite = new CompositeReactPackage(packageNo1, packageNo2); ViewManager managerNo1 = mock(ViewManager.class); when(managerNo1.getName()).thenReturn("ManagerNo1"); final String sameModuleName = "SameModuleName"; ViewManager managerNo2 = mock(ViewManager.class); when(managerNo2.getName()).thenReturn(sameModuleName); ViewManager managerNo3 = mock(ViewManager.class); when(managerNo3.getName()).thenReturn(sameModuleName); ViewManager managerNo4 = mock(ViewManager.class); when(managerNo4.getName()).thenReturn("ManagerNo4"); when(packageNo1.createViewManagers(reactContext)).thenReturn( Arrays.asList(new ViewManager[]{managerNo1, managerNo2})); when(packageNo2.createViewManagers(reactContext)).thenReturn( Arrays.asList(new ViewManager[]{managerNo3, managerNo4})); List<ViewManager> compositeModules = composite.createViewManagers(reactContext); Set<ViewManager> expected = new HashSet<>( Arrays.asList(new ViewManager[]{managerNo1, managerNo3, managerNo4}) ); Set<ViewManager> actual = new HashSet<>(compositeModules); assertEquals(expected, actual); }
JSPackagerClient implements ReconnectingWebSocket.MessageCallback { @Override public void onMessage(ResponseBody response) { if (response.contentType() != WebSocket.TEXT) { FLog.w( TAG, "Websocket received message with payload of unexpected type " + response.contentType()); return; } try { JSONObject message = new JSONObject(response.string()); int version = message.optInt("version"); String method = message.optString("method"); Object id = message.opt("id"); Object params = message.opt("params"); if (version != PROTOCOL_VERSION) { FLog.e( TAG, "Message with incompatible or missing version of protocol received: " + version); return; } if (method == null) { abortOnMessage(id, "No method provided"); return; } RequestHandler handler = mRequestHandlers.get(method); if (handler == null) { abortOnMessage(id, "No request handler for method: " + method); return; } if (id == null) { handler.onNotification(params); } else { handler.onRequest(params, new ResponderImpl(id)); } } catch (Exception e) { FLog.e(TAG, "Handling the message failed", e); } finally { response.close(); } } JSPackagerClient(String clientId, PackagerConnectionSettings settings, Map<String, RequestHandler> requestHandlers); void init(); void close(); @Override void onMessage(ResponseBody response); }
@Test public void test_onMessage_ShouldTriggerNotification() throws IOException { RequestHandler handler = mock(RequestHandler.class); final JSPackagerClient client = new JSPackagerClient("test_client", mSettings, createRH("methodValue", handler)); client.onMessage( ResponseBody.create( WebSocket.TEXT, "{\"version\": 2, \"method\": \"methodValue\", \"params\": \"paramsValue\"}")); verify(handler).onNotification(eq("paramsValue")); verify(handler, never()).onRequest(any(), any(Responder.class)); } @Test public void test_onMessage_ShouldTriggerRequest() throws IOException { RequestHandler handler = mock(RequestHandler.class); final JSPackagerClient client = new JSPackagerClient("test_client", mSettings, createRH("methodValue", handler)); client.onMessage( ResponseBody.create( WebSocket.TEXT, "{\"version\": 2, \"id\": \"idValue\", \"method\": \"methodValue\", \"params\": \"paramsValue\"}")); verify(handler, never()).onNotification(any()); verify(handler).onRequest(eq("paramsValue"), any(Responder.class)); } @Test public void test_onMessage_WithoutParams_ShouldTriggerNotification() throws IOException { RequestHandler handler = mock(RequestHandler.class); final JSPackagerClient client = new JSPackagerClient("test_client", mSettings, createRH("methodValue", handler)); client.onMessage( ResponseBody.create( WebSocket.TEXT, "{\"version\": 2, \"method\": \"methodValue\"}")); verify(handler).onNotification(eq(null)); verify(handler, never()).onRequest(any(), any(Responder.class)); } @Test public void test_onMessage_WithInvalidContentType_ShouldNotTriggerCallback() throws IOException { RequestHandler handler = mock(RequestHandler.class); final JSPackagerClient client = new JSPackagerClient("test_client", mSettings, createRH("methodValue", handler)); client.onMessage( ResponseBody.create( WebSocket.BINARY, "{\"version\": 2, \"method\": \"methodValue\"}")); verify(handler, never()).onNotification(any()); verify(handler, never()).onRequest(any(), any(Responder.class)); } @Test public void test_onMessage_WithoutMethod_ShouldNotTriggerCallback() throws IOException { RequestHandler handler = mock(RequestHandler.class); final JSPackagerClient client = new JSPackagerClient("test_client", mSettings, createRH("methodValue", handler)); client.onMessage( ResponseBody.create( WebSocket.TEXT, "{\"version\": 2}")); verify(handler, never()).onNotification(any()); verify(handler, never()).onRequest(any(), any(Responder.class)); } @Test public void test_onMessage_With_Null_Action_ShouldNotTriggerCallback() throws IOException { RequestHandler handler = mock(RequestHandler.class); final JSPackagerClient client = new JSPackagerClient("test_client", mSettings, createRH("methodValue", handler)); client.onMessage( ResponseBody.create( WebSocket.TEXT, "{\"version\": 2, \"method\": null}")); verify(handler, never()).onNotification(any()); verify(handler, never()).onRequest(any(), any(Responder.class)); } @Test public void test_onMessage_WithInvalidMethod_ShouldNotTriggerCallback() throws IOException { RequestHandler handler = mock(RequestHandler.class); final JSPackagerClient client = new JSPackagerClient("test_client", mSettings, createRH("methodValue", handler)); client.onMessage( ResponseBody.create( WebSocket.BINARY, "{\"version\": 2, \"method\": \"methodValue2\"}")); verify(handler, never()).onNotification(any()); verify(handler, never()).onRequest(any(), any(Responder.class)); } @Test public void test_onMessage_WrongVersion_ShouldNotTriggerCallback() throws IOException { RequestHandler handler = mock(RequestHandler.class); final JSPackagerClient client = new JSPackagerClient("test_client", mSettings, createRH("methodValue", handler)); client.onMessage( ResponseBody.create( WebSocket.TEXT, "{\"version\": 1, \"method\": \"methodValue\"}")); verify(handler, never()).onNotification(any()); verify(handler, never()).onRequest(any(), any(Responder.class)); }
PdfParser { static List<String> extractTextLinesFromPdf(InputStream pdfStream) { PdfReader pdfReader = null; try { pdfReader = new PdfReader(pdfStream); List<String> textLines = new ArrayList<>(); for (int page = 1; page <= pdfReader.getNumberOfPages(); page++) { String textFromPage = PdfTextExtractor.getTextFromPage(pdfReader, page); String[] linesFromPage = textFromPage.split("\n"); for (String lineFromPage : linesFromPage) { lineFromPage = lineFromPage.trim(); int previousLength; do { previousLength = lineFromPage.length(); lineFromPage = lineFromPage.replaceAll(" ", " "); } while (previousLength != lineFromPage.length()); if (isTextLinePdfParsingJunk(lineFromPage)) continue; textLines.add(lineFromPage); } } return textLines; } catch (IOException e) { throw new UncheckedIOException(e); } finally { if (pdfReader != null) pdfReader.close(); } } static Codebook parseCodebookPdf(SupportedCodebook codebookSource); static final String FIELD_NAME_LABEL; static final String FIELD_NAME_DESCRIPTION; static final String FIELD_NAME_SHORT_NAME; static final String FIELD_NAME_LONG_NAME; static final String FIELD_NAME_TYPE; }
@Test public void extractTextLinesFromPdf_ffsClaims() throws IOException { try (InputStream codebookPdfStream = SupportedCodebook.FFS_CLAIMS.getCodebookPdfInputStream();) { List<String> codebookTextLines = PdfParser.extractTextLinesFromPdf(codebookPdfStream); Assert.assertNotNull(codebookTextLines); Assert.assertTrue(codebookTextLines.size() > 100); } }
PdfParser { static List<List<String>> findVariableSections(List<String> codebookTextLines) { int firstVariableLine = findFirstVariableLine(codebookTextLines); int lastVariableLine = findLastVariableLine(codebookTextLines); List<List<String>> variableSectionLineGroups = new ArrayList<>(); List<String> sectionBuilder = new ArrayList<>(); for (int lineIndex = firstVariableLine; lineIndex <= lastVariableLine; lineIndex++) { String line = codebookTextLines.get(lineIndex); if (!isDocumentMetadata(line)) sectionBuilder.add(line); if (containsVariableLabelField(line)) { if (sectionBuilder.size() == 2) { } else { List<String> completedSection = sectionBuilder.subList(0, sectionBuilder.size() - 2); variableSectionLineGroups.add(new ArrayList<>(completedSection)); completedSection.clear(); } } } if (!sectionBuilder.isEmpty()) variableSectionLineGroups.add(new ArrayList<>(sectionBuilder)); return variableSectionLineGroups; } static Codebook parseCodebookPdf(SupportedCodebook codebookSource); static final String FIELD_NAME_LABEL; static final String FIELD_NAME_DESCRIPTION; static final String FIELD_NAME_SHORT_NAME; static final String FIELD_NAME_LONG_NAME; static final String FIELD_NAME_TYPE; }
@Test public void findVariableSections() throws IOException { for (SupportedCodebook supportedCodebook : SupportedCodebook.values()) { try (InputStream codebookPdfStream = supportedCodebook.getCodebookPdfInputStream();) { LOGGER.info("Looking for sections in codebook: {}", supportedCodebook.name()); List<String> codebookTextLines = PdfParser.extractTextLinesFromPdf(codebookPdfStream); List<List<String>> variableSections = PdfParser.findVariableSections(codebookTextLines); for (List<String> variableSection : variableSections) { Assert.assertNotNull(variableSection); Assert.assertTrue(variableSection.size() >= 10); } Predicate<? super String> searchFieldFilter = l -> l.startsWith("SHORT_NAME:"); List<String> searchFieldLines = codebookTextLines.stream().filter(searchFieldFilter) .collect(Collectors.toList()); Assert.assertEquals("Not all instances of that field are unique.", searchFieldLines.size(), new HashSet<>(searchFieldLines).size()); for (String searchFieldLine : searchFieldLines) { boolean foundSection = false; for (List<String> variableSection : variableSections) { for (String line : variableSection) if (searchFieldLine.equals(line)) foundSection = true; } Assert.assertTrue(String.format("Can't find search field line: '%s'", searchFieldLine), foundSection); } } } }
PdfParser { public static Codebook parseCodebookPdf(SupportedCodebook codebookSource) { try (InputStream codebookPdfStream = codebookSource.getCodebookPdfInputStream();) { List<String> codebookTextLines = extractTextLinesFromPdf(codebookPdfStream); Codebook codebook = new Codebook(codebookSource); List<List<String>> variableSections = findVariableSections(codebookTextLines); for (List<String> variableSection : variableSections) { Variable variable = parseVariable(codebook, variableSection); codebook.getVariables().add(variable); } return codebook; } catch (IOException e) { throw new UncheckedIOException(e); } } static Codebook parseCodebookPdf(SupportedCodebook codebookSource); static final String FIELD_NAME_LABEL; static final String FIELD_NAME_DESCRIPTION; static final String FIELD_NAME_SHORT_NAME; static final String FIELD_NAME_LONG_NAME; static final String FIELD_NAME_TYPE; }
@Test public void parseCodebookPdf() throws IOException { for (SupportedCodebook supportedCodebook : SupportedCodebook.values()) { LOGGER.info("Looking for sections in codebook: {}", supportedCodebook.name()); Codebook codebook = PdfParser.parseCodebookPdf(supportedCodebook); Assert.assertNotNull(codebook); Assert.assertTrue("Not as many variables as expected: " + codebook.getVariables().size(), codebook.getVariables().size() > 50); for (Variable variable : codebook.getVariables()) { assertVariableIsValid(variable); } } } @Test public void parseCodebookPdf_DUAL_MO() throws IOException { Codebook codebook = PdfParser.parseCodebookPdf(SupportedCodebook.BENEFICIARY_SUMMARY); Variable variable = codebook.getVariables().stream().filter(v -> v.getId().equals("DUAL_MO")).findAny().get(); String expectedDescription1 = "This variable is the number of months during the year that the beneficiary" + " was dually eligible (i.e., he/she was also eligible for Medicaid benefits)."; String expectedComment1 = "CCW derived this variable by counting the number of months where the beneficiary" + " had dual eligibility (DUAL_STUS_CD_XX not equal to '00' or '**'). There are different ways to" + " classify dually eligible beneficiaries - in terms of whether he/she is enrolled in full or" + " partial benefits. Additional information regarding various ways to identify dually enrolled" + " populations, refer to a CCW Technical Guidance document entitled: \"Options in Determining Dual" + " Eligibles\""; Assert.assertEquals("Months of Dual Eligibility", variable.getLabel()); assertParagraphsEquals(Arrays.asList(expectedDescription1), variable.getDescription()); Assert.assertEquals("DUAL_MO", variable.getShortName().get()); Assert.assertEquals("DUAL_ELGBL_MOS_NUM", variable.getLongName()); Assert.assertEquals(VariableType.CHAR, variable.getType().get()); Assert.assertEquals(new Integer(2), variable.getLength()); Assert.assertEquals("CMS Enrollment Database (EDB) (derived)", variable.getSource().get()); Assert.assertEquals("The value in this field is between '00' through '12'.", variable.getValueFormat().get()); Assert.assertFalse(variable.getValueGroups().isPresent()); assertParagraphsEquals(Arrays.asList(expectedComment1), variable.getComment()); } @Test public void parseCodebookPdf_DSH_OP_CLM_VAL_AMT() throws IOException { Codebook codebook = PdfParser.parseCodebookPdf(SupportedCodebook.FFS_CLAIMS); Variable variable = codebook.getVariables().stream().filter(v -> v.getId().equals("DSH_OP_CLM_VAL_AMT")) .findAny().get(); String expectedDescription1 = "This is one component of the total amount that is payable on prospective" + " payment system (PPS) claims, and reflects the DSH (disproportionate share hospital) payments" + " for operating expenses (such as labor) for the claim."; String expectedDescription2 = "There are two types of DSH amounts that may be payable for many PPS claims;" + " the other type of DSH payment is for the DSH capital amount (variable called" + " CLM_PPS_CPTL_DSPRPRTNT_SHR_AMT)."; String expectedDescription3 = "Both operating and capital DSH payments are components of the PPS, as well" + " as numerous other factors."; String expectedComment1 = "Medicare payments are described in detail in a series of Medicare Payment" + " Advisory Commission (MedPAC) documents called “Payment Basics” (see:" + " http: String expectedComment2 = "Also in the Medicare Learning Network (MLN) “Payment System Fact Sheet Series”" + " (see: " + "http: + ")."; String expectedComment3 = "DERIVATION RULES: If there is a value code '18' (i.e., in the Value Code File, if the" + " VAL_CD='18') then this dollar amount (VAL_AMT) is used to populate this field.\""; Assert.assertEquals("Operating Disproportionate Share (DSH) Amount", variable.getLabel()); assertParagraphsEquals(Arrays.asList(expectedDescription1, expectedDescription2, expectedDescription3), variable.getDescription()); Assert.assertEquals("DSH_OP", variable.getShortName().get()); Assert.assertEquals("DSH_OP_CLM_VAL_AMT", variable.getLongName()); Assert.assertEquals(VariableType.NUM, variable.getType().get()); Assert.assertEquals(new Integer(12), variable.getLength()); Assert.assertEquals("NCH", variable.getSource().get()); Assert.assertEquals("XXX.XX", variable.getValueFormat().get()); Assert.assertFalse(variable.getValueGroups().isPresent()); assertParagraphsEquals(Arrays.asList(expectedComment1, expectedComment2, expectedComment3), variable.getComment()); } @Test public void parseCodebookPdf_CARR_LINE_PRVDR_TYPE_CD() throws IOException { Codebook codebook = PdfParser.parseCodebookPdf(SupportedCodebook.FFS_CLAIMS); Variable variable = codebook.getVariables().stream().filter(v -> v.getId().equals("CARR_LINE_PRVDR_TYPE_CD")) .findAny().get(); String expectedDescription1 = "Code identifying the type of provider furnishing the service for this line" + " item on the carrier claim."; Assert.assertEquals("Carrier Line Provider Type Code", variable.getLabel()); assertParagraphsEquals(Arrays.asList(expectedDescription1), variable.getDescription()); Assert.assertEquals("PRV_TYPE", variable.getShortName().get()); Assert.assertEquals("CARR_LINE_PRVDR_TYPE_CD", variable.getLongName()); Assert.assertEquals(VariableType.CHAR, variable.getType().get()); Assert.assertEquals(new Integer(1), variable.getLength()); Assert.assertEquals("NCH", variable.getSource().get()); Assert.assertFalse(variable.getValueFormat().isPresent()); Assert.assertEquals(2, variable.getValueGroups().get().size()); Assert.assertEquals(8, variable.getValueGroups().get().get(0).getValues().size()); assertParagraphsEquals(Arrays.asList("For Physician/Supplier Claims:"), variable.getValueGroups().get().get(0).getDescription()); Assert.assertEquals(9, variable.getValueGroups().get().get(1).getValues().size()); assertParagraphsEquals( Arrays.asList("NOTE: PRIOR TO VERSION H, DME claims also used this code; the" + " following were valid code VALUES:"), variable.getValueGroups().get().get(1).getDescription()); Value value_0_3 = variable.getValueGroups().get().get(0).getValues().get(3); Assert.assertEquals("3", value_0_3.getCode()); Assert.assertEquals("Institutional provider", value_0_3.getDescription()); Value value_1_8 = variable.getValueGroups().get().get(1).getValues().get(8); Assert.assertEquals("8", value_1_8.getCode()); Assert.assertEquals("Other entities for whom EI numbers are used in coding the ID field or proprietorship" + " for whom EI numbers are used in coding the ID field.", value_1_8.getDescription()); Assert.assertFalse(variable.getComment().isPresent()); }
PdfParser { static String parseLabel(List<String> variableSection) { List<String> fieldText = extractFieldContent(variableSection, FIELD_NAME_LABEL, FIELD_NAME_LABEL_ALT1); List<String> fieldParagraphs = extractParagraphs(fieldText); if (fieldParagraphs.size() != 1) throw new IllegalStateException( String.format("Invalid '%s' field in variable section: %s", FIELD_NAME_LABEL, variableSection)); return fieldParagraphs.get(0); } static Codebook parseCodebookPdf(SupportedCodebook codebookSource); static final String FIELD_NAME_LABEL; static final String FIELD_NAME_DESCRIPTION; static final String FIELD_NAME_SHORT_NAME; static final String FIELD_NAME_LONG_NAME; static final String FIELD_NAME_TYPE; }
@Test public void parseLabel_multiline() { String[] variableSection = new String[] { "CLM_NEXT_GNRTN_ACO_IND_CD1", "LABEL: Claim Next Generation (NG) Accountable Care Organization (ACO) Indicator Code –", "Population-Based Payment (PBP)", "DESCRIPTION: The field identifies the claims that qualify for specific claims processing edits" + " related to", }; String parsedLabel = PdfParser.parseLabel(Arrays.asList(variableSection)); Assert.assertEquals( "Claim Next Generation (NG) Accountable Care Organization (ACO) Indicator Code – Population-Based" + " Payment (PBP)", parsedLabel); }
DatabaseSchemaManager { public static void createOrUpdateSchema(DataSource dataSource) { LOGGER.info("Schema create/upgrade: running..."); Flyway flyway = new Flyway(); flyway.setCleanDisabled(true); flyway.setDataSource(dataSource); flyway.setPlaceholders(createScriptPlaceholdersMap(dataSource)); flyway.migrate(); LOGGER.info("Schema create/upgrade: complete."); } static void createOrUpdateSchema(DataSource dataSource); static void dropIndexes(DataSource dataSource); }
@Test public void createOrUpdateSchemaOnHsql() { JDBCDataSource hsqlDataSource = new JDBCDataSource(); hsqlDataSource.setUrl("jdbc:hsqldb:mem:test"); DatabaseSchemaManager.createOrUpdateSchema(hsqlDataSource); }
CommandContext { public boolean hasFlag(char ch) { return booleanFlags.contains(ch) || valueFlags.containsKey(ch); } CommandContext(String args); CommandContext(String[] args); CommandContext(String args, Set<Character> valueFlags); CommandContext(String args, Set<Character> valueFlags, boolean allowHangingFlag); CommandContext(String[] args, Set<Character> valueFlags); CommandContext(String[] args, Set<Character> valueFlags, boolean allowHangingFlag, CommandLocals locals); CommandContext(String[] args, Set<Character> valueFlags, boolean allowHangingFlag, CommandLocals locals, boolean parseFlags); static String[] split(String args); SuggestionContext getSuggestionContext(); String getCommand(); boolean matches(String command); String getString(int index); String getString(int index, String def); String getJoinedStrings(int initialIndex); String getRemainingString(int start); String getString(int start, int end); int getInteger(int index); int getInteger(int index, int def); double getDouble(int index); double getDouble(int index, double def); String[] getSlice(int index); String[] getPaddedSlice(int index, int padding); String[] getParsedSlice(int index); String[] getParsedPaddedSlice(int index, int padding); boolean hasFlag(char ch); Set<Character> getFlags(); Map<Character, String> getValueFlags(); String getFlag(char ch); String getFlag(char ch, String def); int getFlagInteger(char ch); int getFlagInteger(char ch, int def); double getFlagDouble(char ch); double getFlagDouble(char ch, double def); int argsLength(); CommandLocals getLocals(); }
@Test public void testFlagsAnywhere() { try { CommandContext context = new CommandContext("r hello -f"); assertTrue(context.hasFlag('f')); CommandContext context2 = new CommandContext("r hello -f world"); assertTrue(context2.hasFlag('f')); } catch (CommandException e) { log.warn("Error", e); fail("Error creating CommandContext"); } }
Location { public Location setY(double y) { return new Location(extent, position.withY(y), yaw, pitch); } Location(Extent extent); Location(Extent extent, double x, double y, double z); Location(Extent extent, Vector3 position); Location(Extent extent, double x, double y, double z, Vector3 direction); Location(Extent extent, double x, double y, double z, float yaw, float pitch); Location(Extent extent, Vector3 position, Vector3 direction); Location(Extent extent, Vector3 position, float yaw, float pitch); Extent getExtent(); Location setExtent(Extent extent); float getYaw(); Location setYaw(float yaw); float getPitch(); Location setPitch(float pitch); Location setDirection(float yaw, float pitch); Vector3 getDirection(); Direction getDirectionEnum(); Location setDirection(Vector3 direction); Vector3 toVector(); double getX(); int getBlockX(); Location setX(double x); double getY(); int getBlockY(); Location setY(double y); double getZ(); int getBlockZ(); Location setZ(double z); Location setPosition(Vector3 position); @Override boolean equals(Object o); @Override int hashCode(); }
@Test public void testSetY() throws Exception { World world = mock(World.class); Location location1 = new Location(world, Vector3.ZERO); Location location2 = location1.setY(TEST_VALUE); assertEquals(0, location1.getY(), EPSILON); assertEquals(0, location2.getX(), EPSILON); assertEquals(TEST_VALUE, location2.getY(), EPSILON); assertEquals(0, location2.getZ(), EPSILON); }
Location { public double getZ() { return position.getZ(); } Location(Extent extent); Location(Extent extent, double x, double y, double z); Location(Extent extent, Vector3 position); Location(Extent extent, double x, double y, double z, Vector3 direction); Location(Extent extent, double x, double y, double z, float yaw, float pitch); Location(Extent extent, Vector3 position, Vector3 direction); Location(Extent extent, Vector3 position, float yaw, float pitch); Extent getExtent(); Location setExtent(Extent extent); float getYaw(); Location setYaw(float yaw); float getPitch(); Location setPitch(float pitch); Location setDirection(float yaw, float pitch); Vector3 getDirection(); Direction getDirectionEnum(); Location setDirection(Vector3 direction); Vector3 toVector(); double getX(); int getBlockX(); Location setX(double x); double getY(); int getBlockY(); Location setY(double y); double getZ(); int getBlockZ(); Location setZ(double z); Location setPosition(Vector3 position); @Override boolean equals(Object o); @Override int hashCode(); }
@Test public void testGetZ() throws Exception { World world = mock(World.class); Location location = new Location(world, Vector3.at(0, 0, TEST_VALUE)); assertEquals(TEST_VALUE, location.getZ(), EPSILON); }
Location { public int getBlockZ() { return (int) Math.floor(position.getZ()); } Location(Extent extent); Location(Extent extent, double x, double y, double z); Location(Extent extent, Vector3 position); Location(Extent extent, double x, double y, double z, Vector3 direction); Location(Extent extent, double x, double y, double z, float yaw, float pitch); Location(Extent extent, Vector3 position, Vector3 direction); Location(Extent extent, Vector3 position, float yaw, float pitch); Extent getExtent(); Location setExtent(Extent extent); float getYaw(); Location setYaw(float yaw); float getPitch(); Location setPitch(float pitch); Location setDirection(float yaw, float pitch); Vector3 getDirection(); Direction getDirectionEnum(); Location setDirection(Vector3 direction); Vector3 toVector(); double getX(); int getBlockX(); Location setX(double x); double getY(); int getBlockY(); Location setY(double y); double getZ(); int getBlockZ(); Location setZ(double z); Location setPosition(Vector3 position); @Override boolean equals(Object o); @Override int hashCode(); }
@Test public void testGetBlockZ() throws Exception { World world = mock(World.class); Location location = new Location(world, Vector3.at(0, 0, TEST_VALUE)); assertEquals(TEST_VALUE, location.getBlockZ()); }
Location { public Location setZ(double z) { return new Location(extent, position.withZ(z), yaw, pitch); } Location(Extent extent); Location(Extent extent, double x, double y, double z); Location(Extent extent, Vector3 position); Location(Extent extent, double x, double y, double z, Vector3 direction); Location(Extent extent, double x, double y, double z, float yaw, float pitch); Location(Extent extent, Vector3 position, Vector3 direction); Location(Extent extent, Vector3 position, float yaw, float pitch); Extent getExtent(); Location setExtent(Extent extent); float getYaw(); Location setYaw(float yaw); float getPitch(); Location setPitch(float pitch); Location setDirection(float yaw, float pitch); Vector3 getDirection(); Direction getDirectionEnum(); Location setDirection(Vector3 direction); Vector3 toVector(); double getX(); int getBlockX(); Location setX(double x); double getY(); int getBlockY(); Location setY(double y); double getZ(); int getBlockZ(); Location setZ(double z); Location setPosition(Vector3 position); @Override boolean equals(Object o); @Override int hashCode(); }
@Test public void testSetZ() throws Exception { World world = mock(World.class); Location location1 = new Location(world, Vector3.ZERO); Location location2 = location1.setZ(TEST_VALUE); assertEquals(0, location1.getZ(), EPSILON); assertEquals(0, location2.getX(), EPSILON); assertEquals(0, location2.getY(), EPSILON); assertEquals(TEST_VALUE, location2.getZ(), EPSILON); }
MorePaths { public static Stream<Path> iterPaths(Path path) { Deque<Path> parents = new ArrayDeque<>(path.getNameCount()); Path next = path; while (next != null) { parents.addFirst(next); next = next.getParent(); } return ImmutableList.copyOf(parents).stream(); } private MorePaths(); static Comparator<Path> oldestFirst(); static Comparator<Path> newestFirst(); static Stream<Path> iterPaths(Path path); static Spliterator<Path> optimizedSpliterator(Path path); }
@Test void testRelative() { assertEquals( paths("a", "a/b", "a/b/c"), MorePaths.iterPaths(Paths.get("a/b/c")).collect(toList()) ); } @Test void testAbsolute() { assertEquals( paths("/", "/a", "/a/b", "/a/b/c"), MorePaths.iterPaths(Paths.get("/a/b/c")).collect(toList()) ); } @Test void testEmpty() { assertEquals( paths(""), MorePaths.iterPaths(Paths.get("")).collect(toList()) ); } @Test void testJustFile() { assertEquals( paths("a"), MorePaths.iterPaths(Paths.get("a")).collect(toList()) ); }
EventBus { public void register(Object object) { subscribeAll(finder.findAllSubscribers(object)); } void subscribe(Class<?> clazz, EventHandler handler); void subscribeAll(Multimap<Class<?>, EventHandler> handlers); void unsubscribe(Class<?> clazz, EventHandler handler); void unsubscribeAll(Multimap<Class<?>, EventHandler> handlers); void register(Object object); void unregister(Object object); void post(Object event); }
@Test public void testRegister() { Subscriber subscriber = new Subscriber(); eventBus.register(subscriber); Event e1 = new Event(); eventBus.post(e1); Event e2 = new Event(); eventBus.post(e2); assertEquals(asList(e1, e2), subscriber.events); }
EventBus { public void unregister(Object object) { unsubscribeAll(finder.findAllSubscribers(object)); } void subscribe(Class<?> clazz, EventHandler handler); void subscribeAll(Multimap<Class<?>, EventHandler> handlers); void unsubscribe(Class<?> clazz, EventHandler handler); void unsubscribeAll(Multimap<Class<?>, EventHandler> handlers); void register(Object object); void unregister(Object object); void post(Object event); }
@Test public void testUnregister() { Subscriber subscriber = new Subscriber(); eventBus.register(subscriber); Event e1 = new Event(); eventBus.post(e1); eventBus.unregister(subscriber); Event e2 = new Event(); eventBus.post(e2); assertEquals(singletonList(e1), subscriber.events); }
CommandContext { public String[] getSlice(int index) { String[] slice = new String[originalArgs.length - index]; System.arraycopy(originalArgs, index, slice, 0, originalArgs.length - index); return slice; } CommandContext(String args); CommandContext(String[] args); CommandContext(String args, Set<Character> valueFlags); CommandContext(String args, Set<Character> valueFlags, boolean allowHangingFlag); CommandContext(String[] args, Set<Character> valueFlags); CommandContext(String[] args, Set<Character> valueFlags, boolean allowHangingFlag, CommandLocals locals); CommandContext(String[] args, Set<Character> valueFlags, boolean allowHangingFlag, CommandLocals locals, boolean parseFlags); static String[] split(String args); SuggestionContext getSuggestionContext(); String getCommand(); boolean matches(String command); String getString(int index); String getString(int index, String def); String getJoinedStrings(int initialIndex); String getRemainingString(int start); String getString(int start, int end); int getInteger(int index); int getInteger(int index, int def); double getDouble(int index); double getDouble(int index, double def); String[] getSlice(int index); String[] getPaddedSlice(int index, int padding); String[] getParsedSlice(int index); String[] getParsedPaddedSlice(int index, int padding); boolean hasFlag(char ch); Set<Character> getFlags(); Map<Character, String> getValueFlags(); String getFlag(char ch); String getFlag(char ch, String def); int getFlagInteger(char ch); int getFlagInteger(char ch, int def); double getFlagDouble(char ch); double getFlagDouble(char ch, double def); int argsLength(); CommandLocals getLocals(); }
@Test public void testSlice() { try { CommandContext context = new CommandContext("foo bar baz"); assertArrayEquals(new String[] { "foo", "bar", "baz" }, context.getSlice(0)); } catch (CommandException e) { log.warn("Error", e); fail("Error creating CommandContext"); } }
BlockMap extends AbstractMap<BlockVector3, V> { @Override public V get(Object key) { BlockVector3 vec = (BlockVector3) key; Int2ObjectMap<V> activeMap = maps.get(toGroupKey(vec)); if (activeMap == null) { return null; } return activeMap.get(toInnerKey(vec)); } private BlockMap(Supplier<Int2ObjectMap<V>> subMapSupplier); private BlockMap(Supplier<Int2ObjectMap<V>> subMapSupplier, Map<? extends BlockVector3, ? extends V> source); static BlockMap<V> create(); static BlockMap<BaseBlock> createForBaseBlock(); static BlockMap<V> copyOf(Map<? extends BlockVector3, ? extends V> source); @Override V put(BlockVector3 key, V value); @Override V getOrDefault(Object key, V defaultValue); @Override void forEach(BiConsumer<? super BlockVector3, ? super V> action); @Override void replaceAll(BiFunction<? super BlockVector3, ? super V, ? extends V> function); @Override V putIfAbsent(BlockVector3 key, V value); @Override boolean remove(Object key, Object value); @Override boolean replace(BlockVector3 key, V oldValue, V newValue); @Override V replace(BlockVector3 key, V value); @Override V computeIfAbsent(BlockVector3 key, Function<? super BlockVector3, ? extends V> mappingFunction); @Override V computeIfPresent(BlockVector3 key, BiFunction<? super BlockVector3, ? super V, ? extends V> remappingFunction); @Override V compute(BlockVector3 key, BiFunction<? super BlockVector3, ? super V, ? extends V> remappingFunction); @Override V merge(BlockVector3 key, V value, BiFunction<? super V, ? super V, ? extends V> remappingFunction); @Override Set<Entry<BlockVector3, V>> entrySet(); @Override boolean containsValue(Object value); @Override boolean containsKey(Object key); @Override V get(Object key); @Override V remove(Object key); @SuppressWarnings("unchecked") @Override void putAll(Map<? extends BlockVector3, ? extends V> m); @Override void clear(); @Override int size(); @Override Collection<V> values(); @Override boolean equals(Object o); @Override int hashCode(); }
@Test @DisplayName("throws ClassCastException if invalid argument to get") void throwsFromGetOnInvalidArgument() { assertThrows(ClassCastException.class, () -> map.get("")); }
Expression { public double evaluate(double... values) throws EvaluationException { return evaluate(values, WorldEdit.getInstance().getConfiguration().calculationTimeout); } private Expression(String expression, String... variableNames); static Expression compile(String expression, String... variableNames); double evaluate(double... values); double evaluate(double[] values, int timeout); void optimize(); String getSource(); @Override String toString(); SlotTable getSlots(); ExpressionEnvironment getEnvironment(); void setEnvironment(ExpressionEnvironment environment); }
@TestFactory public Stream<DynamicNode> testEvaluate() throws ExpressionException { List<ExpressionTestCase> testCases = ImmutableList.of( testCase("1 - 2 + 3", 2), testCase("2 + +4", 6), testCase("2 - -4", 6), testCase("2 * -4", -8), testCase("sin(5)", sin(5)), testCase("atan2(3, 4)", atan2(3, 4)), testCase("min(1, 2)", 1), testCase("max(1, 2)", 2), testCase("max(1, 2, 3, 4, 5)", 5), testCase("0 || 5", 5), testCase("2 || 5", 2), testCase("2 && 5", 5), testCase("5 && 0", 0), testCase("false ? 1 : 2", 2), testCase("true ? 1 : 2", 1), testCase("true ? true ? 1 : 2 : 3", 1), testCase("true ? false ? 1 : 2 : 3", 2), testCase("false ? true ? 1 : 2 : 3", 3), testCase("false ? false ? 1 : 2 : 3", 3), testCase("return 1; 0", 1) ); return testCases.stream() .map(testCase -> dynamicTest( testCase.getExpression(), () -> checkTestCase(testCase) )); }
Expression { public static Expression compile(String expression, String... variableNames) throws ExpressionException { return new Expression(expression, variableNames); } private Expression(String expression, String... variableNames); static Expression compile(String expression, String... variableNames); double evaluate(double... values); double evaluate(double[] values, int timeout); void optimize(); String getSource(); @Override String toString(); SlotTable getSlots(); ExpressionEnvironment getEnvironment(); void setEnvironment(ExpressionEnvironment environment); }
@Test public void testErrors() { { ExpressionException e = assertThrows(ExpressionException.class, () -> compile("#")); assertEquals(0, e.getPosition(), "Error position"); } { ExpressionException e = assertThrows(ExpressionException.class, () -> compile("x")); assertEquals(0, e.getPosition(), "Error position"); } { ExpressionException e = assertThrows(ExpressionException.class, () -> compile("x()")); assertEquals(0, e.getPosition(), "Error position"); } { ExpressionException e = assertThrows(ExpressionException.class, () -> compile("return")); assertEquals(6, e.getPosition(), "Error position"); } assertThrows(ExpressionException.class, () -> compile("(")); assertThrows(ExpressionException.class, () -> compile("x(")); { ExpressionException e = assertThrows(ExpressionException.class, () -> compile("atan2(1)")); assertEquals(0, e.getPosition(), "Error position"); } { ExpressionException e = assertThrows(ExpressionException.class, () -> compile("atan2(1, 2, 3)")); assertEquals(0, e.getPosition(), "Error position"); } { ExpressionException e = assertThrows(ExpressionException.class, () -> compile("rotate(1, 2, 3)")); assertEquals(7, e.getPosition(), "Error position"); } }
BlockTransformExtent extends AbstractDelegateExtent { public static <B extends BlockStateHolder<B>> B transform(B block, Transform transform) { checkNotNull(block); checkNotNull(transform); B result = block; List<? extends Property<?>> properties = block.getBlockType().getProperties(); for (Property<?> property : properties) { if (property instanceof DirectionalProperty) { DirectionalProperty dirProp = (DirectionalProperty) property; Direction value = (Direction) block.getState(property); if (value != null) { Vector3 newValue = getNewStateValue(dirProp.getValues(), transform, value.toVector()); if (newValue != null) { result = result.with(dirProp, Direction.findClosest(newValue, Direction.Flag.ALL)); } } } else if (property instanceof EnumProperty) { EnumProperty enumProp = (EnumProperty) property; if (property.getName().equals("axis")) { Direction value = null; switch ((String) block.getState(property)) { case "x": value = Direction.EAST; break; case "y": value = Direction.UP; break; case "z": value = Direction.NORTH; break; default: break; } if (value != null) { Vector3 newValue = getNewStateValue(Direction.valuesOf(Direction.Flag.UPRIGHT | Direction.Flag.CARDINAL), transform, value.toVector()); if (newValue != null) { String axis = null; Direction newDir = Direction.findClosest(newValue, Direction.Flag.UPRIGHT | Direction.Flag.CARDINAL); if (newDir == Direction.NORTH || newDir == Direction.SOUTH) { axis = "z"; } else if (newDir == Direction.EAST || newDir == Direction.WEST) { axis = "x"; } else if (newDir == Direction.UP || newDir == Direction.DOWN) { axis = "y"; } if (axis != null) { result = result.with(enumProp, axis); } } } } else if (property.getName().equals("type") && transform instanceof AffineTransform) { if (((AffineTransform) transform).isHorizontalFlip()) { String value = (String) block.getState(property); String newValue = null; if ("left".equals(value)) { newValue = "right"; } else if ("right".equals(value)) { newValue = "left"; } if (newValue != null && enumProp.getValues().contains(newValue)) { result = result.with(enumProp, newValue); } } if (((AffineTransform) transform).isVerticalFlip()) { String value = (String) block.getState(property); String newValue = null; if ("bottom".equals(value)) { newValue = "top"; } else if ("top".equals(value)) { newValue = "bottom"; } if (newValue != null && enumProp.getValues().contains(newValue)) { result = result.with(enumProp, newValue); } } } else if (property.getName().equals("half") && transform instanceof AffineTransform) { if (((AffineTransform) transform).isVerticalFlip()) { String value = (String) block.getState(property); String newValue = null; if ("bottom".equals(value)) { newValue = "top"; } else if ("top".equals(value)) { newValue = "bottom"; } if (newValue != null && enumProp.getValues().contains(newValue)) { result = result.with(enumProp, newValue); } } } else if (property.getName().equals("shape") && transform instanceof AffineTransform) { if (((AffineTransform) transform).isHorizontalFlip()) { String value = (String) block.getState(property); String newValue = null; if ("outer_left".equals(value)) { newValue = "outer_right"; } else if ("outer_right".equals(value)) { newValue = "outer_left"; } else if ("inner_left".equals(value)) { newValue = "inner_right"; } else if ("inner_right".equals(value)) { newValue = "inner_left"; } if (newValue != null && enumProp.getValues().contains(newValue)) { result = result.with(enumProp, newValue); } } } } else if (property instanceof IntegerProperty) { IntegerProperty intProp = (IntegerProperty) property; if (property.getName().equals("rotation")) { if (intProp.getValues().size() == 16) { Optional<Direction> direction = Direction.fromRotationIndex(block.getState(intProp)); int horizontalFlags = Direction.Flag.CARDINAL | Direction.Flag.ORDINAL | Direction.Flag.SECONDARY_ORDINAL; if (direction.isPresent()) { Vector3 vec = getNewStateValue(Direction.valuesOf(horizontalFlags), transform, direction.get().toVector()); if (vec != null) { OptionalInt newRotation = Direction.findClosest(vec, horizontalFlags).toRotationIndex(); if (newRotation.isPresent()) { result = result.with(intProp, newRotation.getAsInt()); } } } } } } } Map<String, Object> directionalProperties = new HashMap<>(); for (Property<?> prop : properties) { if (directionNames.contains(prop.getName())) { if (prop instanceof BooleanProperty && (Boolean) block.getState(prop) || prop instanceof EnumProperty && !block.getState(prop).toString().equals("none")) { String origProp = prop.getName().toUpperCase(Locale.ROOT); Direction dir = Direction.valueOf(origProp); Direction closest = Direction.findClosest(transform.apply(dir.toVector()), Direction.Flag.CARDINAL); if (closest != null) { String closestProp = closest.name().toLowerCase(Locale.ROOT); if (prop instanceof BooleanProperty) { result = result.with((BooleanProperty) prop, Boolean.FALSE); directionalProperties.put(closestProp, Boolean.TRUE); } else { if (prop.getValues().contains("none")) { @SuppressWarnings("unchecked") Property<Object> propAsObj = (Property<Object>) prop; result = result.with(propAsObj, "none"); } directionalProperties.put(closestProp, block.getState(prop)); } } } } } if (!directionalProperties.isEmpty()) { for (String directionName : directionNames) { Property<Object> dirProp = block.getBlockType().getProperty(directionName); result = result.with(dirProp, directionalProperties.get(directionName)); } } return result; } BlockTransformExtent(Extent extent, Transform transform); Transform getTransform(); @Override BlockState getBlock(BlockVector3 position); @Override BaseBlock getFullBlock(BlockVector3 position); @Override boolean setBlock(BlockVector3 location, B block); static B transform(B block, Transform transform); }
@Test public void testTransform() { for (BlockType type : BlockType.REGISTRY.values()) { if (ignored.contains(type)) { continue; } BlockState base = type.getDefaultState(); BlockState rotated = base; for (int i = 1; i < 4; i++) { rotated = BlockTransformExtent.transform(base, ROTATE_90); } assertEquals(base, rotated); rotated = base; for (int i = 1; i < 4; i++) { rotated = BlockTransformExtent.transform(base, ROTATE_NEG_90); } assertEquals(base, rotated); } }
FileSystemSnapshotDatabase implements SnapshotDatabase { public Path getRoot() { return root; } FileSystemSnapshotDatabase(Path root, ArchiveNioSupport archiveNioSupport); static ZonedDateTime tryParseDate(Path path); static URI createUri(String name); static FileSystemSnapshotDatabase maybeCreate( Path root, ArchiveNioSupport archiveNioSupport ); Path getRoot(); @Override String getScheme(); @Override Optional<Snapshot> getSnapshot(URI name); @Override Stream<Snapshot> getSnapshots(String worldName); }
@DisplayName("makes the root directory absolute if needed") @Test void rootIsAbsoluteDir() throws IOException { Path root = newTempDb(); try { Path relative = root.getFileSystem().getPath("relative"); Files.createDirectories(relative); FileSystemSnapshotDatabase db2 = new FileSystemSnapshotDatabase(relative, ArchiveNioSupports.combined()); assertEquals(root.getFileSystem().getPath(".").toRealPath() .resolve(relative), db2.getRoot()); Path absolute = root.resolve("absolute"); Files.createDirectories(absolute); FileSystemSnapshotDatabase db3 = new FileSystemSnapshotDatabase(absolute, ArchiveNioSupports.combined()); assertEquals(absolute, db3.getRoot()); } finally { deleteTree(root); } }
DinnerPermsResolver implements PermissionsResolver { @Override @SuppressWarnings("deprecation") public boolean hasPermission(String name, String permission) { return hasPermission(server.getOfflinePlayer(name), permission); } DinnerPermsResolver(Server server); static PermissionsResolver factory(Server server, YAMLProcessor config); @Override void load(); @Override @SuppressWarnings("deprecation") boolean hasPermission(String name, String permission); @Override @SuppressWarnings("deprecation") boolean hasPermission(String worldName, String name, String permission); @Override @SuppressWarnings("deprecation") boolean inGroup(String name, String group); @Override @SuppressWarnings("deprecation") String[] getGroups(String name); @Override boolean hasPermission(OfflinePlayer player, String permission); @Override boolean hasPermission(String worldName, OfflinePlayer player, String permission); @Override boolean inGroup(OfflinePlayer player, String group); @Override String[] getGroups(OfflinePlayer player); Permissible getPermissible(OfflinePlayer offline); int internalHasPermission(Permissible perms, String permission); @Override String getDetectionMessage(); static final String GROUP_PREFIX; }
@Test public void testBasicResolving() { final TestOfflinePermissible permissible = new TestOfflinePermissible(); permissible.setPermission("testperm.test1", true); assertTrue(resolver.hasPermission(permissible, "testperm.test1")); assertFalse(resolver.hasPermission(permissible, "testperm.somethingelse")); assertFalse(resolver.hasPermission(permissible, "testperm.test1.anything")); assertFalse(resolver.hasPermission(permissible, "completely.unrelated")); permissible.clearPermissions(); } @Test public void testBasicWildcardResolution() { final TestOfflinePermissible permissible = new TestOfflinePermissible(); permissible.setPermission("commandbook.spawnmob.*", true); assertTrue(resolver.hasPermission(permissible, "commandbook.spawnmob.pig")); assertTrue(resolver.hasPermission(permissible, "commandbook.spawnmob.spider")); assertTrue(resolver.hasPermission(permissible, "commandbook.spawnmob.spider.skeleton")); permissible.clearPermissions(); } @Test public void testNegatingNodes() { final TestOfflinePermissible permissible = new TestOfflinePermissible(); permissible.setPermission("commandbook.*", true); permissible.setPermission("commandbook.cuteasianboys", false); permissible.setPermission("commandbook.warp.*", false); permissible.setPermission("commandbook.warp.create", true); assertTrue(resolver.hasPermission(permissible, "commandbook.motd")); assertFalse(resolver.hasPermission(permissible, "commandbook.cuteasianboys")); assertFalse(resolver.hasPermission(permissible, "commandbook.warp.remove")); assertTrue(resolver.hasPermission(permissible, "commandbook.warp.create")); permissible.clearPermissions(); }