method2testcases
stringlengths
118
6.63k
### Question: AnnotatedSqlStatement { public Map<String, Converter> getOutConverters() { return outConverters; } AnnotatedSqlStatement(LSql lSql, String statementSourceName, String statementName, String typeAnnotation, String sqlString); com.w11k.lsql.LSql getlSql(); String getStatementSourceName(); String getStatementName(); String getTypeAnnotation(); String getSqlString(); ImmutableMap<String, List<Parameter>> getParameters(); Map<String, Converter> getOutConverters(); PreparedStatement createPreparedStatement(Map<String, Object> queryParameters, Map<String, Converter> parameterConverters); }### Answer: @Test() public void outConverterConfiguration() { addConfigHook(testConfig -> { testConfig.getDialect().getConverterRegistry().addTypeAlias("ai", new AtomicIntegerConverter()); }); setup(); String sql = "-- column age: ai\nselect age from person where id = 1;"; AnnotatedSqlStatement as = new AnnotatedSqlStatement( this.lSql, "source", "stmtName", "", sql); Converter converter = as.getOutConverters().get("age"); assertNotNull(converter); PlainQuery query = new AnnotatedSqlStatementToQuery<PlainQuery>(as, emptyMap()) { protected PlainQuery createQueryInstance(LSql lSql, PreparedStatement ps, Map<String, Converter> outConverters) { return new PlainQuery(lSql, ps, outConverters); } }.query(); List<Row> rows = query.toList(); assertEquals(rows.size(), 1); Row row = rows.get(0); Object age = row.get("age"); assertEquals(age.getClass(), AtomicInteger.class); }
### Question: LSql { public void executeRawSql(String sql) { Statement st = this.createStatement(); try { st.execute(sql); } catch (SQLException e) { throw new RuntimeException(e); } } LSql(Class<? extends Config> configClass, Callable<Connection> connectionProvider); LSql(Class<? extends Config> configClass, DataSource dataSource); void clearTables(); Callable<Connection> getConnectionProvider(); Iterable<Table> getTables(); Iterable<PojoTable<?>> getPojoTables(); ObjectMapper getObjectMapper(); void setObjectMapper(ObjectMapper objectMapper); InitColumnCallback getInitColumnCallback(); void setInitColumnCallback(InitColumnCallback initColumnCallback); Class<? extends GenericDialect> getDialectClass(); LSqlFile readSqlFile(Class clazz, String fileName); LSqlFile readSqlFile(Class<?> clazz); synchronized Table table(String javaSchemaAndTableName); synchronized Table tableBySqlName(String sqlSchemaAndTableName); @SuppressWarnings("unchecked") @Deprecated synchronized PojoTable<T> table(String tableName, Class<T> pojoClass); Statement createStatement(); void executeRawSql(String sql); @Deprecated PlainQuery executeRawQuery(String sql); @Deprecated PojoQuery<T> executeRawQuery(String sql, Class<T> pojoClass); AnnotatedSqlStatementToQuery<PlainQuery> createSqlStatement(String sqlString); AnnotatedSqlStatementToQuery<PlainQuery> createSqlStatement(String sqlString, String sourceName, String stmtName); String convertExternalSqlToInternalSql(String externalSql); String convertInternalSqlToExternalSql(String internalSql); String convertInternalSqlToRowKey(String internalSql); String convertRowKeyToInternalSql(String rowKey); Converter getConverterForSqlType(int sqlType); Converter getConverterForJavaType(Class<?> clazz); Converter getConverterForAlias(String alias); String getSqlSchemaAndTableNameFromResultSetMetaData( ResultSetMetaData metaData, int columnIndex); Optional<Object> extractGeneratedPk(Table table, ResultSet resultSet); StatementCreator getStatementCreator(); String getSqlColumnNameFromResultSetMetaData( ResultSetMetaData metaData, int columnIndex); Converter getConverterForTableColumn(String schemaAndTableName, String javaColumnName, int sqlType); boolean isUseColumnTypeForConverterLookupInQueries(); Config getConfig(); @Override String toString(); static final ObjectMapper OBJECT_MAPPER; }### Answer: @Test public void execute() { createTable("CREATE TABLE table1 (name TEXT, age INT)"); lSql.executeRawSql("INSERT INTO table1 (name, age) VALUES ('cus1', 20)"); } @Test(expectedExceptions = RuntimeException.class) public void executeShouldThrowRuntimeExceptionOnWrongStatement() { lSql.executeRawSql("CREATE TABLE table1 (name TEXT, age INT)"); lSql.executeRawSql("INSERT INTO tableX (name, age) VALUES ('cus1', 20)"); }
### Question: LinkedRow extends Row { public Optional<?> save() { return table.save(this); } Table getTable(); Object getId(); void setId(Object id); Object getRevision(); void setRevision(Object revision); void removeIdAndRevision(); @Override Object put(String key, Object value); LinkedRow putAllKnown(Row from); Optional<?> insert(); Optional<?> save(); void delete(); T convertTo(Class<T> pojoClass); @Override LinkedRow addKeyVals(Object... keyVals); }### Answer: @Test public void save() { createTable("CREATE TABLE table1 (id INTEGER PRIMARY KEY, age INT)"); Table table1 = lSql.table("table1"); LinkedRow row1 = table1.newLinkedRow(); row1.addKeyVals("id", 1, "age", 1); Optional<?> row1Id = row1.save(); assertTrue(row1Id.isPresent()); assertEquals(row1Id.get(), 1); LinkedRow queriedRow1 = table1.load(1).get(); assertEquals(queriedRow1.getInt("age"), (Integer) 1); queriedRow1.put("age", 99); queriedRow1.save(); LinkedRow queriedRow1b = table1.load(1).get(); assertEquals(queriedRow1b.getInt("age"), (Integer) 99); }
### Question: LinkedRow extends Row { public void delete() { Object id = get(table.getPrimaryKeyColumn().get()); if (id == null) { throw new IllegalStateException("Can not delete this LinkedRow because the primary key value is not present."); } table.delete(this); } Table getTable(); Object getId(); void setId(Object id); Object getRevision(); void setRevision(Object revision); void removeIdAndRevision(); @Override Object put(String key, Object value); LinkedRow putAllKnown(Row from); Optional<?> insert(); Optional<?> save(); void delete(); T convertTo(Class<T> pojoClass); @Override LinkedRow addKeyVals(Object... keyVals); }### Answer: @Test public void delete() { createTable("CREATE TABLE table1 (id INTEGER PRIMARY KEY, age INT)"); Table table1 = lSql.table("table1"); LinkedRow row1 = table1.newLinkedRow(); row1.addKeyVals("id", 1, "age", 1); row1.save(); assertEquals(table1.load(1).get().getInt("age"), (Integer) 1); row1.delete(); assertFalse(table1.load(1).isPresent()); }
### Question: LinkedRow extends Row { public Optional<?> insert() { return table.insert(this); } Table getTable(); Object getId(); void setId(Object id); Object getRevision(); void setRevision(Object revision); void removeIdAndRevision(); @Override Object put(String key, Object value); LinkedRow putAllKnown(Row from); Optional<?> insert(); Optional<?> save(); void delete(); T convertTo(Class<T> pojoClass); @Override LinkedRow addKeyVals(Object... keyVals); }### Answer: @Test public void newLinkedRowCopiesDataWithIdAndRevisionColumn() { createTable("CREATE TABLE table1 (id INTEGER PRIMARY KEY, age INT, revision INT DEFAULT 0)"); Table table1 = lSql.table("table1"); table1.enableRevisionSupport(); table1.insert(Row.fromKeyVals("id", 1, "age", 1)); LinkedRow row = table1.load(1).get(); assertTrue(row.containsKey("id")); assertTrue(row.containsKey("revision")); LinkedRow copy = table1.newLinkedRow(row); assertTrue(copy.containsKey("id")); assertTrue(copy.containsKey("revision")); }
### Question: LinkedRow extends Row { public void removeIdAndRevision() { remove(table.getPrimaryKeyColumn().get()); if (table.getRevisionColumn().isPresent()) { remove(table.getRevisionColumn().get().getColumnName()); } } Table getTable(); Object getId(); void setId(Object id); Object getRevision(); void setRevision(Object revision); void removeIdAndRevision(); @Override Object put(String key, Object value); LinkedRow putAllKnown(Row from); Optional<?> insert(); Optional<?> save(); void delete(); T convertTo(Class<T> pojoClass); @Override LinkedRow addKeyVals(Object... keyVals); }### Answer: @Test public void removeIdAndRevision() { createTable("CREATE TABLE table1 (id INTEGER PRIMARY KEY, age INT, revision INT DEFAULT 0)"); Table table1 = lSql.table("table1"); table1.enableRevisionSupport(); LinkedRow row = table1.newLinkedRow( "id", 1, "age", 1, "revision", 1 ); row.removeIdAndRevision(); assertFalse(row.containsKey("id")); assertTrue(row.containsKey("age")); assertFalse(row.containsKey("revision")); }
### Question: Row extends ForwardingMap<String, Object> { public Row addKeyVals(Object... keyVals) { checkArgument( keyVals.length == 0 || keyVals.length % 2 == 0, "content must be a list of iterant key value pairs."); Iterable<List<Object>> partition = Iterables.partition(newArrayList(keyVals), 2); for (List<Object> objects : partition) { Object key = objects.get(0); checkArgument(key instanceof String, "argument " + key + " is not a String"); Object value = objects.get(1); put(key.toString(), value); } return this; } Row(); Row(Map<String, Object> data); static Row fromKeyVals(Object... keyVals); Row addKeyVals(Object... keyVals); @Override Object put(String key, Object value); A getAs(Class<A> type, String key); A getAs(Class<A> type, String key, boolean convert); A getAsOr(Class<A> type, String key, A defaultValue); Optional<Object> getOptional(String key); Integer getInt(String key); Long getLong(String key); Double getDouble(String key); Float getFloat(String key); Boolean getBoolean(String key); BigDecimal getBigDecimal(String key); DateTime getDateTime(String key); String getString(String key); Row getRow(String key); Blob getBlob(String key); byte[] getByteArray(String key); @SuppressWarnings("unchecked") List<A> getAsListOf(Class<A> clazz, String key); @SuppressWarnings("unchecked") Set<A> getAsSetOf(Class<A> clazz, String key); boolean hasNonNullValue(String key); Row pick(String... keys); Row putAllIfAbsent(Map<String, Object> source); Row copy(); @Override String toString(); @Deprecated static boolean LEGACY_CONVERT_VALUE_ON_GET; }### Answer: @Test public void addKeyVals() { Row r = new Row().addKeyVals("a", 1, "b", "val"); assertEquals(r.get("a"), 1); assertEquals(r.get("b"), "val"); }
### Question: CodeGenUtils { public static String getJavaCodeName(String str, boolean insertUnderscoreOnCaseChange, boolean startUppercase) { if (str.length() == 0) { return str; } StringBuilder result = new StringBuilder(); String firstChar = str.substring(0, 1); result.append(startUppercase ? firstChar.toUpperCase() : firstChar); int idx = 1; while (idx < str.length()) { char prevChar = str.charAt(idx - 1); char currChar = str.charAt(idx); boolean isCaseChange = isLowerCase(prevChar) && isUpperCase(currChar); boolean isWordSep = prevChar == '_'; boolean changeCase = isCaseChange || isWordSep; if (changeCase) { if (insertUnderscoreOnCaseChange) { result.append("_"); } if (currChar != '_') { result.append(toUpperCase(currChar)); } } else { if (currChar != '_') { result.append(currChar); } } idx++; } return result.toString(); } static String escapeSqlStringForJavaSourceFile(String line); static String getJavaCodeName(String str, boolean insertUnderscoreOnCaseChange, boolean startUppercase); static String escapeSqlStringForJavaDoc(String line); static String firstCharUpperCase(String name); static String joinStringsAsPackageName(String... packageNames); static String getSubPathFromFileInParent(String parent, String childInParent); static File getFileFromBaseDirAndPackageName(File baseDir, String packageName); static File getOutputFile(File exportRootDir, String packageName, String fileName); static void writeContent(String content, File target); static void rollback(LSql lSql); static void log(String... strings); }### Answer: @Test public void getJavaCodeNameTests() { assertEquals(getJavaCodeName( "a", false, false), "a"); assertEquals(getJavaCodeName( "a", false, true), "A"); assertEquals(getJavaCodeName( "abc_def", false, false), "abcDef"); assertEquals(getJavaCodeName( "abc_def", false, true), "AbcDef"); assertEquals(getJavaCodeName( "abc_def", true, true), "Abc_Def"); assertEquals(getJavaCodeName( "abc___def", false, false), "abcDef"); assertEquals(getJavaCodeName( "abc___def", true, false), "abc___Def"); assertEquals(getJavaCodeName( "idInteger", true, true), "Id_Integer"); }
### Question: Table { public Optional<?> save(Row row) { return this.save(row, RowSerializer.INSTANCE_SPECIAL_ROWKEY, RowDeserializer.INSTANCE_SPECIAL_ROWKEY); } Table(LSql lSql, String sqlSchemaAndTableName); Table(LSql lSql, String sqlSchemaName, String sqlTableName, String primaryKeyColumn); LSql getlSql(); String getSqlSchemaAndTableName(); String getSchemaName(); String getTableName(); Optional<String> getPrimaryKeyColumn(); Optional<Class<?>> getPrimaryKeyType(); Map<String, Column> getColumns(); @Nullable synchronized Column column(String columnName); @Deprecated PojoTable<T> withPojo(Class<T> pojoClass); void enableRevisionSupport(); void enableRevisionSupport(String revisionColumnName); Optional<Column> getRevisionColumn(); Optional<Object> insert(Row row); Optional<Object> insert(Row row, RowSerializer<Row> rowSerializer, RowDeserializer<Row> rowDeserializer); void update(Row row); void update(Row row, RowSerializer<Row> rowSerializer, RowDeserializer<Row> rowDeserializer); void updateWhere(Row values, Row where); void updateWhere(Row values, Row where, RowSerializer<Row> rowSerializer, RowDeserializer<Row> rowDeserializer); Optional<?> save(Row row); Optional<?> save(Row row, RowSerializer<Row> rowSerializer, RowDeserializer<Row> rowDeserializer); void delete(Object id); void delete(Object id, RowDeserializer<Row> rowDeserializer); void delete(Row row); void delete(Row row, RowDeserializer<Row> rowDeserializer); Optional<LinkedRow> load(Object id); Optional<LinkedRow> load(Object id, RowDeserializer<Row> rowDeserializer); @Deprecated LinkedRow newLinkedRow(); LinkedRow newLinkedRow(Object... keyVals); LinkedRow newLinkedRow(Map<String, Object> data); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer: @Test public void save() throws SQLException { createTable("CREATE TABLE table1 (id SERIAL PRIMARY KEY, name TEXT)"); Table table1 = lSql.table("table1"); Row row = Row.fromKeyVals("name", "Max"); Object id = table1.save(row).get(); assertEquals(id, row.get(table1.getPrimaryKeyColumn().get())); LinkedRow queriedRow = table1.load(id).get(); assertEquals(queriedRow, row); row.put("name", "John"); id = table1.save(row).get(); queriedRow = table1.load(id).get(); assertEquals(queriedRow, row); }
### Question: Table { public void delete(Object id) { this.delete(id, RowDeserializer.INSTANCE_SPECIAL_ROWKEY); } Table(LSql lSql, String sqlSchemaAndTableName); Table(LSql lSql, String sqlSchemaName, String sqlTableName, String primaryKeyColumn); LSql getlSql(); String getSqlSchemaAndTableName(); String getSchemaName(); String getTableName(); Optional<String> getPrimaryKeyColumn(); Optional<Class<?>> getPrimaryKeyType(); Map<String, Column> getColumns(); @Nullable synchronized Column column(String columnName); @Deprecated PojoTable<T> withPojo(Class<T> pojoClass); void enableRevisionSupport(); void enableRevisionSupport(String revisionColumnName); Optional<Column> getRevisionColumn(); Optional<Object> insert(Row row); Optional<Object> insert(Row row, RowSerializer<Row> rowSerializer, RowDeserializer<Row> rowDeserializer); void update(Row row); void update(Row row, RowSerializer<Row> rowSerializer, RowDeserializer<Row> rowDeserializer); void updateWhere(Row values, Row where); void updateWhere(Row values, Row where, RowSerializer<Row> rowSerializer, RowDeserializer<Row> rowDeserializer); Optional<?> save(Row row); Optional<?> save(Row row, RowSerializer<Row> rowSerializer, RowDeserializer<Row> rowDeserializer); void delete(Object id); void delete(Object id, RowDeserializer<Row> rowDeserializer); void delete(Row row); void delete(Row row, RowDeserializer<Row> rowDeserializer); Optional<LinkedRow> load(Object id); Optional<LinkedRow> load(Object id, RowDeserializer<Row> rowDeserializer); @Deprecated LinkedRow newLinkedRow(); LinkedRow newLinkedRow(Object... keyVals); LinkedRow newLinkedRow(Map<String, Object> data); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer: @Test public void delete() throws SQLException { createTable("CREATE TABLE table1 (id SERIAL PRIMARY KEY, name TEXT)"); Table table1 = lSql.table("table1"); Row row = new Row().addKeyVals("name", "Max"); table1.insert(row).get(); int tableSize = lSql.executeRawQuery("SELECT * FROM table1;").toList().size(); assertEquals(tableSize, 1); table1.insert(new Row().addKeyVals("name", "Phil")); table1.delete(row); tableSize = lSql.executeRawQuery("SELECT * FROM table1;").toList().size(); assertEquals(tableSize, 1); }
### Question: AnnotatedSqlStatement { public ImmutableMap<String, List<Parameter>> getParameters() { return ImmutableMap.copyOf(this.parameters); } AnnotatedSqlStatement(LSql lSql, String statementSourceName, String statementName, String typeAnnotation, String sqlString); com.w11k.lsql.LSql getlSql(); String getStatementSourceName(); String getStatementName(); String getTypeAnnotation(); String getSqlString(); ImmutableMap<String, List<Parameter>> getParameters(); Map<String, Converter> getOutConverters(); PreparedStatement createPreparedStatement(Map<String, Object> queryParameters, Map<String, Converter> parameterConverters); }### Answer: @Test public void statementQueryParameter() { setup(); AnnotatedSqlStatementToQuery<PlainQuery> statement = lSql.createSqlStatement("SELECT * FROM \n" + "person \n" + "WHERE \n" + "id = 99999 \n" + "and age = 11 \n;"); ImmutableMap<String, List<AnnotatedSqlStatement.Parameter>> params = statement.getParameters(); assertEquals(params.get("id").get(0).getName(), "id"); assertEquals(params.get("age").get(0).getName(), "age"); List<Row> rows = statement.query("id", (QueryParameter) (ps, index) -> ps.setInt(index, 1)).toList(); assertEquals(rows.size(), 1); } @Test() public void queryParameterTypeAnnotations1() { setup(); AnnotatedSqlStatementToQuery<PlainQuery> statement = lSql.createSqlStatement( "select * from person where age > 18 ;"); AnnotatedSqlStatement.Parameter param = statement.getParameters().get("age").get(0); assertEquals(param.getJavaTypeAlias(), "int"); } @Test() public void queryParameterTypeAnnotations2() { setup(); AnnotatedSqlStatementToQuery<PlainQuery> statement = lSql.createSqlStatement( "select * from person where age > 18 ;"); AnnotatedSqlStatement.Parameter param = statement.getParameters().get("age").get(0); assertEquals(param.getJavaTypeAlias(), "int"); } @Test() public void queryParameterTypeAnnotations3() { setup(); AnnotatedSqlStatementToQuery<PlainQuery> statement = lSql.createSqlStatement( "select * from person where age > 18 ;"); AnnotatedSqlStatement.Parameter param = statement.getParameters().get("p1").get(0); assertEquals(param.getJavaTypeAlias(), "int"); } @Test() public void queryParameterTypeAnnotations4() { setup(); AnnotatedSqlStatementToQuery<PlainQuery> statement = lSql.createSqlStatement( "select * from person where age > 18 ;"); AnnotatedSqlStatement.Parameter param = statement.getParameters().get("p1").get(0); assertEquals(param.getJavaTypeAlias(), "int"); } @Test() public void queryParameterTypeAnnotations5() { setup(); AnnotatedSqlStatementToQuery<PlainQuery> statement = lSql.createSqlStatement( "select * from person where age > 18 ;"); AnnotatedSqlStatement.Parameter param = statement.getParameters().get("p1").get(0); assertEquals(param.getJavaTypeAlias(), "int"); }
### Question: GodEye { public synchronized <T> T getModule(@ModuleName String moduleName) throws UninstallException { Object moduleObj = mModules.get(moduleName); if (moduleObj == null) { throw new UninstallException("module [" + moduleName + "] is not installed."); } try { return (T) moduleObj; } catch (Throwable e) { throw new UnexpectException("module [" + moduleName + "] has wrong instance type"); } } private GodEye(); static GodEye instance(); synchronized GodEye install(final GodEyeConfig godEyeConfig, NotificationConfig notificationConfig); GodEye install(final GodEyeConfig godEyeConfig); GodEye install(final GodEyeConfig godEyeConfig, boolean enableNotification); synchronized GodEye uninstall(); synchronized T getModule(@ModuleName String moduleName); synchronized @ModuleName Set<String> getInstalledModuleNames(); Observable<M> moduleObservable(@ModuleName String moduleName); Disposable observeModule(@ModuleName String moduleName, Consumer<M> consumer); Application getApplication(); @Deprecated void init(Application application); static final Set<String> ALL_MODULE_NAMES; }### Answer: @Test public void getModule() { GodEye.instance().uninstall(); try { GodEye.instance().getModule(null); fail(); } catch (UninstallException ignore) { } try { GodEye.instance().getModule(""); fail(); } catch (UninstallException ignore) { } try { GodEye.instance().getModule(GodEye.ModuleName.STARTUP); fail(); } catch (UninstallException ignore) { } GodEye.instance().install(GodEyeConfig.noneConfigBuilder().withStartupConfig(new StartupConfig()).build()); try { GodEye.instance().getModule(GodEye.ModuleName.STARTUP); } catch (UninstallException e) { fail(); } try { GodEye.instance().<Cpu>getModule(GodEye.ModuleName.STARTUP).config(); fail(); } catch (UninstallException e) { fail(); } catch (ClassCastException ignore) { } }
### Question: GodEyeHelper { public static void onAppStartEnd(StartupInfo startupInfo) throws UninstallException { GodEye.instance().<Startup>getModule(GodEye.ModuleName.STARTUP).produce(startupInfo); L.d("GodEyeHelper onAppStartEnd: " + startupInfo); } static void onPageLoaded(Object page); static void onFragmentPageVisibilityChange(Object fragmentPage, boolean visible); static void onAppStartEnd(StartupInfo startupInfo); static void onNetworkEnd(NetworkInfo networkInfo); @Deprecated static void inspectView(); static void startMethodCanaryRecording(String tag); static void stopMethodCanaryRecording(String tag); static boolean isMethodCanaryRecording(String tag); static void setMonitorAppInfoConext(AppInfoConext appInfoConext); static void startMonitor(int port); static void startMonitor(); static void shutdownMonitor(); }### Answer: @Test public void onAppStartEndWhenNotInstalled() { try { GodEye.instance().uninstall(); GodEyeHelper.onAppStartEnd(null); fail(); } catch (UninstallException ignore) { } } @Test public void onAppStartEndWhenNull() { try { GodEye.instance().uninstall(); GodEye.instance().install(GodEyeConfig.noneConfigBuilder().withStartupConfig(new StartupConfig()).build()); GodEyeHelper.onAppStartEnd(null); } catch (NullPointerException ignore) { } catch (UninstallException e) { fail(); } } @Test public void onAppStartEndSuccess() { try { GodEye.instance().uninstall(); GodEye.instance().install(GodEyeConfig.noneConfigBuilder().withStartupConfig(new StartupConfig()).build()); StartupInfo startupInfo = new StartupInfo(StartupInfo.StartUpType.COLD, 3000); GodEyeHelper.onAppStartEnd(startupInfo); TestObserver testObserver = GodEye.instance().<Startup, StartupInfo>moduleObservable(GodEye.ModuleName.STARTUP).test(); testObserver.assertValue(new Predicate<StartupInfo>() { @Override public boolean test(StartupInfo o) throws Exception { return startupInfo.startupType.equals(o.startupType) && startupInfo.startupTime == o.startupTime; } }); } catch (Throwable e) { fail(); } }
### Question: GodEyeHelper { public static void onNetworkEnd(NetworkInfo networkInfo) throws UninstallException { GodEye.instance().<Network>getModule(GodEye.ModuleName.NETWORK).produce(networkInfo); L.d("GodEyeHelper onNetworkEnd: %s", networkInfo == null ? "null" : networkInfo.toSummaryString()); } static void onPageLoaded(Object page); static void onFragmentPageVisibilityChange(Object fragmentPage, boolean visible); static void onAppStartEnd(StartupInfo startupInfo); static void onNetworkEnd(NetworkInfo networkInfo); @Deprecated static void inspectView(); static void startMethodCanaryRecording(String tag); static void stopMethodCanaryRecording(String tag); static boolean isMethodCanaryRecording(String tag); static void setMonitorAppInfoConext(AppInfoConext appInfoConext); static void startMonitor(int port); static void startMonitor(); static void shutdownMonitor(); }### Answer: @Test public void onNetworkEndWhenNotInstalled() { try { GodEye.instance().uninstall(); GodEyeHelper.onNetworkEnd(null); fail(); } catch (UninstallException ignore) { } } @Test public void onNetworkEndWhenNull() { try { GodEye.instance().uninstall(); GodEye.instance().install(GodEyeConfig.noneConfigBuilder().withNetworkConfig(new NetworkConfig()).build()); GodEyeHelper.onNetworkEnd(null); } catch (NullPointerException ignore) { } catch (UninstallException e) { fail(); } } @Test public void onNetworkEndSuccess() { try { GodEye.instance().uninstall(); GodEye.instance().install(GodEyeConfig.noneConfigBuilder().withNetworkConfig(new NetworkConfig()).build()); NetworkInfo<NetworkContent> networkInfo = new NetworkInfo<>(); networkInfo.isSuccessful = true; networkInfo.message = "message"; GodEyeHelper.onNetworkEnd(networkInfo); TestObserver testObserver = GodEye.instance().<Network, NetworkInfo>moduleObservable(GodEye.ModuleName.NETWORK).test(); testObserver.assertValue(new Predicate<NetworkInfo>() { @Override public boolean test(NetworkInfo o) throws Exception { return networkInfo.isSuccessful == o.isSuccessful && networkInfo.message.equals(o.message); } }); } catch (Throwable e) { fail(); } }
### Question: GodEyeHelper { public static void startMethodCanaryRecording(String tag) throws UninstallException { final MethodCanary methodCanary = GodEye.instance().getModule(GodEye.ModuleName.METHOD_CANARY); methodCanary.startMonitor(tag); } static void onPageLoaded(Object page); static void onFragmentPageVisibilityChange(Object fragmentPage, boolean visible); static void onAppStartEnd(StartupInfo startupInfo); static void onNetworkEnd(NetworkInfo networkInfo); @Deprecated static void inspectView(); static void startMethodCanaryRecording(String tag); static void stopMethodCanaryRecording(String tag); static boolean isMethodCanaryRecording(String tag); static void setMonitorAppInfoConext(AppInfoConext appInfoConext); static void startMonitor(int port); static void startMonitor(); static void shutdownMonitor(); }### Answer: @Test public void startMethodCanaryRecordingWhenNotInstalled() { try { GodEye.instance().uninstall(); GodEyeHelper.startMethodCanaryRecording("tag"); fail(); } catch (UninstallException ignore) { } } @Test public void startMethodCanaryRecordingSuccess() { try { GodEye.instance().uninstall(); GodEye.instance().install(GodEyeConfig.noneConfigBuilder().withMethodCanaryConfig(new MethodCanaryConfig()).build()); GodEyeHelper.startMethodCanaryRecording("tag"); } catch (UninstallException ignore) { fail(); } }
### Question: GodEyeHelper { public static void stopMethodCanaryRecording(String tag) throws UninstallException { final MethodCanary methodCanary = GodEye.instance().getModule(GodEye.ModuleName.METHOD_CANARY); methodCanary.stopMonitor(tag); } static void onPageLoaded(Object page); static void onFragmentPageVisibilityChange(Object fragmentPage, boolean visible); static void onAppStartEnd(StartupInfo startupInfo); static void onNetworkEnd(NetworkInfo networkInfo); @Deprecated static void inspectView(); static void startMethodCanaryRecording(String tag); static void stopMethodCanaryRecording(String tag); static boolean isMethodCanaryRecording(String tag); static void setMonitorAppInfoConext(AppInfoConext appInfoConext); static void startMonitor(int port); static void startMonitor(); static void shutdownMonitor(); }### Answer: @Test public void stopMethodCanaryRecordingWhenNotInstalled() { try { GodEye.instance().uninstall(); GodEyeHelper.stopMethodCanaryRecording("tag"); fail(); } catch (UninstallException ignore) { } } @Test public void stopMethodCanaryRecordingSuccess() { try { GodEye.instance().uninstall(); GodEye.instance().install(GodEyeConfig.noneConfigBuilder().withMethodCanaryConfig(new MethodCanaryConfig()).build()); GodEyeHelper.stopMethodCanaryRecording("tag"); } catch (UninstallException ignore) { fail(); } }
### Question: GodEye { public <S extends SubjectSupport<M>, M> Observable<M> moduleObservable(@ModuleName String moduleName) throws UninstallException { return this.<S>getModule(moduleName).subject(); } private GodEye(); static GodEye instance(); synchronized GodEye install(final GodEyeConfig godEyeConfig, NotificationConfig notificationConfig); GodEye install(final GodEyeConfig godEyeConfig); GodEye install(final GodEyeConfig godEyeConfig, boolean enableNotification); synchronized GodEye uninstall(); synchronized T getModule(@ModuleName String moduleName); synchronized @ModuleName Set<String> getInstalledModuleNames(); Observable<M> moduleObservable(@ModuleName String moduleName); Disposable observeModule(@ModuleName String moduleName, Consumer<M> consumer); Application getApplication(); @Deprecated void init(Application application); static final Set<String> ALL_MODULE_NAMES; }### Answer: @Test public void moduleObservable() { GodEye.instance().uninstall(); try { GodEye.instance().moduleObservable(null); fail(); } catch (UninstallException ignore) { } try { GodEye.instance().moduleObservable(""); fail(); } catch (UninstallException ignore) { } try { GodEye.instance().moduleObservable(GodEye.ModuleName.STARTUP); fail(); } catch (UninstallException ignore) { } GodEye.instance().install(GodEyeConfig.noneConfigBuilder().withStartupConfig(new StartupConfig()).build()); try { GodEye.instance().moduleObservable(GodEye.ModuleName.STARTUP).test().assertNoValues(); } catch (UninstallException e) { fail(); } }
### Question: GodEyeHelper { public static boolean isMethodCanaryRecording(String tag) throws UninstallException { final MethodCanary methodCanary = GodEye.instance().getModule(GodEye.ModuleName.METHOD_CANARY); return methodCanary.isRunning(tag); } static void onPageLoaded(Object page); static void onFragmentPageVisibilityChange(Object fragmentPage, boolean visible); static void onAppStartEnd(StartupInfo startupInfo); static void onNetworkEnd(NetworkInfo networkInfo); @Deprecated static void inspectView(); static void startMethodCanaryRecording(String tag); static void stopMethodCanaryRecording(String tag); static boolean isMethodCanaryRecording(String tag); static void setMonitorAppInfoConext(AppInfoConext appInfoConext); static void startMonitor(int port); static void startMonitor(); static void shutdownMonitor(); }### Answer: @Test public void isMethodCanaryRecordingWhenNotInstalled() { try { GodEye.instance().uninstall(); GodEyeHelper.isMethodCanaryRecording("tag"); fail(); } catch (UninstallException ignore) { } }
### Question: MemoryUtil { public static HeapInfo getAppHeapInfo() { Runtime runtime = Runtime.getRuntime(); HeapInfo heapInfo = new HeapInfo(); heapInfo.freeMemKb = runtime.freeMemory() / 1024; heapInfo.maxMemKb = Runtime.getRuntime().maxMemory() / 1024; heapInfo.allocatedKb = (Runtime.getRuntime().totalMemory() - runtime.freeMemory()) / 1024; return heapInfo; } static HeapInfo getAppHeapInfo(); static PssInfo getAppPssInfo(Context context); static RamInfo getRamInfo(Context context); }### Answer: @Test public void getAppHeapInfo() { HeapInfo heapInfo = MemoryUtil.getAppHeapInfo(); Assert.assertTrue(heapInfo.allocatedKb > 0); Assert.assertTrue(heapInfo.freeMemKb > 0); Assert.assertTrue(heapInfo.maxMemKb > 0); }
### Question: MemoryUtil { public static PssInfo getAppPssInfo(Context context) { final int pid = ProcessUtils.getCurrentPid(); if (sActivityManager == null) { sActivityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); } Debug.MemoryInfo memoryInfo = sActivityManager.getProcessMemoryInfo(new int[]{pid})[0]; PssInfo pssInfo = new PssInfo(); pssInfo.totalPssKb = memoryInfo.getTotalPss(); pssInfo.dalvikPssKb = memoryInfo.dalvikPss; pssInfo.nativePssKb = memoryInfo.nativePss; pssInfo.otherPssKb = memoryInfo.otherPss; return pssInfo; } static HeapInfo getAppHeapInfo(); static PssInfo getAppPssInfo(Context context); static RamInfo getRamInfo(Context context); }### Answer: @Test public void getAppPssInfo() { try { PssInfo pssInfo = MemoryUtil.getAppPssInfo(GodEye.instance().getApplication()); } catch (NullPointerException ignore) { } catch (Throwable e) { Assert.fail(); } }
### Question: MemoryUtil { public static RamInfo getRamInfo(Context context) { if (sActivityManager == null) { sActivityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); } final ActivityManager.MemoryInfo mi = new ActivityManager.MemoryInfo(); sActivityManager.getMemoryInfo(mi); final RamInfo ramMemoryInfo = new RamInfo(); ramMemoryInfo.availMemKb = mi.availMem / 1024; ramMemoryInfo.isLowMemory = mi.lowMemory; ramMemoryInfo.lowMemThresholdKb = mi.threshold / 1024; ramMemoryInfo.totalMemKb = getRamTotalMem(sActivityManager); return ramMemoryInfo; } static HeapInfo getAppHeapInfo(); static PssInfo getAppPssInfo(Context context); static RamInfo getRamInfo(Context context); }### Answer: @Test public void getRamInfo() { RamInfo ramInfo = MemoryUtil.getRamInfo(GodEye.instance().getApplication()); Assert.assertNotNull(ramInfo); }
### Question: MethodCanaryConverter { static MethodsRecordInfo convertToMethodsRecordInfo(long startMillis, long stopMillis, Map<ThreadInfo, List<MethodEvent>> methodEventMap) { MethodsRecordInfo methodsRecordInfo = new MethodsRecordInfo(startMillis, stopMillis, new ArrayList<>()); if (methodEventMap == null || methodEventMap.isEmpty()) { return methodsRecordInfo; } for (Map.Entry<ThreadInfo, List<MethodEvent>> entry : methodEventMap.entrySet()) { List<MethodEvent> methodEvents = entry.getValue(); List<MethodsRecordInfo.MethodInfoOfThreadInfo.MethodInfo> methodInfos = new ArrayList<>(methodEvents.size()); Stack<MethodsRecordInfo.MethodInfoOfThreadInfo.MethodInfo> methodEventsStackOfCurrentThread = new Stack<>(); for (MethodEvent methodEvent : methodEvents) { if (methodEvent.isEnter) { MethodsRecordInfo.MethodInfoOfThreadInfo.MethodInfo methodInfo = new MethodsRecordInfo.MethodInfoOfThreadInfo.MethodInfo(); methodInfo.className = methodEvent.className; methodInfo.methodAccessFlag = methodEvent.methodAccessFlag; methodInfo.methodName = methodEvent.methodName; methodInfo.methodDesc = methodEvent.methodDesc; methodInfo.startMillis = methodEvent.eventTimeMillis; methodInfo.stack = methodEventsStackOfCurrentThread.size(); methodInfos.add(methodInfo); methodEventsStackOfCurrentThread.push(methodInfo); } else { MethodsRecordInfo.MethodInfoOfThreadInfo.MethodInfo methodInfo = null; if (!methodEventsStackOfCurrentThread.empty()) { methodInfo = methodEventsStackOfCurrentThread.pop(); } if (methodInfo != null) { methodInfo.endMillis = methodEvent.eventTimeMillis; } } } methodsRecordInfo.methodInfoOfThreadInfos.add(new MethodsRecordInfo.MethodInfoOfThreadInfo(entry.getKey(), methodInfos)); } return methodsRecordInfo; } }### Answer: @Test public void convertToMethodsRecordInfo() { Map<ThreadInfo, List<MethodEvent>> methodEventMap = mockMethodEventMap(); MethodsRecordInfo methodsRecordInfo = mockMethodsRecordInfo(methodEventMap); Gson gson = new Gson(); String c = gson.toJson(methodsRecordInfo); System.out.println("methodsRecordInfo:\n" + c); assertEquals(methodsRecordInfo.methodInfoOfThreadInfos.size(), methodEventMap.size()); }
### Question: ViewCanaryInternal { @VisibleForTesting Runnable inspectInner(WeakReference<Activity> activity, ViewCanary viewCanary, ViewCanaryConfig config, Map<Activity, List<List<ViewIdWithSize>>> recentLayoutListRecords) { return () -> { try { Activity p = activity.get(); if (p != null) { ViewGroup parent = (ViewGroup) p.getWindow().getDecorView(); inspect(p, parent, viewCanary, config, recentLayoutListRecords); } } catch (Throwable e) { L.e(e); } }; } }### Answer: @Test public void inspectInner() { ActivityController<TestViewCanaryActivity> activityController = Robolectric.buildActivity(TestViewCanaryActivity.class).create().start().resume(); ViewCanaryInternal viewCanaryInternal = new ViewCanaryInternal(); Map<Activity, List<List<ViewIdWithSize>>> recentLayoutListRecords = new HashMap<>(); try { viewCanaryInternal.inspectInner(new WeakReference<>(activityController.get()), GodEye.instance().<ViewCanary>getModule(GodEye.ModuleName.VIEW_CANARY), GodEye.instance().<ViewCanary>getModule(GodEye.ModuleName.VIEW_CANARY).config(), recentLayoutListRecords).run(); GodEye.instance().<ViewCanary, ViewIssueInfo>moduleObservable(GodEye.ModuleName.VIEW_CANARY).test().assertNoValues(); recentLayoutListRecords.put(activityController.get(), new ArrayList<>()); viewCanaryInternal.inspectInner(new WeakReference<>(activityController.get()), GodEye.instance().<ViewCanary>getModule(GodEye.ModuleName.VIEW_CANARY), GodEye.instance().<ViewCanary>getModule(GodEye.ModuleName.VIEW_CANARY).config(), recentLayoutListRecords).run(); GodEye.instance().<ViewCanary, ViewIssueInfo>moduleObservable(GodEye.ModuleName.VIEW_CANARY).test().assertValueCount(1); viewCanaryInternal.inspectInner(new WeakReference<>(activityController.get()), GodEye.instance().<ViewCanary>getModule(GodEye.ModuleName.VIEW_CANARY), GodEye.instance().<ViewCanary>getModule(GodEye.ModuleName.VIEW_CANARY).config(), recentLayoutListRecords).run(); GodEye.instance().<ViewCanary, ViewIssueInfo>moduleObservable(GodEye.ModuleName.VIEW_CANARY).test().assertValueCount(1); } catch (UninstallException e) { Assert.fail(); } }
### Question: Network extends ProduceableSubject<NetworkInfo> implements Install<NetworkConfig> { @Override public void produce(NetworkInfo data) { if (mConfig == null) { L.d("Network is not installed, produce data fail."); return; } super.produce(data); } @Override synchronized boolean install(NetworkConfig config); @Override synchronized void uninstall(); @Override synchronized boolean isInstalled(); @Override NetworkConfig config(); @Override void produce(NetworkInfo data); }### Answer: @Test public void work() { try { NetworkInfo networkInfo0 = new NetworkInfo(); networkInfo0.message = "networkInfo0"; networkInfo0.networkTime = new NetworkTime(); networkInfo0.networkTime.totalTimeMillis = 1000; networkInfo0.networkTime.networkTimeMillisMap = new LinkedHashMap<>(); networkInfo0.networkTime.networkTimeMillisMap.put("AndroidGodEye-Network-Queue", 800L); NetworkInfo networkInfo1 = new NetworkInfo(); networkInfo1.message = "networkInfo1"; NetworkInfo networkInfo2 = new NetworkInfo(); networkInfo2.message = "networkInfo2"; NetworkInfo networkInfo3 = new NetworkInfo(); networkInfo3.message = "networkInfo3"; GodEye.instance().<Network>getModule(GodEye.ModuleName.NETWORK).produce(networkInfo0); GodEye.instance().<Network>getModule(GodEye.ModuleName.NETWORK).produce(networkInfo1); TestObserver<NetworkInfo> testObserver = GodEye.instance().<Network, NetworkInfo>moduleObservable(GodEye.ModuleName.NETWORK).test(); GodEye.instance().<Network>getModule(GodEye.ModuleName.NETWORK).produce(networkInfo2); GodEye.instance().<Network>getModule(GodEye.ModuleName.NETWORK).produce(networkInfo3); testObserver.assertValueCount(4).assertValueAt(0, new Predicate<NetworkInfo>() { @Override public boolean test(NetworkInfo info) throws Exception { Log4Test.d(info); return info.message.equals("networkInfo0") && info.networkTime.totalTimeMillis == 1000; } }).assertValueAt(1, new Predicate<NetworkInfo>() { @Override public boolean test(NetworkInfo info) throws Exception { Log4Test.d(info); return info.message.equals("networkInfo1"); } }).assertValueAt(2, new Predicate<NetworkInfo>() { @Override public boolean test(NetworkInfo info) throws Exception { Log4Test.d(info); return info.message.equals("networkInfo2"); } }).assertValueAt(3, new Predicate<NetworkInfo>() { @Override public boolean test(NetworkInfo info) throws Exception { Log4Test.d(info); return info.message.equals("networkInfo3"); } }); } catch (UninstallException e) { Assert.fail(); } }
### Question: Startup extends ProduceableSubject<StartupInfo> implements Install<StartupConfig> { @Override public void produce(StartupInfo data) { if (mConfig == null) { L.d("Startup is not installed, produce data fail."); return; } super.produce(data); } @Override synchronized boolean install(StartupConfig config); @Override synchronized void uninstall(); @Override synchronized boolean isInstalled(); @Override StartupConfig config(); @Override void produce(StartupInfo data); }### Answer: @Test public void work() { try { GodEye.instance().<Startup>getModule(GodEye.ModuleName.STARTUP).produce(new StartupInfo(StartupInfo.StartUpType.COLD, 1)); GodEye.instance().<Startup>getModule(GodEye.ModuleName.STARTUP).produce(new StartupInfo(StartupInfo.StartUpType.HOT, 2)); TestObserver<StartupInfo> testObserver = GodEye.instance().<Startup, StartupInfo>moduleObservable(GodEye.ModuleName.STARTUP).test(); GodEye.instance().<Startup>getModule(GodEye.ModuleName.STARTUP).produce(new StartupInfo(StartupInfo.StartUpType.COLD, 3)); GodEye.instance().<Startup>getModule(GodEye.ModuleName.STARTUP).produce(new StartupInfo(StartupInfo.StartUpType.HOT, 4)); testObserver.assertValueCount(3).assertValueAt(0, new Predicate<StartupInfo>() { @Override public boolean test(StartupInfo info) throws Exception { Log4Test.d(info); return StartupInfo.StartUpType.HOT.equals(info.startupType) && info.startupTime == 2; } }).assertValueAt(1, new Predicate<StartupInfo>() { @Override public boolean test(StartupInfo info) throws Exception { Log4Test.d(info); return StartupInfo.StartUpType.COLD.equals(info.startupType) && info.startupTime == 3; } }).assertValueAt(2, new Predicate<StartupInfo>() { @Override public boolean test(StartupInfo info) throws Exception { Log4Test.d(info); return StartupInfo.StartUpType.HOT.equals(info.startupType) && info.startupTime == 4; } }); } catch (UninstallException e) { Assert.fail(); } }
### Question: PageLifecycleMethodEventTypes { static boolean isMatch(LifecycleEvent lifecycleEvent0, LifecycleEvent lifecycleEvent1) { return lifecycleEvent0.equals(lifecycleEvent1); } }### Answer: @Test public void isMatch() { Assert.assertTrue(PageLifecycleMethodEventTypes.isMatch(ActivityLifecycleEvent.ON_CREATE, ActivityLifecycleEvent.ON_CREATE)); Assert.assertFalse(PageLifecycleMethodEventTypes.isMatch(FragmentLifecycleEvent.ON_CREATE, ActivityLifecycleEvent.ON_CREATE)); }
### Question: PageLifecycleMethodEventTypes { static LifecycleEvent convert(PageType pageType, MethodEvent lifecycleMethodEvent) { return sPairsOfLifecycleAndMethods.get(new MethodInfoForLifecycle(pageType, lifecycleMethodEvent)); } }### Answer: @Test public void convert() { Assert.assertNull(PageLifecycleMethodEventTypes.convert(PageType.ACTIVITY, mock("class0", "desc0"))); Assert.assertNull(PageLifecycleMethodEventTypes.convert(PageType.ACTIVITY, mock("onCreate", "(Landroid/os/Bundle;)"))); Assert.assertEquals(ActivityLifecycleEvent.ON_CREATE, PageLifecycleMethodEventTypes.convert(PageType.ACTIVITY, mock("onCreate", "(Landroid/os/Bundle;)V"))); Assert.assertEquals(FragmentLifecycleEvent.ON_CREATE, PageLifecycleMethodEventTypes.convert(PageType.FRAGMENT, mock("onCreate", "(Landroid/os/Bundle;)V"))); }
### Question: GodEye { public <S extends SubjectSupport<M>, M> Disposable observeModule(@ModuleName String moduleName, Consumer<M> consumer) throws UninstallException { return this.<S>getModule(moduleName).subject().subscribeOn(Schedulers.computation()).observeOn(Schedulers.computation()).subscribe(consumer); } private GodEye(); static GodEye instance(); synchronized GodEye install(final GodEyeConfig godEyeConfig, NotificationConfig notificationConfig); GodEye install(final GodEyeConfig godEyeConfig); GodEye install(final GodEyeConfig godEyeConfig, boolean enableNotification); synchronized GodEye uninstall(); synchronized T getModule(@ModuleName String moduleName); synchronized @ModuleName Set<String> getInstalledModuleNames(); Observable<M> moduleObservable(@ModuleName String moduleName); Disposable observeModule(@ModuleName String moduleName, Consumer<M> consumer); Application getApplication(); @Deprecated void init(Application application); static final Set<String> ALL_MODULE_NAMES; }### Answer: @Test public void observeModule() { GodEye.instance().init(ApplicationProvider.getApplicationContext()); GodEye.instance().uninstall(); try { GodEye.instance().observeModule(null, null); fail(); } catch (UninstallException ignore) { } try { GodEye.instance().observeModule("", null); fail(); } catch (UninstallException ignore) { } try { GodEye.instance().observeModule(GodEye.ModuleName.STARTUP, null); fail(); } catch (UninstallException ignore) { } GodEye.instance().install(GodEyeConfig.noneConfigBuilder().withStartupConfig(new StartupConfig()).build()); try { GodEye.instance().observeModule(GodEye.ModuleName.STARTUP, null); fail(); } catch (NullPointerException ignore) { } catch (UninstallException e) { fail(); } try { GodEyeHelper.onAppStartEnd(new StartupInfo(StartupInfo.StartUpType.COLD, 1000)); } catch (UninstallException e) { fail(); } try { GodEye.instance().observeModule(GodEye.ModuleName.STARTUP, new Consumer<StartupInfo>() { @Override public void accept(StartupInfo cpuInfo) throws Exception { } }); } catch (UninstallException e) { fail(); } }
### Question: LeakDetector extends ProduceableSubject<LeakQueue.LeakMemoryInfo> implements Install<LeakConfig> { public static LeakDetector instance() { return LeakDetector.InstanceHolder.sINSTANCE; } private LeakDetector(); static LeakDetector instance(); @Override synchronized boolean install(LeakConfig config); @Override synchronized void uninstall(); @Override synchronized boolean isInstalled(); @Override LeakConfig config(); }### Answer: @Test public void work() { try { ApplicationLeak applicationLeak0 = new ApplicationLeak(Arrays.asList(new LeakTrace(LeakTrace.GcRootType.JNI_GLOBAL, new ArrayList<>(), new LeakTraceObject(LeakTraceObject.ObjectType.ARRAY, "", new ArraySet<>(), LeakTraceObject.LeakingStatus.LEAKING, ""), 0))); ApplicationLeak applicationLeak1 = new ApplicationLeak(Arrays.asList(new LeakTrace(LeakTrace.GcRootType.JNI_GLOBAL, new ArrayList<>(), new LeakTraceObject(LeakTraceObject.ObjectType.ARRAY, "", new ArraySet<>(), LeakTraceObject.LeakingStatus.LEAKING, ""), 1))); ApplicationLeak applicationLeak2 = new ApplicationLeak(Arrays.asList(new LeakTrace(LeakTrace.GcRootType.JNI_GLOBAL, new ArrayList<>(), new LeakTraceObject(LeakTraceObject.ObjectType.ARRAY, "", new ArraySet<>(), LeakTraceObject.LeakingStatus.LEAKING, ""), 2))); ApplicationLeak applicationLeak3 = new ApplicationLeak(Arrays.asList(new LeakTrace(LeakTrace.GcRootType.JNI_GLOBAL, new ArrayList<>(), new LeakTraceObject(LeakTraceObject.ObjectType.ARRAY, "", new ArraySet<>(), LeakTraceObject.LeakingStatus.LEAKING, ""), 3))); LeakInfo leakInfo0 = new LeakInfo(0, 0, applicationLeak0); LeakInfo leakInfo1 = new LeakInfo(0, 0, applicationLeak1); LeakInfo leakInfo2 = new LeakInfo(0, 0, applicationLeak2); LeakInfo leakInfo3 = new LeakInfo(0, 0, applicationLeak3); GodEye.instance().<Leak>getModule(GodEye.ModuleName.LEAK_CANARY).produce(leakInfo0); GodEye.instance().<Leak>getModule(GodEye.ModuleName.LEAK_CANARY).produce(leakInfo1); TestObserver<LeakInfo> testObserver = GodEye.instance().<Leak, LeakInfo>moduleObservable(GodEye.ModuleName.LEAK_CANARY).test(); GodEye.instance().<Leak>getModule(GodEye.ModuleName.LEAK_CANARY).produce(leakInfo2); GodEye.instance().<Leak>getModule(GodEye.ModuleName.LEAK_CANARY).produce(leakInfo3); testObserver.assertValueCount(4).assertValueAt(0, new Predicate<LeakInfo>() { @Override public boolean test(LeakInfo heapAnalysis) throws Exception { return 0 == heapAnalysis.info.getLeakTraces().get(0).getRetainedHeapByteSize(); } }).assertValueAt(1, new Predicate<LeakInfo>() { @Override public boolean test(LeakInfo heapAnalysis) throws Exception { return 1 == heapAnalysis.info.getLeakTraces().get(0).getRetainedHeapByteSize(); } }).assertValueAt(2, new Predicate<LeakInfo>() { @Override public boolean test(LeakInfo heapAnalysis) throws Exception { return 2 == heapAnalysis.info.getLeakTraces().get(0).getRetainedHeapByteSize(); } }).assertValueAt(3, new Predicate<LeakInfo>() { @Override public boolean test(LeakInfo heapAnalysis) throws Exception { return 3 == heapAnalysis.info.getLeakTraces().get(0).getRetainedHeapByteSize(); } }); } catch (UninstallException e) { Assert.fail(); } }
### Question: AppSizeUtil { @SuppressWarnings("JavaReflectionMemberAccess") private static void getAppSizeLowerO(Context context, @NonNull final OnGetSizeListener listener) { try { Method method = PackageManager.class.getMethod("getPackageSizeInfo", String.class, IPackageStatsObserver.class); method.invoke(context.getPackageManager(), context.getPackageName(), new IPackageStatsObserver.Stub() { @Override public void onGetStatsCompleted(PackageStats pStats, boolean succeeded) { AppSizeInfo ctAppSizeInfo = new AppSizeInfo(); ctAppSizeInfo.cacheSize = pStats.cacheSize; ctAppSizeInfo.dataSize = pStats.dataSize; ctAppSizeInfo.codeSize = pStats.codeSize; listener.onGetSize(ctAppSizeInfo); } }); } catch (Throwable e) { listener.onError(e); } } }### Answer: @Test(timeout = 5000) @Config(sdk = Build.VERSION_CODES.LOLLIPOP) public void getAppSizeLowerO() { CountDownLatch countDownLatch = new CountDownLatch(1); final AppSizeInfo[] appSizeInfo = new AppSizeInfo[1]; AppSizeUtil.getAppSize(ApplicationProvider.getApplicationContext(), new AppSizeUtil.OnGetSizeListener() { @Override public void onGetSize(AppSizeInfo ctAppSizeInfo) { countDownLatch.countDown(); appSizeInfo[0] = ctAppSizeInfo; } @Override public void onError(Throwable t) { countDownLatch.countDown(); } }); try { countDownLatch.await(3, TimeUnit.SECONDS); } catch (InterruptedException e) { Assert.fail(); } Log4Test.d(String.valueOf(appSizeInfo[0])); Assert.assertTrue(appSizeInfo[0].dataSize >= 0); Assert.assertTrue(appSizeInfo[0].codeSize >= 0); Assert.assertTrue(appSizeInfo[0].cacheSize >= 0); }
### Question: AppSizeUtil { static String formatSize(long size) { if (size / (1024 * 1024 * 1024) > 0) { float tmpSize = (float) (size) / (float) (1024 * 1024 * 1024); DecimalFormat df = new DecimalFormat("#.##"); return df.format(tmpSize) + "GB"; } else if (size / (1024 * 1024) > 0) { float tmpSize = (float) (size) / (float) (1024 * 1024); DecimalFormat df = new DecimalFormat("#.##"); return df.format(tmpSize) + "MB"; } else if (size / 1024 > 0) { return (size / (1024)) + "KB"; } else { return size + "B"; } } }### Answer: @Test public void formatSize() { final long oneByte = 1; final long oneKByte = 1 * 1024; final long oneMByte = 1 * 1024 * 1024; final long oneGByte = 1 * 1024 * 1024 * 1024; Assert.assertEquals("2B", AppSizeUtil.formatSize(oneByte * 2)); Assert.assertEquals("2KB", AppSizeUtil.formatSize(oneKByte * 2 + oneByte)); Assert.assertEquals("2MB", AppSizeUtil.formatSize(oneMByte * 2 + 2 * oneKByte)); Assert.assertEquals("2.1MB", AppSizeUtil.formatSize(oneMByte * 2 + 101 * oneKByte)); Assert.assertEquals("2.1GB", AppSizeUtil.formatSize(oneGByte * 2 + 101 * oneMByte + 101 * oneKByte)); Assert.assertEquals("2GB", AppSizeUtil.formatSize(oneGByte * 2 + 101 * oneKByte)); }
### Question: Sm extends ProduceableSubject<BlockInfo> implements Install<SmConfig> { public void setSmConfigCache(SmConfig smConfigCache) { if (smConfigCache == null || !smConfigCache.isValid()) { return; } SharedPreferences sharedPreferences = GodEye.instance().getApplication().getSharedPreferences("AndroidGodEye", 0); sharedPreferences.edit().putString("SmConfig", JsonUtil.toJson(smConfigCache)).apply(); } @Override synchronized boolean install(SmConfig config); @Override synchronized void uninstall(); @Override synchronized boolean isInstalled(); @Override SmConfig config(); SmConfig installConfig(); void setSmConfigCache(SmConfig smConfigCache); void clearSmConfigCache(); }### Answer: @Test public void setSmConfigCache() { GodEye.instance().uninstall(); GodEye.instance().install(GodEyeConfig.noneConfigBuilder().withSmConfig(new SmConfig()).build()); try { GodEye.instance().<Sm>getModule(GodEye.ModuleName.SM).setSmConfigCache(new SmConfig(true, 200, 150, 100)); Assert.assertEquals(200, GodEye.instance().<Sm>getModule(GodEye.ModuleName.SM).getValidSmConfigCache().longBlockThreshold()); GodEye.instance().<Sm>getModule(GodEye.ModuleName.SM).clearSmConfigCache(); Assert.assertNull(GodEye.instance().<Sm>getModule(GodEye.ModuleName.SM).getValidSmConfigCache()); } catch (UninstallException e) { Assert.fail(); } }
### Question: CpuUsage { @VisibleForTesting static CpuSnapshot parse(String cpuRate, String pidCpuRate) { String[] cpuInfoArray = cpuRate.split("\\s+"); if (cpuInfoArray.length < 9) { throw new IllegalStateException("cpu info array size must great than 9"); } long user = Long.parseLong(cpuInfoArray[2]); long nice = Long.parseLong(cpuInfoArray[3]); long system = Long.parseLong(cpuInfoArray[4]); long idle = Long.parseLong(cpuInfoArray[5]); long ioWait = Long.parseLong(cpuInfoArray[6]); long total = user + nice + system + idle + ioWait + Long.parseLong(cpuInfoArray[7]) + Long.parseLong(cpuInfoArray[8]); String[] pidCpuInfoList = pidCpuRate.split(" "); if (pidCpuInfoList.length < 17) { throw new IllegalStateException("pid cpu info array size must great than 17"); } long appCpuTime = Long.parseLong(pidCpuInfoList[13]) + Long.parseLong(pidCpuInfoList[14]) + Long.parseLong(pidCpuInfoList[15]) + Long.parseLong(pidCpuInfoList[16]); return new CpuSnapshot(user, system, idle, ioWait, total, appCpuTime); } static CpuInfo getCpuInfo(); }### Answer: @Test public void parse() { String deviceCpu0 = "800%cpu 0%user 0%nice 0%sys 800%idle 0%iow 0%irq 0%sirq 0%host"; String appCpu0 = "[7m PID USER PR NI VIRT RES SHR S[%CPU] %MEM TIME+ ARGS \u001B[0m"; try { CpuSnapshot cpuSnapshot = CpuUsage.parse(deviceCpu0, appCpu0); Assert.fail(); } catch (NumberFormatException ignore) { } String deviceCpu1 = "cpu 4473 1068 4565 21155 559 0 29 0 0 0"; String appCpu1 = "3238 (d.godeye.sample) S 1189 1189 0 0 -1 1077961024 25948 0 3 0 94 111 0 0 20 0 35 0 4901 1332465664 16104 4294967295 3078545408 3078556388 3213513904 3213510820 3077933717 0 4612 0 1073779964 4294967295 0 0 17 3 0 0 1 0 0 3078561120 3078561772 3088125952 3213515788 3213515864 3213515864 3213516772 0"; CpuSnapshot cpuSnapshot = CpuUsage.parse(deviceCpu1, appCpu1); Assert.assertEquals(1068, cpuSnapshot.user); Assert.assertEquals(21155, cpuSnapshot.system); Assert.assertEquals(559, cpuSnapshot.idle); Assert.assertEquals(0, cpuSnapshot.ioWait); Assert.assertEquals(27376, cpuSnapshot.total); Assert.assertEquals(205, cpuSnapshot.app); }
### Question: CpuUsage { @VisibleForTesting static float parseCpuRateOfAppByShell(String line, int cpuIndex, Float cpuTotal) { if (line.startsWith(String.valueOf(android.os.Process.myPid()))) { if (cpuIndex == -1) { throw new IllegalStateException("parseCpuRateOfAppByShell but cpuIndex == -1:" + line); } String[] param = line.split("\\s+"); if (param.length <= cpuIndex) { throw new IllegalStateException("parseCpuRateOfAppByShell but param.length <= cpuIndex:" + line); } String cpu = param[cpuIndex]; if (cpu.endsWith("%")) { cpu = cpu.substring(0, cpu.lastIndexOf("%")); } if (cpuTotal == null || cpuTotal <= 0) { throw new IllegalStateException("parseCpuRateOfAppByShell but cpuTotal == null || cpuTotal <= 0:" + line); } try { return Float.parseFloat(cpu) / cpuTotal; } catch (Throwable e) { throw new IllegalStateException("parseCpuRateOfAppByShell but " + e + ":" + line); } } return -1; } static CpuInfo getCpuInfo(); }### Answer: @Test public void parseCpuRateOfAppByShell() { String line2 = "800%cpu 0%user 0%nice 0%sys 800%idle 0%iow 0%irq 0%sirq 0%host"; String line3 = "[7m PID USER PR NI VIRT RES SHR S[%CPU] %MEM TIME+ ARGS \u001B[0m"; String line4 = "0 u0_a591 10 -10 5.4G 131M 80M S 16.0 1.7 0:02.98 cn.hikyson.andr+"; String line5 = "0wfwf fweffwef fwef6.064564f3402.98 cn.hikyson.andr+"; int index = CpuUsage.parseCPUIndex(line3); Map<String, Float> tempCpuDevice = CpuUsage.parseCpuRateOfDeviceAndTotalByShell(line2); try { CpuUsage.parseCpuRateOfAppByShell(line5, index, tempCpuDevice.get("cpu")); Assert.fail(); } catch (IllegalStateException ignore) { } try { CpuUsage.parseCpuRateOfAppByShell(line4, -1, tempCpuDevice.get("cpu")); Assert.fail(); } catch (IllegalStateException ignore) { } try { CpuUsage.parseCpuRateOfAppByShell(line4, index, tempCpuDevice.get("unknown")); Assert.fail(); } catch (IllegalStateException ignore) { } float appCpu0 = CpuUsage.parseCpuRateOfAppByShell(line4, index, tempCpuDevice.get("cpu")); Assert.assertEquals((float) Float.parseFloat("16.0") / 800, appCpu0, 0.1); }
### Question: CpuUsage { @VisibleForTesting static Map<String, Float> parseCpuRateOfDeviceAndTotalByShell(String line) { if (line.matches("^\\d+%\\w+.+\\d+%\\w+")) { String lineLowerCase = line.toLowerCase(Locale.US); String[] cpuList = lineLowerCase.split("\\s+"); Map<String, Float> cpuMap = new HashMap<>(); for (String s : cpuList) { String[] cpuItem = s.split("%"); if (cpuItem.length != 2) { throw new IllegalStateException("parseCpuRateOfDeviceAndTotalByShell but cpuItem.length != 2"); } try { cpuMap.put(cpuItem[1], Float.parseFloat(cpuItem[0])); } catch (Throwable e) { throw new IllegalStateException("parseCpuRateOfDeviceAndTotalByShell but " + e); } } return cpuMap; } return null; } static CpuInfo getCpuInfo(); }### Answer: @Test public void parseCpuRateOfDeviceAndTotalByShell() { String line0 = "[s\u001B[999C\u001B[999B\u001B[6n\u001B[u\u001B[H\u001B[J\u001B[?25l\u001B[H\u001B[J\u001B[s\u001B[999C\u001B[999B\u001B[6n\u001B[uTasks: 2 total, 1 running, 1 sleeping, 0 stopped, 0 zombie"; String line1 = "Mem: 7.2G total, 7.0G used, 266M free, 98M buffers"; String line2 = "800%cpu 0%user 0%nice 0%sys 800%idle 0%iow 0%irq 0%sirq 0%host"; String line3 = "[7m PID USER PR NI VIRT RES SHR S[%CPU] %MEM TIME+ ARGS \u001B[0m"; Map<String, Float> tempCpuDevice0 = CpuUsage.parseCpuRateOfDeviceAndTotalByShell(line0); Map<String, Float> tempCpuDevice1 = CpuUsage.parseCpuRateOfDeviceAndTotalByShell(line1); Map<String, Float> tempCpuDevice2 = CpuUsage.parseCpuRateOfDeviceAndTotalByShell(line2); Map<String, Float> tempCpuDevice3 = CpuUsage.parseCpuRateOfDeviceAndTotalByShell(line3); Assert.assertNull(tempCpuDevice0); Assert.assertNull(tempCpuDevice1); Assert.assertNull(tempCpuDevice3); Assert.assertEquals(800, tempCpuDevice2.get("cpu"), 0); Assert.assertEquals(0, tempCpuDevice2.get("sys"), 0); Assert.assertEquals(800, tempCpuDevice2.get("idle"), 0); }
### Question: CpuUsage { @VisibleForTesting static int parseCPUIndex(String line) { if (line.contains("CPU")) { String[] titles = line.split("\\s+"); for (int i = 0; i < titles.length; i++) { if (titles[i].contains("CPU")) { return i; } } } return -1; } static CpuInfo getCpuInfo(); }### Answer: @Test public void parseCPUIndex() { String line0 = "[s\u001B[999C\u001B[999B\u001B[6n\u001B[u\u001B[H\u001B[J\u001B[?25l\u001B[H\u001B[J\u001B[s\u001B[999C\u001B[999B\u001B[6n\u001B[uTasks: 2 total, 1 running, 1 sleeping, 0 stopped, 0 zombie"; String line1 = "Mem: 7.2G total, 7.0G used, 266M free, 98M buffers"; String line2 = "800%cpu 0%user 0%nice 0%sys 800%idle 0%iow 0%irq 0%sirq 0%host"; String line3 = "[7m PID USER PR NI VIRT RES SHR S[%CPU] %MEM TIME+ ARGS \u001B[0m"; Assert.assertEquals(-1, CpuUsage.parseCPUIndex(line0)); Assert.assertEquals(-1, CpuUsage.parseCPUIndex(line1)); Assert.assertEquals(-1, CpuUsage.parseCPUIndex(line2)); Assert.assertEquals(8, CpuUsage.parseCPUIndex(line3)); }
### Question: ImageCanaryInternal { @VisibleForTesting Runnable inspectInner(WeakReference<Activity> activity, ImageCanary imageCanaryEngine, Set<ImageIssue> imageIssues) { return () -> { try { Activity p = activity.get(); if (p != null) { ViewGroup parent = (ViewGroup) p.getWindow().getDecorView(); recursiveLoopChildren(p, parent, imageCanaryEngine, imageIssues); } } catch (Throwable e) { L.e(e); } }; } ImageCanaryInternal(ImageCanaryConfigProvider imageCanaryConfigProvider); }### Answer: @Test public void inspectInner() { ActivityController<Test4ImageActivity> activityController = Robolectric.buildActivity(Test4ImageActivity.class).create().start().resume(); Test4ImageActivity activity = activityController.get(); ImageCanaryInternal imageCanaryInternal = new ImageCanaryInternal(new DefaultImageCanaryConfigProvider()); ImageCanary imageCanary = new ImageCanary(); HashSet<ImageIssue> hashSet = new HashSet<ImageIssue>(); ImageIssue imageIssue = new ImageIssue(); imageIssue.activityHashCode = activity.hashCode(); imageIssue.imageViewHashCode = activity.imageView3().hashCode(); imageIssue.bitmapWidth = 200; imageIssue.bitmapHeight = 100; imageIssue.issueType = ImageIssue.IssueType.BITMAP_QUALITY_TOO_HIGH; hashSet.add(imageIssue); imageCanaryInternal.inspectInner(new WeakReference<>(activity), imageCanary, hashSet).run(); imageCanary.subject().test().assertValueAt(0, new Predicate<ImageIssue>() { @Override public boolean test(ImageIssue imageIssue) throws Exception { Log4Test.d(imageIssue); return imageIssue.activityHashCode == activity.hashCode() && imageIssue.bitmapWidth == 200 && imageIssue.bitmapHeight == 100 && imageIssue.imageViewWidth == 50 && imageIssue.imageViewHeight == 50 && imageIssue.issueType == ImageIssue.IssueType.BITMAP_QUALITY_TOO_HIGH; } }).assertValueAt(1, new Predicate<ImageIssue>() { @Override public boolean test(ImageIssue imageIssue) throws Exception { Log4Test.d(imageIssue); return imageIssue.activityHashCode == activity.hashCode() && imageIssue.bitmapWidth == 200 && imageIssue.bitmapHeight == 100 && imageIssue.imageViewWidth == 500 && imageIssue.imageViewHeight == 500 && imageIssue.issueType == ImageIssue.IssueType.BITMAP_QUALITY_TOO_LOW; } }).assertValueCount(2); Assert.assertEquals(3, hashSet.size()); }
### Question: NotificationConsumer implements Consumer<NotificationContent> { @Override public void accept(NotificationContent notificationContent) throws Exception { ThreadUtil.ensureWorkThread("NotificationConsumer"); if (mNotification == null) { return; } mNotification.onNotificationReceive(System.currentTimeMillis(), notificationContent); } NotificationConsumer(NotificationListener notifications); @Override void accept(NotificationContent notificationContent); }### Answer: @Test public void accept() { try { new NotificationConsumer(null).accept(new NotificationContent("AndroidGodEye_message", null)); CountDownLatch countDownLatch = new CountDownLatch(1); final NotificationContent[] notificationContent0 = new NotificationContent[1]; new NotificationConsumer(new NotificationListener() { @Override public void onInstalled() { } @Override public void onUninstalled() { } @Override public void onNotificationReceive(long timeMillis, NotificationContent notificationContent) { notificationContent0[0] = notificationContent; countDownLatch.countDown(); } }).accept(new NotificationContent("AndroidGodEye_message", null)); countDownLatch.await(1, TimeUnit.SECONDS); assertEquals("AndroidGodEye_message", notificationContent0[0].message); } catch (Exception e) { fail(); } }
### Question: GodEye { public Application getApplication() { return mApplication; } private GodEye(); static GodEye instance(); synchronized GodEye install(final GodEyeConfig godEyeConfig, NotificationConfig notificationConfig); GodEye install(final GodEyeConfig godEyeConfig); GodEye install(final GodEyeConfig godEyeConfig, boolean enableNotification); synchronized GodEye uninstall(); synchronized T getModule(@ModuleName String moduleName); synchronized @ModuleName Set<String> getInstalledModuleNames(); Observable<M> moduleObservable(@ModuleName String moduleName); Disposable observeModule(@ModuleName String moduleName, Consumer<M> consumer); Application getApplication(); @Deprecated void init(Application application); static final Set<String> ALL_MODULE_NAMES; }### Answer: @Test public void getApplication() { assertNotNull(GodEye.instance().getApplication()); }
### Question: LocalNotificationListenerService extends Service { public static void start(String message, boolean isStartup) { Intent intent = new Intent(GodEye.instance().getApplication(), LocalNotificationListenerService.class); intent.putExtra("message", message); intent.putExtra("isStartup", isStartup); intent.setAction(ACTION_START); ContextCompat.startForegroundService(GodEye.instance().getApplication(), intent); } static void start(String message, boolean isStartup); static void stop(); @Override void onCreate(); @Override int onStartCommand(Intent intent, int flags, int startId); @Nullable @Override IBinder onBind(Intent intent); }### Answer: @Test public void start() { LocalNotificationListenerService.start("AndroidGodEye",false); LocalNotificationListenerService.start("AndroidGodEye",true); }
### Question: LocalNotificationListenerService extends Service { public static void stop() { Intent intent = new Intent(GodEye.instance().getApplication(), LocalNotificationListenerService.class); intent.setAction(ACTION_STOP); GodEye.instance().getApplication().startService(intent); } static void start(String message, boolean isStartup); static void stop(); @Override void onCreate(); @Override int onStartCommand(Intent intent, int flags, int startId); @Nullable @Override IBinder onBind(Intent intent); }### Answer: @Test public void stop() { LocalNotificationListenerService.stop(); }
### Question: L { public static void d(Object msg) { if (sLogProxy != null) { sLogProxy.d(o2String(msg)); } } static void setProxy(LogProxy logProxy); static void d(Object msg); static void d(String format, Object... msgs); static void e(Object msg); static void w(Object msg); static void onRuntimeException(RuntimeException e); static final String DEFAULT_TAG; }### Answer: @Test public void d() { CountDownLatch countDownLatch = new CountDownLatch(4); L.setProxy(new L.LogProxy() { @Override public void d(String msg) { countDownLatch.countDown(); if (countDownLatch.getCount() == 3) { Assert.assertEquals("AndroidGodEye-String", msg); } if (countDownLatch.getCount() == 2) { Assert.assertTrue(msg.contains("AndroidGodEye-Exception")); } if (countDownLatch.getCount() == 1) { Assert.assertTrue(msg.contains(String.valueOf(LTest.this))); } if (countDownLatch.getCount() == 0) { Assert.assertEquals("null", msg); } } @Override public void w(String msg) { } @Override public void e(String msg) { Assert.fail(); } @Override public void onRuntimeException(RuntimeException e) { Assert.fail(); } }); L.d("AndroidGodEye-String"); L.d(new Exception("AndroidGodEye-Exception")); L.d(this); L.d(null); }
### Question: L { public static void e(Object msg) { if (sLogProxy != null) { sLogProxy.e(o2String(msg)); } } static void setProxy(LogProxy logProxy); static void d(Object msg); static void d(String format, Object... msgs); static void e(Object msg); static void w(Object msg); static void onRuntimeException(RuntimeException e); static final String DEFAULT_TAG; }### Answer: @Test public void e() { L.setProxy(new L.LogProxy() { @Override public void d(String msg) { Assert.fail(); } @Override public void w(String msg) { } @Override public void e(String msg) { Assert.assertTrue(msg.contains("AndroidGodEye-Exception")); } @Override public void onRuntimeException(RuntimeException e) { Assert.fail(); } }); L.e(new Exception("AndroidGodEye-Exception")); }
### Question: L { public static void w(Object msg) { if (sLogProxy != null) { sLogProxy.w(o2String(msg)); } } static void setProxy(LogProxy logProxy); static void d(Object msg); static void d(String format, Object... msgs); static void e(Object msg); static void w(Object msg); static void onRuntimeException(RuntimeException e); static final String DEFAULT_TAG; }### Answer: @Test public void w() { L.setProxy(new L.LogProxy() { @Override public void d(String msg) { Assert.fail(); } @Override public void w(String msg) { Assert.assertFalse(msg.isEmpty()); } @Override public void e(String msg) { Assert.fail(); } @Override public void onRuntimeException(RuntimeException e) { Assert.fail(); } }); L.w(new Object()); }
### Question: L { public static void onRuntimeException(RuntimeException e) { if (sLogProxy != null) { sLogProxy.onRuntimeException(e); } } static void setProxy(LogProxy logProxy); static void d(Object msg); static void d(String format, Object... msgs); static void e(Object msg); static void w(Object msg); static void onRuntimeException(RuntimeException e); static final String DEFAULT_TAG; }### Answer: @Test public void onRuntimeException() { L.setProxy(new L.LogProxy() { @Override public void d(String msg) { Assert.fail(); } @Override public void w(String msg) { } @Override public void e(String msg) { Assert.fail(); } @Override public void onRuntimeException(RuntimeException e) { Assert.assertEquals("AndroidGodEye-Exception", e.getMessage()); } }); L.onRuntimeException(new RuntimeException("AndroidGodEye-Exception")); }
### Question: ImageUtil { public static String convertToBase64(Bitmap bitmap, int maxWidth, int maxHeight) { if (bitmap == null) { return null; } long startTime = System.currentTimeMillis(); int[] targetSize = computeTargetSize(bitmap, maxWidth, maxHeight); Bitmap thumbnail = ThumbnailUtils.extractThumbnail(bitmap, targetSize[0], targetSize[1]); ByteArrayOutputStream baos = new ByteArrayOutputStream(); thumbnail.compress(Bitmap.CompressFormat.PNG, 100, baos); String result = Base64.encodeToString(baos.toByteArray(), Base64.DEFAULT); return result; } static String convertToBase64(Bitmap bitmap, int maxWidth, int maxHeight); }### Answer: @Test public void convertToBase64() { String base642 = ImageUtil.convertToBase64(null, 5, 5); Assert.assertNull(base642); Bitmap bitmap = ShadowBitmapFactory.create("AndroidGodEye-Image", null, new Point(10, 10)); String base64 = ImageUtil.convertToBase64(bitmap, 5, 5); Assert.assertNotNull(base64); }
### Question: ImageUtil { @VisibleForTesting static int[] computeTargetSize(Bitmap bitmap, int maxWidth, int maxHeight) { int width = bitmap.getWidth(); int height = bitmap.getHeight(); float targetWidth = width; float targetHeight = height; if (width > maxWidth || height > maxHeight) { float scaleWidth = (width * 1.0f / maxWidth); float scaleHeight = (height * 1.0f / maxHeight); float scale = Math.max(scaleWidth, scaleHeight); targetWidth = width / scale; targetHeight = height / scale; } return new int[]{(int) targetWidth, (int) targetHeight}; } static String convertToBase64(Bitmap bitmap, int maxWidth, int maxHeight); }### Answer: @Test public void computeTargetSizeWidth1Height0() { Bitmap bitmap = ShadowBitmapFactory.create("AndroidGodEye", null, new Point(100, 20)); int[] targetSize0 = ImageUtil.computeTargetSize(bitmap, 30, 30); Assert.assertEquals(30, targetSize0[0]); Assert.assertEquals(6, targetSize0[1]); } @Test public void computeTargetSizeWidth1Height1() { Bitmap bitmap = ShadowBitmapFactory.create("AndroidGodEye", null, new Point(100, 50)); int[] targetSize0 = ImageUtil.computeTargetSize(bitmap, 30, 30); Assert.assertEquals(30, targetSize0[0]); Assert.assertEquals(15, targetSize0[1]); } @Test public void computeTargetSizeWidth0Height1() { Bitmap bitmap = ShadowBitmapFactory.create("AndroidGodEye", null, new Point(25, 50)); int[] targetSize0 = ImageUtil.computeTargetSize(bitmap, 30, 30); Assert.assertEquals(15, targetSize0[0]); Assert.assertEquals(30, targetSize0[1]); } @Test public void computeTargetSizeWidth0Height0() { Bitmap bitmap = ShadowBitmapFactory.create("AndroidGodEye", null, new Point(20, 10)); int[] targetSize0 = ImageUtil.computeTargetSize(bitmap, 30, 30); Assert.assertEquals(20, targetSize0[0]); Assert.assertEquals(10, targetSize0[1]); }
### Question: ThreadUtil { public static boolean isMainThread() { return Looper.myLooper() == Looper.getMainLooper(); } static void setNeedDetectRunningThread(boolean sNeedDetect); static void setMainScheduler(Scheduler sMainScheduler); static void setComputationScheduler(Scheduler sComputationScheduler); static Scheduler mainScheduler(); static Scheduler computationScheduler(); static boolean isMainThread(); static void ensureMainThread(String tag); static void ensureMainThread(); static void ensureWorkThread(String tag); static void ensureWorkThread(); static @NonNull Handler createIfNotExistHandler(String tag); static @Nullable Handler obtainHandler(String tag); static void destoryHandler(String tag); static Executor sMain; }### Answer: @Test public void isMainThread() { boolean isMainThread = ThreadUtil.isMainThread(); assertTrue(isMainThread); final boolean[] isMainThreadInThread = {true}; Thread thread = new Thread(new Runnable() { @Override public void run() { isMainThreadInThread[0] = ThreadUtil.isMainThread(); } }); thread.start(); try { thread.join(); } catch (InterruptedException e) { e.printStackTrace(); } assertFalse(isMainThreadInThread[0]); }
### Question: ProcessUtils { public static String myProcessName(Context context) { if (sProcessName != null) { return sProcessName; } synchronized (sNameLock) { if (sProcessName != null) { return sProcessName; } sProcessName = obtainProcessName(context); return sProcessName; } } static String myProcessName(Context context); static int getCurrentPid(); static int getCurrentUid(); static boolean isMainProcess(Application application); }### Answer: @Test public void myProcessName() { String myProcessName = ProcessUtils.myProcessName(ApplicationProvider.getApplicationContext()); Assert.assertEquals("cn.hikyson.godeye.core", myProcessName); String myProcessName2 = ProcessUtils.myProcessName(ApplicationProvider.getApplicationContext()); Assert.assertEquals("cn.hikyson.godeye.core", myProcessName2); }
### Question: ProcessUtils { public static int getCurrentPid() { return android.os.Process.myPid(); } static String myProcessName(Context context); static int getCurrentPid(); static int getCurrentUid(); static boolean isMainProcess(Application application); }### Answer: @Test public void getCurrentPid() { int pid = ProcessUtils.getCurrentPid(); }
### Question: ProcessUtils { public static int getCurrentUid() { return android.os.Process.myUid(); } static String myProcessName(Context context); static int getCurrentPid(); static int getCurrentUid(); static boolean isMainProcess(Application application); }### Answer: @Test public void getCurrentUid() { int uid = ProcessUtils.getCurrentUid(); }
### Question: ProcessUtils { public static boolean isMainProcess(Application application) { int pid = android.os.Process.myPid(); String processName = ""; ActivityManager manager = (ActivityManager) application.getSystemService (Context.ACTIVITY_SERVICE); for (ActivityManager.RunningAppProcessInfo process : manager.getRunningAppProcesses()) { if (process.pid == pid) { processName = process.processName; } } return application.getPackageName().equals(processName); } static String myProcessName(Context context); static int getCurrentPid(); static int getCurrentUid(); static boolean isMainProcess(Application application); }### Answer: @Test public void isMainProcess() { boolean isMainProcess = ProcessUtils.isMainProcess(ApplicationProvider.getApplicationContext()); Assert.assertTrue(isMainProcess); }
### Question: StacktraceUtil { public static List<String> stackTraceToStringArray(List<StackTraceElement> stackTraceElements) { List<String> stackList = new ArrayList<>(); for (StackTraceElement traceElement : stackTraceElements) { stackList.add(String.valueOf(traceElement)); } return stackList; } static List<String> stackTraceToStringArray(List<StackTraceElement> stackTraceElements); static List<String> getStackTraceOfThread(Thread thread); static String getStringOfThrowable(Throwable throwable); }### Answer: @Test public void stackTraceToStringArray() { List<String> stackTrace = StacktraceUtil.stackTraceToStringArray(Arrays.asList(Thread.currentThread().getStackTrace())); Assert.assertTrue(String.valueOf(stackTrace).contains(StacktraceUtilTest.class.getSimpleName())); }
### Question: StacktraceUtil { public static List<String> getStackTraceOfThread(Thread thread) { StackTraceElement[] stackTraceElements = thread.getStackTrace(); return stackTraceToStringArray(Arrays.asList(stackTraceElements)); } static List<String> stackTraceToStringArray(List<StackTraceElement> stackTraceElements); static List<String> getStackTraceOfThread(Thread thread); static String getStringOfThrowable(Throwable throwable); }### Answer: @Test public void getStackTraceOfThread() { List<String> stackTrace = StacktraceUtil.getStackTraceOfThread(Thread.currentThread()); Assert.assertTrue(String.valueOf(stackTrace).contains(StacktraceUtilTest.class.getSimpleName())); }
### Question: StacktraceUtil { public static String getStringOfThrowable(Throwable throwable) { return throwable.getLocalizedMessage() + "\n" + stackTraceToString(throwable.getStackTrace()); } static List<String> stackTraceToStringArray(List<StackTraceElement> stackTraceElements); static List<String> getStackTraceOfThread(Thread thread); static String getStringOfThrowable(Throwable throwable); }### Answer: @Test public void getStringOfThrowable() { String detail = StacktraceUtil.getStringOfThrowable(new Throwable("AndroidGodEye-Exception")); Assert.assertTrue(detail.contains(StacktraceUtilTest.class.getSimpleName())); Assert.assertTrue(detail.contains("AndroidGodEye-Exception")); }
### Question: ReflectUtil { public static <T> T invokeStaticMethod(String clsName, String methodName, Class<?>[] argsTypes, Object[] args) { return invokeStaticMethod(getClass(clsName), methodName, argsTypes, args); } static T invokeStaticMethod(String clsName, String methodName, Class<?>[] argsTypes, Object[] args); @Nullable static T invokeStaticMethod(Class<?> cls, String methodName, Class<?>[] argsTypes, Object[] args); static T invokeStaticMethodUnSafe(String className, String methodName, Class<?>[] argsTypes, Object[] args); }### Answer: @Test public void invokeStaticMethod() { Object result = ReflectUtil.invokeStaticMethod(ReflectUtilTest.class, "testMethod", new Class<?>[]{String.class, int.class, boolean.class}, new Object[]{"AndroidGodEye-String", 10, false}); Assert.assertTrue((Boolean) result); Object result2 = ReflectUtil.invokeStaticMethod(ReflectUtilTest.class.getName(), "testMethod2", new Class<?>[]{String.class, int.class, boolean.class}, new Object[]{"AndroidGodEye-String", 10, false}); Assert.assertNull(result2); Object result25 = ReflectUtil.invokeStaticMethod(ReflectUtilTest.class, "testMethod", new Class<?>[]{String.class, int.class, boolean.class}, new Object[]{"AndroidGodEye-String", "10", false}); Assert.assertNull(result25); try { Object result3 = ReflectUtil.invokeStaticMethodUnSafe(ReflectUtilTest.class.getName(), "testMethod", new Class<?>[]{String.class, int.class, boolean.class}, new Object[]{"AndroidGodEye-String", 10, false}); Assert.assertTrue((Boolean) result3); } catch (Exception e) { Assert.fail(); } try { Object result4 = ReflectUtil.invokeStaticMethodUnSafe(ReflectUtilTest.class.getName(), "testMethod", new Class<?>[]{String.class, int.class}, new Object[]{"AndroidGodEye-String", 10}); Assert.fail(); } catch (Exception ignore) { } try { Object result4 = ReflectUtil.invokeStaticMethodUnSafe("FakeClass", "testMethod", new Class<?>[]{String.class, int.class}, new Object[]{"AndroidGodEye-String", 10}); Assert.fail(); } catch (Exception ignore) { } }
### Question: GodEyeConfig implements Serializable { public static GodEyeConfig noneConfig() { return noneConfigBuilder().build(); } private GodEyeConfig(); static GodEyeConfigBuilder noneConfigBuilder(); static GodEyeConfig noneConfig(); static GodEyeConfigBuilder defaultConfigBuilder(); static GodEyeConfig defaultConfig(); static GodEyeConfig fromInputStream(InputStream is); static GodEyeConfig fromAssets(String assetsPath); CpuConfig getCpuConfig(); void setCpuConfig(CpuConfig cpuConfig); BatteryConfig getBatteryConfig(); void setBatteryConfig(BatteryConfig batteryConfig); FpsConfig getFpsConfig(); void setFpsConfig(FpsConfig fpsConfig); LeakConfig getLeakConfig(); void setLeakConfig(LeakConfig leakConfig); HeapConfig getHeapConfig(); void setHeapConfig(HeapConfig heapConfig); PssConfig getPssConfig(); void setPssConfig(PssConfig pssConfig); RamConfig getRamConfig(); void setRamConfig(RamConfig ramConfig); NetworkConfig getNetworkConfig(); void setNetworkConfig(NetworkConfig networkConfig); SmConfig getSmConfig(); void setSmConfig(SmConfig smConfig); StartupConfig getStartupConfig(); void setStartupConfig(StartupConfig startupConfig); TrafficConfig getTrafficConfig(); void setTrafficConfig(TrafficConfig trafficConfig); CrashConfig getCrashConfig(); void setCrashConfig(CrashConfig crashConfig); ThreadConfig getThreadConfig(); void setThreadConfig(ThreadConfig threadConfig); PageloadConfig getPageloadConfig(); void setPageloadConfig(PageloadConfig pageloadConfig); MethodCanaryConfig getMethodCanaryConfig(); void setMethodCanaryConfig(MethodCanaryConfig methodCanaryConfig); AppSizeConfig getAppSizeConfig(); void setAppSizeConfig(AppSizeConfig appSizeConfig); ViewCanaryConfig getViewCanaryConfig(); void setViewCanaryConfig(ViewCanaryConfig viewCanaryConfig); ImageCanaryConfig getImageCanaryConfig(); void setImageCanaryConfig(ImageCanaryConfig imageCanaryConfig); @Override String toString(); }### Answer: @Test public void noneConfig() { GodEyeConfig config0 = GodEyeConfig.noneConfig(); assertNull(config0.getAppSizeConfig()); assertNull(config0.getBatteryConfig()); assertNull(config0.getCpuConfig()); assertNull(config0.getCrashConfig()); assertNull(config0.getFpsConfig()); assertNull(config0.getHeapConfig()); assertNull(config0.getImageCanaryConfig()); assertNull(config0.getLeakConfig()); assertNull(config0.getMethodCanaryConfig()); assertNull(config0.getNetworkConfig()); assertNull(config0.getPageloadConfig()); assertNull(config0.getPssConfig()); assertNull(config0.getRamConfig()); assertNull(config0.getSmConfig()); assertNull(config0.getStartupConfig()); assertNull(config0.getThreadConfig()); assertNull(config0.getTrafficConfig()); assertNull(config0.getViewCanaryConfig()); GodEyeConfig config = GodEyeConfig.noneConfigBuilder().build(); assertNull(config.getAppSizeConfig()); assertNull(config.getBatteryConfig()); assertNull(config.getCpuConfig()); assertNull(config.getCrashConfig()); assertNull(config.getFpsConfig()); assertNull(config.getHeapConfig()); assertNull(config.getImageCanaryConfig()); assertNull(config.getLeakConfig()); assertNull(config.getMethodCanaryConfig()); assertNull(config.getNetworkConfig()); assertNull(config.getPageloadConfig()); assertNull(config.getPssConfig()); assertNull(config.getRamConfig()); assertNull(config.getSmConfig()); assertNull(config.getStartupConfig()); assertNull(config.getThreadConfig()); assertNull(config.getTrafficConfig()); assertNull(config.getViewCanaryConfig()); }
### Question: GodEyeConfig implements Serializable { public static GodEyeConfig fromAssets(String assetsPath) { InputStream is = null; try { is = GodEye.instance().getApplication().getAssets().open(assetsPath); return fromInputStream(is); } catch (Exception e) { L.e(e); return GodEyeConfig.noneConfig(); } finally { IoUtil.closeSilently(is); } } private GodEyeConfig(); static GodEyeConfigBuilder noneConfigBuilder(); static GodEyeConfig noneConfig(); static GodEyeConfigBuilder defaultConfigBuilder(); static GodEyeConfig defaultConfig(); static GodEyeConfig fromInputStream(InputStream is); static GodEyeConfig fromAssets(String assetsPath); CpuConfig getCpuConfig(); void setCpuConfig(CpuConfig cpuConfig); BatteryConfig getBatteryConfig(); void setBatteryConfig(BatteryConfig batteryConfig); FpsConfig getFpsConfig(); void setFpsConfig(FpsConfig fpsConfig); LeakConfig getLeakConfig(); void setLeakConfig(LeakConfig leakConfig); HeapConfig getHeapConfig(); void setHeapConfig(HeapConfig heapConfig); PssConfig getPssConfig(); void setPssConfig(PssConfig pssConfig); RamConfig getRamConfig(); void setRamConfig(RamConfig ramConfig); NetworkConfig getNetworkConfig(); void setNetworkConfig(NetworkConfig networkConfig); SmConfig getSmConfig(); void setSmConfig(SmConfig smConfig); StartupConfig getStartupConfig(); void setStartupConfig(StartupConfig startupConfig); TrafficConfig getTrafficConfig(); void setTrafficConfig(TrafficConfig trafficConfig); CrashConfig getCrashConfig(); void setCrashConfig(CrashConfig crashConfig); ThreadConfig getThreadConfig(); void setThreadConfig(ThreadConfig threadConfig); PageloadConfig getPageloadConfig(); void setPageloadConfig(PageloadConfig pageloadConfig); MethodCanaryConfig getMethodCanaryConfig(); void setMethodCanaryConfig(MethodCanaryConfig methodCanaryConfig); AppSizeConfig getAppSizeConfig(); void setAppSizeConfig(AppSizeConfig appSizeConfig); ViewCanaryConfig getViewCanaryConfig(); void setViewCanaryConfig(ViewCanaryConfig viewCanaryConfig); ImageCanaryConfig getImageCanaryConfig(); void setImageCanaryConfig(ImageCanaryConfig imageCanaryConfig); @Override String toString(); }### Answer: @Test public void fromAssets() { Application originApplication = ApplicationProvider.getApplicationContext(); Application application = Mockito.spy(originApplication); Application godeyeApplication = GodEye.instance().getApplication(); GodEye.instance().internalInit(application); AssetManager assetManager = Mockito.spy(application.getAssets()); Mockito.doReturn(assetManager).when(application).getAssets(); try { Mockito.doAnswer(new Answer() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { Object[] args = invocation.getArguments(); Object object = this.getClass().getClassLoader().getResourceAsStream(String.valueOf(args[0])); return object; } }).when(assetManager).open(Mockito.anyString()); } catch (IOException e) { fail(); } GodEyeConfig config = GodEyeConfig.fromAssets("install.config"); assertConfig(config); GodEye.instance().internalInit(godeyeApplication); }
### Question: AndroidDebug { public static boolean isDebugging() { return Debug.isDebuggerConnected(); } static boolean isDebugging(); }### Answer: @Test public void isDebugging() { long startTime = SystemClock.elapsedRealtime(); for (int i = 0; i < 1000; i++) { AndroidDebug.isDebugging(); } Log4Test.d(String.format("AndroidDebugTest isDebugging cost %sms for 1000 times.", SystemClock.elapsedRealtime() - startTime)); }
### Question: Notifier { public static int notice(Context context, Config config) { return notice(context, createNoticeId(), create(context, config)); } static Notification create(Context context, Config config); static int createNoticeId(); static int notice(Context context, Config config); static int notice(Context context, int id, Notification notification); static void cancelNotice(Context context, int id); }### Answer: @Config(sdk = Build.VERSION_CODES.O) @Test @Ignore("local") public void noticeHigherThanO() { notice(); } @Config(sdk = Build.VERSION_CODES.LOLLIPOP) @Test public void noticeLowerThanO() { notice(); }
### Question: GodEyeHelper { public static void onFragmentPageVisibilityChange(Object fragmentPage, boolean visible) throws UninstallException { if (fragmentPage instanceof Fragment) { if (visible) { GodEye.instance().<Pageload>getModule(GodEye.ModuleName.PAGELOAD).onFragmentV4Show((Fragment) fragmentPage); } else { GodEye.instance().<Pageload>getModule(GodEye.ModuleName.PAGELOAD).onFragmentV4Hide((Fragment) fragmentPage); } } else if (fragmentPage instanceof android.app.Fragment) { if (visible) { GodEye.instance().<Pageload>getModule(GodEye.ModuleName.PAGELOAD).onFragmentShow((android.app.Fragment) fragmentPage); } else { GodEye.instance().<Pageload>getModule(GodEye.ModuleName.PAGELOAD).onFragmentHide((android.app.Fragment) fragmentPage); } } else { throw new UnexpectException("GodEyeHelper.onFragmentPageVisibilityChange's fragmentPage must be instance of Fragment."); } L.d("GodEyeHelper onFragmentPageVisibilityChange: " + fragmentPage.getClass().getSimpleName() + ", visible:" + visible); } static void onPageLoaded(Object page); static void onFragmentPageVisibilityChange(Object fragmentPage, boolean visible); static void onAppStartEnd(StartupInfo startupInfo); static void onNetworkEnd(NetworkInfo networkInfo); @Deprecated static void inspectView(); static void startMethodCanaryRecording(String tag); static void stopMethodCanaryRecording(String tag); static boolean isMethodCanaryRecording(String tag); static void setMonitorAppInfoConext(AppInfoConext appInfoConext); static void startMonitor(int port); static void startMonitor(); static void shutdownMonitor(); }### Answer: @Test public void onFragmentPageVisibilityChangeWhenIllegal() { try { GodEye.instance().uninstall(); GodEyeHelper.onFragmentPageVisibilityChange(null, true); fail(); } catch (RuntimeException ignore) { } catch (UninstallException e) { fail(); } }
### Question: WebConfigurer implements ServletContextInitializer, EmbeddedServletContainerCustomizer { @Override public void customize(ConfigurableEmbeddedServletContainer container) { MimeMappings mappings = new MimeMappings(MimeMappings.DEFAULT); mappings.add("html", "text/html;charset=utf-8"); mappings.add("json", "text/html;charset=utf-8"); container.setMimeMappings(mappings); setLocationForStaticAssets(container); if (jHipsterProperties.getHttp().getVersion().equals(JHipsterProperties.Http.Version.V_2_0) && container instanceof UndertowEmbeddedServletContainerFactory) { ((UndertowEmbeddedServletContainerFactory) container) .addBuilderCustomizers(builder -> builder.setServerOption(UndertowOptions.ENABLE_HTTP2, true)); } } WebConfigurer(Environment env, JHipsterProperties jHipsterProperties); @Override void onStartup(ServletContext servletContext); @Override void customize(ConfigurableEmbeddedServletContainer container); @Bean CorsFilter corsFilter(); @Autowired(required = false) void setMetricRegistry(MetricRegistry metricRegistry); }### Answer: @Test public void testCustomizeServletContainer() { env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION); UndertowEmbeddedServletContainerFactory container = new UndertowEmbeddedServletContainerFactory(); webConfigurer.customize(container); assertThat(container.getMimeMappings().get("abs")).isEqualTo("audio/x-mpeg"); assertThat(container.getMimeMappings().get("html")).isEqualTo("text/html;charset=utf-8"); assertThat(container.getMimeMappings().get("json")).isEqualTo("text/html;charset=utf-8"); if (container.getDocumentRoot() != null) { assertThat(container.getDocumentRoot().getPath()).isEqualTo(FilenameUtils.separatorsToSystem("target/www")); } Builder builder = Undertow.builder(); container.getBuilderCustomizers().forEach(c -> c.customize(builder)); OptionMap.Builder serverOptions = (OptionMap.Builder) ReflectionTestUtils.getField(builder, "serverOptions"); assertThat(serverOptions.getMap().get(UndertowOptions.ENABLE_HTTP2)).isNull(); } @Test public void testUndertowHttp2Enabled() { props.getHttp().setVersion(JHipsterProperties.Http.Version.V_2_0); UndertowEmbeddedServletContainerFactory container = new UndertowEmbeddedServletContainerFactory(); webConfigurer.customize(container); Builder builder = Undertow.builder(); container.getBuilderCustomizers().forEach(c -> c.customize(builder)); OptionMap.Builder serverOptions = (OptionMap.Builder) ReflectionTestUtils.getField(builder, "serverOptions"); assertThat(serverOptions.getMap().get(UndertowOptions.ENABLE_HTTP2)).isTrue(); } @Test public void testCustomizeServletContainer() { env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION); UndertowEmbeddedServletContainerFactory container = new UndertowEmbeddedServletContainerFactory(); webConfigurer.customize(container); assertThat(container.getMimeMappings().get("abs")).isEqualTo("audio/x-mpeg"); assertThat(container.getMimeMappings().get("html")).isEqualTo("text/html;charset=utf-8"); assertThat(container.getMimeMappings().get("json")).isEqualTo("text/html;charset=utf-8"); if (container.getDocumentRoot() != null) { assertThat(container.getDocumentRoot().getPath()).isEqualTo("target/www"); } Builder builder = Undertow.builder(); container.getBuilderCustomizers().forEach(c -> c.customize(builder)); OptionMap.Builder serverOptions = (OptionMap.Builder) ReflectionTestUtils.getField(builder, "serverOptions"); assertThat(serverOptions.getMap().get(UndertowOptions.ENABLE_HTTP2)).isNull(); }
### Question: DefaultAudioSink implements AudioSink { @Override public boolean supportsOutput(int channelCount, @C.Encoding int encoding) { if (Util.isEncodingLinearPcm(encoding)) { return encoding != C.ENCODING_PCM_FLOAT || Util.SDK_INT >= 21; } else { return audioCapabilities != null && audioCapabilities.supportsEncoding(encoding) && (channelCount == Format.NO_VALUE || channelCount <= audioCapabilities.getMaxChannelCount()); } } DefaultAudioSink( @Nullable AudioCapabilities audioCapabilities, AudioProcessor[] audioProcessors); DefaultAudioSink( @Nullable AudioCapabilities audioCapabilities, AudioProcessor[] audioProcessors, boolean enableConvertHighResIntPcmToFloat); DefaultAudioSink( @Nullable AudioCapabilities audioCapabilities, AudioProcessorChain audioProcessorChain, boolean enableConvertHighResIntPcmToFloat); @Override void setListener(Listener listener); @Override boolean supportsOutput(int channelCount, @C.Encoding int encoding); @Override long getCurrentPositionUs(boolean sourceEnded); @Override void configure( @C.Encoding int inputEncoding, int inputChannelCount, int inputSampleRate, int specifiedBufferSize, @Nullable int[] outputChannels, int trimStartFrames, int trimEndFrames); @Override void play(); @Override void handleDiscontinuity(); @Override @SuppressWarnings("ReferenceEquality") boolean handleBuffer(ByteBuffer buffer, long presentationTimeUs); @Override void playToEndOfStream(); @Override boolean isEnded(); @Override boolean hasPendingData(); @Override void setPlaybackParameters(PlaybackParameters playbackParameters); @Override PlaybackParameters getPlaybackParameters(); @Override void setAudioAttributes(AudioAttributes audioAttributes); @Override void setAudioSessionId(int audioSessionId); @Override void setAuxEffectInfo(AuxEffectInfo auxEffectInfo); @Override void enableTunnelingV21(int tunnelingAudioSessionId); @Override void disableTunneling(); @Override void setVolume(float volume); @Override void pause(); @Override void flush(); @Override void reset(); static boolean enablePreV21AudioSessionWorkaround; static boolean failOnSpuriousAudioTimestamp; }### Answer: @Config(minSdk = OLDEST_SDK, maxSdk = 20) @Test public void doesNotSupportFloatOutputBeforeApi21() { assertThat(defaultAudioSink.supportsOutput(CHANNEL_COUNT_STEREO, C.ENCODING_PCM_FLOAT)) .isFalse(); } @Config(minSdk = 21, maxSdk = TARGET_SDK) @Test public void supportsFloatOutputFromApi21() { assertThat(defaultAudioSink.supportsOutput(CHANNEL_COUNT_STEREO, C.ENCODING_PCM_FLOAT)) .isTrue(); }
### Question: Hook { boolean isValid() { try { new URL(this.uri); } catch (MalformedURLException ex) { return false; } return this.command != null; } Hook(String uri, FtpEventName command); Hook(); long getId(); String getUri(); FtpEventName getCommand(); void setCommand(FtpEventName command); static final String findByCommand; }### Answer: @Test public void validUri() { Hook cut = new Hook("http: assertTrue(cut.isValid()); } @Test public void invalidUri() { Hook cut = new Hook("asdf", FtpEventName.EVERYTHING); assertFalse(cut.isValid()); }
### Question: RegexReplacement { public String replace(String in) { boolean matches = regex.matcher(in).find(); if(matches) { return in.replaceAll(original, replacement); } else { return in; } } RegexReplacement(String regex, String original, String replacement); boolean match(String in); String replace(String in); }### Answer: @Test public void testReplacement() { RegexReplacement rr = new RegexReplacement("<version.light[a-z-]+4j>\\d*\\.\\d*\\.\\d*</version.light[a-z-]+4j>", "1.5.5", "1.5.6"); String result = rr.replace("<version.light-4j>1.5.5</version.light-4j>"); System.out.println(result); Assert.assertEquals("<version.light-4j>1.5.6</version.light-4j>", result); result = rr.replace("abc"); System.out.println(result); Assert.assertEquals("abc", result); result = rr.replace("abc<version.light-rest-4j>1.5.5</version.light-rest-4j>def"); System.out.println(result); Assert.assertEquals("abc<version.light-rest-4j>1.5.6</version.light-rest-4j>def", result); }
### Question: CommandExecutor implements Executor { @Override public int execute(final List<String> commandInformation, File workingDir) throws IOException, InterruptedException { int exitValue = -99; try { ProcessBuilder pb = new ProcessBuilder(commandInformation); pb.directory(workingDir); Process process = pb.start(); OutputStream stdOutput = process.getOutputStream(); InputStream inputStream = process.getInputStream(); InputStream errorStream = process.getErrorStream(); inputStreamHandler = new ThreadedStreamHandler(inputStream, stdOutput, adminPassword); errorStreamHandler = new ThreadedStreamHandler(errorStream); inputStreamHandler.start(); errorStreamHandler.start(); exitValue = process.waitFor(); inputStreamHandler.interrupt(); errorStreamHandler.interrupt(); inputStreamHandler.join(); errorStreamHandler.join(); } catch (IOException e) { throw e; } catch (InterruptedException e) { throw e; } finally { return exitValue; } } CommandExecutor(); @Override int execute(final List<String> commandInformation, File workingDir); @Override int startServer(final List<String> commandInformation, File workingDir); @Override int startServer(final List<String> commandInformation, final Map<String,String> envVars, File workingDir); @Override StringBuilder getStdout(); @Override StringBuilder getStderr(); @Override void stopServers(); static List<Process> processes; }### Answer: @Test public void testSimpleCommand() throws IOException, InterruptedException { List<String> commands = new ArrayList<String>(); commands.add("/bin/sh"); commands.add("-c"); commands.add("ls -l /var/tmp | wc -l"); Executor executor = SingletonServiceFactory.getBean(Executor.class); int result = executor.execute(commands, new File(System.getProperty("user.home"))); } @Test public void testLsCommand() throws IOException, InterruptedException { List<String> commands = new ArrayList<>(); commands.add("ls"); Executor executor = SingletonServiceFactory.getBean(Executor.class); int result = executor.execute(commands, new File(System.getProperty("user.home"))); } @Test public void testGitClone() throws IOException, InterruptedException { List<String> commands = new ArrayList<>(); commands.add("bash"); commands.add("-c"); commands.add("rm -rf light-4j"); Executor executor = SingletonServiceFactory.getBean(Executor.class); int result = executor.execute(commands, new File(System.getProperty("java.io.tmpdir"))); commands = new ArrayList<>(); commands.add("bash"); commands.add("-c"); commands.add("git clone https: result = executor.execute(commands, new File(System.getProperty("java.io.tmpdir"))); commands = new ArrayList<>(); commands.add("bash"); commands.add("-c"); commands.add("git checkout master"); Path path = Paths.get(System.getProperty("java.io.tmpdir"),"light-4j"); result = executor.execute(commands, path.toFile()); }
### Question: ExtendedProperties implements Map<String, String>, Serializable, Cloneable { @Override public void putAll(final Map<? extends String, ? extends String> map) { for (Entry<? extends String, ? extends String> entry : map.entrySet()) { put(entry.getKey(), entry.getValue()); } } ExtendedProperties(); ExtendedProperties(final Map<String, String> defaults); static ExtendedProperties fromProperties(final Properties props); @Override void clear(); @Override String get(final Object key); String get(final Object key, final String defaultValue); String get(final Object key, final boolean process); boolean getBoolean(final String key); boolean getBoolean(final String key, final boolean defaultValue); long getLong(final String key); long getLong(final String key, final long defaultValue); int getInteger(final String key); int getInteger(final String key, final int defaultValue); @Override String put(final String key, final String value); @Override boolean containsKey(final Object key); @Override boolean containsValue(final Object value); @Override Set<Entry<String, String>> entrySet(); @Override boolean isEmpty(); @Override void putAll(final Map<? extends String, ? extends String> map); @Override String remove(final Object key); @Override Collection<String> values(); @Override Set<String> keySet(); @Override int size(); String processPropertyValue(final String input); @Override boolean equals(final Object obj); @Override int hashCode(); Properties toProperties(); @Override String toString(); void load(final InputStream is); void load(final InputStream is, final String encoding); void load(final Reader reader); void store(final OutputStream os, final String comments, final boolean sorted, final boolean process); void store(final OutputStream os, final String encoding, final String comments, final boolean sorted, final boolean process); void store(final Writer writer, final String comments, final boolean sorted, final boolean process); @Override ExtendedProperties clone(); }### Answer: @Test public void testPutAll() { ExtendedProperties newProps = new ExtendedProperties(); newProps.putAll(props); assertProps(newProps); }
### Question: CheckHtml4String extends WebDriverStep { @Override public void execute() { log.info("String '{}' must {}exist in the page source. Search is {}case-sensitive.", string, mustExist ? "" : "not ", caseSensitive ? "" : "not "); String pageSource = getWebDriver().getPageSource(); boolean outcome = caseSensitive ? pageSource.contains(string) : containsIgnoreCase(pageSource, string); if (mustExist != outcome) { if (mustExist) { throw new ValidationException("Could not find string '" + string + "' (case-sensitive=" + caseSensitive + ")"); } throw new ValidationException("String '" + string + "' must not occur"); } } CheckHtml4String(final String string); CheckHtml4String(final String string, final boolean caseSensitive); CheckHtml4String(final String string, final boolean caseSensitive, final boolean mustExist); @Override void execute(); }### Answer: @Test public void stringMustExistCaseSensitively() { CheckHtml4String checkHtml4String = new CheckHtml4String("Case-Sensitive"); checkHtml4String.setWebDriver(webDriver); checkHtml4String.execute(); } @Test public void stringMustExistNotCaseSensitively() { CheckHtml4String checkHtml4String = new CheckHtml4String("case-sensitive", false); checkHtml4String.setWebDriver(webDriver); checkHtml4String.execute(); } @Test public void stringMustNotExistCaseSensitively() { CheckHtml4String checkHtml4String = new CheckHtml4String("foo", true, false); checkHtml4String.setWebDriver(webDriver); checkHtml4String.execute(); } @Test public void stringMustNotExistNotCaseSensitively() { CheckHtml4String checkHtml4String = new CheckHtml4String("foo", false, false); checkHtml4String.setWebDriver(webDriver); checkHtml4String.execute(); }
### Question: ExcelDataSource extends BaseDataSource { @Override public boolean hasMoreData(final String dataSetKey) { for (ExcelFile excelFile : getExcelFiles()) { Map<String, List<Map<String, String>>> data = excelFile.getData(); List<Map<String, String>> dataList = data.get(dataSetKey); if (dataList != null) { MutableInt counter = dataSetIndices.get(dataSetKey); int size = dataList.size(); return counter == null && size > 0 || size > counter.getValue(); } } return false; } @Inject ExcelDataSource(final Configuration configuration, final DataFormatter dataFormatter); @Override boolean hasMoreData(final String dataSetKey); @Override void doReset(); }### Answer: @Test public void testHasMoreData() { ExcelDataSource dataSource = createDataSource("src/test/resources/rowbased.xlsx", DataOrientation.rowbased); String dataSetKey = "sheet_0"; for (int i = 0; i < 3; ++i) { if (dataSource.hasMoreData(dataSetKey)) { dataSource.getNextDataSet(dataSetKey); } } assertThat(dataSource.hasMoreData(dataSetKey)).describedAs("no more data should be available").isFalse(); }
### Question: CsvDataSource extends BaseDataSource { @Override public boolean hasMoreData(final String dataSetKey) { if (getCsvFiles().containsKey(dataSetKey)) { CsvFile csvFile = getCsvFiles().get(dataSetKey); if (csvFile.lines == null) { try { csvFile.load(); } catch (IOException e) { throw new IllegalArgumentException("Could not load CSV file " + csvFile.fileName, e); } } return csvFile.hasNextLine(); } return false; } @Inject CsvDataSource(final Configuration configuration); @Override boolean hasMoreData(final String dataSetKey); @Override void doReset(); }### Answer: @Test public void testHasMoreData() { int i = 0; while (ds.hasMoreData("bar")) { ds.getNextDataSet("bar"); ++i; } Assert.assertEquals(i, 2); i = 0; while (ds.hasMoreData("foo")) { ds.getNextDataSet("foo"); ++i; } Assert.assertEquals(i, 2); }
### Question: ContainerDataSource implements DataSource { @Override public DataSet getNextDataSet(final String key) { List<? extends DataSource> dataSources = dataSourcesProvider.get(); for (DataSource ds : dataSources) { DataSet data = ds.getNextDataSet(key); if (data != null) { return data; } } return null; } @Inject ContainerDataSource(final Provider<List<? extends DataSource>> dataSourcesProvider); @Override DataSet getNextDataSet(final String key); @Override DataSet getCurrentDataSet(final String key); @Override Map<String, DataSet> getCurrentDataSets(); @Override boolean hasMoreData(final String dataSetKey); @Override void resetFixedValue(final String dataSetKey, final String entryKey); @Override void resetFixedValues(final String dataSetKey); @Override void resetFixedValues(); @Override void setFixedValue(final String dataSetKey, final String entryKey, final String value); @Override String getName(); @Override void copyDataSetKey(final String key, final String newKey); @Override void removeDataSet(final String key); @Override String toString(); @Override void reset(); }### Answer: @Test public void testDataSetsAvailable() { DataSet data1 = ds.getNextDataSet("test1"); Assert.assertNotNull(data1); DataSet data2 = ds.getNextDataSet("test2"); Assert.assertNotNull(data2); } @Test public void testDataSetNotAvailable() { DataSet data = ds.getNextDataSet("test3"); Assert.assertNull(data); }
### Question: ExtendedProperties implements Map<String, String>, Serializable, Cloneable { public Properties toProperties() { Properties props = new Properties(); for (String key : keySet()) { props.put(key, get(key)); } return props; } ExtendedProperties(); ExtendedProperties(final Map<String, String> defaults); static ExtendedProperties fromProperties(final Properties props); @Override void clear(); @Override String get(final Object key); String get(final Object key, final String defaultValue); String get(final Object key, final boolean process); boolean getBoolean(final String key); boolean getBoolean(final String key, final boolean defaultValue); long getLong(final String key); long getLong(final String key, final long defaultValue); int getInteger(final String key); int getInteger(final String key, final int defaultValue); @Override String put(final String key, final String value); @Override boolean containsKey(final Object key); @Override boolean containsValue(final Object value); @Override Set<Entry<String, String>> entrySet(); @Override boolean isEmpty(); @Override void putAll(final Map<? extends String, ? extends String> map); @Override String remove(final Object key); @Override Collection<String> values(); @Override Set<String> keySet(); @Override int size(); String processPropertyValue(final String input); @Override boolean equals(final Object obj); @Override int hashCode(); Properties toProperties(); @Override String toString(); void load(final InputStream is); void load(final InputStream is, final String encoding); void load(final Reader reader); void store(final OutputStream os, final String comments, final boolean sorted, final boolean process); void store(final OutputStream os, final String encoding, final String comments, final boolean sorted, final boolean process); void store(final Writer writer, final String comments, final boolean sorted, final boolean process); @Override ExtendedProperties clone(); }### Answer: @Test public void testToProperties() { Properties legacyProps = props.toProperties(); Assert.assertEquals(legacyProps.size(), 7); Assert.assertEquals(legacyProps.getProperty("prop1"), "öäü~@€^°é"); Assert.assertEquals(legacyProps.getProperty("prop2"), "testtest"); Assert.assertEquals(legacyProps.getProperty("prop3="), "test\\"); Assert.assertEquals(legacyProps.getProperty("prop4test"), ""); Assert.assertEquals(legacyProps.getProperty("def=Prop1:"), "foo"); Assert.assertEquals(legacyProps.getProperty("defProp2 "), "bar"); Assert.assertEquals(legacyProps.getProperty("moreProp"), "more\\Prop"); }
### Question: ArchiveDataSource extends BaseDataSource { @Override public boolean hasMoreData(final String dataSetKey) { return true; } @Inject ArchiveDataSource(final Configuration configuration); @Override boolean hasMoreData(final String dataSetKey); @Override void doReset(); }### Answer: @Test(dataProvider = "dataSources") public void testHasMoreData(final DataSource ds) { Assert.assertTrue(ds.hasMoreData("countryId")); Assert.assertTrue(ds.hasMoreData("languageId")); Assert.assertTrue(ds.hasMoreData("searchTerm")); }
### Question: LoremIpsumGenerator { public String generateLoremIpsum(final int length) { if (loremLength < length) { int multiplier = length / loremLength; int remainder = length % loremLength; StrBuilder sb = new StrBuilder(multiplier * length + remainder); for (int i = 0; i < multiplier; ++i) { sb.append(loremIpsum); } sb.append(loremIpsum.substring(0, remainder)); return sb.toString(); } return loremIpsum.substring(0, length); } @Inject LoremIpsumGenerator(@LoremIpsum final String loremIpsum); String generateLoremIpsum(final int length); }### Answer: @Test public void testMinimum() { String result = generator.generateLoremIpsum(1); assertEquals(result, "L"); } @Test public void testMaximum() { String result = generator.generateLoremIpsum(loremIpsum.length()); assertEquals(result, loremIpsum); } @Test public void testMultiple() { String result = generator.generateLoremIpsum(10000); assertEquals(result.length(), 10000); }
### Question: LoremIpsumField extends Field { @Override public String getString(final FieldCase c) { int size = c.getSize(); if (size == FieldCase.JUST_ABOVE_MAX) { size++; } else if (size == FieldCase.JUST_BELOW_MIN) { size--; } if (size <= 0) { return ""; } int loremLength = loremIpsum.length(); if (loremLength < size) { int multiplier = size / loremLength; int remainder = size % loremLength; StrBuilder sb = new StrBuilder(multiplier * size + remainder); for (int i = 0; i < multiplier; ++i) { sb.append(loremIpsum); } sb.append(loremIpsum.substring(0, remainder)); return sb.toString(); } return loremIpsum.substring(0, size); } LoremIpsumField(final MathRandom random, final Element element, final String characterSetId); @Override int getMaxLength(); @Override Range getRange(); @Override void setRange(final Range range); @Override String getString(final FieldCase c); }### Answer: @Test public void testMinimum() { String value = field.getString(new FieldCase(1)); assertEquals(value, "L"); } @Test public void testMaximum() { String value = field.getString(new FieldCase(100)); assertEquals(value, loremIpsum.substring(0, 100)); } @Test public void testVeryLongOne() { String value = field.getString(new FieldCase(10000)); assertEquals(value.length(), 10000); }
### Question: DataSetAdapter extends ForwardingMap<String, String> { @Override public String get(final Object key) { String[] pair = getKeysPair(key); if (pair.length == 1) { return null; } String dsKey = pair[0]; DataSet currentDataSet = dataSourceProvider.get().getCurrentDataSet(dsKey); if (currentDataSet == null) { log.warn("No data set available: '" + dsKey + "'. Forgot to call 'generate?'"); return null; } String value = pair[1]; String[] split = value.split(JFunkConstants.INDEXED_KEY_SEPARATOR); return split.length > 1 ? currentDataSet.getValue(split[0], Integer.parseInt(split[1])) : currentDataSet.getValue(split[0]); } @Inject DataSetAdapter(final Provider<DataSource> dataSourceProvider); @Override String get(final Object key); }### Answer: @Test public void testExistingValues() { dataSource.getNextDataSet("test"); String testValue1 = adapter.get("test testKey1"); Assert.assertEquals(testValue1, "testValue1"); String testValue2 = adapter.get("test testKey2"); Assert.assertEquals(testValue2, "testValue2"); } @Test public void testNulls() { dataSource.getNextDataSet("test"); String testValue1 = adapter.get("keyWithoutValue"); Assert.assertNull(testValue1); String testValue2 = adapter.get("nonExistingDsKey foo"); Assert.assertNull(testValue2); }
### Question: ScreenCapturer { public static void captureScreen(final File file) { Rectangle rectangle = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()); captureScreenRect(file, rectangle); } @Inject ScreenCapturer(@ModuleArchiveDir final Provider<File> moduleArchiveDirProvider, final Set<Class<? extends AbstractBaseEvent>> screenCaptureEvents, final Provider<MutableInt> counterProvider, @CaptureScreenOnError final boolean captureScreenOnError); static void captureScreen(final File file); static void captureScreenRect(final File file, final Rectangle rectangle); @Subscribe @AllowConcurrentEvents void handleEvent(final AbstractBaseEvent event); void captureAndArchiveScreen(final String screenshotName); }### Answer: @Test(groups = "excludeFromCI") public void testCaptureScreen() throws IOException { testFileOrDir = File.createTempFile("jFunkScreenCapture", ".png"); ScreenCapturer.captureScreen(testFileOrDir); assertThat(testFileOrDir).exists(); }
### Question: ExtendedProperties implements Map<String, String>, Serializable, Cloneable { @Override public ExtendedProperties clone() { try { ExtendedProperties clone = (ExtendedProperties) super.clone(); clone.keySet = null; clone.entrySet = null; clone.values = null; clone.propsMap = new ConcurrentHashMap<String, String>(propsMap); if (defaults != null) { if (defaults instanceof ExtendedProperties) { clone.defaults = ((ExtendedProperties) defaults).clone(); } else { clone.defaults = Maps.newHashMap(defaults); } } return clone; } catch (CloneNotSupportedException ex) { throw new IllegalStateException(ex); } } ExtendedProperties(); ExtendedProperties(final Map<String, String> defaults); static ExtendedProperties fromProperties(final Properties props); @Override void clear(); @Override String get(final Object key); String get(final Object key, final String defaultValue); String get(final Object key, final boolean process); boolean getBoolean(final String key); boolean getBoolean(final String key, final boolean defaultValue); long getLong(final String key); long getLong(final String key, final long defaultValue); int getInteger(final String key); int getInteger(final String key, final int defaultValue); @Override String put(final String key, final String value); @Override boolean containsKey(final Object key); @Override boolean containsValue(final Object value); @Override Set<Entry<String, String>> entrySet(); @Override boolean isEmpty(); @Override void putAll(final Map<? extends String, ? extends String> map); @Override String remove(final Object key); @Override Collection<String> values(); @Override Set<String> keySet(); @Override int size(); String processPropertyValue(final String input); @Override boolean equals(final Object obj); @Override int hashCode(); Properties toProperties(); @Override String toString(); void load(final InputStream is); void load(final InputStream is, final String encoding); void load(final Reader reader); void store(final OutputStream os, final String comments, final boolean sorted, final boolean process); void store(final OutputStream os, final String encoding, final String comments, final boolean sorted, final boolean process); void store(final Writer writer, final String comments, final boolean sorted, final boolean process); @Override ExtendedProperties clone(); }### Answer: @Test public void testClone() { ExtendedProperties clone = props.clone(); assertProps(clone); }
### Question: ScreenCapturer { @Subscribe @AllowConcurrentEvents public void handleEvent(final AbstractBaseEvent event) { Class<? extends AbstractBaseEvent> clazz = event.getClass(); boolean errorCapture = captureScreenOnError(event); boolean eventConfigured = screenCaptureEvents.contains(clazz); if (eventConfigured || errorCapture) { String screenshotName = clazz.getSimpleName(); if (errorCapture) { screenshotName += "_error"; } captureAndArchiveScreen(screenshotName); } } @Inject ScreenCapturer(@ModuleArchiveDir final Provider<File> moduleArchiveDirProvider, final Set<Class<? extends AbstractBaseEvent>> screenCaptureEvents, final Provider<MutableInt> counterProvider, @CaptureScreenOnError final boolean captureScreenOnError); static void captureScreen(final File file); static void captureScreenRect(final File file, final Rectangle rectangle); @Subscribe @AllowConcurrentEvents void handleEvent(final AbstractBaseEvent event); void captureAndArchiveScreen(final String screenshotName); }### Answer: @Test(dataProvider = "exception", groups = "excludeFromCI") public void testHandleEvent(final Exception ex) { testFileOrDir = new File(System.getProperty("java.io.tmpdir"), UUID.randomUUID().toString()); MutableInt counter = new MutableInt(); Set<Class<? extends AbstractBaseEvent>> eventClasses = ImmutableSet.<Class<? extends AbstractBaseEvent>>of(BeforeModuleEvent.class); ScreenCapturer capturer = new ScreenCapturer(Providers.of(testFileOrDir), eventClasses, Providers.of(counter), ex != null); int c = counter.intValue(); EventBus eventBus = new EventBus(); eventBus.register(capturer); eventBus.post(new BeforeModuleEvent(new DummyModule())); eventBus.post(new AfterModuleEvent(new DummyModule(), ex)); assertThat(new File(testFileOrDir, String.format("screenshots/%04d_BeforeModuleEvent.png", c))).exists(); if (ex == null) { assertThat(new File(testFileOrDir, String.format("screenshots/%04d_AfterModuleEvent.png", ++c))).doesNotExist(); assertThat(new File(testFileOrDir, String.format("screenshots/%04d_AfterModuleEvent_error.png", ++c))).doesNotExist(); } else { assertThat(new File(testFileOrDir, String.format("screenshots/%04d_AfterModuleEvent_error.png", ++c))).exists(); } }
### Question: CsvDataProcessor { @Inject CsvDataProcessor(final Provider<Configuration> configProvider, final Provider<DataSource> dataSourceProvider) { this.configProvider = configProvider; this.dataSourceProvider = dataSourceProvider; } @Inject CsvDataProcessor(final Provider<Configuration> configProvider, final Provider<DataSource> dataSourceProvider); void processFile(final Reader reader, final String delimiter, final char quoteChar, final Runnable command); }### Answer: @Test public void testCsvDataProcessor() { final Configuration config = new Configuration(Charsets.UTF_8); config.put("foo", "foovalue"); final DataSource dataSource = new TestDataSource(config); CsvDataProcessor csvProc = new CsvDataProcessor(Providers.of(config), Providers.of(dataSource)); final MutableInt counter = new MutableInt(); csvProc.processFile(new StringReader(CSV_LINES), ";", '\0', new Runnable() { @Override public void run() { dataSource.getNextDataSet("test"); int counterValue = counter.intValue(); assertEquals(config.get("foo"), "foo" + counterValue); assertEquals(dataSource.getCurrentDataSet("test").getValue("testKey1"), "newTestValue1" + counterValue); assertEquals(dataSource.getCurrentDataSet("test").getValue("testKey2"), "testValue2"); dataSource.setFixedValue("test", "testKey1", "blablubb"); dataSource.setFixedValue("test", "testKey2", "blablubb"); counter.increment(); } }); }
### Question: EmailModule extends BaseJFunkGuiceModule { @Provides @Singleton SetMultimap<String, MailAccount> provideEmailAddressPools(final Configuration config) { SetMultimap<String, MailAccount> result = HashMultimap.create(); Set<String> accountIdCache = newHashSet(); for (Entry<String, String> entry : config.entrySet()) { String key = entry.getKey(); Matcher matcher = MAIL_ACCOUNT_START_PATTERN.matcher(key); if (matcher.matches()) { String pool = matcher.group(1); String suffix = substringAfterLast(key, pool + '.'); matcher = MAIL_ACCOUNT_END_PATTERN.matcher(suffix); String accountId = matcher.find() ? substringBeforeLast(suffix, ".") : suffix; if (accountIdCache.contains(accountId)) { continue; } accountIdCache.add(accountId); String user = config.processPropertyValue(format(MAIL_USER_KEY_TEMPLATE, pool, accountId, accountId)); String password = config.processPropertyValue(format(MAIL_PASSWORD_KEY_TEMPLATE, pool, accountId)); String address = config.processPropertyValue(format(MAIL_ADDRESS_KEY_TEMPLATE, pool, accountId, accountId)); result.put(pool, new MailAccount(accountId, address, user, password)); } } return result; } }### Answer: @Test public void testProvideEmailAddressPools() { Configuration config = new Configuration(Charsets.UTF_8); config.put("mail.default.user", "defaultuser"); config.put("mail.default.password", "defaultpass"); config.put("mail.default.domain", "defdom.com"); config.put("mail.pool.pool1.test.account.1", ""); config.put("mail.pool.pool1.test.account.2", ""); config.put("mail.pool.pool1.test.account.3.user", "foo"); config.put("mail.pool.pool1.test.account.3.password", "foopass"); config.put("mail.pool.pool1.test.account.3.address", "[email protected]"); config.put("mail.pool.pool2.testaccount1", ""); config.put("mail.pool.pool2.testaccount2", ""); EmailModule module = new EmailModule(); SetMultimap<String, MailAccount> pools = module.provideEmailAddressPools(config); assertThat(pools.size()).isEqualTo(5); assertThat(pools.containsEntry("pool1", new MailAccount("test.account.1", "[email protected]", "defaultuser", "defaultpass"))).isTrue(); assertThat(pools.containsEntry("pool1", new MailAccount("test.account.2", "[email protected]", "defaultuser", "defaultpass"))).isTrue(); assertThat(pools.containsEntry("pool1", new MailAccount("test.account.3", "[email protected]", "foo", "foopass"))).isTrue(); assertThat(pools.containsEntry("pool2", new MailAccount("testaccount1", "[email protected]", "defaultuser", "defaultpass"))).isTrue(); assertThat(pools.containsEntry("pool2", new MailAccount("testaccount2", "[email protected]", "defaultuser", "defaultpass"))).isTrue(); }
### Question: MailAccountManager { public MailAccount reserveMailAccount() { return reserveMailAccount(DEFAULT_ACCOUNT_RESERVATION_KEY); } @Inject MailAccountManager(final SetMultimap<String, MailAccount> emailAddressPools, final MathRandom random, final Provider<EventBus> eventBusProvider, final Configuration config); MailAccount reserveMailAccount(); MailAccount reserveMailAccount(final String accountReservationKey); MailAccount reserveMailAccount(final String accountReservationKey, final String pool); MailAccount lookupUsedMailAccountForCurrentThread(final String accountReservationKey); boolean isReserved(final MailAccount mailAccount); Set<MailAccount> getReservedMailAccountsForCurrentThread(); Set<String> getRegisteredAccountReservationKeysForCurrentThread(); void releaseAllMailAccounts(); void releaseAllMailAccountsForThread(); void releaseMailAccountForThread(final MailAccount account); void releaseMailAccountForThread(final String accountReservationKey); static final String DEFAULT_ACCOUNT_RESERVATION_KEY; }### Answer: @Test public void mailboxShouldBePurgedOnReservation() { init(1); MailboxPurger purger = mock(MailboxPurger.class); eventBus.register(purger); try { MailAccount mailAccount = manager.reserveMailAccount(); verify(purger) .purgeMailbox( new MailAccountReservationEvent(MailAccountManager.DEFAULT_ACCOUNT_RESERVATION_KEY, mailAccount)); } finally { eventBus.unregister(purger); } }
### Question: ExtendedProperties implements Map<String, String>, Serializable, Cloneable { public static ExtendedProperties fromProperties(final Properties props) { ExtendedProperties result = new ExtendedProperties(); for (Enumeration<?> en = props.propertyNames(); en.hasMoreElements();) { String key = (String) en.nextElement(); String value = props.getProperty(key); result.put(key, value); } return result; } ExtendedProperties(); ExtendedProperties(final Map<String, String> defaults); static ExtendedProperties fromProperties(final Properties props); @Override void clear(); @Override String get(final Object key); String get(final Object key, final String defaultValue); String get(final Object key, final boolean process); boolean getBoolean(final String key); boolean getBoolean(final String key, final boolean defaultValue); long getLong(final String key); long getLong(final String key, final long defaultValue); int getInteger(final String key); int getInteger(final String key, final int defaultValue); @Override String put(final String key, final String value); @Override boolean containsKey(final Object key); @Override boolean containsValue(final Object value); @Override Set<Entry<String, String>> entrySet(); @Override boolean isEmpty(); @Override void putAll(final Map<? extends String, ? extends String> map); @Override String remove(final Object key); @Override Collection<String> values(); @Override Set<String> keySet(); @Override int size(); String processPropertyValue(final String input); @Override boolean equals(final Object obj); @Override int hashCode(); Properties toProperties(); @Override String toString(); void load(final InputStream is); void load(final InputStream is, final String encoding); void load(final Reader reader); void store(final OutputStream os, final String comments, final boolean sorted, final boolean process); void store(final OutputStream os, final String encoding, final String comments, final boolean sorted, final boolean process); void store(final Writer writer, final String comments, final boolean sorted, final boolean process); @Override ExtendedProperties clone(); }### Answer: @Test public void testFromProperties() { Properties p = new Properties(); p.setProperty("test1", "test1"); p.setProperty("test2", "test2"); p.setProperty("test3", "test3"); ExtendedProperties extProps = ExtendedProperties.fromProperties(p); Assert.assertEquals(extProps.size(), 3); Assert.assertEquals(extProps.get("test1"), "test1"); Assert.assertEquals(extProps.get("test2"), "test2"); Assert.assertEquals(extProps.get("test3"), "test3"); }
### Question: ExtendedProperties implements Map<String, String>, Serializable, Cloneable { @Override public Set<String> keySet() { if (keySet == null) { keySet = new KeySet(); } return keySet; } ExtendedProperties(); ExtendedProperties(final Map<String, String> defaults); static ExtendedProperties fromProperties(final Properties props); @Override void clear(); @Override String get(final Object key); String get(final Object key, final String defaultValue); String get(final Object key, final boolean process); boolean getBoolean(final String key); boolean getBoolean(final String key, final boolean defaultValue); long getLong(final String key); long getLong(final String key, final long defaultValue); int getInteger(final String key); int getInteger(final String key, final int defaultValue); @Override String put(final String key, final String value); @Override boolean containsKey(final Object key); @Override boolean containsValue(final Object value); @Override Set<Entry<String, String>> entrySet(); @Override boolean isEmpty(); @Override void putAll(final Map<? extends String, ? extends String> map); @Override String remove(final Object key); @Override Collection<String> values(); @Override Set<String> keySet(); @Override int size(); String processPropertyValue(final String input); @Override boolean equals(final Object obj); @Override int hashCode(); Properties toProperties(); @Override String toString(); void load(final InputStream is); void load(final InputStream is, final String encoding); void load(final Reader reader); void store(final OutputStream os, final String comments, final boolean sorted, final boolean process); void store(final OutputStream os, final String encoding, final String comments, final boolean sorted, final boolean process); void store(final Writer writer, final String comments, final boolean sorted, final boolean process); @Override ExtendedProperties clone(); }### Answer: @Test public void testKeySet() { Set<String> keySet = props.keySet(); Assert.assertEquals(props.size(), 7); Assert.assertEquals(keySet.size(), 7); Assert.assertTrue(keySet.contains("defProp2 ")); Assert.assertTrue(props.containsKey("defProp2 ")); props.put("newProp", "foo"); Assert.assertEquals(props.size(), 8); Assert.assertEquals(keySet.size(), 8); Assert.assertTrue(keySet.contains("newProp")); props.remove("newProp"); Assert.assertEquals(props.size(), 7); Assert.assertEquals(keySet.size(), 7); Assert.assertTrue(!keySet.contains("newProp")); Assert.assertTrue(!props.containsKey("newProp")); keySet.remove("moreProp"); Assert.assertEquals(props.size(), 6); Assert.assertEquals(keySet.size(), 6); Assert.assertTrue(!keySet.contains("moreProp")); Assert.assertTrue(!props.containsKey("moreProp")); keySet.clear(); Assert.assertTrue(keySet.isEmpty()); Assert.assertTrue(props.isEmpty()); }
### Question: ExtendedProperties implements Map<String, String>, Serializable, Cloneable { @Override public Collection<String> values() { if (values == null) { values = new Values(); } return values; } ExtendedProperties(); ExtendedProperties(final Map<String, String> defaults); static ExtendedProperties fromProperties(final Properties props); @Override void clear(); @Override String get(final Object key); String get(final Object key, final String defaultValue); String get(final Object key, final boolean process); boolean getBoolean(final String key); boolean getBoolean(final String key, final boolean defaultValue); long getLong(final String key); long getLong(final String key, final long defaultValue); int getInteger(final String key); int getInteger(final String key, final int defaultValue); @Override String put(final String key, final String value); @Override boolean containsKey(final Object key); @Override boolean containsValue(final Object value); @Override Set<Entry<String, String>> entrySet(); @Override boolean isEmpty(); @Override void putAll(final Map<? extends String, ? extends String> map); @Override String remove(final Object key); @Override Collection<String> values(); @Override Set<String> keySet(); @Override int size(); String processPropertyValue(final String input); @Override boolean equals(final Object obj); @Override int hashCode(); Properties toProperties(); @Override String toString(); void load(final InputStream is); void load(final InputStream is, final String encoding); void load(final Reader reader); void store(final OutputStream os, final String comments, final boolean sorted, final boolean process); void store(final OutputStream os, final String encoding, final String comments, final boolean sorted, final boolean process); void store(final Writer writer, final String comments, final boolean sorted, final boolean process); @Override ExtendedProperties clone(); }### Answer: @Test public void testValues() { Collection<String> values = props.values(); Assert.assertEquals(props.size(), 7); Assert.assertEquals(values.size(), 7); Assert.assertTrue(values.contains("öäü~@€^°é")); Assert.assertTrue(values.contains("testtest")); Assert.assertTrue(values.contains("test\\")); Assert.assertTrue(values.contains("")); Assert.assertTrue(values.contains("foo")); Assert.assertTrue(values.contains("bar")); Assert.assertTrue(values.contains("more\\Prop")); props.put("value", "value"); Assert.assertTrue(values.contains("value")); props.remove("value"); Assert.assertTrue(!values.contains("value")); }
### Question: ExtendedProperties implements Map<String, String>, Serializable, Cloneable { @Override public Set<Entry<String, String>> entrySet() { if (entrySet == null) { entrySet = new EntrySet(); } return entrySet; } ExtendedProperties(); ExtendedProperties(final Map<String, String> defaults); static ExtendedProperties fromProperties(final Properties props); @Override void clear(); @Override String get(final Object key); String get(final Object key, final String defaultValue); String get(final Object key, final boolean process); boolean getBoolean(final String key); boolean getBoolean(final String key, final boolean defaultValue); long getLong(final String key); long getLong(final String key, final long defaultValue); int getInteger(final String key); int getInteger(final String key, final int defaultValue); @Override String put(final String key, final String value); @Override boolean containsKey(final Object key); @Override boolean containsValue(final Object value); @Override Set<Entry<String, String>> entrySet(); @Override boolean isEmpty(); @Override void putAll(final Map<? extends String, ? extends String> map); @Override String remove(final Object key); @Override Collection<String> values(); @Override Set<String> keySet(); @Override int size(); String processPropertyValue(final String input); @Override boolean equals(final Object obj); @Override int hashCode(); Properties toProperties(); @Override String toString(); void load(final InputStream is); void load(final InputStream is, final String encoding); void load(final Reader reader); void store(final OutputStream os, final String comments, final boolean sorted, final boolean process); void store(final OutputStream os, final String encoding, final String comments, final boolean sorted, final boolean process); void store(final Writer writer, final String comments, final boolean sorted, final boolean process); @Override ExtendedProperties clone(); }### Answer: @Test public void testEntrySet() { SimpleEntry entry = new SimpleEntry("newProp", "foo"); Set<Entry<String, String>> entrySet = props.entrySet(); props.put("newProp", "foo"); Assert.assertEquals(props.size(), 8); Assert.assertEquals(entrySet.size(), 8); Assert.assertTrue(entrySet.contains(entry)); Assert.assertTrue(props.containsKey(entry.getKey())); props.remove("newProp"); Assert.assertEquals(props.size(), 7); Assert.assertEquals(entrySet.size(), 7); Assert.assertTrue(!entrySet.contains(entry)); Assert.assertTrue(!props.containsKey(entry.getKey())); entry = new SimpleEntry("moreProp", "more\\Prop"); entrySet.remove(entry); Assert.assertEquals(props.size(), 6); Assert.assertEquals(entrySet.size(), 6); Assert.assertTrue(!entrySet.contains(entry)); Assert.assertTrue(!props.containsKey(entry.getKey())); entrySet.clear(); Assert.assertTrue(entrySet.isEmpty()); Assert.assertTrue(props.isEmpty()); }
### Question: ExtendedProperties implements Map<String, String>, Serializable, Cloneable { @Override public boolean containsKey(final Object key) { return propsMap.containsKey(key) ? true : defaults != null && defaults.containsKey(key); } ExtendedProperties(); ExtendedProperties(final Map<String, String> defaults); static ExtendedProperties fromProperties(final Properties props); @Override void clear(); @Override String get(final Object key); String get(final Object key, final String defaultValue); String get(final Object key, final boolean process); boolean getBoolean(final String key); boolean getBoolean(final String key, final boolean defaultValue); long getLong(final String key); long getLong(final String key, final long defaultValue); int getInteger(final String key); int getInteger(final String key, final int defaultValue); @Override String put(final String key, final String value); @Override boolean containsKey(final Object key); @Override boolean containsValue(final Object value); @Override Set<Entry<String, String>> entrySet(); @Override boolean isEmpty(); @Override void putAll(final Map<? extends String, ? extends String> map); @Override String remove(final Object key); @Override Collection<String> values(); @Override Set<String> keySet(); @Override int size(); String processPropertyValue(final String input); @Override boolean equals(final Object obj); @Override int hashCode(); Properties toProperties(); @Override String toString(); void load(final InputStream is); void load(final InputStream is, final String encoding); void load(final Reader reader); void store(final OutputStream os, final String comments, final boolean sorted, final boolean process); void store(final OutputStream os, final String encoding, final String comments, final boolean sorted, final boolean process); void store(final Writer writer, final String comments, final boolean sorted, final boolean process); @Override ExtendedProperties clone(); }### Answer: @Test public void testContainsKey() { Assert.assertTrue(props.containsKey("prop1")); Assert.assertTrue(props.containsKey("prop2")); Assert.assertTrue(props.containsKey("prop3=")); Assert.assertTrue(props.containsKey("prop4test")); Assert.assertTrue(props.containsKey("def=Prop1:")); Assert.assertTrue(props.containsKey("defProp2 ")); Assert.assertTrue(props.containsKey("moreProp")); }
### Question: ExtendedProperties implements Map<String, String>, Serializable, Cloneable { @Override public boolean containsValue(final Object value) { for (String key : keySet()) { if (value.equals(get(key))) { return true; } } return false; } ExtendedProperties(); ExtendedProperties(final Map<String, String> defaults); static ExtendedProperties fromProperties(final Properties props); @Override void clear(); @Override String get(final Object key); String get(final Object key, final String defaultValue); String get(final Object key, final boolean process); boolean getBoolean(final String key); boolean getBoolean(final String key, final boolean defaultValue); long getLong(final String key); long getLong(final String key, final long defaultValue); int getInteger(final String key); int getInteger(final String key, final int defaultValue); @Override String put(final String key, final String value); @Override boolean containsKey(final Object key); @Override boolean containsValue(final Object value); @Override Set<Entry<String, String>> entrySet(); @Override boolean isEmpty(); @Override void putAll(final Map<? extends String, ? extends String> map); @Override String remove(final Object key); @Override Collection<String> values(); @Override Set<String> keySet(); @Override int size(); String processPropertyValue(final String input); @Override boolean equals(final Object obj); @Override int hashCode(); Properties toProperties(); @Override String toString(); void load(final InputStream is); void load(final InputStream is, final String encoding); void load(final Reader reader); void store(final OutputStream os, final String comments, final boolean sorted, final boolean process); void store(final OutputStream os, final String encoding, final String comments, final boolean sorted, final boolean process); void store(final Writer writer, final String comments, final boolean sorted, final boolean process); @Override ExtendedProperties clone(); }### Answer: @Test public void testContainsValue() { Assert.assertTrue(props.containsValue("öäü~@€^°é")); Assert.assertTrue(props.containsValue("testtest")); Assert.assertTrue(props.containsValue("test\\")); Assert.assertTrue(props.containsValue("")); Assert.assertTrue(props.containsValue("foo")); Assert.assertTrue(props.containsValue("bar")); Assert.assertTrue(props.containsValue("more\\Prop")); }
### Question: ThreadScope extends BaseScope { @Override public <T> Provider<T> scope(final Key<T> key, final Provider<T> unscoped) { return new Provider<T>() { @Override public T get() { Map<Key<?>, Object> map = getScopeMapForCurrentThread(); checkState(map != null, "No scope map found for the current thread. Forgot to call enterScope()?"); return getScopedObject(key, unscoped, map); } @Override public String toString() { return String.format("%s[%s]", unscoped, ThreadScope.this); } }; } @Override Provider<T> scope(final Key<T> key, final Provider<T> unscoped); @Override void enterScope(); void enterScopeNonInheritable(); boolean isScopeEntered(); @Override void exitScope(); }### Answer: @Test public void testToString() { ThreadScope scope = new ThreadScope(); Provider<String> prov = scope.scope(Key.get(String.class), new Provider<String>() { @Override public String get() { return "dummy"; } @Override public String toString() { return get(); } }); Assert.assertEquals(prov.toString(), "dummy[ThreadScope]"); }
### Question: WmsVersion implements Comparable<WmsVersion> { @Override public int compareTo(WmsVersion o) { if (o == null) { throw new NullPointerException("Version to compare to must not be null"); } if (this.major != o.major) { return this.major < o.major ? -1 : 1; } if (this.minor != o.minor) { return this.minor < o.minor ? -1 : 1; } if (this.build != o.build) { return this.build < o.build ? -1 : 1; } return 0; } WmsVersion(String version); WmsVersion(int major, int minor, int build); int getMajor(); int getMinor(); int getBuild(); @Override int compareTo(WmsVersion o); @Override String toString(); String toVersionString(); static void validateVersion(String version); }### Answer: @Test public void testCompareTo() { WmsVersion version111 = new WmsVersion("1.1.1"); WmsVersion version112 = new WmsVersion("1.1.2"); WmsVersion version110 = new WmsVersion("1.1"); WmsVersion version130 = new WmsVersion("1.3"); WmsVersion version200 = new WmsVersion("2.0"); assertThat(version111.compareTo(version112), is(-1)); assertThat(version112.compareTo(version111), is(1)); assertThat(version111.compareTo(version130), is(-1)); assertThat(version130.compareTo(version111), is(1)); assertThat(version130.compareTo(version130), is(0)); assertThat(version110.compareTo(version111), is(-1)); assertThat(version200.compareTo(version111), is(1)); assertThat(version130.compareTo(version200), is(-1)); } @Test(expected = NullPointerException.class) public void testCompareToNull() { WmsVersion version = new WmsVersion("1.1.1"); version.compareTo(null); }
### Question: WmsRequestBuilder { public WmsRequestBuilder transparent(boolean transparent) { parameters.put(WmsRequestParameter.TRANSPARENT, Boolean .valueOf(transparent) .toString()); return this; } static WmsRequestBuilder createGetMapRequest(String serviceUrl); static WmsRequestBuilder createGetMapRequest( Map<WmsRequestParameter, String> params); WmsRequestBuilder layers(String layers); WmsRequestBuilder styles(String styles); WmsRequestBuilder format(String format); WmsRequestBuilder boundingBox(String boundingBox); WmsRequestBuilder transparent(boolean transparent); WmsRequestBuilder version(String version); WmsRequestBuilder srsCrs(String srsCrs); WmsRequestBuilder urlParameters(String urlParameters); WmsRequestBuilder width(int width); WmsRequestBuilder height(int height); URL toMapUrl(); }### Answer: @Test public void testTransparent() throws MalformedURLException { String url = basicRequestBuilder().toMapUrl().toExternalForm(); assertThat(url, containsString("TRANSPARENT=FALSE")); }
### Question: WmsRequestBuilder { public WmsRequestBuilder version(String version) { parameters.put(WmsRequestParameter.VERSION, version); return this; } static WmsRequestBuilder createGetMapRequest(String serviceUrl); static WmsRequestBuilder createGetMapRequest( Map<WmsRequestParameter, String> params); WmsRequestBuilder layers(String layers); WmsRequestBuilder styles(String styles); WmsRequestBuilder format(String format); WmsRequestBuilder boundingBox(String boundingBox); WmsRequestBuilder transparent(boolean transparent); WmsRequestBuilder version(String version); WmsRequestBuilder srsCrs(String srsCrs); WmsRequestBuilder urlParameters(String urlParameters); WmsRequestBuilder width(int width); WmsRequestBuilder height(int height); URL toMapUrl(); }### Answer: @Test public void testVersion() throws MalformedURLException { String url = basicRequestBuilder().toMapUrl().toExternalForm(); assertThat(url, containsString("VERSION=1.1.1")); }
### Question: WmsVersion implements Comparable<WmsVersion> { @Override public String toString() { return format("%d.%d.%d", major, minor, build); } WmsVersion(String version); WmsVersion(int major, int minor, int build); int getMajor(); int getMinor(); int getBuild(); @Override int compareTo(WmsVersion o); @Override String toString(); String toVersionString(); static void validateVersion(String version); }### Answer: @Test public void testToString() { WmsVersion version = new WmsVersion("1.3"); assertThat(version.toString(), is("1.3.0")); }
### Question: WmsVersion implements Comparable<WmsVersion> { public String toVersionString() { StringBuilder version = new StringBuilder(); version.append(major); if (minor != 0) { version.append('.').append(minor); } if (build != 0) { version.append('.').append(build); } return version.toString(); } WmsVersion(String version); WmsVersion(int major, int minor, int build); int getMajor(); int getMinor(); int getBuild(); @Override int compareTo(WmsVersion o); @Override String toString(); String toVersionString(); static void validateVersion(String version); }### Answer: @Test public void testToVersionString() { WmsVersion version1 = new WmsVersion(1, 0, 0); assertThat(version1.toVersionString(), is("1")); WmsVersion version13 = new WmsVersion(1, 3, 0); assertThat(version13.toVersionString(), is("1.3")); WmsVersion version111 = new WmsVersion(1, 1, 1); assertThat(version111.toVersionString(), is("1.1.1")); }
### Question: WmsMapElementHtmlHandler implements GenericElementHtmlHandler { @Override public boolean toExport(JRGenericPrintElement element) { return true; } static WmsMapElementHtmlHandler getInstance(); @Override String getHtmlFragment(JRHtmlExporterContext context, JRGenericPrintElement element); @Override boolean toExport(JRGenericPrintElement element); }### Answer: @Test public void testToExport() { assertTrue(handler.toExport(null)); }
### Question: WmsMapElementHtmlHandler implements GenericElementHtmlHandler { @Override public String getHtmlFragment(JRHtmlExporterContext context, JRGenericPrintElement element) { Map<String, Object> contextMap = new HashMap<String, Object>(); contextMap.put("mapCanvasId", "map_canvas_" + element.hashCode()); if (context.getExporter() instanceof JRXhtmlExporter) { contextMap.put("xhtml", "xhtml"); JRXhtmlExporter xhtmlExporter = (JRXhtmlExporter) context.getExporter(); contextMap.put("elementX", xhtmlExporter.toSizeUnit(element.getX())); contextMap.put("elementY", xhtmlExporter.toSizeUnit(element.getY())); } else { JRHtmlExporter htmlExporter = (JRHtmlExporter) context.getExporter(); contextMap.put("elementX", htmlExporter.toSizeUnit(element.getX())); contextMap.put("elementY", htmlExporter.toSizeUnit(element.getY())); } contextMap.put("elementId", element.getKey()); contextMap.put("elementWidth", element.getWidth()); contextMap.put("elementHeight", element.getHeight()); if (element.getModeValue() == ModeEnum.OPAQUE) { contextMap.put("backgroundColor", JRColorUtil.getColorHexa(element.getBackcolor())); } WmsRequestBuilder requestBuilder = WmsMapElementImageProvider.mapRequestBuilder(element); try { contextMap.put("wmsMapUrl", requestBuilder.toMapUrl()); } catch (MalformedURLException e) { throw new RuntimeException("Unable to build WMS map service url", e); } return VelocityUtil.processTemplate(MAP_ELEMENT_HTML_TEMPLATE, contextMap); } static WmsMapElementHtmlHandler getInstance(); @Override String getHtmlFragment(JRHtmlExporterContext context, JRGenericPrintElement element); @Override boolean toExport(JRGenericPrintElement element); }### Answer: @Ignore("Moved test from generic element") @Test public void testGetHtmlFragment() { JRGenericPrintElement element = mock(JRGenericPrintElement.class); when(element.getParameterNames()).thenReturn(parameters.keySet()); when(element.getParameterValue(WmsRequestParameter.WMS_URL.name())) .thenReturn(BASE_URL); when(element.getParameterValue(WmsRequestParameter.LAYERS.name())) .thenReturn("Hintergrund"); when(element.getParameterValue(WmsRequestParameter.BBOX.name())) .thenReturn("1,1,1,1"); when(element.getParameterValue(WmsRequestParameter.SRS_CRS.name())) .thenReturn("EPSG:21781"); when(element.getWidth()).thenReturn(100); when(element.getHeight()).thenReturn(100); String htmlFragment = handler.getHtmlFragment( mock(JRHtmlExporterContext.class), element); assertThat(htmlFragment, startsWith("<img ")); assertThat(htmlFragment, containsString(BASE_URL)); assertThat(htmlFragment, containsString("WIDTH=100")); assertThat(htmlFragment, containsString("HEIGHT=100")); }
### Question: WmsMapElementGraphics2DHandler implements GenericElementGraphics2DHandler { @Override public void exportElement(JRGraphics2DExporterContext context, JRGenericPrintElement element, Graphics2D grx, Offset offset) { try { JRGraphics2DExporter exporter = (JRGraphics2DExporter) context .getExporter(); ImageDrawer imageDrawer = exporter.getFrameDrawer().getDrawVisitor() .getImageDrawer(); JRPrintImage image = getImage(context.getJasperReportsContext(), element); imageDrawer.draw(grx, image, offset.getX(), offset.getY()); } catch (Exception e) { throw new RuntimeException(e); } } static WmsMapElementGraphics2DHandler getInstance(); @Override void exportElement(JRGraphics2DExporterContext context, JRGenericPrintElement element, Graphics2D grx, Offset offset); @Override boolean toExport(JRGenericPrintElement element); }### Answer: @Ignore @Test public void testExportElement() throws JRException { JRGraphics2DExporter exporter = new JRGraphics2DExporter(); JRGraphics2DExporterContext context = mock(JRGraphics2DExporterContext.class); when(context.getExporter()).thenReturn(exporter); JRGenericPrintElement element = mock(JRGenericPrintElement.class); java.awt.Container container = new Container(); Graphics2D graphics = (Graphics2D) container.getGraphics(); Offset offset = new Offset(0, 0); handler.exportElement(context, element, graphics, offset); }
### Question: WmsMapElementGraphics2DHandler implements GenericElementGraphics2DHandler { @Override public boolean toExport(JRGenericPrintElement element) { return true; } static WmsMapElementGraphics2DHandler getInstance(); @Override void exportElement(JRGraphics2DExporterContext context, JRGenericPrintElement element, Graphics2D grx, Offset offset); @Override boolean toExport(JRGenericPrintElement element); }### Answer: @Test public void testToExport() { assertTrue(handler.toExport(mock(JRGenericPrintElement.class))); }
### Question: WmsRequestBuilder { public URL toMapUrl() throws MalformedURLException { StringBuilder url = new StringBuilder(); Map<WmsRequestParameter, String> params = new LinkedHashMap<WmsRequestParameter, String>(this.parameters); String wmsUrl = params.remove(WmsRequestParameter.WMS_URL).toString(); url.append(wmsUrl); if (wmsUrl.indexOf("?") == -1) { url.append("?"); } java.util.List<String> paramList = new ArrayList<String>(); for (WmsRequestParameter parameter : WmsRequestParameter.parameterValues()) { if (parameter == WmsRequestParameter.URL_PARAMETERS) { continue; } Object defaultValue = parameter.defaultValue(params); if (params.containsKey(parameter) || parameter.isRequired(params) || defaultValue != null) { String parameterName = parameter.parameterName(params); Object value = parameter.extract(params); paramList.add(encodeParameter(parameterName, value.toString())); } } Iterator<String> iterator = paramList.iterator(); while (iterator.hasNext()) { String param = iterator.next(); url.append(param); if (iterator.hasNext()) { url.append("&"); } } Object urlParams = params.remove(WmsRequestParameter.URL_PARAMETERS); if (urlParams != null) { String extraUrlParams = urlParams.toString(); if (!extraUrlParams.startsWith("&")) { url.append("&"); } url.append(extraUrlParams); } return new URL(url.toString()); } static WmsRequestBuilder createGetMapRequest(String serviceUrl); static WmsRequestBuilder createGetMapRequest( Map<WmsRequestParameter, String> params); WmsRequestBuilder layers(String layers); WmsRequestBuilder styles(String styles); WmsRequestBuilder format(String format); WmsRequestBuilder boundingBox(String boundingBox); WmsRequestBuilder transparent(boolean transparent); WmsRequestBuilder version(String version); WmsRequestBuilder srsCrs(String srsCrs); WmsRequestBuilder urlParameters(String urlParameters); WmsRequestBuilder width(int width); WmsRequestBuilder height(int height); URL toMapUrl(); }### Answer: @Test public void testStylesDefaults() throws MalformedURLException { String url = basicRequestBuilder() .toMapUrl().toExternalForm(); assertThat(url, containsString("STYLE=%2C%2C")); System.out.println(url); } @Test public void testFormatDefault() throws MalformedURLException { String url = basicRequestBuilder().toMapUrl().toExternalForm(); assertThat(url, containsString("FORMAT=image%2Fpng")); }
### Question: Station { @JsonSetter("tags") public void setTags(final String commaTags) { tagList = Arrays.asList(commaTags.split(",")); } @JsonGetter("tags") String getTags(); @JsonSetter("tags") void setTags(final String commaTags); @JsonGetter("language") String getLanguage(); @JsonSetter("language") void setLanguage(final String commaLanguages); @Override String toString(); }### Answer: @Test public void setTagsCommaSeparated() { Station testMe = new Station(); testMe.setTags("foo,bar,baz"); assertThat(Arrays.asList("foo", "bar", "baz"), is(testMe.getTagList())); }