method2testcases
stringlengths 118
3.08k
|
---|
### Question:
MapPoolDuplicateAction extends AbstractAction { @Override public void actionPerformed(ActionEvent e) { int idx = mapPoolJTable.getSelectedRow(); final Map map = mapPool.get(mapPoolJTable.convertRowIndexToModel(idx)); actionPerformed(map); } MapPoolDuplicateAction(MapPoolJTable mapPoolJTable); @Override void actionPerformed(ActionEvent e); Map actionPerformed(final Map map); }### Answer:
@Test public void testDuplicateMap() throws AtlasException, FactoryException, TransformException, SAXException, IOException, ParserConfigurationException { AtlasConfigEditable ace = GpTestingUtil .getAtlasConfigE(TestAtlas.small); Map map1 = ace.getMapPool().get(0); File htmlDir1 = ace.getHtmlDirFor(map1); int count1 = htmlDir1.list().length; long size1 = FileUtils.sizeOfDirectory(htmlDir1); assertTrue("map html dir may not be empty for this test", count1 > 0); MapPoolDuplicateAction mapPoolDuplicateAction = new MapPoolDuplicateAction( new MapPoolJTable(ace)); if (TestingUtil.INTERACTIVE) { Map map2 = mapPoolDuplicateAction.actionPerformed(map1); assertFalse(map1.equals(map2)); File htmlDir2 = ace.getHtmlDirFor(map2); assertFalse(htmlDir1.equals(htmlDir2)); long size2 = FileUtils.sizeOfDirectory(htmlDir2); int count2 = htmlDir2.list().length; assertEquals(size1, size2); assertEquals(count1, count2); assertFalse("SVN files should have been omitted during copy", new File(htmlDir2, ".svn").exists()); FileUtils.deleteDirectory(htmlDir2); } ace.deleteAtlas(); } |
### Question:
AvUtil extends GpCoreUtil { public static String fixBrokenBgColor(String oldHtml) { return oldHtml.replaceAll("color\\s?=\\s?[\",']([0-9,a-f,A-F]{6})[\",']", "#$1"); } static String fixBrokenBgColor(String oldHtml); static boolean fixBrokenBgColor(File oldHtml); }### Answer:
@Test public void testFixBrokenBgColor(){ String oldHtml = "<html> <head> </head> <body bgcolor=\"ffe07a\"> <p><img height=\"298\" src=\"images/n4_java_vulkan_semeru_rauch_lava.jpg\" align=\"top\" width=\"447\">" + "</p><p><font size=\"+1\">Eruption des Vulkans Semeru auf der indonesischen Insel Java, 2004 </font><br><a href=\"browser: "licence</a> M. Rietze </p></body></html>"; asserFixed(oldHtml, "#ffe07a"); asserFixed("bgcolor='blue'", "blue"); asserFixed("bgcolor='#0000DD'", "'#0000DD'"); asserFixed("bgcolor='ffe07a'", "#ffe07a"); asserFixed("color='ffe07a'", "#ffe07a"); asserFixed("bgcolor='FFE07A'", "#FFE07A"); } |
### Question:
UniqueValuesAddGUI extends CancellableDialogAdapter { public UniqueValuesAddGUI(Component owner, final UniqueValuesRulesListInterface<VALUETYPE> rulesList) { super(owner); this.rulesList = rulesList; initialize(); String title = ASUtil.R("UniqueValuesRuleList.AddAllValues.SearchingMsg"); final AtlasStatusDialog statusDialog = new AtlasStatusDialog(owner, title, title); AtlasSwingWorker<Set<VALUETYPE>> findUniques = new AtlasSwingWorker<Set<VALUETYPE>>(statusDialog) { @Override protected Set<VALUETYPE> doInBackground() throws Exception { return rulesList.getAllUniqueValuesThatAreNotYetIncluded(); } }; try { Set<VALUETYPE> uniqueValues = findUniques.executeModal(); if (uniqueValues.size() == 0) AVSwingUtil.showMessageDialog(UniqueValuesAddGUI.this, ASUtil.R("UniqueValues.NothingToAdd")); DefaultListModel defaultListModel = new DefaultListModel(); for (VALUETYPE uv : uniqueValues) { defaultListModel.addElement(uv); } getJListValues().setModel(defaultListModel); SwingUtil.setRelativeFramePosition(UniqueValuesAddGUI.this, owner, SwingUtil.BOUNDS_OUTER, SwingUtil.NORTHEAST); } catch (CancellationException e) { dispose(); return; } catch (Exception e) { ExceptionDialog.show(e); dispose(); return; } } UniqueValuesAddGUI(Component owner, final UniqueValuesRulesListInterface<VALUETYPE> rulesList); @Override void cancel(); @Override boolean okClose(); }### Answer:
@Test public void testUniqueValuesAddGUI() throws Throwable { final UniqueValuesRuleList rl = new RuleListFactory( GTTestingUtil.TestDatasetsVector.kreise.getStyledFS()) .createUniqueValuesRulesList(true); if (TestingUtil.INTERACTIVE) { UniqueValuesAddGUI dialog = new UniqueValuesAddGUI(null, rl); TestingUtil.testGui(dialog, 1); } } |
### Question:
SymbolSelectorGUI extends AtlasDialog { public SymbolSelectorGUI(Component owner, AtlasStylerVector asv, String title, final SingleRuleList singleSymbolRuleList) { super(owner); if (asv == null) throw new IllegalStateException("asv may not be null here!"); this.asv = asv; if (title != null) setTitle(title); else setTitle(DIALOG_TITLE); this.singleSymbolRuleList = singleSymbolRuleList; initialize(); } SymbolSelectorGUI(Component owner, AtlasStylerVector asv,
String title, final SingleRuleList singleSymbolRuleList); static final String PROPERTY_CANCEL_CHANGES; static final String PROPERTY_CLOSED; }### Answer:
@Test public void testSymbolSelectorGUI() throws Throwable { if (!TestingUtil.isInteractive()) return; AtlasStylerVector asv = AsTestingUtil .getAtlasStyler(TestDatasetsVector.polygonSnow); SinglePolygonSymbolRuleList singleSymbolRuleList = RuleListFactory .createSinglePolygonSymbolRulesList(new Translation( "test with defaults"), true); asv.addRulesList(singleSymbolRuleList); PolygonSymbolizer ps = (PolygonSymbolizer) singleSymbolRuleList.getSymbolizers().get(0); ps.setFill(StylingUtil.STYLE_BUILDER.createFill()); ps.getFill().setGraphicFill(StylingUtil.STYLE_BUILDER.createGraphic()); ps.getFill().getGraphicFill().setSize(StylingUtil.ff.literal(5.0)); assertEquals(5., singleSymbolRuleList.getSizeBiggest(), 0.0); SymbolSelectorGUI ssg = new SymbolSelectorGUI(null, asv, "", singleSymbolRuleList); JComboBox jComboBoxSize = ssg.getJComboBoxSize(); jComboBoxSize.setSelectedIndex(10); System.out.println(StylingUtil.sldToString(asv.getStyle())); assertEquals(10., singleSymbolRuleList.getSizeBiggest(), 0.0); } |
### Question:
FeatureClassificationGUI extends ClassificationGUI { private AtlasStylerVector getAtlasStyler() { return (AtlasStylerVector) atlasStyler; } FeatureClassificationGUI(Component owner,
FeatureClassification classifier, AtlasStylerVector atlasStyler,
String title); FeatureClassification getClassifier(); }### Answer:
@Test public void testShowGuiWithoutValueAttribute() throws Throwable { if (!hasGui()) return; AtlasStylerVector asv = AsTestingUtil .getAtlasStyler(TestDatasetsVector.countryShp); FeatureClassification classifier = new FeatureClassification( asv.getStyledFeatures()); ClassificationGUI gui = new FeatureClassificationGUI(null, classifier, asv, "junit test vector classification"); TestingUtil.testGui(gui); }
@Test public void testShowGui() throws Throwable { if (!hasGui()) return; AtlasStylerVector asv = AsTestingUtil .getAtlasStyler(TestDatasetsVector.countryShp); FeatureClassification classifier = new FeatureClassification( asv.getStyledFeatures()); classifier.setValue_field_name(FeatureUtil.getNumericalFieldNames( asv.getStyledFeatures().getSchema()).get(0)); ClassificationGUI gui = new FeatureClassificationGUI(null, classifier, asv, "junit test vector classification"); TestingUtil.testGui(gui); } |
### Question:
TextLabelingClassLanguageSelectorDialog extends
CancellableDialogAdapter { public TextLabelingClassLanguageSelectorDialog(Component parentGui, TextRuleList rulesList) { super(parentGui, ASUtil .R("TextSymbolizerClass.CreateALanguageDefault.DialogTitle")); this.rulesList = rulesList; lcb = new LanguagesComboBox(AtlasStylerVector.getLanguages(), rulesList.getDefaultLanguages()); setContentPane(new JPanel(new MigLayout("wrap 1, w 400"))); getContentPane() .add(new JLabel( ASUtil.R("TextSymbolizerClass.CreateALanguageDefault.Explanation")), ""); getContentPane().add(lcb, "w 300, center"); getContentPane().add(getOkButton(), "split 2, tag ok"); getContentPane().add(getCancelButton(), "tag cancel"); pack(); SwingUtil.setRelativeFramePosition(this, parentGui, 0.5, 0.5); } TextLabelingClassLanguageSelectorDialog(Component parentGui,
TextRuleList rulesList); @Override boolean close(); @Override void cancel(); String getSelectedLanguage(); }### Answer:
@Test public void testTextLabelingClassLanguageSelectorDialog() throws Throwable { if (!hasGui()) return; TextRuleList textRulesList = new RuleListFactory( GTTestingUtil.TestDatasetsVector.countryShp.getStyledFS()) .createTextRulesList(true); TextLabelingClassLanguageSelectorDialog d = new TextLabelingClassLanguageSelectorDialog( null, textRulesList); d.setVisible(true); d.pack(); TestingUtil.testGui(d, 100); } |
### Question:
LineSymbolEditGUI extends AbstractStyleEditGUI { public LineSymbolEditGUI(final AtlasStylerVector asv, final org.geotools.styling.LineSymbolizer symbolizer) { super(asv); this.symbolizer = symbolizer; initialize(); } LineSymbolEditGUI(final AtlasStylerVector asv, final org.geotools.styling.LineSymbolizer symbolizer); }### Answer:
@Test public void testLineSymbolEditGUI() throws Throwable { if (!TestingUtil.isInteractive()) return; LineSymbolEditGUI lineSymbolEditGUI = new LineSymbolEditGUI( AsTestingUtil.getAtlasStyler(TestDatasetsVector.countryShp), ps); TestingUtil.testGui(lineSymbolEditGUI); } |
### Question:
PolygonSymbolEditGUI extends AbstractStyleEditGUI { public PolygonSymbolEditGUI(final AtlasStylerVector asv, final org.geotools.styling.PolygonSymbolizer symbolizer) { super(asv); this.symbolizer = symbolizer; initialize(); } PolygonSymbolEditGUI(final AtlasStylerVector asv,
final org.geotools.styling.PolygonSymbolizer symbolizer); }### Answer:
@Test public void testPolygonSymbolEditGUI() throws Throwable { if (!TestingUtil.isInteractive()) return; ps.setFill(null); ps.setStroke(null); PolygonSymbolEditGUI polygonSymbolEditGUI = new PolygonSymbolEditGUI(AsTestingUtil.getAtlasStyler(TestDatasetsVector.countryShp),ps); TestingUtil.testGui(polygonSymbolEditGUI); } |
### Question:
AtlasStylerPane extends JSplitPane implements ClosableSubwindows { public AtlasStylerPane(StylerDialog stylerDialog) { this.asd = stylerDialog; this.atlasStyler = stylerDialog.getAtlasStyler(); initialize(); atlasStyler.setQuite(true); { for (AbstractRulesList ruleList : atlasStyler.getRuleLists()) { createEditorComponent(ruleList); } } getRulesListsListTablePanel().getRulesListTable().getSelectionModel() .addListSelectionListener(listenToSelectionInTable); if (getRulesListsListTablePanel().getRulesListTable().getSelectedRow() != -1) { int s1 = getRulesListsListTablePanel().getRulesListTable() .getSelectedRow(); getRulesListsListTablePanel().getRulesListTable() .getSelectionModel().clearSelection(); getRulesListsListTablePanel().getRulesListTable() .getSelectionModel().addSelectionInterval(s1, s1); } atlasStyler.setQuite(false); } AtlasStylerPane(StylerDialog stylerDialog); void changeEditorComponent(JComponent newComponent); void changeEditorComponent(AbstractRulesList ruleList); JComponent createEditorComponent(AbstractRulesList ruleList); void dispose(); }### Answer:
@Test public void testAtlasStylerPane() throws Throwable { if (!TestingUtil.hasGui()) return; StylerDialog asd = new StylerDialog(null, atlasStylerPolygon, null); TestingUtil.testGui(asd); } |
### Question:
AddRulesListDialog extends AtlasDialog implements Cancellable { public AddRulesListDialog(Component owner, AtlasStyler atlasStyler) { super(owner, ASUtil.R("AddRulesListDialog.title", atlasStyler.getTitle())); this.owner = owner; this.atlasStyler = atlasStyler; jComboBoxRuleListType = new RulesListJComboBox(atlasStyler); jComboBoxRuleListType.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { updateImage(); } }); initGui(); } AddRulesListDialog(Component owner, AtlasStyler atlasStyler); @Override void cancel(); @Override boolean close(); }### Answer:
@Test public void testAddRulesListDialog() throws Throwable { if (!TestingUtil.isInteractive()) return; AtlasStylerVector as = AsTestingUtil .getAtlasStyler(TestDatasetsVector.countryShp); AddRulesListDialog addRulesListDialog = new AddRulesListDialog(null, as); TestingUtil.testGui(addRulesListDialog); } |
### Question:
DpEntryFactory { public static DpEntry create(AtlasConfigEditable ace, File file, Component owner) throws AtlasImportException { for (DpEntryTesterInterface test : testers) { if (test.test(owner, file)) return test.create(ace, file, owner); } return null; } private DpEntryFactory(); static DpEntry create(AtlasConfigEditable ace, File file,
Component owner); static boolean test(File file, Component owner); static final FileFilter FILEFILTER_ALL_DPE_IMPORTABLE; final static List<DpEntryTesterInterface> testers; }### Answer:
@Test public void testCreate() throws IOException, URISyntaxException { } |
### Question:
GraphicEditGUI extends AbstractStyleEditGUI { public GraphicEditGUI(final AtlasStylerVector asv, final Graphic graphic_, GeometryForm geomForm) { super(asv); this.geometryForm = geomForm; if (graphic_ != null) { this.graphic = graphic_; } else { this.graphic = StylingUtil.STYLE_BUILDER.createGraphic(); firePropertyChange(PROPERTY_UPDATED, null, null); } final int countGraphicalSymbols = graphic.graphicalSymbols().size(); if (countGraphicalSymbols == 0) { graphic.graphicalSymbols().add( StylingUtil.STYLE_BUILDER.createMark(MARKTYPE.square .toWellKnownName())); } else if (countGraphicalSymbols > 1) { LOGGER.warn("The Graphic " + graphic + " contains more than one graphical symbols. Only the first one will be kept."); GraphicalSymbol firstGraphicalSymbol = graphic.graphicalSymbols() .get(0); graphic.graphicalSymbols().clear(); graphic.graphicalSymbols().add(firstGraphicalSymbol); } initialize(); } GraphicEditGUI(final AtlasStylerVector asv, final Graphic graphic_,
GeometryForm geomForm); }### Answer:
@Test public void testGraphicEditGUI() throws Throwable { if (!TestingUtil.isInteractive()) return; Graphic g = StylingUtil.STYLE_BUILDER.createGraphic(); GraphicEditGUI graphicEditGUI = new GraphicEditGUI( AsTestingUtil.getAtlasStyler(TestDatasetsVector.countryShp), g, GeometryForm.POINT); TestingUtil.testGui(graphicEditGUI, 220); } |
### Question:
SVGSelector extends CancellableDialogAdapter { public void changeURL(URL newUrl) { url = newUrl; LOGGER.debug("Changing " + this.getClass().getSimpleName() + " URL to " + url.getFile()); jList = null; rescan(false); jScrollPane1.setViewportView(getJList()); jTextFieldURL.setText(url.getFile()); jButtonUp.setEnabled(!url.toString().equals( FreeMapSymbols.SVG_URL + "/")); } SVGSelector(Window owner, GeometryForm geomForm,
ExternalGraphic[] preSelection); @Override void cancel(); void changeURL(URL newUrl); static final String PROPERTY_UPDATED; }### Answer:
@Test public void testSvgSelectorGui() throws Throwable { if (!TestingUtil.hasGui()) return; SVGSelector svgSelector = new SVGSelector(null, GeometryForm.POLYGON, null); svgSelector.changeURL(new URL(FreeMapSymbols.SVG_URL + "/" + "osm")); TestingUtil.testGui(svgSelector,600); } |
### Question:
GPProps { protected static void init(final String propertiesFilename, final String appDirname) { GpUtil.initGpLogging(); GPProps.propertiesFilename = propertiesFilename; GPProps.appDirname = appDirname; try { final FileInputStream inStream = new FileInputStream( getPropertiesFile()); try { properties.load(inStream); } finally { inStream.close(); } } catch (final Exception e) { LOGGER.error(e); ExceptionDialog .show(null, e,"Cannot save properties","<html>The properties file is not accessible. <br />Please check the permissions for <b>"+getPropertiesFile().getAbsolutePath()+"</b> to permanently keep your Geopublisher configuration.</html>"); } upgrade(); } static Properties getProperties(); static String get(final Keys key); static String get(final Keys key, final String def); static boolean getBoolean(final Keys key); static boolean getBoolean(Keys key, boolean defaultValue); static Integer getInt(final Keys key, final Integer def); static void resetProperties(final Component guiOwner); static final void set(final Keys key, final Boolean value); static final void set(final Keys key, final Integer value); static final void set(final Keys key, final String value); static void store(); static void upgrade(); static final String PROPERTIES_FILENAME; static final String PROPERTIES_FOLDER; }### Answer:
@Test public void testInit() { GPProps.init(GPProps.PROPERTIES_FILENAME, GPProps.PROPERTIES_FOLDER); } |
### Question:
GpUtil { public static void initBugReporting() { ExceptionDialog.setMailDestinationAddress("[email protected]"); ExceptionDialog.setSmtpMailer(bugReportMailer); ExceptionDialog.addAdditionalAppInfo(ReleaseUtil .getVersionInfo(GpUtil.class)); } static void initGpLogging(); static void initBugReporting(); static Set<Locale> getAvailableLocales(); static String R(String key, Object... values); static String R(final String key, Locale reqLanguage,
final Object... values); final static String getRandomID(String prefix); static void writeCpg(DpLayerVectorFeatureSource dpe); static File chooseFileOpenFallback(Component parent,
File startFolder, String title, FileExtensionFilter... filters); static void checkAndResetTmpDir(String path); static final FileExtensionFilter IMAGE_FILE_FILTER; static final FileExtensionFilter GIS_FILE_FILTER; static final Mailer bugReportMailer; static final IOFileFilter FontsFilesFilter; static final MbDecimalFormatter MbDecimalFormatter; }### Answer:
@Test public void testSendGPBugReport_WithAddInfos() { GpUtil.initBugReporting(); assertEquals(3, ExceptionDialog.getAdditionalAppInfo().size()); for (Object o : ExceptionDialog.getAdditionalAppInfo()) { System.out.println(o.toString()); } } |
### Question:
GpUtil { public static void initGpLogging() throws FactoryConfigurationError { if (Logger.getRootLogger().getAllAppenders().hasMoreElements()) return; DOMConfigurator.configure(GPProps.class .getResource("/geopublishing_log4j.xml")); Logger.getRootLogger().addAppender( Logger.getLogger("dummy").getAppender("gpFileLogger")); String logLevelStr = GPProps.get(Keys.logLevel); if (logLevelStr != null) { Logger.getRootLogger().setLevel(Level.toLevel(logLevelStr)); } initBugReporting(); } static void initGpLogging(); static void initBugReporting(); static Set<Locale> getAvailableLocales(); static String R(String key, Object... values); static String R(final String key, Locale reqLanguage,
final Object... values); final static String getRandomID(String prefix); static void writeCpg(DpLayerVectorFeatureSource dpe); static File chooseFileOpenFallback(Component parent,
File startFolder, String title, FileExtensionFilter... filters); static void checkAndResetTmpDir(String path); static final FileExtensionFilter IMAGE_FILE_FILTER; static final FileExtensionFilter GIS_FILE_FILTER; static final Mailer bugReportMailer; static final IOFileFilter FontsFilesFilter; static final MbDecimalFormatter MbDecimalFormatter; }### Answer:
@Test @Ignore public void testInitGpLogging() { GpUtil.initGpLogging(); assertEquals(2, countRootLoggers()); GpUtil.initGpLogging(); assertEquals(2, countRootLoggers()); } |
### Question:
ASProps { protected static void init(String propertiesFilename, String appDirname) { ASProps.propertiesFilename = propertiesFilename; ASProps.appDirname = appDirname; try { properties.load(new FileInputStream(getPropertiesFile())); } catch (FileNotFoundException e) { } catch (IOException e) { LOGGER.error(e); } } static final String get(Keys key); static boolean get(Keys key, boolean def); static String get(Keys key, String def); static Integer getInt(Keys key, Integer def); static Component getOwner(); static void resetProperties(); static final void set(Keys key, Integer value); static final void set(Keys key, String value); static void setOwner(Window owner); static void store(); static final String DEFAULT_CHARSET_NAME; static final String PROPERTIES_FILENAME; static final String PROPERTIES_FOLDER; }### Answer:
@Test public void testInit() { ASProps.init(ASProps.PROPERTIES_FILENAME, ASProps.PROPERTIES_FOLDER); } |
### Question:
BooleanConverter extends DefaultObjectConverter<Boolean> { @Override public String toString(Boolean object, ConverterContext context) { if (Boolean.FALSE.equals(object)) { return getFalse(); } else if (Boolean.TRUE.equals(object)) { return getTrue(); } else { return getNull(); } } BooleanConverter(); @Override String toString(Boolean object, ConverterContext context); @Override Boolean fromString(String string, ConverterContext context); }### Answer:
@Test public void testToString() throws Exception { Assert.assertEquals("True", _converter.toString(true)); Assert.assertEquals("False", _converter.toString(false)); } |
### Question:
BooleanConverter extends DefaultObjectConverter<Boolean> { @Override public Boolean fromString(String string, ConverterContext context) { if (string.equalsIgnoreCase(getTrue())) { return Boolean.TRUE; } else if (string.equalsIgnoreCase("true")) { return Boolean.TRUE; } else if (string.equalsIgnoreCase(getFalse())) { return Boolean.FALSE; } else if (string.equalsIgnoreCase("false")) { return Boolean.FALSE; } else { return null; } } BooleanConverter(); @Override String toString(Boolean object, ConverterContext context); @Override Boolean fromString(String string, ConverterContext context); }### Answer:
@Test public void testFromString() throws Exception { Assert.assertEquals(Boolean.TRUE, _converter.fromString("true")); Assert.assertEquals(Boolean.TRUE, _converter.fromString("True")); Assert.assertEquals(Boolean.FALSE, _converter.fromString("false")); Assert.assertEquals(Boolean.FALSE, _converter.fromString("False")); } |
### Question:
PercentConverter extends DoubleConverter { @Override public Double fromString(String string, ConverterContext context) { Number number = numberFromString(string, context); if (number == null) { number = Double.parseDouble(string); } if (string != null && !string.trim().endsWith("%") && number != null) { number = number.doubleValue() / 100; } return number != null ? number.doubleValue() : null; } PercentConverter(); PercentConverter(Locale locale); PercentConverter(NumberFormat format); @Override Double fromString(String string, ConverterContext context); static final ConverterContext CONTEXT; }### Answer:
@Test public void testFromString() throws Exception { Assert.assertEquals(0.5, _converter.fromString("50%"), 0.001); Assert.assertEquals(0.5, _converter.fromString("50"), 0.001); Assert.assertEquals(0.005, _converter.fromString("0.5"), 0.001); } |
### Question:
DecorationPane extends StackPane implements DecorationSupport { public Parent getContent() { return _content; } DecorationPane(); DecorationPane(Parent content); Parent getContent(); void setContent(Parent content); @Override void positionInArea(Node child, double areaX, double areaY, double areaWidth, double areaHeight, double areaBaselineOffset, HPos hAlignment, VPos vAlignment); }### Answer:
@Test public void loadFXMLWithExplicitContent() throws Exception { URL resource = DecorationPaneTest.class.getClassLoader().getResource("jidefx/scene/control/decoration/DecorationPaneTestExplicitContent.fxml"); FXMLLoader loader = new FXMLLoader(resource); loader.load(); DecorationPaneTestController controller = loader.getController(); assertNotNull(controller.decorationPane); assertNotNull(controller.content); assertEquals(controller.content, controller.decorationPane.getContent()); }
@Test public void loadFXMLWithImplicitContent() throws Exception { URL resource = DecorationPaneTest.class.getClassLoader().getResource("jidefx/scene/control/decoration/DecorationPaneTestImplicitContent.fxml"); FXMLLoader loader = new FXMLLoader(resource); loader.load(); DecorationPaneTestController controller = loader.getController(); assertNotNull(controller.decorationPane); assertNotNull(controller.content); assertEquals(controller.content, controller.decorationPane.getContent()); } |
### Question:
HelloWorld { public void setPhrase( String phrase ) throws IllegalArgumentException { if( phrase == null ) { throw new IllegalArgumentException( "Phrase may not be null " ); } this.phrase = phrase; } String getPhrase(); void setPhrase( String phrase ); String getName(); void setName( String name ); String say(); }### Answer:
@Test public void givenHelloWorldWhenSetInvalidPhraseThenThrowException() { try { helloWorld.setPhrase( null ); fail( "Should not be allowed to set phrase to null" ); } catch( IllegalArgumentException e ) { } } |
### Question:
ValueBuilderTemplate { public T newInstance( ModuleDescriptor module ) { ValueBuilder<T> builder = module.instance().newValueBuilder( type ); build( builder.prototype() ); return builder.newInstance(); } protected ValueBuilderTemplate( Class<T> type ); T newInstance( ModuleDescriptor module ); }### Answer:
@Test public void testTemplate() { new TestBuilder( "Rickard" ).newInstance( module ); }
@Test public void testAnonymousTemplate() { new ValueBuilderTemplate<TestValue>( TestValue.class ) { @Override protected void build( TestValue prototype ) { prototype.name().set( "Rickard" ); } }.newInstance( module ); } |
### Question:
HelloWorld { public void setName( String name ) throws IllegalArgumentException { if( name == null ) { throw new IllegalArgumentException( "Name may not be null " ); } this.name = name; } String getPhrase(); void setPhrase( String phrase ); String getName(); void setName( String name ); String say(); }### Answer:
@Test public void givenHelloWorldWhenSetInvalidNameThenThrowException() { try { helloWorld.setName( null ); fail( "Should not be allowed to set name to null" ); } catch( IllegalArgumentException e ) { } } |
### Question:
Collectors { public static <T> Collector<T, ?, T> single() throws IllegalArgumentException { Supplier<T> thrower = () -> { throw new IllegalArgumentException( "No or more than one element in stream" ); }; return java.util.stream.Collectors.collectingAndThen( java.util.stream.Collectors.reducing( ( a, b ) -> null ), optional -> optional.orElseGet( thrower ) ); } private Collectors(); static Collector<T, ?, T> single(); static Collector<T, ?, Optional<T>> singleOrEmpty(); static Collector<T, ?, Map<K, U>> toMap(); static Collector<T, ?, M> toMap( Supplier<M> mapSupplier ); static Collector<T, ?, M> toMap( Function<? super T, ? extends K> keyMapper,
Function<? super T, ? extends U> valueMapper,
Supplier<M> mapSupplier ); static Collector<T, ?, Map<K, U>> toMapWithNullValues(); static Collector<T, ?, M> toMapWithNullValues( Supplier<M> mapSupplier ); static Collector<T, ?, M> toMapWithNullValues( Function<? super T, ? extends K> keyMapper,
Function<? super T, ? extends U> valueMapper,
Supplier<M> mapSupplier ); }### Answer:
@Test public void single() { assertThat( Stream.of( 1L ).collect( Collectors.single() ), is( 1L ) ); try { Stream.of().collect( Collectors.single() ); fail( "Should have failed" ); } catch( IllegalArgumentException ex ) {} try { Stream.of( 1, 1 ).collect( Collectors.single() ); fail( "Should have failed" ); } catch( IllegalArgumentException ex ) {} try { Stream.of( 1, 1, 1 ).collect( Collectors.single() ); fail( "Should have failed" ); } catch( IllegalArgumentException ex ) {} } |
### Question:
Collectors { public static <T extends Map.Entry<K, U>, K, U> Collector<T, ?, Map<K, U>> toMap() { return toMap( Map.Entry::getKey, Map.Entry::getValue, HashMap::new ); } private Collectors(); static Collector<T, ?, T> single(); static Collector<T, ?, Optional<T>> singleOrEmpty(); static Collector<T, ?, Map<K, U>> toMap(); static Collector<T, ?, M> toMap( Supplier<M> mapSupplier ); static Collector<T, ?, M> toMap( Function<? super T, ? extends K> keyMapper,
Function<? super T, ? extends U> valueMapper,
Supplier<M> mapSupplier ); static Collector<T, ?, Map<K, U>> toMapWithNullValues(); static Collector<T, ?, M> toMapWithNullValues( Supplier<M> mapSupplier ); static Collector<T, ?, M> toMapWithNullValues( Function<? super T, ? extends K> keyMapper,
Function<? super T, ? extends U> valueMapper,
Supplier<M> mapSupplier ); }### Answer:
@Test public void toMap() { Map<String, String> input = new LinkedHashMap<>(); input.put( "foo", "bar" ); input.put( "bazar", "cathedral" ); Map<String, String> output = input.entrySet().stream().collect( Collectors.toMap() ); assertThat( output.get( "foo" ), equalTo( "bar" ) ); assertThat( output.get( "bazar" ), equalTo( "cathedral" ) ); }
@Test public void toMapRejectNullValues() { Map<String, String> input = new LinkedHashMap<>(); input.put( "foo", "bar" ); input.put( "bazar", null ); try { input.entrySet().stream().collect( Collectors.toMap() ); fail( "Should have failed, that's the default Map::merge behaviour" ); } catch( NullPointerException expected ) {} } |
### Question:
Collectors { public static <T extends Map.Entry<K, U>, K, U> Collector<T, ?, Map<K, U>> toMapWithNullValues() { return toMapWithNullValues( Map.Entry::getKey, Map.Entry::getValue, HashMap::new ); } private Collectors(); static Collector<T, ?, T> single(); static Collector<T, ?, Optional<T>> singleOrEmpty(); static Collector<T, ?, Map<K, U>> toMap(); static Collector<T, ?, M> toMap( Supplier<M> mapSupplier ); static Collector<T, ?, M> toMap( Function<? super T, ? extends K> keyMapper,
Function<? super T, ? extends U> valueMapper,
Supplier<M> mapSupplier ); static Collector<T, ?, Map<K, U>> toMapWithNullValues(); static Collector<T, ?, M> toMapWithNullValues( Supplier<M> mapSupplier ); static Collector<T, ?, M> toMapWithNullValues( Function<? super T, ? extends K> keyMapper,
Function<? super T, ? extends U> valueMapper,
Supplier<M> mapSupplier ); }### Answer:
@Test public void toMapWithNullValues() { Map<String, String> input = new LinkedHashMap<>(); input.put( "foo", "bar" ); input.put( "bazar", null ); Map<String, String> output = input.entrySet().stream().collect( Collectors.toMapWithNullValues() ); assertThat( output.get( "foo" ), equalTo( "bar" ) ); assertThat( output.get( "bazar" ), nullValue() ); } |
### Question:
UnitOfWorkTemplate { @SuppressWarnings( "unchecked" ) public RESULT withModule( Module module ) throws ThrowableType, UnitOfWorkCompletionException { int loop = 0; ThrowableType ex = null; do { UnitOfWork uow = module.unitOfWorkFactory().newUnitOfWork( usecase ); try { RESULT result = withUnitOfWork( uow ); if( complete ) { try { uow.complete(); return result; } catch( ConcurrentEntityModificationException e ) { ex = (ThrowableType) e; } } } catch( Throwable e ) { ex = (ThrowableType) e; } finally { uow.discard(); } } while( loop++ < retries ); throw ex; } protected UnitOfWorkTemplate(); protected UnitOfWorkTemplate( int retries, boolean complete ); protected UnitOfWorkTemplate( Usecase usecase, int retries, boolean complete ); @SuppressWarnings( "unchecked" ) RESULT withModule( Module module ); }### Answer:
@Test public void testTemplate() throws UnitOfWorkCompletionException { new UnitOfWorkTemplate<Void, RuntimeException>() { @Override protected Void withUnitOfWork( UnitOfWork uow ) throws RuntimeException { new EntityBuilderTemplate<TestEntity>( TestEntity.class ) { @Override protected void build( TestEntity prototype ) { prototype.name().set( "Rickard" ); } }.newInstance( module.instance() ); return null; } }.withModule( module.instance() ); } |
### Question:
HasTypesCollectors { public static <T extends HasTypes> Collector<T, ?, List<T>> closestTypes( T hasTypes ) { return hasTypesToListCollector( hasTypes, new HasAssignableToType<>( hasTypes ) ); } private HasTypesCollectors(); static Collector<T, ?, Optional<T>> matchingType( T hasTypes ); static Collector<T, ?, Optional<T>> closestType( T hasTypes ); static Collector<T, ?, List<T>> matchingTypes( T hasTypes ); static Collector<T, ?, List<T>> closestTypes( T hasTypes ); static Collector<T, ?, Optional<T>> matchingType( Type type ); static Collector<T, ?, Optional<T>> closestType( Type type ); static Collector<T, ?, List<T>> matchingTypes( Type type ); static Collector<T, ?, List<T>> closestTypes( Type type ); }### Answer:
@Test public void selectClosestValueTypes() { List<ValueType> list = new ArrayList<ValueType>() {{ add( ValueType.of( String.class ) ); add( ValueType.of( Identity.class ) ); }}; List<ValueType> result = list.stream() .collect( HasTypesCollectors.closestTypes( StringIdentity.class ) ); assertThat( result.size(), is( 1 ) ); assertThat( result.get( 0 ), equalTo( ValueType.of( Identity.class ) ) ); } |
### Question:
QualifiedName implements Comparable<QualifiedName> { public String type() { return typeName.normalized(); } QualifiedName( TypeName typeName, String name ); static QualifiedName fromAccessor( AccessibleObject method ); static QualifiedName fromClass( Class type, String name ); static QualifiedName fromName( String type, String name ); static QualifiedName fromFQN( String fullQualifiedName ); String type(); String name(); String toURI(); String toNamespace(); @Override String toString(); @Override boolean equals( Object o ); @Override int hashCode(); @Override int compareTo( QualifiedName other ); boolean isOriginatingFrom( Class<?> mixinType ); }### Answer:
@Test public void testQualifiedNameWithDollar() { assertThat( "Name containing dollar is modified", new QualifiedName( TypeName.nameOf( "Test$Test" ), "satisfiedBy" ).type(), equalTo( "Test-Test" ) ); } |
### Question:
QualifiedName implements Comparable<QualifiedName> { public static QualifiedName fromFQN( String fullQualifiedName ) { Objects.requireNonNull( fullQualifiedName, "qualifiedName" ); int idx = fullQualifiedName.lastIndexOf( ":" ); if( idx == -1 ) { throw new IllegalArgumentException( "Name '" + fullQualifiedName + "' is not a qualified name" ); } final String type = fullQualifiedName.substring( 0, idx ); final String name = fullQualifiedName.substring( idx + 1 ); return new QualifiedName( TypeName.nameOf( type ), name ); } QualifiedName( TypeName typeName, String name ); static QualifiedName fromAccessor( AccessibleObject method ); static QualifiedName fromClass( Class type, String name ); static QualifiedName fromName( String type, String name ); static QualifiedName fromFQN( String fullQualifiedName ); String type(); String name(); String toURI(); String toNamespace(); @Override String toString(); @Override boolean equals( Object o ); @Override int hashCode(); @Override int compareTo( QualifiedName other ); boolean isOriginatingFrom( Class<?> mixinType ); }### Answer:
@Test public void nonNullArguments4() { assertThrows( NullPointerException.class, () -> QualifiedName.fromFQN( null ) ); } |
### Question:
QualifiedName implements Comparable<QualifiedName> { public static QualifiedName fromAccessor( AccessibleObject method ) { Objects.requireNonNull( method, "method" ); return fromClass( ( (Member) method ).getDeclaringClass(), ( (Member) method ).getName() ); } QualifiedName( TypeName typeName, String name ); static QualifiedName fromAccessor( AccessibleObject method ); static QualifiedName fromClass( Class type, String name ); static QualifiedName fromName( String type, String name ); static QualifiedName fromFQN( String fullQualifiedName ); String type(); String name(); String toURI(); String toNamespace(); @Override String toString(); @Override boolean equals( Object o ); @Override int hashCode(); @Override int compareTo( QualifiedName other ); boolean isOriginatingFrom( Class<?> mixinType ); }### Answer:
@Test public void nonNullArguments5() { assertThrows( NullPointerException.class, () -> QualifiedName.fromAccessor( null ) ); } |
### Question:
QualifiedName implements Comparable<QualifiedName> { public static QualifiedName fromClass( Class type, String name ) { return new QualifiedName( TypeName.nameOf( type ), name ); } QualifiedName( TypeName typeName, String name ); static QualifiedName fromAccessor( AccessibleObject method ); static QualifiedName fromClass( Class type, String name ); static QualifiedName fromName( String type, String name ); static QualifiedName fromFQN( String fullQualifiedName ); String type(); String name(); String toURI(); String toNamespace(); @Override String toString(); @Override boolean equals( Object o ); @Override int hashCode(); @Override int compareTo( QualifiedName other ); boolean isOriginatingFrom( Class<?> mixinType ); }### Answer:
@Test public void nonNullArguments6() { assertThrows( NullPointerException.class, () -> QualifiedName.fromClass( null, "satisfiedBy" ) ); }
@Test public void nonNullArguments7() { assertThrows( NullPointerException.class, () -> QualifiedName.fromClass( null, null ) ); } |
### Question:
ScriptMixin implements InvocationHandler, ScriptReloadable, ScriptRedirect, ScriptAttributes, ScriptAttributes.All { @Override public Object invoke( Object proxy, Method method, Object[] objects ) throws Throwable { Object result = ( (Invocable) engine ).invokeFunction( method.getName(), objects ); return castInvocationResult( method.getReturnType(), result ); } ScriptMixin( @Structure PolygeneSPI spi,
@This Object thisComposite,
@State StateHolder state,
@Structure Layer layer,
@Structure Module module,
@Structure Application application ); @Override Object invoke( Object proxy, Method method, Object[] objects ); @Override void reloadScript(); @Override void setStdOut( Writer writer ); @Override void setStdErr( Writer writer ); @Override void setStdIn( Reader reader ); @Override Object getAttribute( String name ); @Override Object getEngineAttribute( String name ); @Override Object getGlobalAttribute( String name ); @Override void setEngineAttribute( String name, Object value ); @Override void setGlobalAttribute( String name, Object value ); }### Answer:
@Test public void testInvoke() throws Throwable { DomainType domain1 = transientBuilderFactory.newTransient( DomainType.class ); assertThat(domain1.do1("her message"), equalTo("[her message]") ); } |
### Question:
EntityTypeSerializer { public EntityTypeSerializer() { dataTypes.put( String.class.getName(), XMLSchema.STRING ); dataTypes.put( Integer.class.getName(), XMLSchema.INT ); dataTypes.put( Boolean.class.getName(), XMLSchema.BOOLEAN ); dataTypes.put( Byte.class.getName(), XMLSchema.BYTE ); dataTypes.put( BigDecimal.class.getName(), XMLSchema.DECIMAL ); dataTypes.put( Double.class.getName(), XMLSchema.DOUBLE ); dataTypes.put( Long.class.getName(), XMLSchema.LONG ); dataTypes.put( Short.class.getName(), XMLSchema.SHORT ); dataTypes.put( Instant.class.getName(), XMLSchema.LONG ); dataTypes.put( OffsetDateTime.class.getName(), XMLSchema.DATETIME ); dataTypes.put( ZonedDateTime.class.getName(), XMLSchema.DATETIME ); dataTypes.put( LocalDateTime.class.getName(), XMLSchema.DATETIME ); dataTypes.put( LocalDate.class.getName(), XMLSchema.DATE ); dataTypes.put( LocalTime.class.getName(), XMLSchema.TIME ); dataTypes.put( Duration.class.getName(), XMLSchema.DURATION ); dataTypes.put( Period.class.getName(), XMLSchema.DURATION ); } EntityTypeSerializer(); Iterable<Statement> serialize( final EntityDescriptor entityDescriptor ); }### Answer:
@Test public void testEntityTypeSerializer() throws RDFHandlerException { EntityDescriptor entityDescriptor = module.entityDescriptor(TestEntity.class.getName()); Iterable<Statement> graph = serializer.serialize( entityDescriptor ); String[] prefixes = new String[]{ "rdf", "dc", " vc", "polygene" }; String[] namespaces = new String[]{ Rdfs.RDF, DcRdf.NAMESPACE, "http: new RdfXmlSerializer().serialize( graph, new PrintWriter( System.out ), prefixes, namespaces ); } |
### Question:
SendMail { public void sendSimpleMail(String subject, String to, String context) { SimpleMailMessage simpleMailMessage = new SimpleMailMessage(); simpleMailMessage.setFrom(from); simpleMailMessage.setTo(to); simpleMailMessage.setSubject(subject); simpleMailMessage.setText(context); try { javaMailSender.send(simpleMailMessage); log.info("sucessss:{}", from); } catch (Exception e) { log.info("error:{}", from); } } void sendSimpleMail(String subject, String to, String context); void sendFileMail(String subject, String to, String context, String filepath); void sendHtmlMail(String subject, String to, String context); void sendtemplateHtmlMail(String subject, String to, String name); void sendstaticMail(String subject, String to, String context, String filepath, String fileid); }### Answer:
@Test public void hello() throws Exception { sendMail.sendSimpleMail("aaaa","[email protected]","sdas"); } |
### Question:
SendMail { public void sendtemplateHtmlMail(String subject, String to, String name) { MimeMessage mimeMessage = javaMailSender.createMimeMessage(); try { MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true); helper.setSubject(subject); helper.setTo(to); helper.setFrom(from); String filepath = "C:\\Users\\Administrator\\Desktop\\ocly.png"; FileSystemResource resource = new FileSystemResource(new File(filepath)); String filename = filepath.substring(filepath.lastIndexOf(File.separator)); helper.addAttachment(filename, resource); Context context = new Context(); context.setVariable("name", name); String templateHtml = templateEngine.process("emailTemplate", context); log.info("来看看模板长啥样 {}",templateHtml); helper.setText(templateHtml, true); helper.addInline("ocly", resource); javaMailSender.send(mimeMessage); log.info("模板邮件发送成功"); } catch (MessagingException e) { log.error("模板邮件发送失败"); } } void sendSimpleMail(String subject, String to, String context); void sendFileMail(String subject, String to, String context, String filepath); void sendHtmlMail(String subject, String to, String context); void sendtemplateHtmlMail(String subject, String to, String name); void sendstaticMail(String subject, String to, String context, String filepath, String fileid); }### Answer:
@Test public void hellomaiTemplate() throws Exception { sendMail.sendtemplateHtmlMail("你好,模板邮件加附件加图片","[email protected]","Bocly"); } |
### Question:
DateConverterUtils { public static Date convert2Date(LocalDate localDate) { if (localDate == null) { return null; } return convert2Date(localDate.atStartOfDay()); } private DateConverterUtils(); static Date convert2Date(LocalDate localDate); static Date convert2Date(LocalDateTime localDateTime); static LocalDateTime convert2LocalDateTime(Date date); static LocalDate convert2LocalDate(Date date); static long convert2Timestamp(LocalDateTime localDateTime); }### Answer:
@Test public void shouldBeNull_whenInputLocalDateIsNull_ofConvert2Date() { LocalDate input = null; Date output = DateConverterUtils.convert2Date(input); Date expected = null; assertThat(output).isEqualTo(expected); }
@Test public void shouldBeOk_whenInputLocalDateIs20170101T010101_ofConvert2Date() { LocalDate input = createLocalDate("2017-01-01T01:01:01"); Date output = DateConverterUtils.convert2Date(input); Date expected = createDate("2017-01-01T00:00:00"); assertThat(output).isEqualTo(expected); }
@Test public void shouldBeNull_whenInputLocalDateTimeIsNull_ofConvert2Date() { LocalDateTime input = null; Date output = DateConverterUtils.convert2Date(input); Date expected = null; assertThat(output).isEqualTo(expected); }
@Test public void shouldBeOk_whenInputLocalDateTimeIs20170101T010101_ofConvert2Date() { LocalDateTime input = createLocalDateTime("2017-01-01T01:01:01"); Date output = DateConverterUtils.convert2Date(input); Date expected = createDate("2017-01-01T01:01:01"); assertThat(output).isEqualTo(expected); } |
### Question:
Base64Utils { public static String encode(byte[] data) { if (data == null) { return null; } return Base64.getEncoder().encodeToString(data); } private Base64Utils(); static String encode(byte[] data); static String encode(String data); static String decode(byte[] data); static String decode(String data); }### Answer:
@Test public void shouldBeOk_whenEncodeHelloString() { String input = "hello"; String output = Base64Utils.encode(input); String expected = "aGVsbG8="; assertThat(output).isEqualTo(expected); }
@Test public void shouldBeOk_whenEncodeHelloByte() { byte[] input = "hello".getBytes(); String output = Base64Utils.encode(input); String expected = "aGVsbG8="; assertThat(output).isEqualTo(expected); }
@Test public void shouldBeNull_whenEncodeNullString() { String input = null; String output = Base64Utils.encode(input); String expected = null; assertThat(output).isEqualTo(expected); }
@Test public void shouldBeNull_whenEncodeNullByte() { byte[] input = null; String output = Base64Utils.encode(input); String expected = null; assertThat(output).isEqualTo(expected); } |
### Question:
Base64Utils { public static String decode(byte[] data) { if (data == null) { return null; } try { return new String(Base64.getDecoder().decode(data)); } catch (IllegalArgumentException ex) { return null; } } private Base64Utils(); static String encode(byte[] data); static String encode(String data); static String decode(byte[] data); static String decode(String data); }### Answer:
@Test public void shouldBeNull_whenDecodeNullString() { String input = null; String output = Base64Utils.decode(input); String expected = null; assertThat(output).isEqualTo(expected); }
@Test public void shouldBeNull_whenDecodeNullByte() { byte[] input = null; String output = Base64Utils.decode(input); String expected = null; assertThat(output).isEqualTo(expected); }
@Test public void shouldBeNull_whenDecodeInvalidString() { String input = "aGVsbG8=xxxx"; String output = Base64Utils.decode(input); String expected = null; assertThat(output).isEqualTo(expected); }
@Test public void shouldBeNull_whenDecodeInvalidByte() { byte[] input = "aGVsbG8=xxxx".getBytes(); String output = Base64Utils.decode(input); String expected = null; assertThat(output).isEqualTo(expected); }
@Test public void shouldBeOk_whenDecodeHelloString() { String input = "aGVsbG8="; String output = Base64Utils.decode(input); String expected = "hello"; assertThat(output).isEqualTo(expected); }
@Test public void shouldBeOk_whenDecodeHelloByte() { byte[] input = "aGVsbG8=".getBytes(); String output = Base64Utils.decode(input); String expected = "hello"; assertThat(output).isEqualTo(expected); } |
### Question:
CookieSpecBuilder { public String build() { List<String> builder = new ArrayList<>(); builder.add(String.format("%s=%s", getKey(), getValue())); if (hasText(getPath())) { builder.add(String.format("Path=%s", getPath())); } if (Objects.equals(Boolean.TRUE, getHttpOnly())) { builder.add("HttpOnly"); } if (hasText(getSameSite())) { builder.add(String.format("SameSite=%s", getSameSite())); } if (Objects.equals(Boolean.TRUE, getSecure())) { builder.add("Secure"); } if (getMaxAge() > 0) { builder.add(String.format("Max-Age=%s", getMaxAge())); } if (getExpires() != null) { builder.add(String.format("Expires=%s", makeExpires())); } return builder.stream().collect(Collectors.joining("; ")); } CookieSpecBuilder(String key, String value); CookieSpecBuilder setPath(String path); CookieSpecBuilder setHttpOnly(Boolean httpOnly); CookieSpecBuilder setSameSite(String s); CookieSpecBuilder sameSiteStrict(); CookieSpecBuilder setSecure(Boolean s); CookieSpecBuilder setExpires(LocalDateTime expires); CookieSpecBuilder setMaxAge(int maxAge); String build(); String getKey(); String getValue(); String getPath(); Boolean getHttpOnly(); String getSameSite(); Boolean getSecure(); LocalDateTime getExpires(); int getMaxAge(); }### Answer:
@Test public void shouldBeOk_whenHaveOnlyKeyValue() { String output = new CookieSpecBuilder("X-CSRF-Token", "xyz").build(); String expected = "X-CSRF-Token=xyz; Path=/; HttpOnly"; assertThat(output).isEqualTo(expected); } |
### Question:
QuerystringBuilder { public String build() { return getParams().entrySet() .stream() .map(param -> param.getKey() + "=" + encode(param.getValue())) .collect(Collectors.joining("&")); } QuerystringBuilder addParameter(String name, String value); String build(); }### Answer:
@Test public void shouldBeEmptyString_whenEmptyParameter() { QuerystringBuilder input = new QuerystringBuilder(); String output = input.build(); String expected = ""; assertThat(output).isEqualTo(expected); } |
### Question:
DefaultUUIDGenerator implements UUIDGenerator { @Override public String generate() { return UUID.randomUUID().toString(); } @Override String generate(); }### Answer:
@Test public void test() { String output = generator.generate(); int expected = 36; assertThat(output.length()).isEqualTo(expected); } |
### Question:
DefaultIdGenerator implements IdGenerator { @Override public String generate() { return ObjectId.get().toString(); } @Override String generate(); }### Answer:
@Test public void test() { String output = generator.generate(); int expected = 24; assertThat(output.length()).isEqualTo(expected); } |
### Question:
DefaultUserDetails implements UserDetails { @Override public Collection<? extends GrantedAuthority> getAuthorities() { return authorities().stream() .map(SimpleGrantedAuthority::new) .collect(Collectors.toList()); } @Override Collection<? extends GrantedAuthority> getAuthorities(); @Override String getPassword(); @Override String getUsername(); @Override boolean isAccountNonExpired(); @Override boolean isAccountNonLocked(); @Override boolean isCredentialsNonExpired(); @Override boolean isEnabled(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer:
@Test public void shouldBeSingleElement() { Collection<? extends GrantedAuthority> output = userDetails.getAuthorities(); int expected = 1; assertThat(output.size()).isEqualTo(expected); assertThat(output.iterator().next().getAuthority()).isEqualTo("admin"); } |
### Question:
DefaultUserDetails implements UserDetails { @Override public boolean isAccountNonExpired() { return true; } @Override Collection<? extends GrantedAuthority> getAuthorities(); @Override String getPassword(); @Override String getUsername(); @Override boolean isAccountNonExpired(); @Override boolean isAccountNonLocked(); @Override boolean isCredentialsNonExpired(); @Override boolean isEnabled(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer:
@Test public void shouldBeTrue_whenIsAccountNonExpired() { boolean output = userDetails.isAccountNonExpired(); boolean expected = true; assertThat(output).isEqualTo(expected); } |
### Question:
DefaultUserDetails implements UserDetails { @Override public boolean isAccountNonLocked() { return true; } @Override Collection<? extends GrantedAuthority> getAuthorities(); @Override String getPassword(); @Override String getUsername(); @Override boolean isAccountNonExpired(); @Override boolean isAccountNonLocked(); @Override boolean isCredentialsNonExpired(); @Override boolean isEnabled(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer:
@Test public void shouldBeTrue_whenIsAccountNonLocked() { boolean output = userDetails.isAccountNonLocked(); boolean expected = true; assertThat(output).isEqualTo(expected); } |
### Question:
DefaultUserDetails implements UserDetails { @Override public boolean isCredentialsNonExpired() { return true; } @Override Collection<? extends GrantedAuthority> getAuthorities(); @Override String getPassword(); @Override String getUsername(); @Override boolean isAccountNonExpired(); @Override boolean isAccountNonLocked(); @Override boolean isCredentialsNonExpired(); @Override boolean isEnabled(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer:
@Test public void shouldBeTrue_whenIsCredentialsNonExpired() { boolean output = userDetails.isCredentialsNonExpired(); boolean expected = true; assertThat(output).isEqualTo(expected); } |
### Question:
DefaultUserDetails implements UserDetails { @Override public boolean isEnabled() { return true; } @Override Collection<? extends GrantedAuthority> getAuthorities(); @Override String getPassword(); @Override String getUsername(); @Override boolean isAccountNonExpired(); @Override boolean isAccountNonLocked(); @Override boolean isCredentialsNonExpired(); @Override boolean isEnabled(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer:
@Test public void shouldBeTrue_whenIsEnabled() { boolean output = userDetails.isEnabled(); boolean expected = true; assertThat(output).isEqualTo(expected); } |
### Question:
DefaultUserDetails implements UserDetails { @Override public int hashCode() { int hash = 5; return 89 * hash + Objects.hashCode(this.username); } @Override Collection<? extends GrantedAuthority> getAuthorities(); @Override String getPassword(); @Override String getUsername(); @Override boolean isAccountNonExpired(); @Override boolean isAccountNonLocked(); @Override boolean isCredentialsNonExpired(); @Override boolean isEnabled(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer:
@Test public void shouldBeMinus1405401465_whenCallHashCode() { int output = userDetails.hashCode(); int expected = -1405401465; assertThat(output).isEqualTo(expected); } |
### Question:
DefaultUserDetails implements UserDetails { @Override public boolean equals(Object obj) { return ObjectEquals.of(this) .equals(obj, (orgin, other) -> Objects.equals(orgin.getUsername(), other.getUsername())); } @Override Collection<? extends GrantedAuthority> getAuthorities(); @Override String getPassword(); @Override String getUsername(); @Override boolean isAccountNonExpired(); @Override boolean isAccountNonLocked(); @Override boolean isCredentialsNonExpired(); @Override boolean isEnabled(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer:
@Test public void shouldBeFalse_whenNotEqualsUsername() { UserDetails obj = DefaultUserDetails.builder() .username("admin") .build(); boolean output = userDetails.equals(obj); boolean expected = false; assertThat(output).isEqualTo(expected); }
@Test public void shouldBeTrue_whenEqualsUsername() { UserDetails obj = DefaultUserDetails.builder() .username("jittagornp") .build(); boolean output = userDetails.equals(obj); boolean expected = true; assertThat(output).isEqualTo(expected); } |
### Question:
SHA384Hashing extends AbstractHashing { @Override public String hash(byte[] data) { try { if (isEmpty(data)) { return null; } MessageDigest digest = MessageDigest.getInstance("SHA-384"); return new String(Hex.encode(digest.digest(data))); } catch (NoSuchAlgorithmException ex) { LOG.warn(null, ex); return null; } } @Override String hash(byte[] data); }### Answer:
@Test public void hashHelloWorld() { byte[] input = "Hello World".getBytes(); String output = hashing.hash(input); String expected = "99514329186b2f6ae4a1329e7ee6c610a729636335174ac6b740f9028396fcc803d0e93863a7c3d90f86beee782f4f3f"; assertThat(output).isEqualTo(expected); }
@Test public void hashPublicKey() throws IOException { try (InputStream inputStream = getClass().getResourceAsStream("/key/public-key.pub")) { byte[] input = IOUtils.toByteArray(inputStream); String output = hashing.hash(input); String expected = "0eea0c8acf694a8bf86e5c11873bd9aa1b4ab630d27b0ee434c885e4e0d198936ee10770f306f66d8eb618daa584972a"; assertThat(output).isEqualTo(expected); } } |
### Question:
ShortHashing extends AbstractHashing { @Override public String hash(byte[] data) { return subString(hashing.hash(data)); } ShortHashing(Hashing hashing, int length); @Override String hash(byte[] data); }### Answer:
@Test public void sholdBe32Characters() { String input = "Hello World"; String output = shortHashing.hash(input.getBytes()); System.out.println("output => " + output); assertTrue(shortHashing.matches(input.getBytes(), output)); } |
### Question:
CustomSession implements ExpiringSession, Serializable { @Override public int getMaxInactiveIntervalInSeconds() { return this.maxInactiveInterval; } CustomSession(); CustomSession(int maxInactiveInterval); void setMaxInactiveInterval(int interval); @Override void setMaxInactiveIntervalInSeconds(int interval); @Override int getMaxInactiveIntervalInSeconds(); @Override boolean isExpired(); @Override @SuppressWarnings("unchecked") T getAttribute(String attributeName); @Override Set<String> getAttributeNames(); Map<String, Object> getAttributes(); @Override void setAttribute(String attributeName, Object attributeValue); @Override void removeAttribute(String attributeName); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer:
@Test public void maxInactiveIntervalShouldBe1800_whenNewInstance() { CustomSession session = new CustomSession(); int maxInactiveInterval = session.getMaxInactiveIntervalInSeconds(); int expected = 1800; assertThat(maxInactiveInterval).isEqualTo(expected); } |
### Question:
CustomSession implements ExpiringSession, Serializable { public Map<String, Object> getAttributes() { return new HashMap<>(this.attributes); } CustomSession(); CustomSession(int maxInactiveInterval); void setMaxInactiveInterval(int interval); @Override void setMaxInactiveIntervalInSeconds(int interval); @Override int getMaxInactiveIntervalInSeconds(); @Override boolean isExpired(); @Override @SuppressWarnings("unchecked") T getAttribute(String attributeName); @Override Set<String> getAttributeNames(); Map<String, Object> getAttributes(); @Override void setAttribute(String attributeName, Object attributeValue); @Override void removeAttribute(String attributeName); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer:
@Test public void attributesShouldBeEmpty_whenNewInstance() { CustomSession session = new CustomSession(); Map<String, Object> attributes = session.getAttributes(); Map<String, Object> empty = new HashMap<>(); assertThat(attributes).isEqualTo(empty); } |
### Question:
CustomSession implements ExpiringSession, Serializable { @Override public boolean isExpired() { return isExpired(convert2Timestamp(now())); } CustomSession(); CustomSession(int maxInactiveInterval); void setMaxInactiveInterval(int interval); @Override void setMaxInactiveIntervalInSeconds(int interval); @Override int getMaxInactiveIntervalInSeconds(); @Override boolean isExpired(); @Override @SuppressWarnings("unchecked") T getAttribute(String attributeName); @Override Set<String> getAttributeNames(); Map<String, Object> getAttributes(); @Override void setAttribute(String attributeName, Object attributeValue); @Override void removeAttribute(String attributeName); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer:
@Test public void shouldBeNotExpire_whenNewInstance() { CustomSession session = new CustomSession(); boolean output = session.isExpired(); boolean expected = false; assertThat(output).isEqualTo(expected); }
@Test public void shouldBeNotExpire_whenMaxInactiveIntervalIsNegativeValue() { CustomSession session = new CustomSession(-1); boolean output = session.isExpired(); boolean expected = false; assertThat(output).isEqualTo(expected); } |
### Question:
DateConverterUtils { public static LocalDate convert2LocalDate(Date date) { if (date == null) { return null; } return convert2LocalDateTime(date).toLocalDate(); } private DateConverterUtils(); static Date convert2Date(LocalDate localDate); static Date convert2Date(LocalDateTime localDateTime); static LocalDateTime convert2LocalDateTime(Date date); static LocalDate convert2LocalDate(Date date); static long convert2Timestamp(LocalDateTime localDateTime); }### Answer:
@Test public void shouldBeNull_whenInputDateIsNull_ofConvert2LocalDate() { Date input = null; LocalDate output = DateConverterUtils.convert2LocalDate(input); LocalDate expected = null; assertThat(output).isEqualTo(expected); }
@Test public void shouldBeOk_whenInputDateIs20170101T010101_ofConvert2LocalDate() { Date input = createDate("2017-01-01T01:01:01"); LocalDate output = DateConverterUtils.convert2LocalDate(input); LocalDate expected = createLocalDate("2017-01-01T00:00:00"); assertThat(output).isEqualTo(expected); } |
### Question:
DateConverterUtils { public static LocalDateTime convert2LocalDateTime(Date date) { if (date == null) { return null; } return LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault()); } private DateConverterUtils(); static Date convert2Date(LocalDate localDate); static Date convert2Date(LocalDateTime localDateTime); static LocalDateTime convert2LocalDateTime(Date date); static LocalDate convert2LocalDate(Date date); static long convert2Timestamp(LocalDateTime localDateTime); }### Answer:
@Test public void shouldBeNull_whenInputDateIsNull_ofConvert2LocalDateTime() { Date input = null; LocalDateTime output = DateConverterUtils.convert2LocalDateTime(input); LocalDateTime expected = null; assertThat(output).isEqualTo(expected); }
@Test public void shouldBeOk_whenInputDateIs20170101T010101_ofConvert2LocalDateTime() { Date input = createDate("2017-01-01T01:01:01"); LocalDateTime output = DateConverterUtils.convert2LocalDateTime(input); LocalDateTime expected = createLocalDateTime("2017-01-01T01:01:01"); assertThat(output).isEqualTo(expected); } |
### Question:
ProductService { public void classicalDelete(Long id) { authService.checkAccess(); System.out.println("Delete Product."); } void insert(Product product); void classicalDelete(Long id); void baseAopDelete(Long id); @AdminOnly void annoAopDelete(Long id); }### Answer:
@Test(expected = Exception.class) public void classicalDelete() throws Exception { CurrentUserHolder.set("frank"); productService.classicalDelete(1L); } |
### Question:
ProductService { public void baseAopDelete(Long id) { System.out.println("Delete Product."); } void insert(Product product); void classicalDelete(Long id); void baseAopDelete(Long id); @AdminOnly void annoAopDelete(Long id); }### Answer:
@Test public void baseAopDelete() throws Exception { CurrentUserHolder.set("frank"); productService.baseAopDelete(1L); } |
### Question:
ProductService { @AdminOnly public void annoAopDelete(Long id) { System.out.println("Delete Product."); } void insert(Product product); void classicalDelete(Long id); void baseAopDelete(Long id); @AdminOnly void annoAopDelete(Long id); }### Answer:
@Test(expected = Exception.class) public void annoAopDelete() throws Exception { CurrentUserHolder.set("frank"); productService.baseAopDelete(1L); } |
### Question:
CaseStudy { public static void demonstrate() { String code = "The code"; Course course = Courses.findByCode(code); Lecturer lecturer = course.getLecturer(); String name = lecturer.getName(); System.out.println(name); } static void demonstrate(); }### Answer:
@Test public void demonstrateTest() { CaseStudy.demonstrate(); String expected = String.format("The lecturer%s", System.lineSeparator()); String obtained = out.toString(); assertEquals(obtained, expected); } |
### Question:
App { public static double mean(List<Double> numbers) { double sum = 0; for (double f : numbers) { sum += f; } return sum / numbers.size(); } static void main(String[] args); static List<Double> compute(); static List<Double> loadFromFile(String filepath); static double mean(List<Double> numbers); static double std(List<Double> numbers, double mean); static List<Double> normalize(List<Double> numbers, double mean, double std); static void writeToFile(List<Double> numbers); }### Answer:
@Test public void meanWithNegatives() { List<Double> numbers = Arrays.asList(-1d,1d); double mean = App.mean(numbers); assertEquals(0, mean, 0); }
@Test public void zeroMean() { List<Double> zeroes = Arrays.asList(0d,0d,0d,0d); double mean = App.mean(zeroes); assertEquals(0, mean, 0); } |
### Question:
App { public static double std(List<Double> numbers, double mean) { double sumSquare = 0; for (double f : numbers) { double diff = f - mean; sumSquare += diff * diff; } return Math.sqrt(sumSquare / numbers.size()); } static void main(String[] args); static List<Double> compute(); static List<Double> loadFromFile(String filepath); static double mean(List<Double> numbers); static double std(List<Double> numbers, double mean); static List<Double> normalize(List<Double> numbers, double mean, double std); static void writeToFile(List<Double> numbers); }### Answer:
@Test public void zeroStd() { List<Double> zeroes = Arrays.asList(0d,0d,0d,0d); double std = App.std(zeroes, 0); assertEquals(0, std, 0); } |
### Question:
RecursiveFibonacci { @Requires("0 <= n") @Ensures("0 <= result") public int apply(int n) { if (0 == n || 1 == n) { return n; } else { return apply(n - 1) + apply(n - 2); } } @Requires("0 <= n") @Ensures("0 <= result") int apply(int n); }### Answer:
@Test(expected = PreconditionError.class) public void fibOnNegativeFails() { RecursiveFibonacci fib = new RecursiveFibonacci(); fib.apply(-1); }
@Test public void fibOf4() { RecursiveFibonacci fib = new RecursiveFibonacci(); assertEquals(3, fib.apply(4)); } |
### Question:
App { public String getGreeting() { return "Hello world."; } String getGreeting(); static void main(String[] args); }### Answer:
@Test void appHasAGreeting() { App classUnderTest = new App(); assertNotNull(classUnderTest.getGreeting(), "app should have a greeting"); }
@Test public void testAppHasAGreeting() { App classUnderTest = new App(); assertNotNull("app should have a greeting", classUnderTest.getGreeting()); } |
### Question:
Loan { public static Loan createTermLoan(double commitment, int riskTaking, Date maturity){ return new Loan(null, commitment, 0.00, riskTaking, maturity, null); } private Loan(CapitalStrategy capitalStrategy, double commitment, double outstanding, int riskTaking, Date maturity, Date expiry); static Loan createTermLoan(double commitment, int riskTaking, Date maturity); static Loan createRevolverLoan(double commitment, double outstanding, int customerRating, Date maturity, Date expiry); static Loan createRevolverLoan(double commitment, int customerRating, Date maturity, Date expiry); static Loan createRCTLLoan(CapitalStrategy capitalStrategy, double commitment, int riskTaking, Date maturity, Date expiry); }### Answer:
@Test public void testTermLoanNoPayments() { Loan termLoan = Loan.createTermLoan(2.0, 1, Date.from(Instant.now())); assertNotNull(termLoan); System.out.println("Test term loan"); } |
### Question:
Loan { public static Loan createRevolverLoan(double commitment, double outstanding, int customerRating, Date maturity, Date expiry){ return new Loan(null, commitment, outstanding, customerRating, maturity, expiry); } private Loan(CapitalStrategy capitalStrategy, double commitment, double outstanding, int riskTaking, Date maturity, Date expiry); static Loan createTermLoan(double commitment, int riskTaking, Date maturity); static Loan createRevolverLoan(double commitment, double outstanding, int customerRating, Date maturity, Date expiry); static Loan createRevolverLoan(double commitment, int customerRating, Date maturity, Date expiry); static Loan createRCTLLoan(CapitalStrategy capitalStrategy, double commitment, int riskTaking, Date maturity, Date expiry); }### Answer:
@Test public void testRevolverLoan() { Loan revolverLoan = Loan.createRevolverLoan(2.0, 1.0, 1, Date.from(Instant.now()), Date.from(Instant.now())); assertNotNull(revolverLoan); System.out.println("Test revolver loan"); } |
### Question:
App { public static List<Double> compute() throws FileNotFoundException { List<Double> numbers = loadFromFile("data"); double mean = mean(numbers); double std = std(numbers, mean); List<Double> normalized = normalize(numbers, mean, std); System.out.println(normalized); writeToFile(normalized); return normalized; } static void main(String[] args); static List<Double> compute(); static List<Double> loadFromFile(String filepath); static double mean(List<Double> numbers); static double std(List<Double> numbers, double mean); static List<Double> normalize(List<Double> numbers, double mean, double std); static void writeToFile(List<Double> numbers); }### Answer:
@Test public void computeYieldsCorrectResult() throws FileNotFoundException { List<Double> normalized = App.compute(); List<Double> expected = Arrays.asList( -1.5666989036012806, -1.2185435916898848, -0.8703882797784892, -0.5222329678670935, -0.17407765595569785, 0.17407765595569785, 0.5222329678670935, 0.8703882797784892, 1.2185435916898848, 1.5666989036012806 ); assertEquals(expected, normalized); } |
### Question:
App { public static List<Double> loadFromFile(String filepath) throws FileNotFoundException { File file = new File(filepath); Scanner scanner = new Scanner(file); List<Double> numbers = new ArrayList<>(); while (scanner.hasNextDouble()) { double number = scanner.nextDouble(); numbers.add(number); } scanner.close(); return numbers; } static void main(String[] args); static List<Double> compute(); static List<Double> loadFromFile(String filepath); static double mean(List<Double> numbers); static double std(List<Double> numbers, double mean); static List<Double> normalize(List<Double> numbers, double mean, double std); static void writeToFile(List<Double> numbers); }### Answer:
@Test public void loadCorrectFile() throws FileNotFoundException { List<Double> expected = Arrays.asList(1d,2d,3d,4d,5d,6d,7d,8d,9d,10d); List<Double> loaded = App.loadFromFile("data"); assertEquals(expected, loaded); }
@Test public void loadWrongFileThrows() throws FileNotFoundException { assertThrows(FileNotFoundException.class, () -> { App.loadFromFile("loremipsum"); }); } |
### Question:
Utils { public static AudioStream getHighestQualityAudio(List<AudioStream> audioStreams) { int highestQualityIndex = 0; for (int i = 1; i < audioStreams.size(); i++) { AudioStream audioStream = audioStreams.get(i); if (audioStream.avgBitrate > audioStreams.get(highestQualityIndex).avgBitrate) highestQualityIndex = i; } return audioStreams.get(highestQualityIndex); } static int getDefaultResolution(String defaultResolution, String preferredFormat, List<VideoStream> videoStreams); static int getDefaultResolution(Context context, List<VideoStream> videoStreams); static int getPopupDefaultResolution(Context context, List<VideoStream> videoStreams); static int getPreferredAudioFormat(Context context, List<AudioStream> audioStreams); static AudioStream getHighestQualityAudio(List<AudioStream> audioStreams); static ArrayList<VideoStream> getSortedStreamVideosList(Context context, List<VideoStream> videoStreams, List<VideoStream> videoOnlyStreams, boolean ascendingOrder); static ArrayList<VideoStream> getSortedStreamVideosList(MediaFormat preferredFormat, boolean showHigherResolutions, List<VideoStream> videoStreams, List<VideoStream> videoOnlyStreams, boolean ascendingOrder); static void sortStreamList(List<VideoStream> videoStreams, final boolean ascendingOrder); }### Answer:
@Test public void getHighestQualityAudioTest() throws Exception { assertEquals(320, Utils.getHighestQualityAudio(audioStreamsTestList).avgBitrate); } |
### 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:
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:
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 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:
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:
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 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:
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); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.