method2testcases
stringlengths
118
6.63k
### Question: ConfigPv implements Comparable<ConfigPv> { @Override public boolean equals(Object other) { if(other instanceof ConfigPv) { ConfigPv otherConfigPv = (ConfigPv)other; return Objects.equals(pvName, otherConfigPv.getPvName()) && Objects.equals(readbackPvName, otherConfigPv.getReadbackPvName()) && Objects.equals(readOnly, otherConfigPv.isReadOnly()); } return false; } @Override boolean equals(Object other); @Override int hashCode(); @Override String toString(); @Override int compareTo(ConfigPv other); }### Answer: @Test public void testEquals() { ConfigPv configPV1 = ConfigPv.builder().pvName("a").readbackPvName("b").readOnly(true).build(); assertFalse(configPV1.equals(new Object())); assertFalse(configPV1.equals(null)); ConfigPv configPV2 = ConfigPv.builder().pvName("a").readbackPvName("b").readOnly(true).build(); ConfigPv configPV3 = ConfigPv.builder().pvName("a").readbackPvName("c").readOnly(true).build(); assertEquals(configPV1, configPV2); assertNotEquals(configPV1, configPV3); configPV1 = ConfigPv.builder().pvName("a").readbackPvName("b").readOnly(true).build(); configPV2 = ConfigPv.builder().pvName("b").readbackPvName("b").readOnly(true).build(); assertNotEquals(configPV1, configPV2); configPV1 = ConfigPv.builder().pvName("a").readOnly(true).build(); configPV2 = ConfigPv.builder().pvName("b").readOnly(true).build(); assertNotEquals(configPV1, configPV2); configPV1 = ConfigPv.builder().pvName("a").readOnly(true).build(); configPV2 = ConfigPv.builder().pvName("a").readOnly(true).build(); assertEquals(configPV1, configPV2); }
### Question: ConfigPv implements Comparable<ConfigPv> { @Override public int hashCode() { return Objects.hash(pvName, readbackPvName, readOnly); } @Override boolean equals(Object other); @Override int hashCode(); @Override String toString(); @Override int compareTo(ConfigPv other); }### Answer: @Test public void testHashCode() { ConfigPv configPV1 = ConfigPv.builder().pvName("a").readbackPvName("b").readOnly(true).build(); ConfigPv configPV2 = ConfigPv.builder().pvName("a").readbackPvName("b").readOnly(true).build(); assertEquals(configPV1.hashCode(), configPV2.hashCode()); configPV1 = ConfigPv.builder().pvName("a").readbackPvName("b").readOnly(true).build(); configPV2 = ConfigPv.builder().pvName("b").readbackPvName("b").readOnly(true).build(); assertNotEquals(configPV1.hashCode(), configPV2.hashCode()); configPV1 = ConfigPv.builder().pvName("a").readOnly(true).build(); configPV2 = ConfigPv.builder().pvName("b").readOnly(true).build(); assertNotEquals(configPV1.hashCode(), configPV2.hashCode()); configPV1 = ConfigPv.builder().pvName("a").readOnly(true).build(); configPV2 = ConfigPv.builder().pvName("a").readOnly(true).build(); assertEquals(configPV1.hashCode(), configPV2.hashCode()); }
### Question: PropertyManager { public void setDesiredNumberOfFeaturesPerRunner(int desiredNumberOfFeaturesPerRunner) { this.desiredNumberOfFeaturesPerRunner = desiredNumberOfFeaturesPerRunner; } @Inject PropertyManager(final CucableLogger logger, final FileIO fileIO); String getSourceRunnerTemplateFile(); void setSourceRunnerTemplateFile(final String sourceRunnerTemplateFile); String getGeneratedRunnerDirectory(); void setGeneratedRunnerDirectory(final String generatedRunnerDirectory); List<CucableFeature> getSourceFeatures(); void setSourceFeatures(final String sourceFeatures); String getGeneratedFeatureDirectory(); void setGeneratedFeatureDirectory(final String generatedFeatureDirectory); int getNumberOfTestRuns(); void setNumberOfTestRuns(final int numberOfTestRuns); String getIncludeScenarioTags(); void setIncludeScenarioTags(final String includeScenarioTags); ParallelizationMode getParallelizationMode(); void setParallelizationMode(final String parallelizationMode); Map<String, String> getCustomPlaceholders(); void setCustomPlaceholders(final Map<String, String> customPlaceholders); int getDesiredNumberOfRunners(); void setDesiredNumberOfRunners(final int desiredNumberOfRunners); int getDesiredNumberOfFeaturesPerRunner(); void setDesiredNumberOfFeaturesPerRunner(int desiredNumberOfFeaturesPerRunner); List<String> getScenarioNames(); void setScenarioNames(final String scenarioNames); void checkForMissingMandatoryProperties(); void checkForDisallowedPropertyCombinations(); void logProperties(); boolean isCucumberFeatureListFileSource(); }### Answer: @Test public void setDesiredNumberOfFeaturesPerRunnerTest() { propertyManager.setDesiredNumberOfFeaturesPerRunner(5); assertThat(propertyManager.getDesiredNumberOfFeaturesPerRunner(), is(5)); }
### Question: PropertyManager { public void setParallelizationMode(final String parallelizationMode) throws CucablePluginException { try { this.parallelizationMode = ParallelizationMode.valueOf(parallelizationMode.toUpperCase()); } catch (IllegalArgumentException e) { throw new CucablePluginException( "Unknown <parallelizationMode> '" + parallelizationMode + "'. Please use 'scenarios' or 'features'." ); } } @Inject PropertyManager(final CucableLogger logger, final FileIO fileIO); String getSourceRunnerTemplateFile(); void setSourceRunnerTemplateFile(final String sourceRunnerTemplateFile); String getGeneratedRunnerDirectory(); void setGeneratedRunnerDirectory(final String generatedRunnerDirectory); List<CucableFeature> getSourceFeatures(); void setSourceFeatures(final String sourceFeatures); String getGeneratedFeatureDirectory(); void setGeneratedFeatureDirectory(final String generatedFeatureDirectory); int getNumberOfTestRuns(); void setNumberOfTestRuns(final int numberOfTestRuns); String getIncludeScenarioTags(); void setIncludeScenarioTags(final String includeScenarioTags); ParallelizationMode getParallelizationMode(); void setParallelizationMode(final String parallelizationMode); Map<String, String> getCustomPlaceholders(); void setCustomPlaceholders(final Map<String, String> customPlaceholders); int getDesiredNumberOfRunners(); void setDesiredNumberOfRunners(final int desiredNumberOfRunners); int getDesiredNumberOfFeaturesPerRunner(); void setDesiredNumberOfFeaturesPerRunner(int desiredNumberOfFeaturesPerRunner); List<String> getScenarioNames(); void setScenarioNames(final String scenarioNames); void checkForMissingMandatoryProperties(); void checkForDisallowedPropertyCombinations(); void logProperties(); boolean isCucumberFeatureListFileSource(); }### Answer: @Test public void wrongParallelizationModeTest() throws CucablePluginException { expectedException.expect(CucablePluginException.class); expectedException.expectMessage("Unknown <parallelizationMode> 'unknown'. Please use 'scenarios' or 'features'."); propertyManager.setParallelizationMode("unknown"); }
### Question: PropertyManager { public void checkForMissingMandatoryProperties() throws CucablePluginException { List<String> missingProperties = new ArrayList<>(); if (sourceFeatures == null || sourceFeatures.isEmpty()) { saveMissingProperty("", "<sourceFeatures>", missingProperties); } saveMissingProperty(sourceRunnerTemplateFile, "<sourceRunnerTemplateFile>", missingProperties); saveMissingProperty(generatedRunnerDirectory, "<generatedRunnerDirectory>", missingProperties); saveMissingProperty(generatedFeatureDirectory, "<generatedFeatureDirectory>", missingProperties); if (!missingProperties.isEmpty()) { throw new WrongOrMissingPropertiesException(missingProperties); } } @Inject PropertyManager(final CucableLogger logger, final FileIO fileIO); String getSourceRunnerTemplateFile(); void setSourceRunnerTemplateFile(final String sourceRunnerTemplateFile); String getGeneratedRunnerDirectory(); void setGeneratedRunnerDirectory(final String generatedRunnerDirectory); List<CucableFeature> getSourceFeatures(); void setSourceFeatures(final String sourceFeatures); String getGeneratedFeatureDirectory(); void setGeneratedFeatureDirectory(final String generatedFeatureDirectory); int getNumberOfTestRuns(); void setNumberOfTestRuns(final int numberOfTestRuns); String getIncludeScenarioTags(); void setIncludeScenarioTags(final String includeScenarioTags); ParallelizationMode getParallelizationMode(); void setParallelizationMode(final String parallelizationMode); Map<String, String> getCustomPlaceholders(); void setCustomPlaceholders(final Map<String, String> customPlaceholders); int getDesiredNumberOfRunners(); void setDesiredNumberOfRunners(final int desiredNumberOfRunners); int getDesiredNumberOfFeaturesPerRunner(); void setDesiredNumberOfFeaturesPerRunner(int desiredNumberOfFeaturesPerRunner); List<String> getScenarioNames(); void setScenarioNames(final String scenarioNames); void checkForMissingMandatoryProperties(); void checkForDisallowedPropertyCombinations(); void logProperties(); boolean isCucumberFeatureListFileSource(); }### Answer: @Test public void logMissingPropertiesTest() throws CucablePluginException { expectedException.expect(WrongOrMissingPropertiesException.class); expectedException.expectMessage("Properties not specified correctly in the configuration section of your pom file: [<sourceFeatures>, <sourceRunnerTemplateFile>, <generatedRunnerDirectory>, <generatedFeatureDirectory>]"); propertyManager.checkForMissingMandatoryProperties(); }
### Question: CucableLogger { public void info(final CharSequence logString, CucableLogLevel... cucableLogLevels) { log(LogLevel.INFO, logString, cucableLogLevels); } void initialize(final Log mojoLogger, final String currentLogLevel); void logInfoSeparator(final CucableLogLevel... cucableLogLevels); void info(final CharSequence logString, CucableLogLevel... cucableLogLevels); void warn(final CharSequence logString); }### Answer: @Test public void infoTest() { logger.initialize(mockedLogger, "default"); logger.info("Test"); verify(mockedLogger, times(1)) .info("Test"); }
### Question: CucableLogger { public void logInfoSeparator(final CucableLogLevel... cucableLogLevels) { info("-------------------------------------", cucableLogLevels); } void initialize(final Log mojoLogger, final String currentLogLevel); void logInfoSeparator(final CucableLogLevel... cucableLogLevels); void info(final CharSequence logString, CucableLogLevel... cucableLogLevels); void warn(final CharSequence logString); }### Answer: @Test public void logInfoSeparatorTest() { logger.initialize(mockedLogger, "default"); logger.logInfoSeparator(CucableLogger.CucableLogLevel.DEFAULT); verify(mockedLogger, times(1)) .info("-------------------------------------"); }
### Question: GherkinTranslations { String getScenarioKeyword(final String language) { GherkinDialect dialect; try { dialect = gherkinDialectProvider.getDialect(language, null); } catch (Exception e) { return SCENARIO; } return dialect.getScenarioKeywords().get(0); } @Inject GherkinTranslations(); }### Answer: @Test public void getScenarioKeywordTesnt() { assertThat(gherkinTranslations.getScenarioKeyword("en"), is("Scenario")); assertThat(gherkinTranslations.getScenarioKeyword("de"), is("Szenario")); assertThat(gherkinTranslations.getScenarioKeyword("no"), is("Scenario")); assertThat(gherkinTranslations.getScenarioKeyword("ro"), is("Scenariu")); assertThat(gherkinTranslations.getScenarioKeyword("ru"), is("Сценарий")); assertThat(gherkinTranslations.getScenarioKeyword("fr"), is("Scénario")); assertThat(gherkinTranslations.getScenarioKeyword("gibberish"), is("Scenario")); }
### Question: GherkinDocumentParser { private String replacePlaceholderInString( final String sourceString, final Map<String, List<String>> exampleMap, final int rowIndex) { String result = sourceString; Matcher m = SCENARIO_OUTLINE_PLACEHOLDER_PATTERN.matcher(sourceString); while (m.find()) { String currentPlaceholder = m.group(0); List<String> placeholderColumn = exampleMap.get(currentPlaceholder); if (placeholderColumn != null) { result = result.replace(currentPlaceholder, placeholderColumn.get(rowIndex)); } } return result; } @Inject GherkinDocumentParser( final GherkinToCucableConverter gherkinToCucableConverter, final GherkinTranslations gherkinTranslations, final PropertyManager propertyManager, final CucableLogger logger); List<SingleScenario> getSingleScenariosFromFeature( final String featureContent, final String featureFilePath, final List<Integer> scenarioLineNumbers); int matchScenarioWithScenarioNames(String language, String stringToMatch); }### Answer: @Test public void replacePlaceholderInStringTest() throws Exception { String featureContent = "Feature: test feature 3\n" + "\n" + " Scenario Outline: This is a scenario with <key> and <value>!\n" + " Given this is a step\n" + "\n" + " Examples:\n" + " | key | value |\n" + " | 1 | one |\n"; List<SingleScenario> singleScenariosFromFeature = gherkinDocumentParser.getSingleScenariosFromFeature(featureContent, "", null); assertThat(singleScenariosFromFeature.get(0).getScenarioName(), is("Scenario: This is a scenario with 1 and one!")); }
### Question: GherkinDocumentParser { private DataTable replaceDataTableExamplePlaceholder( final DataTable dataTable, final Map<String, List<String>> exampleMap, final int rowIndex ) { if (dataTable == null) { return null; } List<List<String>> dataTableRows = dataTable.getRows(); DataTable replacedDataTable = new DataTable(); for (List<String> dataTableRow : dataTableRows) { List<String> replacedDataTableRow = new ArrayList<>(); for (String dataTableCell : dataTableRow) { replacedDataTableRow.add(replacePlaceholderInString(dataTableCell, exampleMap, rowIndex)); } replacedDataTable.addRow(replacedDataTableRow); } return replacedDataTable; } @Inject GherkinDocumentParser( final GherkinToCucableConverter gherkinToCucableConverter, final GherkinTranslations gherkinTranslations, final PropertyManager propertyManager, final CucableLogger logger); List<SingleScenario> getSingleScenariosFromFeature( final String featureContent, final String featureFilePath, final List<Integer> scenarioLineNumbers); int matchScenarioWithScenarioNames(String language, String stringToMatch); }### Answer: @Test public void replaceDataTableExamplePlaceholderTest() throws Exception { String featureContent = "Feature: test feature 3\n" + "\n" + " Scenario Outline: This is a scenario outline\n" + " When I search for key <key>\n" + " | test | <key> | <value> |" + "\n" + " Examples:\n" + " | key | value |\n" + " | 1 | one |\n"; List<SingleScenario> singleScenariosFromFeature = gherkinDocumentParser.getSingleScenariosFromFeature(featureContent, "", null); assertThat(singleScenariosFromFeature.size(), is(1)); assertThat(singleScenariosFromFeature.get(0).getSteps().size(), is(1)); DataTable dataTable = singleScenariosFromFeature.get(0).getSteps().get(0).getDataTable(); assertThat(dataTable.getRows().size(), is(1)); List<String> firstRow = dataTable.getRows().get(0); assertThat(firstRow.get(0), is("test")); assertThat(firstRow.get(1), is("1")); assertThat(firstRow.get(2), is("one")); }
### Question: GherkinToCucableConverter { List<com.trivago.vo.Step> convertGherkinStepsToCucableSteps(final List<Step> gherkinSteps) { List<com.trivago.vo.Step> steps = new ArrayList<>(); for (Step gherkinStep : gherkinSteps) { com.trivago.vo.Step step; com.trivago.vo.DataTable dataTable = null; String docString = null; Node argument = gherkinStep.getArgument(); if (argument instanceof DataTable) { dataTable = convertGherkinDataTableToCucableDataTable((DataTable) argument); } else if (argument instanceof DocString) { docString = ((DocString) argument).getContent(); } String keywordAndName = gherkinStep.getKeyword().concat(gherkinStep.getText()); step = new com.trivago.vo.Step(keywordAndName, dataTable, docString); steps.add(step); } return steps; } }### Answer: @Test public void convertGherkinStepsToCucableStepsTest() { List<Step> gherkinSteps = Arrays.asList( new Step(new Location(1, 1), "Given ", "this is a test step", null), new Step(new Location(2, 1), "Then ", "I get a test result", null) ); List<com.trivago.vo.Step> steps = gherkinToCucableConverter.convertGherkinStepsToCucableSteps(gherkinSteps); assertThat(steps.size(), is(gherkinSteps.size())); com.trivago.vo.Step firstStep = steps.get(0); assertThat(firstStep.getName(), is("Given this is a test step")); com.trivago.vo.Step secondStep = steps.get(1); assertThat(secondStep.getName(), is("Then I get a test result")); }
### Question: GherkinToCucableConverter { Map<String, List<String>> convertGherkinExampleTableToCucableExampleMap( final Examples exampleTable ) { Map<String, List<String>> exampleMap; List<TableCell> headerCells = exampleTable.getTableHeader().getCells(); exampleMap = headerCells.stream().collect( Collectors.toMap(headerCell -> "<" + headerCell.getValue() + ">", headerCell -> new ArrayList<>(), (a, b) -> b, LinkedHashMap::new)); Object[] columnKeys = exampleMap.keySet().toArray(); List<TableRow> tableBody = exampleTable.getTableBody(); tableBody.stream().map(TableRow::getCells).forEachOrdered( cells -> IntStream.range(0, cells.size()).forEachOrdered(i -> { String columnKey = (String) columnKeys[i]; List<String> values = exampleMap.get(columnKey); values.add(cells.get(i).getValue()); })); return exampleMap; } }### Answer: @Test public void convertGherkinExampleTableToCucableExampleMapTest() { Location location = new Location(1, 2); List<Tag> tags = new ArrayList<>(); Tag tag = new Tag(location, "@tag"); tags.add(tag); String keyword = "keyword"; String name = "name"; String description = "description"; List<TableCell> headerCells = new ArrayList<>(); headerCells.add(new TableCell(location, "headerCell1")); headerCells.add(new TableCell(location, "headerCell2")); headerCells.add(new TableCell(location, "headerCell3")); TableRow tableHeader = new TableRow(location, headerCells); List<TableRow> tableBody = new ArrayList<>(); List<TableCell> bodyCells = new ArrayList<>(); bodyCells.add(new TableCell(location, "bodyCell1")); bodyCells.add(new TableCell(location, "bodyCell2")); bodyCells.add(new TableCell(location, "bodyCell3")); tableBody.add(new TableRow(location, bodyCells)); bodyCells = new ArrayList<>(); bodyCells.add(new TableCell(location, "bodyCell4")); bodyCells.add(new TableCell(location, "bodyCell5")); bodyCells.add(new TableCell(location, "bodyCell6")); tableBody.add(new TableRow(location, bodyCells)); Examples examples = new Examples(location, tags, keyword, name, description, tableHeader, tableBody); List<String> includeTags = new ArrayList<>(); List<String> excludeTags = new ArrayList<>(); Map<String, List<String>> table = gherkinToCucableConverter.convertGherkinExampleTableToCucableExampleMap(examples); assertThat(table.size(), is(3)); }
### Question: FeatureFileContentRenderer { private String formatDataTableString(final DataTable dataTable) { if (dataTable == null) { return ""; } char dataTableSeparator = '|'; StringBuilder dataTableStringBuilder = new StringBuilder(); for (List<String> rowValues : dataTable.getRows()) { dataTableStringBuilder.append(dataTableSeparator); for (String rowValue : rowValues) { dataTableStringBuilder.append(rowValue).append(dataTableSeparator); } dataTableStringBuilder.append(LINE_SEPARATOR); } return dataTableStringBuilder.toString(); } }### Answer: @Test public void formatDataTableStringTest() { String expectedOutput = "Feature: featureName\n" + "featureDescription\n" + "\n" + "Scenario: scenarioName\n" + "scenarioDescription\n" + "Step 1\n" + "|cell11|cell12|cell13|\n" + "|cell21|cell22|cell23|\n" + "\n# Source feature: TESTPATH\n" + "# Generated by Cucable\n"; String featureName = "Feature: featureName"; String featureLanguage = ""; String featureDescription = "featureDescription"; String scenarioName = "Scenario: scenarioName"; String scenarioDescription = "scenarioDescription"; DataTable dataTable = new DataTable(); dataTable.addRow(Arrays.asList("cell11", "cell12", "cell13")); dataTable.addRow(Arrays.asList("cell21", "cell22", "cell23")); List<Step> steps = Collections.singletonList(new Step("Step 1", dataTable, null)); String featureFilePath = "TESTPATH"; SingleScenario singleScenario = new SingleScenario(featureName, featureFilePath, featureLanguage, featureDescription, scenarioName, scenarioDescription, new ArrayList<>(), new ArrayList<>()); singleScenario.setSteps(steps); String renderedFeatureFileContent = featureFileContentRenderer.getRenderedFeatureFileContent(singleScenario); renderedFeatureFileContent = renderedFeatureFileContent.replaceAll("\\r\\n", "\n"); assertThat(renderedFeatureFileContent, is(expectedOutput)); }
### Question: FeatureFileContentRenderer { private String formatDocString(final String docString) { if (docString == null || docString.isEmpty()) { return ""; } return "\"\"\"" + LINE_SEPARATOR + docString + LINE_SEPARATOR + "\"\"\"" + LINE_SEPARATOR; } }### Answer: @Test public void formatDocStringTest() { String expectedOutput = "Feature: featureName\n" + "\n" + "Scenario: scenarioName\n" + "Step 1\n" + "\"\"\"\n" + "DOCSTRING LINE 1\n" + "DOCSTRING LINE 2\n" + "\"\"\"\n" + "\n# Source feature: TESTPATH\n" + "# Generated by Cucable\n"; String featureName = "Feature: featureName"; String scenarioName = "Scenario: scenarioName"; List<Step> steps = Collections.singletonList(new Step("Step 1", null, "DOCSTRING LINE 1\nDOCSTRING LINE 2")); String featureFilePath = "TESTPATH"; SingleScenario singleScenario = new SingleScenario(featureName, featureFilePath, null, null, scenarioName, null, new ArrayList<>(), new ArrayList<>()); singleScenario.setSteps(steps); String renderedFeatureFileContent = featureFileContentRenderer.getRenderedFeatureFileContent(singleScenario); renderedFeatureFileContent = renderedFeatureFileContent.replaceAll("\\r\\n", "\n"); assertThat(renderedFeatureFileContent, is(expectedOutput)); }
### Question: CucablePlugin extends AbstractMojo { public void execute() throws CucablePluginException { logger.initialize(getLog(), logLevel); propertyManager.setSourceRunnerTemplateFile(sourceRunnerTemplateFile); propertyManager.setGeneratedRunnerDirectory(generatedRunnerDirectory); propertyManager.setSourceFeatures(sourceFeatures); propertyManager.setGeneratedFeatureDirectory(generatedFeatureDirectory); propertyManager.setNumberOfTestRuns(numberOfTestRuns); propertyManager.setIncludeScenarioTags(includeScenarioTags); propertyManager.setParallelizationMode(parallelizationMode); propertyManager.setCustomPlaceholders(customPlaceholders); propertyManager.setDesiredNumberOfRunners(desiredNumberOfRunners); propertyManager.setDesiredNumberOfFeaturesPerRunner(desiredNumberOfFeaturesPerRunner); propertyManager.setScenarioNames(scenarioNames); propertyManager.checkForMissingMandatoryProperties(); propertyManager.checkForDisallowedPropertyCombinations(); logPluginInformationHeader(); propertyManager.logProperties(); fileManager.prepareGeneratedFeatureAndRunnerDirectories(); featureFileConverter.generateParallelizableFeatures(propertyManager.getSourceFeatures()); } @Inject CucablePlugin( PropertyManager propertyManager, FileSystemManager fileManager, FeatureFileConverter featureFileConverter, CucableLogger logger ); void execute(); }### Answer: @Test public void logInvocationTest() throws Exception { cucablePlugin.execute(); verify(logger, times(1)).initialize(mojoLogger, "default"); verify(logger, times(1)).info(anyString(), any(CucableLogger.CucableLogLevel.class)); verify(logger, times(2)).logInfoSeparator(any(CucableLogger.CucableLogLevel.class)); }
### Question: FileIO { public void writeContentToFile(String content, String filePath) throws FileCreationException { try { FileUtils.fileWrite(filePath, "UTF-8", content); } catch (IOException e) { throw new FileCreationException(filePath); } } void writeContentToFile(String content, String filePath); String readContentFromFile(String filePath); }### Answer: @Test(expected = FileCreationException.class) public void writeToInvalidFileTest() throws Exception { fileIO.writeContentToFile(null, ""); }
### Question: FileIO { public String readContentFromFile(String filePath) throws MissingFileException { try { return FileUtils.fileRead(filePath, "UTF-8"); } catch (IOException e) { throw new MissingFileException(filePath); } } void writeContentToFile(String content, String filePath); String readContentFromFile(String filePath); }### Answer: @Test(expected = MissingFileException.class) public void readFromMissingFileTest() throws Exception { String wrongPath = testFolder.getRoot().getPath().concat("/missing.tmp"); fileIO.readContentFromFile(wrongPath); }
### Question: FileSystemManager { public void prepareGeneratedFeatureAndRunnerDirectories() throws CucablePluginException { createDirIfNotExists(propertyManager.getGeneratedFeatureDirectory()); removeFilesFromPath(propertyManager.getGeneratedFeatureDirectory(), "feature"); createDirIfNotExists(propertyManager.getGeneratedRunnerDirectory()); removeFilesFromPath(propertyManager.getGeneratedRunnerDirectory(), "java"); } @Inject FileSystemManager(PropertyManager propertyManager); List<Path> getPathsFromCucableFeature(final CucableFeature cucableFeature); void prepareGeneratedFeatureAndRunnerDirectories(); }### Answer: @Test(expected = PathCreationException.class) public void prepareGeneratedFeatureAndRunnerDirsMissingFeatureDirTest() throws Exception { when(propertyManager.getGeneratedFeatureDirectory()).thenReturn(""); fileSystemManager.prepareGeneratedFeatureAndRunnerDirectories(); } @Test(expected = PathCreationException.class) public void prepareGeneratedFeatureAndRunnerDirsMissingRunnerDirTest() throws Exception { String featurePath = testFolder.getRoot().getPath().concat("/featureDir"); when(propertyManager.getGeneratedFeatureDirectory()).thenReturn(featurePath); when(propertyManager.getGeneratedRunnerDirectory()).thenReturn(""); fileSystemManager.prepareGeneratedFeatureAndRunnerDirectories(); } @Test public void prepareGeneratedFeatureAndRunnerDirsTest() throws Exception { String featurePath = testFolder.getRoot().getPath().concat("/featureDir"); String runnerPath = testFolder.getRoot().getPath().concat("/runnerDir"); when(propertyManager.getGeneratedFeatureDirectory()).thenReturn(featurePath); when(propertyManager.getGeneratedRunnerDirectory()).thenReturn(runnerPath); fileSystemManager.prepareGeneratedFeatureAndRunnerDirectories(); }
### Question: FileSystemManager { public List<Path> getPathsFromCucableFeature(final CucableFeature cucableFeature) throws CucablePluginException { if (cucableFeature == null) { return Collections.emptyList(); } String sourceFeatures = cucableFeature.getName(). replace("file: File sourceFeaturesFile = new File(sourceFeatures); if (sourceFeatures.trim().isEmpty()) { return Collections.emptyList(); } if (sourceFeaturesFile.isFile() && sourceFeatures.endsWith(FEATURE_FILE_EXTENSION)) { return Collections.singletonList(Paths.get(sourceFeatures)); } if (sourceFeaturesFile.isDirectory()) { return getFilesWithFeatureExtension(sourceFeatures); } throw new CucablePluginException( sourceFeatures + " is not a feature file or a directory." ); } @Inject FileSystemManager(PropertyManager propertyManager); List<Path> getPathsFromCucableFeature(final CucableFeature cucableFeature); void prepareGeneratedFeatureAndRunnerDirectories(); }### Answer: @Test public void getPathsFromCucableFeatureNullTest() throws CucablePluginException { List<Path> pathsFromCucableFeature = fileSystemManager.getPathsFromCucableFeature(null); assertThat(pathsFromCucableFeature, is(notNullValue())); assertThat(pathsFromCucableFeature.size(), is(0)); } @Test(expected = CucablePluginException.class) public void getPathsFromCucableFeatureInvalidFeatureTest() throws CucablePluginException { CucableFeature cucableFeatures = new CucableFeature("name.feature", null); fileSystemManager.getPathsFromCucableFeature(cucableFeatures); } @Test public void getPathsFromCucableFeatureValidEmptyPathTest() throws CucablePluginException { CucableFeature cucableFeatures = new CucableFeature(testFolder.getRoot().getPath(), null); List<Path> pathsFromCucableFeature = fileSystemManager.getPathsFromCucableFeature(cucableFeatures); assertThat(pathsFromCucableFeature, is(notNullValue())); assertThat(pathsFromCucableFeature.size(), is(0)); } @Test public void getPathsFromCucableFeatureFullPathTest() throws CucablePluginException { CucableFeature cucableFeatures = new CucableFeature("src/test/resources", null); List<Path> pathsFromCucableFeature = fileSystemManager.getPathsFromCucableFeature(cucableFeatures); assertThat(pathsFromCucableFeature, is(notNullValue())); assertThat(pathsFromCucableFeature.size(), is(2)); } @Test public void getPathsFromCucableFeatureValidFeatureTest() throws CucablePluginException { CucableFeature cucableFeatures = new CucableFeature("src/test/resources/feature1.feature", null); List<Path> pathsFromCucableFeature = fileSystemManager.getPathsFromCucableFeature(cucableFeatures); assertThat(pathsFromCucableFeature, is(notNullValue())); assertThat(pathsFromCucableFeature.size(), is(1)); }
### Question: PropertyManager { public void setGeneratedRunnerDirectory(final String generatedRunnerDirectory) { this.generatedRunnerDirectory = generatedRunnerDirectory; } @Inject PropertyManager(final CucableLogger logger, final FileIO fileIO); String getSourceRunnerTemplateFile(); void setSourceRunnerTemplateFile(final String sourceRunnerTemplateFile); String getGeneratedRunnerDirectory(); void setGeneratedRunnerDirectory(final String generatedRunnerDirectory); List<CucableFeature> getSourceFeatures(); void setSourceFeatures(final String sourceFeatures); String getGeneratedFeatureDirectory(); void setGeneratedFeatureDirectory(final String generatedFeatureDirectory); int getNumberOfTestRuns(); void setNumberOfTestRuns(final int numberOfTestRuns); String getIncludeScenarioTags(); void setIncludeScenarioTags(final String includeScenarioTags); ParallelizationMode getParallelizationMode(); void setParallelizationMode(final String parallelizationMode); Map<String, String> getCustomPlaceholders(); void setCustomPlaceholders(final Map<String, String> customPlaceholders); int getDesiredNumberOfRunners(); void setDesiredNumberOfRunners(final int desiredNumberOfRunners); int getDesiredNumberOfFeaturesPerRunner(); void setDesiredNumberOfFeaturesPerRunner(int desiredNumberOfFeaturesPerRunner); List<String> getScenarioNames(); void setScenarioNames(final String scenarioNames); void checkForMissingMandatoryProperties(); void checkForDisallowedPropertyCombinations(); void logProperties(); boolean isCucumberFeatureListFileSource(); }### Answer: @Test public void setGeneratedRunnerDirectoryTest() { propertyManager.setGeneratedRunnerDirectory("test"); assertThat(propertyManager.getGeneratedRunnerDirectory(), is("test")); }
### Question: PropertyManager { public void setGeneratedFeatureDirectory(final String generatedFeatureDirectory) { this.generatedFeatureDirectory = generatedFeatureDirectory; } @Inject PropertyManager(final CucableLogger logger, final FileIO fileIO); String getSourceRunnerTemplateFile(); void setSourceRunnerTemplateFile(final String sourceRunnerTemplateFile); String getGeneratedRunnerDirectory(); void setGeneratedRunnerDirectory(final String generatedRunnerDirectory); List<CucableFeature> getSourceFeatures(); void setSourceFeatures(final String sourceFeatures); String getGeneratedFeatureDirectory(); void setGeneratedFeatureDirectory(final String generatedFeatureDirectory); int getNumberOfTestRuns(); void setNumberOfTestRuns(final int numberOfTestRuns); String getIncludeScenarioTags(); void setIncludeScenarioTags(final String includeScenarioTags); ParallelizationMode getParallelizationMode(); void setParallelizationMode(final String parallelizationMode); Map<String, String> getCustomPlaceholders(); void setCustomPlaceholders(final Map<String, String> customPlaceholders); int getDesiredNumberOfRunners(); void setDesiredNumberOfRunners(final int desiredNumberOfRunners); int getDesiredNumberOfFeaturesPerRunner(); void setDesiredNumberOfFeaturesPerRunner(int desiredNumberOfFeaturesPerRunner); List<String> getScenarioNames(); void setScenarioNames(final String scenarioNames); void checkForMissingMandatoryProperties(); void checkForDisallowedPropertyCombinations(); void logProperties(); boolean isCucumberFeatureListFileSource(); }### Answer: @Test public void setGeneratedFeatureDirectoryTest() { propertyManager.setGeneratedFeatureDirectory("test"); assertThat(propertyManager.getGeneratedFeatureDirectory(), is("test")); }
### Question: PropertyManager { public void setDesiredNumberOfRunners(final int desiredNumberOfRunners) { this.desiredNumberOfRunners = desiredNumberOfRunners; } @Inject PropertyManager(final CucableLogger logger, final FileIO fileIO); String getSourceRunnerTemplateFile(); void setSourceRunnerTemplateFile(final String sourceRunnerTemplateFile); String getGeneratedRunnerDirectory(); void setGeneratedRunnerDirectory(final String generatedRunnerDirectory); List<CucableFeature> getSourceFeatures(); void setSourceFeatures(final String sourceFeatures); String getGeneratedFeatureDirectory(); void setGeneratedFeatureDirectory(final String generatedFeatureDirectory); int getNumberOfTestRuns(); void setNumberOfTestRuns(final int numberOfTestRuns); String getIncludeScenarioTags(); void setIncludeScenarioTags(final String includeScenarioTags); ParallelizationMode getParallelizationMode(); void setParallelizationMode(final String parallelizationMode); Map<String, String> getCustomPlaceholders(); void setCustomPlaceholders(final Map<String, String> customPlaceholders); int getDesiredNumberOfRunners(); void setDesiredNumberOfRunners(final int desiredNumberOfRunners); int getDesiredNumberOfFeaturesPerRunner(); void setDesiredNumberOfFeaturesPerRunner(int desiredNumberOfFeaturesPerRunner); List<String> getScenarioNames(); void setScenarioNames(final String scenarioNames); void checkForMissingMandatoryProperties(); void checkForDisallowedPropertyCombinations(); void logProperties(); boolean isCucumberFeatureListFileSource(); }### Answer: @Test public void setDesiredNumberOfRunnersTest() { propertyManager.setDesiredNumberOfRunners(12); assertThat(propertyManager.getDesiredNumberOfRunners(), is(12)); }
### Question: LineServerManager { public static void manage(String line, final LineListener lineListener) { if (isNotRunningAlready() && isSurefirePluginStarting(line)) { server = new LineServer(PORT); server.addListener(lineListener); server.start(); running.set(true); } else if (isRunning() && isBuildFinished(line)) { server.stop(); running.set(false); server = null; } } static void manage(String line, final LineListener lineListener); static boolean enabled; }### Answer: @Test public void shouldNotTryAndProcessingAnyThingIfTheBuildFailsBeforeSurefireEvenBegins() { manage(buildFailure(), lineProcessor); assertTrue(canNotConnectToServer()); } @Test public void shouldShutdownTheServerWhenTheBuildFails() { manage(surefire(), lineProcessor); manage(buildFailure(), lineProcessor); assertTrue(canNotConnectToServer()); } @Test public void shouldShutdownTheServerWhenTheBuildIsASuccess() { manage(surefire(), lineProcessor); manage(buildSuccess(), lineProcessor); assertTrue(canNotConnectToServer()); } @Test public void shouldNotBlowUpTryingToStartTheServerAgainIfTheSurefireIsRanAgain() { manage(surefire(), lineProcessor); manage(surefire(), lineProcessor); } @Test public void shouldNotKillTheServerIfTheSurefireIsRanAgain() { manage(surefire(), lineProcessor); manage(surefire(), lineProcessor); assertTrue(canConnectToServer()); } @Test public void shouldStartTheServerWhenTheSurefirePluginIsAboutToStart() { manage(surefire(), lineProcessor); assertTrue(canConnectToServer()); } @Test public void shouldNotStartForJustAnyPluginStarting() { manage(plugin("some-other-plugin"), lineProcessor); assertTrue(canNotConnectToServer()); }
### Question: ColorLinesMatchingPatternFilter implements LogEntryFilter { @Override public String filter(Context context) { for (LinePatternColoringConfig coloring : context.config.getColoring()) { if (isMatch(context, coloring)) { String result = ansi().render( context.entryText.replaceAll(coloring.getPattern(), coloring.getRender()) ).toString(); if (context.debug) { logDebugInfo(context, coloring, result); } return result; } } return context.entryText; } ColorLinesMatchingPatternFilter(); @Override String filter(Context context); }### Answer: @Test(expected = RuntimeException.class) public void blowUpForUnknownColor() { Config config = config(colorConfig("hello", "@|unknown $0|@")); filter.filter(context(config, "hello")); } @Test public void noForegroundColor() { Config config = config(colorConfig("hello", "@|bg_red $0|@")); String result = filter.filter(context(config, "hello")); assertEquals(ansi().bg(RED).a("hello").reset().toString(), result); } @Test public void noBackgroundColor() { Config config = config(colorConfig("hello", "@|white $0|@")); String result = filter.filter(context(config, "hello")); assertEquals(ansi().fg(WHITE).a("hello").reset().toString(), result); } @Test public void lineMatchesWithBackgroundAndForegroundColor() { Config config = config(colorConfig("hello", "@|bg_red,fg_white $0|@")); String result = filter.filter(context(config, "hello")); assertEquals(ansi().bg(RED).fg(WHITE).a("hello").reset().toString(), result); } @Test public void allowEmptyRenderValue() { Config config = config(colorConfig("hello", "")); assertEquals("", filter.filter(context(config, "hello"))); } @Test public void multipleColorConfigs() { Config config = config(colorConfig("hello", "bg_red,fg_white"), colorConfig("world", "@|bg_green,fg_blue $0|@")); String result = filter.filter(context(config, "world")); assertEquals(ansi().bg(GREEN).fg(BLUE).a("world").reset().toString(), result); } @Test public void lineDoesNotMatch() { Config config = config(colorConfig("hello", "@|bg_red,fg_white $0|@")); assertEquals("world", filter.filter(context(config, "world"))); }
### Question: LogFilterApplier { public String apply(String text, String logLevel) { if (System.getProperties().containsKey(OFF_SWITCH)) { return text; } boolean displayDebugInfo = showDebugInfo(); if (config == null) config = configLoader.loadConfiguration(displayDebugInfo); String result = text; if (displayDebugInfo) System.out.println("Original log Text: [" + text + "]"); for (LogEntryFilter filter : filters) { LogEntryFilter.Context context = new LogEntryFilter.Context( result, config, displayDebugInfo, logLevel ); result = filter.filter(context); if (displayDebugInfo) System.out.println("Log text filtered by " + filter + ": [" + result + "]"); if (StringUtils.isBlank(result)) { return result; } } return result; } LogFilterApplier(); String apply(String text, String logLevel); boolean showDebugInfo(); void setConfigLoader(ConfigLoader configLoader); static final String OFF_SWITCH; static final String DEBUG_SWITCH; }### Answer: @Test public void systemPropertySwitchGivenToShutOffFiltering() { System.setProperty(OFF_SWITCH, ""); config.setRemoveLogLevel(true); assertEquals("[INFO] text", applier.apply("[INFO] text", MockLogLevel.INFO.name())); } @Test public void shouldNotAttemptToLoadSystemPropertyConfigFileWhenNoValueIsGiven() { expectSystemPropertyConfig(null); applier.apply("[INFO] test", MockLogLevel.INFO.name()); verify(serializer, never()).load(new File("")); } @Test public void envVariableConfigFileLocation() { config.setRemoveLogLevel(true); expectEnvConfig(config); expectGlobalConfig(new Config()); assertEquals("test", applier.apply("[INFO] test", MockLogLevel.INFO.name())); } @Test public void systemPropertyLocationOfConfigFileShouldTrumpEverything() { Config systemPropertyConfig = new Config(); systemPropertyConfig.setRemoveLogLevel(true); expectSystemPropertyConfig(systemPropertyConfig); expectGlobalConfig(new Config()); expectEnvConfig(new Config()); assertEquals("test", applier.apply("[INFO] test", MockLogLevel.INFO.name())); } @Test public void shouldAttemptToLoadConfigFileInUsersHomeDirectory() { Config globalConfig = new Config(); globalConfig.setRemoveLogLevel(true); expectUserHomeConfig(globalConfig); expectGlobalConfig(new Config()); assertEquals("test", applier.apply("[INFO] test", MockLogLevel.INFO.name())); } @Test public void shouldAttemptToFindAGlobalConfigFileInTheClassPathBeforeUsingTheDefault() { Config globalConfig = new Config(); globalConfig.setRemoveLogLevel(true); expectGlobalConfig(globalConfig); assertEquals("test", applier.apply("[INFO] test", MockLogLevel.INFO.name())); } @Test public void shouldNotAddTimestampToLineThatHasBeenClearedByAnotherFilter() { ClearLineFilter.clearLine = true; config.setTimestampPattern("yyyy/MM/dd"); assertEquals("", applier.apply("[INFO] test", MockLogLevel.INFO.name())); } @Test public void shouldNotAddTimestampToBlankLines() { config.setTimestampPattern("yyyy/MM/dd"); assertEquals("", applier.apply("", MockLogLevel.INFO.name())); } @Test public void configuredAddTimestampAndRemoveLogLevel() { config.setRemoveLogLevel(true); config.setTimestampPattern("yyyy/MM/dd"); assertTrue(applier.apply("[INFO] text", MockLogLevel.INFO.name()).matches("[0-9]{4}/[0-9]{2}/[0-9]{2} text")); } @Test public void configuredToRemoveLogLevel() { config.setRemoveLogLevel(true); assertEquals("text", applier.apply("[INFO] text", MockLogLevel.INFO.name())); } @Test public void nothingIsConfigured() { assertEquals("[INFO] text", applier.apply("[INFO] text", MockLogLevel.INFO.name())); }
### Question: RemoveLogLevelFilter implements LogEntryFilter { @Override public String filter(Context context) { if (context.config.isRemoveLogLevel()) { String text = context.entryText; text = text.replace("[" + context.logLevel + "] ", ""); text = text.replace("[" + context.logLevel.toLowerCase() + "] ", ""); return text; } return context.entryText; } @Override String filter(Context context); }### Answer: @Test public void shouldNotCareAboutCase() { assertEquals("", filter.filter(context("info", true, MockLogLevel.INFO.name()))); } @Test public void removeLeadingScopeText() { for (MockLogLevel level : MockLogLevel.values()) { assertEquals("", filter.filter(context(true, level.name()))); } } @Test public void doNotThingWithTheFlagIsFalse() { for (MockLogLevel level : MockLogLevel.values()) { assertEquals("[" + level.name() + "] ", filter.filter(context(false, level.name()))); } }
### Question: AddTimestampFilter implements LogEntryFilter { @Override public String filter(Context context) { StringBuilder builder = new StringBuilder(); if (isPatternProvided(context)) { builder.append(formatter(context).format(new Date())); builder.append(" "); } builder.append(context.entryText); return builder.toString(); } @Override String filter(Context context); }### Answer: @Test public void patternProvided() { SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy"); assertEquals(format.format(new Date()) + " entry", filter.filter(context("entry", "MM/dd/yyyy"))); } @Test public void noDatePatternProvided() { assertEquals("entry", filter.filter(context("entry", " "))); }
### Question: Slf4jLogLevel { public static String toString(int level) { String text = ""; switch (level) { case LocationAwareLogger.TRACE_INT: text = "TRACE"; break; case LocationAwareLogger.DEBUG_INT: text = "DEBUG"; break; case LocationAwareLogger.WARN_INT: text = "WARN"; break; case LocationAwareLogger.ERROR_INT: text = "ERROR"; break; case LocationAwareLogger.INFO_INT: text = "INFO"; break; default: throw new IllegalArgumentException("Not sure what log level this is (level=" + level + ")"); } return text; } static String toString(int level); }### Answer: @Test(expected = IllegalArgumentException.class) public void unsupportedLevel() { Slf4jLogLevel.toString(Integer.MAX_VALUE); } @Test public void levels() { assertEquals("TRACE", Slf4jLogLevel.toString(LocationAwareLogger.TRACE_INT)); assertEquals("DEBUG", Slf4jLogLevel.toString(LocationAwareLogger.DEBUG_INT)); assertEquals("INFO", Slf4jLogLevel.toString(LocationAwareLogger.INFO_INT)); assertEquals("WARN", Slf4jLogLevel.toString(LocationAwareLogger.WARN_INT)); assertEquals("ERROR", Slf4jLogLevel.toString(LocationAwareLogger.ERROR_INT)); }
### Question: RedisPoolProperty { public static RedisPoolProperty initByIdFromConfig(String id){ RedisPoolProperty property = new RedisPoolProperty(); String pre = id+Configs.SEPARATE; List<String> lists = MythReflect.getFieldByClass(RedisPoolProperty.class); Map<String ,Object> map = new HashMap<>(); MythProperties config; try { config = PropertyFile.getProperties(Configs.PROPERTY_FILE); for (String field:lists){ map.put(field,config.getString(pre+field)); } property = (RedisPoolProperty) MythReflect.setFieldsValue(property,map); } catch (Exception e) { e.printStackTrace(); } return property; } static RedisPoolProperty initByIdFromConfig(String id); static void updateConfigFile(RedisPoolProperty property); @Override String toString(); }### Answer: @Test public void testInitByIdFromConfig() throws Exception { }
### Question: PoolManagement { public boolean switchPool(String PoolId) { try { if (PropertyFile.getAllPoolConfig().containsKey(PoolId)) { currentPoolId = PoolId; return true; } else { return false; } } catch (ReadConfigException e) { e.printStackTrace(); return false; } } private PoolManagement(); synchronized static PoolManagement getInstance(); RedisPools getRedisPool(); RedisPools getRedisPool(String poolId); RedisPools createRedisPoolAndConnection(RedisPoolProperty property); String createRedisPool(RedisPoolProperty property); boolean checkConnection(RedisPoolProperty property); boolean switchPool(String PoolId); String deleteRedisPool(String poolId); boolean clearAllPools(); boolean destroyRedisPool(String poolId); boolean destroyRedisPool(RedisPools redisPools); ConcurrentMap<String, RedisPools> getPoolMap(); }### Answer: @Test public void testSwitchPool() throws Exception { }
### Question: PoolManagement { public String deleteRedisPool(String poolId) throws IOException { try { configFile = PropertyFile.getProperties(propertyFile); String exist = configFile.getString(poolId + Configs.SEPARATE + Configs.POOL_ID); if (exist == null) { logger.error(ExceptionInfo.DELETE_POOL_NOT_EXIST + poolId); return null; } for (String key : MythReflect.getFieldByClass(RedisPoolProperty.class)) { PropertyFile.delete(poolId + Configs.SEPARATE + key); } } catch (Exception e) { logger.error(ExceptionInfo.OPEN_CONFIG_FAILED, e); return null; } logger.info(NoticeInfo.DELETE_POOL_SUCCESS + poolId, PoolManagement.class); return poolId; } private PoolManagement(); synchronized static PoolManagement getInstance(); RedisPools getRedisPool(); RedisPools getRedisPool(String poolId); RedisPools createRedisPoolAndConnection(RedisPoolProperty property); String createRedisPool(RedisPoolProperty property); boolean checkConnection(RedisPoolProperty property); boolean switchPool(String PoolId); String deleteRedisPool(String poolId); boolean clearAllPools(); boolean destroyRedisPool(String poolId); boolean destroyRedisPool(RedisPools redisPools); ConcurrentMap<String, RedisPools> getPoolMap(); }### Answer: @Test public void testDeleteRedisPool() throws Exception { String id = null; String result = poolManagement.deleteRedisPool(id); Assert.assertEquals(id, result); }
### Question: PoolManagement { public boolean clearAllPools() throws Exception { int maxId = PropertyFile.getMaxId(); for (int i = Configs.START_ID; i <= maxId; i++) { String result = deleteRedisPool(i + ""); if (result != null) { logger.info(NoticeInfo.DELETE_POOL_SUCCESS + i); } else { logger.info(NoticeInfo.DELETE_POOL_FAILED + i); } } return true; } private PoolManagement(); synchronized static PoolManagement getInstance(); RedisPools getRedisPool(); RedisPools getRedisPool(String poolId); RedisPools createRedisPoolAndConnection(RedisPoolProperty property); String createRedisPool(RedisPoolProperty property); boolean checkConnection(RedisPoolProperty property); boolean switchPool(String PoolId); String deleteRedisPool(String poolId); boolean clearAllPools(); boolean destroyRedisPool(String poolId); boolean destroyRedisPool(RedisPools redisPools); ConcurrentMap<String, RedisPools> getPoolMap(); }### Answer: @Test public void testClearAllPools() throws Exception { }
### Question: PoolManagement { public boolean destroyRedisPool(String poolId) { if (poolMap.containsKey(poolId)) { boolean flag = poolMap.get(poolId).destroyPool(); poolMap.remove(poolId); return flag; } else { return false; } } private PoolManagement(); synchronized static PoolManagement getInstance(); RedisPools getRedisPool(); RedisPools getRedisPool(String poolId); RedisPools createRedisPoolAndConnection(RedisPoolProperty property); String createRedisPool(RedisPoolProperty property); boolean checkConnection(RedisPoolProperty property); boolean switchPool(String PoolId); String deleteRedisPool(String poolId); boolean clearAllPools(); boolean destroyRedisPool(String poolId); boolean destroyRedisPool(RedisPools redisPools); ConcurrentMap<String, RedisPools> getPoolMap(); }### Answer: @Test public void testDestroyRedisPool() throws Exception { boolean result = poolManagement.destroyRedisPool("1292"); Assert.assertEquals(false, result); }
### Question: MythReflect { public static List<String> getFieldsByInstance(Object object) throws IllegalAccessException { target = object.getClass(); return getFieldByClass(target); } static List<String> getFieldsByInstance(Object object); static List<String> getFieldByClass(Class targets); static Map<String, Object> getFieldsValue(Object object); static Object setFieldsValue(Object object, Map<String, Object> maps); }### Answer: @Test public void testGetFieldsByInstance() throws Exception { Target target = new Target(); List<String> result = MythReflect.getFieldsByInstance(target); Assert.assertEquals(Collections.<String>singletonList("name"), result); }
### Question: MythReflect { public static List<String> getFieldByClass(Class targets) { target = targets; List<String> list = new ArrayList<>(); Field[] fields = target.getDeclaredFields(); for (Field field : fields) { field.setAccessible(true); String name = field.getName(); list.add(name); } return list; } static List<String> getFieldsByInstance(Object object); static List<String> getFieldByClass(Class targets); static Map<String, Object> getFieldsValue(Object object); static Object setFieldsValue(Object object, Map<String, Object> maps); }### Answer: @Test public void testGetFieldByClass() throws Exception { List<String> result = MythReflect.getFieldByClass(Target.class); Assert.assertEquals(Collections.<String>singletonList("name"), result); }
### Question: MythReflect { public static Map<String, Object> getFieldsValue(Object object) throws IllegalAccessException { Map<String, Object> map = new HashMap<>(); target = object.getClass(); for (Field field : target.getDeclaredFields()) { field.setAccessible(true); Object value = field.get(object); String name = field.getName(); map.put(name, value); } return map; } static List<String> getFieldsByInstance(Object object); static List<String> getFieldByClass(Class targets); static Map<String, Object> getFieldsValue(Object object); static Object setFieldsValue(Object object, Map<String, Object> maps); }### Answer: @Test public void testGetFieldsValue() throws Exception { Target target = new Target(); target.setName("myth"); Map<String, Object> result = MythReflect.getFieldsValue(target); Assert.assertEquals(new HashMap<String, Object>() {{ put("name", "myth"); }}, result); }
### Question: MythReflect { public static Object setFieldsValue(Object object, Map<String, Object> maps) throws Exception { target = object.getClass(); try { for (Field field : target.getDeclaredFields()) { field.setAccessible(true); String type = field.getType().getName(); switch (type) { case "java.lang.Integer": field.set(object, Integer.parseInt(maps.get(field.getName()).toString())); break; case "java.lang.String": field.set(object, maps.get(field.getName())); break; case "boolean": field.set(object, "true".equals(maps.get(field.getName()).toString())); break; } } } catch (Exception e) { throw new TypeErrorException(ExceptionInfo.TYPE_ERROR, e, MythReflect.class); } return object; } static List<String> getFieldsByInstance(Object object); static List<String> getFieldByClass(Class targets); static Map<String, Object> getFieldsValue(Object object); static Object setFieldsValue(Object object, Map<String, Object> maps); }### Answer: @Test public void testSetFieldsValue() throws Exception { Target target = new Target(); Target result = (Target) MythReflect.setFieldsValue(target, new HashMap<String, Object>() {{ put("name", "myth"); }}); Assert.assertEquals("myth", result.getName()); }
### Question: MythTime { public static String getTime() { Date date = new Date(); simpleDateFormat = new SimpleDateFormat("HH:mm:ss:MM"); return simpleDateFormat.format(date); } static String getTime(); static String getDateTime(); static String getDate(); }### Answer: @Test public void getTime() throws Exception { System.out.println(MythTime.getTime()); }
### Question: MythTime { public static String getDateTime() { Date date = new Date(); simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:MM"); return simpleDateFormat.format(date); } static String getTime(); static String getDateTime(); static String getDate(); }### Answer: @Test public void getDateTime() throws Exception { System.out.println(MythTime.getDateTime()); }
### Question: PropertyFile { public static String save(String key, String value) throws ReadConfigException { String result; try { getFromFile(); result = (String)props.setProperty(key, value); props.store(fos, "Update '" + key + "' value"); } catch (IOException e) { e.printStackTrace(); throw new ReadConfigException(ExceptionInfo.SAVE_CONFIG__KEY_FAILED,e,PropertyFile.class); } return result; } static MythProperties getProperties(String propertyFile); static String save(String key, String value); static String delete(String key); static String update(String key,String value); static int getMaxId(); static Map<String,RedisPoolProperty> getAllPoolConfig(); }### Answer: @Test public void testSave() throws Exception { PropertyFile.delete(testKey); String result = PropertyFile.save(testKey, "value"); PropertyFile.delete(testKey); Assert.assertEquals(null, result); }
### Question: MythTime { public static String getDate() { Date date = new Date(); simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd"); return simpleDateFormat.format(date); } static String getTime(); static String getDateTime(); static String getDate(); }### Answer: @Test public void testDate(){ System.out.println(MythTime.getDate()); }
### Question: RedisList extends Commands { public long rPush(String key, String... values) { return getJedis().rpush(key, values); } private RedisList(); synchronized static RedisList getInstance(); long rPush(String key, String... values); long lPush(String key, String... values); long lPushX(String key, String... value); long rPushX(String key, String... value); String rPop(String key); String lPop(String key); String rPopLPush(String one, String other); long length(String key); String setByIndex(String key, long index, String value); long insertAfter(String key, String pivot, String value); long insertBefore(String key, String pivot, String value); List<String> range(String key, long start, long end); List<String> allElements(String key); long remove(String key, long count, String value); String trim(String key, long start, long end); String index(String key, long index); }### Answer: @Test public void testRPush() throws Exception { redisList.deleteKey(testKey); redisList.rPush(testKey, "values"); redisList.rPush(testKey, "values"); redisList.rPush(testKey, "values"); redisList.rPush(testKey, "values"); redisList.rPush(testKey, "values"); long result = redisList.rPush(testKey, "values"); Assert.assertEquals(6L, result); } @Test public void testType() throws Exception { deleteKeyForTest(); redisList.rPush(testKey,"er"); String result = redisList.type(testKey); Assert.assertEquals("list", result); deleteKeyForTest(); }
### Question: RedisList extends Commands { public long lPush(String key, String... values) { return getJedis().lpush(key, values); } private RedisList(); synchronized static RedisList getInstance(); long rPush(String key, String... values); long lPush(String key, String... values); long lPushX(String key, String... value); long rPushX(String key, String... value); String rPop(String key); String lPop(String key); String rPopLPush(String one, String other); long length(String key); String setByIndex(String key, long index, String value); long insertAfter(String key, String pivot, String value); long insertBefore(String key, String pivot, String value); List<String> range(String key, long start, long end); List<String> allElements(String key); long remove(String key, long count, String value); String trim(String key, long start, long end); String index(String key, long index); }### Answer: @Test public void testLPush() throws Exception { redisList.deleteKey(testKey); long result = redisList.lPush(testKey, "values"); Assert.assertEquals(1L, result); }
### Question: RedisList extends Commands { public long lPushX(String key, String... value) { return getJedis().lpushx(key, value); } private RedisList(); synchronized static RedisList getInstance(); long rPush(String key, String... values); long lPush(String key, String... values); long lPushX(String key, String... value); long rPushX(String key, String... value); String rPop(String key); String lPop(String key); String rPopLPush(String one, String other); long length(String key); String setByIndex(String key, long index, String value); long insertAfter(String key, String pivot, String value); long insertBefore(String key, String pivot, String value); List<String> range(String key, long start, long end); List<String> allElements(String key); long remove(String key, long count, String value); String trim(String key, long start, long end); String index(String key, long index); }### Answer: @Test public void testLPushX() throws Exception { redisList.deleteKey(testKey); long result = redisList.lPushX(testKey, "value"); Assert.assertEquals(0L, result); }
### Question: RedisList extends Commands { public long rPushX(String key, String... value) { return getJedis().rpushx(key, value); } private RedisList(); synchronized static RedisList getInstance(); long rPush(String key, String... values); long lPush(String key, String... values); long lPushX(String key, String... value); long rPushX(String key, String... value); String rPop(String key); String lPop(String key); String rPopLPush(String one, String other); long length(String key); String setByIndex(String key, long index, String value); long insertAfter(String key, String pivot, String value); long insertBefore(String key, String pivot, String value); List<String> range(String key, long start, long end); List<String> allElements(String key); long remove(String key, long count, String value); String trim(String key, long start, long end); String index(String key, long index); }### Answer: @Test public void testRPushX() throws Exception { deleteKeyForTest(); long result = redisList.rPushX(testKey, "value"); Assert.assertEquals(0L, result); }
### Question: RedisList extends Commands { public String rPop(String key) { return getJedis().rpop(key); } private RedisList(); synchronized static RedisList getInstance(); long rPush(String key, String... values); long lPush(String key, String... values); long lPushX(String key, String... value); long rPushX(String key, String... value); String rPop(String key); String lPop(String key); String rPopLPush(String one, String other); long length(String key); String setByIndex(String key, long index, String value); long insertAfter(String key, String pivot, String value); long insertBefore(String key, String pivot, String value); List<String> range(String key, long start, long end); List<String> allElements(String key); long remove(String key, long count, String value); String trim(String key, long start, long end); String index(String key, long index); }### Answer: @Test public void testRPop() throws Exception { deleteKeyForTest(); redisList.rPush(testKey,"1","2"); String result = redisList.rPop(testKey); Assert.assertEquals("2", result); deleteKeyForTest(); }
### Question: RedisList extends Commands { public String lPop(String key) { return getJedis().lpop(key); } private RedisList(); synchronized static RedisList getInstance(); long rPush(String key, String... values); long lPush(String key, String... values); long lPushX(String key, String... value); long rPushX(String key, String... value); String rPop(String key); String lPop(String key); String rPopLPush(String one, String other); long length(String key); String setByIndex(String key, long index, String value); long insertAfter(String key, String pivot, String value); long insertBefore(String key, String pivot, String value); List<String> range(String key, long start, long end); List<String> allElements(String key); long remove(String key, long count, String value); String trim(String key, long start, long end); String index(String key, long index); }### Answer: @Test public void testLPop() throws Exception { redisList.deleteKey(testKey); String result = redisList.lPop(testKey); Assert.assertEquals(null, result); }
### Question: RedisList extends Commands { public String rPopLPush(String one, String other) { return getJedis().rpoplpush(one, other); } private RedisList(); synchronized static RedisList getInstance(); long rPush(String key, String... values); long lPush(String key, String... values); long lPushX(String key, String... value); long rPushX(String key, String... value); String rPop(String key); String lPop(String key); String rPopLPush(String one, String other); long length(String key); String setByIndex(String key, long index, String value); long insertAfter(String key, String pivot, String value); long insertBefore(String key, String pivot, String value); List<String> range(String key, long start, long end); List<String> allElements(String key); long remove(String key, long count, String value); String trim(String key, long start, long end); String index(String key, long index); }### Answer: @Test public void testRPopLPush() throws Exception { redisList.deleteKey("one"); redisList.deleteKey("other"); redisList.rPush("one","1"); redisList.rPush("other","2"); Assert.assertEquals("1",redisList.rPopLPush("one", "other")); Assert.assertEquals(null,redisList.rPopLPush("one", "other")); redisList.deleteKey("one"); redisList.deleteKey("other"); }
### Question: RedisList extends Commands { public long length(String key) { return getJedis().llen(key); } private RedisList(); synchronized static RedisList getInstance(); long rPush(String key, String... values); long lPush(String key, String... values); long lPushX(String key, String... value); long rPushX(String key, String... value); String rPop(String key); String lPop(String key); String rPopLPush(String one, String other); long length(String key); String setByIndex(String key, long index, String value); long insertAfter(String key, String pivot, String value); long insertBefore(String key, String pivot, String value); List<String> range(String key, long start, long end); List<String> allElements(String key); long remove(String key, long count, String value); String trim(String key, long start, long end); String index(String key, long index); }### Answer: @Test public void testLength() throws Exception { deleteKeyForTest(); redisList.rPush(testKey,"1"); redisList.lPush(testKey,"2"); long result = redisList.length(testKey); Assert.assertEquals(2L, result); deleteKeyForTest(); }
### Question: RedisList extends Commands { public String setByIndex(String key, long index, String value) throws ActionErrorException { String result; try { result = getJedis().lset(key, index, value); return result; } catch (Exception e) { throw new ActionErrorException(ExceptionInfo.KEY_NOT_EXIST, e, RedisList.class); } } private RedisList(); synchronized static RedisList getInstance(); long rPush(String key, String... values); long lPush(String key, String... values); long lPushX(String key, String... value); long rPushX(String key, String... value); String rPop(String key); String lPop(String key); String rPopLPush(String one, String other); long length(String key); String setByIndex(String key, long index, String value); long insertAfter(String key, String pivot, String value); long insertBefore(String key, String pivot, String value); List<String> range(String key, long start, long end); List<String> allElements(String key); long remove(String key, long count, String value); String trim(String key, long start, long end); String index(String key, long index); }### Answer: @Test public void testSetByIndex() throws Exception { redisList.lPush(testKey,"12"); String result = redisList.setByIndex(testKey, 0L, "value"); Assert.assertEquals("OK", result); deleteKeyForTest(); }
### Question: PropertyFile { public static String delete(String key) throws ReadConfigException { String result; try { getFromFile(); result = (String) props.remove(key); props.store(fos, "Delete '" + key + "' value"); }catch (Exception e){ e.printStackTrace(); throw new ReadConfigException(ExceptionInfo.DELETE_CONFIG_KEY_FAILED,e,PropertyFile.class); } return result; } static MythProperties getProperties(String propertyFile); static String save(String key, String value); static String delete(String key); static String update(String key,String value); static int getMaxId(); static Map<String,RedisPoolProperty> getAllPoolConfig(); }### Answer: @Test public void testDelete() throws Exception { String result = PropertyFile.delete(testKey); Assert.assertEquals(null, result); }
### Question: RedisList extends Commands { public long insertAfter(String key, String pivot, String value) { return getJedis().linsert(key, BinaryClient.LIST_POSITION.AFTER, pivot, value); } private RedisList(); synchronized static RedisList getInstance(); long rPush(String key, String... values); long lPush(String key, String... values); long lPushX(String key, String... value); long rPushX(String key, String... value); String rPop(String key); String lPop(String key); String rPopLPush(String one, String other); long length(String key); String setByIndex(String key, long index, String value); long insertAfter(String key, String pivot, String value); long insertBefore(String key, String pivot, String value); List<String> range(String key, long start, long end); List<String> allElements(String key); long remove(String key, long count, String value); String trim(String key, long start, long end); String index(String key, long index); }### Answer: @Test public void testInsertAfter() throws Exception { deleteKeyForTest(); redisList.lPush(testKey,"12"); long result = redisList.insertAfter(testKey, "12", "value"); Assert.assertEquals(2L, result); deleteKeyForTest(); }
### Question: RedisList extends Commands { public long insertBefore(String key, String pivot, String value) { return getJedis().linsert(key, BinaryClient.LIST_POSITION.BEFORE, pivot, value); } private RedisList(); synchronized static RedisList getInstance(); long rPush(String key, String... values); long lPush(String key, String... values); long lPushX(String key, String... value); long rPushX(String key, String... value); String rPop(String key); String lPop(String key); String rPopLPush(String one, String other); long length(String key); String setByIndex(String key, long index, String value); long insertAfter(String key, String pivot, String value); long insertBefore(String key, String pivot, String value); List<String> range(String key, long start, long end); List<String> allElements(String key); long remove(String key, long count, String value); String trim(String key, long start, long end); String index(String key, long index); }### Answer: @Test public void testInsertBefore() throws Exception { deleteKeyForTest(); redisList.lPush(testKey,"12"); long result = redisList.insertBefore(testKey, "12", "value"); Assert.assertEquals(2L, result); deleteKeyForTest(); }
### Question: RedisList extends Commands { public List<String> range(String key, long start, long end) { logger.debug("Get range: [" + key + "] form " + start + " to " + end); return getJedis().lrange(key, start, end); } private RedisList(); synchronized static RedisList getInstance(); long rPush(String key, String... values); long lPush(String key, String... values); long lPushX(String key, String... value); long rPushX(String key, String... value); String rPop(String key); String lPop(String key); String rPopLPush(String one, String other); long length(String key); String setByIndex(String key, long index, String value); long insertAfter(String key, String pivot, String value); long insertBefore(String key, String pivot, String value); List<String> range(String key, long start, long end); List<String> allElements(String key); long remove(String key, long count, String value); String trim(String key, long start, long end); String index(String key, long index); }### Answer: @Test public void testRange() throws Exception { deleteKeyForTest(); redisList.rPush(testKey,"23","12"); List<String> result = redisList.range(testKey, 0L, -1L); Assert.assertEquals(Arrays.<String>asList("23","12"), result); deleteKeyForTest(); }
### Question: RedisList extends Commands { public long remove(String key, long count, String value) { return getJedis().lrem(key, count, value); } private RedisList(); synchronized static RedisList getInstance(); long rPush(String key, String... values); long lPush(String key, String... values); long lPushX(String key, String... value); long rPushX(String key, String... value); String rPop(String key); String lPop(String key); String rPopLPush(String one, String other); long length(String key); String setByIndex(String key, long index, String value); long insertAfter(String key, String pivot, String value); long insertBefore(String key, String pivot, String value); List<String> range(String key, long start, long end); List<String> allElements(String key); long remove(String key, long count, String value); String trim(String key, long start, long end); String index(String key, long index); }### Answer: @Test public void testRemove() throws Exception { deleteKeyForTest(); redisList.lPush(testKey,"23","123","23"); redisList.remove(testKey, 1L, "23"); Assert.assertEquals(Arrays.<String>asList("123","23"), redisList.allElements(testKey)); redisList.lPush(testKey,"23"); redisList.remove(testKey, -1L, "23"); Assert.assertEquals(Arrays.<String>asList("23","123"), redisList.allElements(testKey)); deleteKeyForTest(); }
### Question: RedisList extends Commands { public String trim(String key, long start, long end) { return getJedis().ltrim(key, start, end); } private RedisList(); synchronized static RedisList getInstance(); long rPush(String key, String... values); long lPush(String key, String... values); long lPushX(String key, String... value); long rPushX(String key, String... value); String rPop(String key); String lPop(String key); String rPopLPush(String one, String other); long length(String key); String setByIndex(String key, long index, String value); long insertAfter(String key, String pivot, String value); long insertBefore(String key, String pivot, String value); List<String> range(String key, long start, long end); List<String> allElements(String key); long remove(String key, long count, String value); String trim(String key, long start, long end); String index(String key, long index); }### Answer: @Test public void testTrim() throws Exception { deleteKeyForTest(); redisList.rPush(testKey,"1","2","3","4"); String result = redisList.trim(testKey, 0L, 1L); Assert.assertEquals(Arrays.<String>asList("1","2"), redisList.allElements(testKey)); Assert.assertEquals("OK",result); }
### Question: RedisList extends Commands { public String index(String key, long index) { return getJedis().lindex(key, index); } private RedisList(); synchronized static RedisList getInstance(); long rPush(String key, String... values); long lPush(String key, String... values); long lPushX(String key, String... value); long rPushX(String key, String... value); String rPop(String key); String lPop(String key); String rPopLPush(String one, String other); long length(String key); String setByIndex(String key, long index, String value); long insertAfter(String key, String pivot, String value); long insertBefore(String key, String pivot, String value); List<String> range(String key, long start, long end); List<String> allElements(String key); long remove(String key, long count, String value); String trim(String key, long start, long end); String index(String key, long index); }### Answer: @Test public void testIndex() throws Exception { deleteKeyForTest(); redisList.rPush(testKey,"tests"); String result = redisList.index(testKey, 0L); Assert.assertEquals("tests", result); deleteKeyForTest(); }
### Question: RedisSet extends Commands { public Long save(String key, String... member) { return getJedis().sadd(key, member); } private RedisSet(); synchronized static RedisSet getInstance(); Long save(String key, String... member); Long remove(String key, String... members); Set<String> getMembersSet(String key); String pop(String key); Set<String> pop(String key, long count); Long size(String key); boolean contain(String key, String member); String randomMember(String key); List<String> randomMember(String key, int count); Set<String> inter(String... keys); Long interStore(String key, String... keys); Set<String> union(String... keys); Long unionStore(String key, String... keys); Set<String> diff(String... keys); Long diffStore(String key, String... keys); Long moveMember(String fromKey, String toKey, String member); }### Answer: @Test public void testAdd() throws Exception { deleteKey(); Long result = redisSet.save(key, "member","12","12"); Assert.assertEquals((Long)2L, result); showKey(); deleteKey(); }
### Question: RedisSet extends Commands { public Long remove(String key, String... members) { return getJedis().srem(key, members); } private RedisSet(); synchronized static RedisSet getInstance(); Long save(String key, String... member); Long remove(String key, String... members); Set<String> getMembersSet(String key); String pop(String key); Set<String> pop(String key, long count); Long size(String key); boolean contain(String key, String member); String randomMember(String key); List<String> randomMember(String key, int count); Set<String> inter(String... keys); Long interStore(String key, String... keys); Set<String> union(String... keys); Long unionStore(String key, String... keys); Set<String> diff(String... keys); Long diffStore(String key, String... keys); Long moveMember(String fromKey, String toKey, String member); }### Answer: @Test public void testRemove() throws Exception { redisSet.save(key,"2","23","3434","343223"); Long result = redisSet.remove(key, "2","23"); Assert.assertEquals((Long)2L, result); deleteKey(); }
### Question: RedisSet extends Commands { public Set<String> getMembersSet(String key) { return getJedis().smembers(key); } private RedisSet(); synchronized static RedisSet getInstance(); Long save(String key, String... member); Long remove(String key, String... members); Set<String> getMembersSet(String key); String pop(String key); Set<String> pop(String key, long count); Long size(String key); boolean contain(String key, String member); String randomMember(String key); List<String> randomMember(String key, int count); Set<String> inter(String... keys); Long interStore(String key, String... keys); Set<String> union(String... keys); Long unionStore(String key, String... keys); Set<String> diff(String... keys); Long diffStore(String key, String... keys); Long moveMember(String fromKey, String toKey, String member); }### Answer: @Test public void testGetMembersSet() throws Exception { redisSet.save(key,"2","23"); Set<String> result = redisSet.getMembersSet(key); Assert.assertEquals(new HashSet<String>(Arrays.asList("2","23")), result); deleteKey(); }
### Question: PropertyFile { public static String update(String key,String value) throws ReadConfigException { String result; try { props = getProperties(Configs.PROPERTY_FILE); OutputStream fos = new FileOutputStream(Configs.PROPERTY_FILE); result = (String)props.replace(key,value); props.store(fos, "Update '" + key + "' value"); }catch (Exception e){ e.printStackTrace(); throw new ReadConfigException(ExceptionInfo.UPDATE_CONFIG_KEY_FAILED,e,PropertyFile.class); } return result; } static MythProperties getProperties(String propertyFile); static String save(String key, String value); static String delete(String key); static String update(String key,String value); static int getMaxId(); static Map<String,RedisPoolProperty> getAllPoolConfig(); }### Answer: @Test public void testUpdate() throws Exception { PropertyFile.save(testKey,"origin"); String result = PropertyFile.update(testKey, "value"); PropertyFile.delete(testKey); Assert.assertEquals("origin", result); }
### Question: RedisSet extends Commands { public String pop(String key) { return getJedis().spop(key); } private RedisSet(); synchronized static RedisSet getInstance(); Long save(String key, String... member); Long remove(String key, String... members); Set<String> getMembersSet(String key); String pop(String key); Set<String> pop(String key, long count); Long size(String key); boolean contain(String key, String member); String randomMember(String key); List<String> randomMember(String key, int count); Set<String> inter(String... keys); Long interStore(String key, String... keys); Set<String> union(String... keys); Long unionStore(String key, String... keys); Set<String> diff(String... keys); Long diffStore(String key, String... keys); Long moveMember(String fromKey, String toKey, String member); }### Answer: @Test public void testPop() throws Exception { redisSet.save(key,"1","2","3"); String result = redisSet.pop(key); System.out.println("随机删除:"+result); Long results = redisSet.size(key); Assert.assertEquals((Long)2L,results); deleteKey(); }
### Question: RedisSet extends Commands { public boolean contain(String key, String member) { return getJedis().sismember(key, member); } private RedisSet(); synchronized static RedisSet getInstance(); Long save(String key, String... member); Long remove(String key, String... members); Set<String> getMembersSet(String key); String pop(String key); Set<String> pop(String key, long count); Long size(String key); boolean contain(String key, String member); String randomMember(String key); List<String> randomMember(String key, int count); Set<String> inter(String... keys); Long interStore(String key, String... keys); Set<String> union(String... keys); Long unionStore(String key, String... keys); Set<String> diff(String... keys); Long diffStore(String key, String... keys); Long moveMember(String fromKey, String toKey, String member); }### Answer: @Test public void testContain() throws Exception { redisSet.save(key,"member"); boolean result = redisSet.contain(key, "member"); Assert.assertEquals(true, result); deleteKey(); }
### Question: RedisSet extends Commands { public String randomMember(String key) { return getJedis().srandmember(key); } private RedisSet(); synchronized static RedisSet getInstance(); Long save(String key, String... member); Long remove(String key, String... members); Set<String> getMembersSet(String key); String pop(String key); Set<String> pop(String key, long count); Long size(String key); boolean contain(String key, String member); String randomMember(String key); List<String> randomMember(String key, int count); Set<String> inter(String... keys); Long interStore(String key, String... keys); Set<String> union(String... keys); Long unionStore(String key, String... keys); Set<String> diff(String... keys); Long diffStore(String key, String... keys); Long moveMember(String fromKey, String toKey, String member); }### Answer: @Test public void testRandomMember() throws Exception { redisSet.save(key,"sa"); String result = redisSet.randomMember(key); assert result!=null; deleteKey(); }
### Question: RedisSet extends Commands { public Set<String> inter(String... keys) { return getJedis().sinter(keys); } private RedisSet(); synchronized static RedisSet getInstance(); Long save(String key, String... member); Long remove(String key, String... members); Set<String> getMembersSet(String key); String pop(String key); Set<String> pop(String key, long count); Long size(String key); boolean contain(String key, String member); String randomMember(String key); List<String> randomMember(String key, int count); Set<String> inter(String... keys); Long interStore(String key, String... keys); Set<String> union(String... keys); Long unionStore(String key, String... keys); Set<String> diff(String... keys); Long diffStore(String key, String... keys); Long moveMember(String fromKey, String toKey, String member); }### Answer: @Test public void testInter() throws Exception { redisSet.save(key,"1","2","3"); redisSet.save("1","2","4"); Set<String> result = redisSet.inter(key,"1"); Assert.assertEquals(new HashSet<String>(Arrays.asList("2")), result); redisSet.deleteKey(key,"1"); }
### Question: RedisSet extends Commands { public Long interStore(String key, String... keys) { return getJedis().sinterstore(key, keys); } private RedisSet(); synchronized static RedisSet getInstance(); Long save(String key, String... member); Long remove(String key, String... members); Set<String> getMembersSet(String key); String pop(String key); Set<String> pop(String key, long count); Long size(String key); boolean contain(String key, String member); String randomMember(String key); List<String> randomMember(String key, int count); Set<String> inter(String... keys); Long interStore(String key, String... keys); Set<String> union(String... keys); Long unionStore(String key, String... keys); Set<String> diff(String... keys); Long diffStore(String key, String... keys); Long moveMember(String fromKey, String toKey, String member); }### Answer: @Test public void testInterStore() throws Exception { redisSet.save("store","1","23","45"); System.out.println(redisSet.getMembersSet("store")); redisSet.save(key,"1","2","3"); redisSet.save("1","2","4"); Long f = redisSet.interStore("store",key,"1"); System.out.println(f+" : "+redisSet.getMembersSet("store").toString()); Set<String> result = redisSet.getMembersSet("store"); Assert.assertEquals(new HashSet<String>(Arrays.asList("2")),result); redisSet.deleteKey(key,"1","store"); }
### Question: RedisSet extends Commands { public Set<String> union(String... keys) { return getJedis().sunion(keys); } private RedisSet(); synchronized static RedisSet getInstance(); Long save(String key, String... member); Long remove(String key, String... members); Set<String> getMembersSet(String key); String pop(String key); Set<String> pop(String key, long count); Long size(String key); boolean contain(String key, String member); String randomMember(String key); List<String> randomMember(String key, int count); Set<String> inter(String... keys); Long interStore(String key, String... keys); Set<String> union(String... keys); Long unionStore(String key, String... keys); Set<String> diff(String... keys); Long diffStore(String key, String... keys); Long moveMember(String fromKey, String toKey, String member); }### Answer: @Test public void testUnion() throws Exception { redisSet.save("1","1","2","3"); redisSet.save("2","2","3","4"); Set<String> result = redisSet.union("1","2"); Assert.assertEquals(new HashSet<String>(Arrays.asList("1","2","3","4")), result); redisSet.deleteKey("1","2"); }
### Question: RedisSet extends Commands { public Long unionStore(String key, String... keys) { return getJedis().sunionstore(key, keys); } private RedisSet(); synchronized static RedisSet getInstance(); Long save(String key, String... member); Long remove(String key, String... members); Set<String> getMembersSet(String key); String pop(String key); Set<String> pop(String key, long count); Long size(String key); boolean contain(String key, String member); String randomMember(String key); List<String> randomMember(String key, int count); Set<String> inter(String... keys); Long interStore(String key, String... keys); Set<String> union(String... keys); Long unionStore(String key, String... keys); Set<String> diff(String... keys); Long diffStore(String key, String... keys); Long moveMember(String fromKey, String toKey, String member); }### Answer: @Test public void testUnionStore() throws Exception { redisSet.save("1","1","2","3"); redisSet.save("2","2","3","4"); Long num = redisSet.unionStore("store","1","2"); System.out.println(num); Set<String> result = redisSet.getMembersSet("store"); Assert.assertEquals(new HashSet<String>(Arrays.asList("1","2","3","4")), result); redisSet.deleteKey("1","2","store"); }
### Question: RedisSet extends Commands { public Set<String> diff(String... keys) { return getJedis().sdiff(keys); } private RedisSet(); synchronized static RedisSet getInstance(); Long save(String key, String... member); Long remove(String key, String... members); Set<String> getMembersSet(String key); String pop(String key); Set<String> pop(String key, long count); Long size(String key); boolean contain(String key, String member); String randomMember(String key); List<String> randomMember(String key, int count); Set<String> inter(String... keys); Long interStore(String key, String... keys); Set<String> union(String... keys); Long unionStore(String key, String... keys); Set<String> diff(String... keys); Long diffStore(String key, String... keys); Long moveMember(String fromKey, String toKey, String member); }### Answer: @Test public void testDiff() throws Exception { redisSet.save("1","1","2","3","5"); redisSet.save("2","2","3","4","6"); redisSet.save("3","1","4"); Set<String> result = redisSet.diff("1","2","3"); Assert.assertEquals(new HashSet<String>(Arrays.asList("5")), result); redisSet.deleteKey("1","2"); }
### Question: RedisSet extends Commands { public Long diffStore(String key, String... keys) { return getJedis().sdiffstore(key, keys); } private RedisSet(); synchronized static RedisSet getInstance(); Long save(String key, String... member); Long remove(String key, String... members); Set<String> getMembersSet(String key); String pop(String key); Set<String> pop(String key, long count); Long size(String key); boolean contain(String key, String member); String randomMember(String key); List<String> randomMember(String key, int count); Set<String> inter(String... keys); Long interStore(String key, String... keys); Set<String> union(String... keys); Long unionStore(String key, String... keys); Set<String> diff(String... keys); Long diffStore(String key, String... keys); Long moveMember(String fromKey, String toKey, String member); }### Answer: @Test public void testDiffStore() throws Exception { redisSet.save("1","1","2","3","5"); redisSet.save("2","2","3","4","6"); redisSet.save("3","1","4"); Long num = redisSet.diffStore("store","1","2","3"); System.out.println(num); Set<String> result = redisSet.getMembersSet("store"); Assert.assertEquals(new HashSet<String>(Arrays.asList("5")), result); redisSet.deleteKey("store","1","2","3"); }
### Question: RedisSet extends Commands { public Long moveMember(String fromKey, String toKey, String member) { return getJedis().smove(fromKey, toKey, member); } private RedisSet(); synchronized static RedisSet getInstance(); Long save(String key, String... member); Long remove(String key, String... members); Set<String> getMembersSet(String key); String pop(String key); Set<String> pop(String key, long count); Long size(String key); boolean contain(String key, String member); String randomMember(String key); List<String> randomMember(String key, int count); Set<String> inter(String... keys); Long interStore(String key, String... keys); Set<String> union(String... keys); Long unionStore(String key, String... keys); Set<String> diff(String... keys); Long diffStore(String key, String... keys); Long moveMember(String fromKey, String toKey, String member); }### Answer: @Test public void testMoveMember() throws Exception { redisSet.save("1","2","3"); redisSet.save("2","2"); Long re = redisSet.moveMember("1", "2", "3"); System.out.println(re); Set<String> results = redisSet.getMembersSet("2"); Assert.assertEquals(new HashSet<String>(Arrays.asList("2","3")),results); redisSet.deleteKey("1","2"); }
### Question: PropertyFile { public static int getMaxId() throws ReadConfigException { String maxId; try { props = getProperties(Configs.PROPERTY_FILE); maxId = props.getString(Configs.MAX_POOL_ID); if (maxId == null) { save(Configs.MAX_POOL_ID, Configs.START_ID + ""); props = getProperties(Configs.PROPERTY_FILE); maxId = props.getString(Configs.MAX_POOL_ID); } }catch (Exception e){ e.printStackTrace(); throw new ReadConfigException(ExceptionInfo.OPEN_CONFIG_FAILED+"-获取maxId",e,PropertyFile.class); } return Integer.parseInt(maxId); } static MythProperties getProperties(String propertyFile); static String save(String key, String value); static String delete(String key); static String update(String key,String value); static int getMaxId(); static Map<String,RedisPoolProperty> getAllPoolConfig(); }### Answer: @Test public void testMaxId() throws ReadConfigException { int maxId = PropertyFile.getMaxId(); System.out.println(maxId); assert(maxId>=1000); }
### Question: RedisSortSet extends Commands { public Long save(String key, Double score, String member) { return getJedis().zadd(key, score, member); } private RedisSortSet(); synchronized static RedisSortSet getInstance(); Long save(String key, Double score, String member); Long index(String key, String member); Double score(String key, String member); Long rank(String key, String member); Set<String> range(String key, long start, long end); Set<Tuple> rangeWithScores(String key, long start, long end); Set<String> rangeByIndex(String key, long start, long end); Set<String> rangeByScore(String key, Double min, Double max); Set<String> rangeByLex(String key, String max, String min); Long removeByLex(String key, String min, String max); Long countByLex(String key, String min, String max); Set<String> getMemberSet(String key); Set<String> getMemberSetDesc(String key); Set<Tuple> getMemberSetWithScore(String key); Long interStore(String desKey, String... fromKey); Double increase(String key, Double score, String member); Long remove(String key, String... value); Long removeByRank(String key, long start, long end); Long removeByScore(String key, Double min, Double max); Long size(String key); Long count(String key, double min, double max); }### Answer: @Test public void testAdd() throws Exception { redisSortSet.save(key,3.3,"one"); redisSortSet.save(key,5.3,"two"); Long result = redisSortSet.save(key, 2.12, "member"); show(); Assert.assertEquals((Long)1L, result); }
### Question: RedisSortSet extends Commands { public Long index(String key, String member) { return getJedis().zrank(key, member); } private RedisSortSet(); synchronized static RedisSortSet getInstance(); Long save(String key, Double score, String member); Long index(String key, String member); Double score(String key, String member); Long rank(String key, String member); Set<String> range(String key, long start, long end); Set<Tuple> rangeWithScores(String key, long start, long end); Set<String> rangeByIndex(String key, long start, long end); Set<String> rangeByScore(String key, Double min, Double max); Set<String> rangeByLex(String key, String max, String min); Long removeByLex(String key, String min, String max); Long countByLex(String key, String min, String max); Set<String> getMemberSet(String key); Set<String> getMemberSetDesc(String key); Set<Tuple> getMemberSetWithScore(String key); Long interStore(String desKey, String... fromKey); Double increase(String key, Double score, String member); Long remove(String key, String... value); Long removeByRank(String key, long start, long end); Long removeByScore(String key, Double min, Double max); Long size(String key); Long count(String key, double min, double max); }### Answer: @Test public void testIndex() throws Exception { redisSortSet.save(key, 2.12, "members"); redisSortSet.save(key, 2.52, "member"); redisSortSet.save(key, 2.02, "member"); Long result = redisSortSet.index(key, "member"); show(); Assert.assertEquals((Long)0L, result); }
### Question: RedisSortSet extends Commands { public Double score(String key, String member) { return getJedis().zscore(key, member); } private RedisSortSet(); synchronized static RedisSortSet getInstance(); Long save(String key, Double score, String member); Long index(String key, String member); Double score(String key, String member); Long rank(String key, String member); Set<String> range(String key, long start, long end); Set<Tuple> rangeWithScores(String key, long start, long end); Set<String> rangeByIndex(String key, long start, long end); Set<String> rangeByScore(String key, Double min, Double max); Set<String> rangeByLex(String key, String max, String min); Long removeByLex(String key, String min, String max); Long countByLex(String key, String min, String max); Set<String> getMemberSet(String key); Set<String> getMemberSetDesc(String key); Set<Tuple> getMemberSetWithScore(String key); Long interStore(String desKey, String... fromKey); Double increase(String key, Double score, String member); Long remove(String key, String... value); Long removeByRank(String key, long start, long end); Long removeByScore(String key, Double min, Double max); Long size(String key); Long count(String key, double min, double max); }### Answer: @Test public void testScore() throws Exception { redisSortSet.save(key, 2.52, "member"); Double result = redisSortSet.score(key, "member"); show(); Assert.assertEquals((Double)2.52, result); }
### Question: RedisSortSet extends Commands { public Long rank(String key, String member) { return getJedis().zrevrank(key, member); } private RedisSortSet(); synchronized static RedisSortSet getInstance(); Long save(String key, Double score, String member); Long index(String key, String member); Double score(String key, String member); Long rank(String key, String member); Set<String> range(String key, long start, long end); Set<Tuple> rangeWithScores(String key, long start, long end); Set<String> rangeByIndex(String key, long start, long end); Set<String> rangeByScore(String key, Double min, Double max); Set<String> rangeByLex(String key, String max, String min); Long removeByLex(String key, String min, String max); Long countByLex(String key, String min, String max); Set<String> getMemberSet(String key); Set<String> getMemberSetDesc(String key); Set<Tuple> getMemberSetWithScore(String key); Long interStore(String desKey, String... fromKey); Double increase(String key, Double score, String member); Long remove(String key, String... value); Long removeByRank(String key, long start, long end); Long removeByScore(String key, Double min, Double max); Long size(String key); Long count(String key, double min, double max); }### Answer: @Test public void testRank() throws Exception { redisSortSet.save(key, 2.52, "member"); redisSortSet.save(key, 2.52, "members"); Long result = redisSortSet.rank(key, "member"); Assert.assertEquals((Long)1L, result); }
### Question: RedisSortSet extends Commands { public Set<String> rangeByIndex(String key, long start, long end) { return getJedis().zrevrange(key, start, end); } private RedisSortSet(); synchronized static RedisSortSet getInstance(); Long save(String key, Double score, String member); Long index(String key, String member); Double score(String key, String member); Long rank(String key, String member); Set<String> range(String key, long start, long end); Set<Tuple> rangeWithScores(String key, long start, long end); Set<String> rangeByIndex(String key, long start, long end); Set<String> rangeByScore(String key, Double min, Double max); Set<String> rangeByLex(String key, String max, String min); Long removeByLex(String key, String min, String max); Long countByLex(String key, String min, String max); Set<String> getMemberSet(String key); Set<String> getMemberSetDesc(String key); Set<Tuple> getMemberSetWithScore(String key); Long interStore(String desKey, String... fromKey); Double increase(String key, Double score, String member); Long remove(String key, String... value); Long removeByRank(String key, long start, long end); Long removeByScore(String key, Double min, Double max); Long size(String key); Long count(String key, double min, double max); }### Answer: @Test public void testRangeByIndex() throws Exception { redisSortSet.save(key,2.3,"a"); redisSortSet.save(key,2.3,"b"); redisSortSet.save(key,2.1,"c"); Set<String> result = redisSortSet.rangeByIndex(key, 0L, 1L); for(String s:result){ System.out.println(s); } show(); Assert.assertEquals(new HashSet<String>(Arrays.asList("b","a")), result); }
### Question: RedisSortSet extends Commands { public Set<String> rangeByScore(String key, Double min, Double max) { return getJedis().zrevrangeByScore(key, max, min); } private RedisSortSet(); synchronized static RedisSortSet getInstance(); Long save(String key, Double score, String member); Long index(String key, String member); Double score(String key, String member); Long rank(String key, String member); Set<String> range(String key, long start, long end); Set<Tuple> rangeWithScores(String key, long start, long end); Set<String> rangeByIndex(String key, long start, long end); Set<String> rangeByScore(String key, Double min, Double max); Set<String> rangeByLex(String key, String max, String min); Long removeByLex(String key, String min, String max); Long countByLex(String key, String min, String max); Set<String> getMemberSet(String key); Set<String> getMemberSetDesc(String key); Set<Tuple> getMemberSetWithScore(String key); Long interStore(String desKey, String... fromKey); Double increase(String key, Double score, String member); Long remove(String key, String... value); Long removeByRank(String key, long start, long end); Long removeByScore(String key, Double min, Double max); Long size(String key); Long count(String key, double min, double max); }### Answer: @Test public void testRangeByScore() throws Exception { redisSortSet.save(key,2.3,"a"); redisSortSet.save(key,2.3,"b"); redisSortSet.save(key,2.1,"c"); Set<String> result = redisSortSet.rangeByScore(key, 0d, 2.2d); for(String s:result){ System.out.println(s); } show(); Assert.assertEquals(new HashSet<String>(Arrays.asList("b","a","c")), result); }
### Question: RedisSortSet extends Commands { public Long interStore(String desKey, String... fromKey) { return getJedis().zinterstore(desKey, fromKey); } private RedisSortSet(); synchronized static RedisSortSet getInstance(); Long save(String key, Double score, String member); Long index(String key, String member); Double score(String key, String member); Long rank(String key, String member); Set<String> range(String key, long start, long end); Set<Tuple> rangeWithScores(String key, long start, long end); Set<String> rangeByIndex(String key, long start, long end); Set<String> rangeByScore(String key, Double min, Double max); Set<String> rangeByLex(String key, String max, String min); Long removeByLex(String key, String min, String max); Long countByLex(String key, String min, String max); Set<String> getMemberSet(String key); Set<String> getMemberSetDesc(String key); Set<Tuple> getMemberSetWithScore(String key); Long interStore(String desKey, String... fromKey); Double increase(String key, Double score, String member); Long remove(String key, String... value); Long removeByRank(String key, long start, long end); Long removeByScore(String key, Double min, Double max); Long size(String key); Long count(String key, double min, double max); }### Answer: @Test public void testInterStore() throws Exception { redisSortSet.save(key,1.1,"a"); redisSortSet.save(key,1.1,"b"); redisSortSet.save("key1",1.1,"b"); redisSortSet.save("key1",1.1,"a"); redisSortSet.save("key2",1.1,"a"); redisSortSet.save(key,1.1,"t"); Long result = redisSortSet.interStore("desKey", key,"key1"); show(key,"key1","desKey","key2"); Assert.assertEquals((Long)2L, result); }
### Question: RedisSortSet extends Commands { public Double increase(String key, Double score, String member) { return getJedis().zincrby(key, score, member); } private RedisSortSet(); synchronized static RedisSortSet getInstance(); Long save(String key, Double score, String member); Long index(String key, String member); Double score(String key, String member); Long rank(String key, String member); Set<String> range(String key, long start, long end); Set<Tuple> rangeWithScores(String key, long start, long end); Set<String> rangeByIndex(String key, long start, long end); Set<String> rangeByScore(String key, Double min, Double max); Set<String> rangeByLex(String key, String max, String min); Long removeByLex(String key, String min, String max); Long countByLex(String key, String min, String max); Set<String> getMemberSet(String key); Set<String> getMemberSetDesc(String key); Set<Tuple> getMemberSetWithScore(String key); Long interStore(String desKey, String... fromKey); Double increase(String key, Double score, String member); Long remove(String key, String... value); Long removeByRank(String key, long start, long end); Long removeByScore(String key, Double min, Double max); Long size(String key); Long count(String key, double min, double max); }### Answer: @Test public void testIncrease() throws Exception { redisSortSet.save(key,1.1,"member"); Double result = redisSortSet.increase(key, 1.1, "member"); show(); Assert.assertEquals((Double)2.2d, result); }
### Question: RedisSortSet extends Commands { public Long remove(String key, String... value) { return getJedis().zrem(key, value); } private RedisSortSet(); synchronized static RedisSortSet getInstance(); Long save(String key, Double score, String member); Long index(String key, String member); Double score(String key, String member); Long rank(String key, String member); Set<String> range(String key, long start, long end); Set<Tuple> rangeWithScores(String key, long start, long end); Set<String> rangeByIndex(String key, long start, long end); Set<String> rangeByScore(String key, Double min, Double max); Set<String> rangeByLex(String key, String max, String min); Long removeByLex(String key, String min, String max); Long countByLex(String key, String min, String max); Set<String> getMemberSet(String key); Set<String> getMemberSetDesc(String key); Set<Tuple> getMemberSetWithScore(String key); Long interStore(String desKey, String... fromKey); Double increase(String key, Double score, String member); Long remove(String key, String... value); Long removeByRank(String key, long start, long end); Long removeByScore(String key, Double min, Double max); Long size(String key); Long count(String key, double min, double max); }### Answer: @Test public void testRemove() throws Exception { redisSortSet.save(key,1.1,"value"); Long result = redisSortSet.remove(key, "value"); show(); Assert.assertEquals((Long)1L, result); }
### Question: RedisSortSet extends Commands { public Long removeByRank(String key, long start, long end) { return getJedis().zremrangeByRank(key, start, end); } private RedisSortSet(); synchronized static RedisSortSet getInstance(); Long save(String key, Double score, String member); Long index(String key, String member); Double score(String key, String member); Long rank(String key, String member); Set<String> range(String key, long start, long end); Set<Tuple> rangeWithScores(String key, long start, long end); Set<String> rangeByIndex(String key, long start, long end); Set<String> rangeByScore(String key, Double min, Double max); Set<String> rangeByLex(String key, String max, String min); Long removeByLex(String key, String min, String max); Long countByLex(String key, String min, String max); Set<String> getMemberSet(String key); Set<String> getMemberSetDesc(String key); Set<Tuple> getMemberSetWithScore(String key); Long interStore(String desKey, String... fromKey); Double increase(String key, Double score, String member); Long remove(String key, String... value); Long removeByRank(String key, long start, long end); Long removeByScore(String key, Double min, Double max); Long size(String key); Long count(String key, double min, double max); }### Answer: @Test public void testRemoveByRank() throws Exception { redisSortSet.save(key,2.3,"a"); redisSortSet.save(key,2.3,"b"); redisSortSet.save(key,2.1,"c"); redisSortSet.save(key,2.3,"d"); redisSortSet.save(key,2.3,"r"); redisSortSet.save(key,2.1,"u"); Long result = redisSortSet.removeByRank(key, 0L, 1L); show(); Assert.assertEquals((Long)2L, result); }
### Question: PropertyFile { public static Map<String,RedisPoolProperty> getAllPoolConfig() throws ReadConfigException { Map<String,RedisPoolProperty> map = new HashMap<>(); int maxId; try { maxId = getMaxId(); props = getProperties(Configs.PROPERTY_FILE); } catch (IOException e) { e.printStackTrace(); logger.error(ExceptionInfo.OPEN_CONFIG_FAILED,e); return map; } for(int i=Configs.START_ID;i<=maxId;i++){ String poolId = props.getString(i+Configs.SEPARATE+Configs.POOL_ID); if(poolId==null) continue; RedisPoolProperty property = RedisPoolProperty.initByIdFromConfig(poolId); map.put(poolId,property); } return map; } static MythProperties getProperties(String propertyFile); static String save(String key, String value); static String delete(String key); static String update(String key,String value); static int getMaxId(); static Map<String,RedisPoolProperty> getAllPoolConfig(); }### Answer: @Test public void testList() throws Exception { Map<String,RedisPoolProperty> map = PropertyFile.getAllPoolConfig(); for(String key:map.keySet()){ System.out.println(">> "+key+" <<"); RedisPoolProperty property = map.get(key); Map lists= MythReflect.getFieldsValue(property); for(Object keys:lists.keySet()){ System.out.println(keys.toString()+":"+lists.get(keys)); } System.out.println("----------------------------------------------------"); } }
### Question: RedisSortSet extends Commands { public Long removeByScore(String key, Double min, Double max) { return getJedis().zremrangeByScore(key, min, max); } private RedisSortSet(); synchronized static RedisSortSet getInstance(); Long save(String key, Double score, String member); Long index(String key, String member); Double score(String key, String member); Long rank(String key, String member); Set<String> range(String key, long start, long end); Set<Tuple> rangeWithScores(String key, long start, long end); Set<String> rangeByIndex(String key, long start, long end); Set<String> rangeByScore(String key, Double min, Double max); Set<String> rangeByLex(String key, String max, String min); Long removeByLex(String key, String min, String max); Long countByLex(String key, String min, String max); Set<String> getMemberSet(String key); Set<String> getMemberSetDesc(String key); Set<Tuple> getMemberSetWithScore(String key); Long interStore(String desKey, String... fromKey); Double increase(String key, Double score, String member); Long remove(String key, String... value); Long removeByRank(String key, long start, long end); Long removeByScore(String key, Double min, Double max); Long size(String key); Long count(String key, double min, double max); }### Answer: @Test public void testRemoveByScore() throws Exception { redisSortSet.save(key,2.3,"a"); redisSortSet.save(key,2.3,"b"); redisSortSet.save(key,2.1,"c"); redisSortSet.save(key,1.9,"d"); redisSortSet.save(key,2.0,"r"); redisSortSet.save(key,2.1,"u"); Long result = redisSortSet.removeByScore(key, 1.9d, 2.1d); Assert.assertEquals((Long)4L, result); }
### Question: RedisSortSet extends Commands { public Long size(String key) { return getJedis().zcard(key); } private RedisSortSet(); synchronized static RedisSortSet getInstance(); Long save(String key, Double score, String member); Long index(String key, String member); Double score(String key, String member); Long rank(String key, String member); Set<String> range(String key, long start, long end); Set<Tuple> rangeWithScores(String key, long start, long end); Set<String> rangeByIndex(String key, long start, long end); Set<String> rangeByScore(String key, Double min, Double max); Set<String> rangeByLex(String key, String max, String min); Long removeByLex(String key, String min, String max); Long countByLex(String key, String min, String max); Set<String> getMemberSet(String key); Set<String> getMemberSetDesc(String key); Set<Tuple> getMemberSetWithScore(String key); Long interStore(String desKey, String... fromKey); Double increase(String key, Double score, String member); Long remove(String key, String... value); Long removeByRank(String key, long start, long end); Long removeByScore(String key, Double min, Double max); Long size(String key); Long count(String key, double min, double max); }### Answer: @Test public void testSize() throws Exception { redisSortSet.save(key,2.3,"a"); redisSortSet.save(key,2.3,"b"); redisSortSet.save(key,2.1,"c"); Long result = redisSortSet.size(key); show(); Assert.assertEquals((Long)3L, result); }
### Question: RedisSortSet extends Commands { public Long count(String key, double min, double max) { return getJedis().zcount(key, min, max); } private RedisSortSet(); synchronized static RedisSortSet getInstance(); Long save(String key, Double score, String member); Long index(String key, String member); Double score(String key, String member); Long rank(String key, String member); Set<String> range(String key, long start, long end); Set<Tuple> rangeWithScores(String key, long start, long end); Set<String> rangeByIndex(String key, long start, long end); Set<String> rangeByScore(String key, Double min, Double max); Set<String> rangeByLex(String key, String max, String min); Long removeByLex(String key, String min, String max); Long countByLex(String key, String min, String max); Set<String> getMemberSet(String key); Set<String> getMemberSetDesc(String key); Set<Tuple> getMemberSetWithScore(String key); Long interStore(String desKey, String... fromKey); Double increase(String key, Double score, String member); Long remove(String key, String... value); Long removeByRank(String key, long start, long end); Long removeByScore(String key, Double min, Double max); Long size(String key); Long count(String key, double min, double max); }### Answer: @Test public void testCount() throws Exception { redisSortSet.save(key,2.3,"a"); redisSortSet.save(key,2.3,"b"); redisSortSet.save(key,2.1,"c"); Long result = redisSortSet.count(key, 2.1,2.2); show(); Assert.assertEquals((Long)1L, result); }
### Question: RedisKey extends Commands { public String set(String key, String value) { return getJedis().set(key, value); } private RedisKey(); synchronized static RedisKey getInstance(); String get(String key); String set(String key, String value); byte[] dump(String key); Long setExpire(String key, int second, String value); String setExpireMs(String key, long second, String value); long increaseKey(String key); long decreaseKey(String key); long append(String key, String value); List<String> getMultiKeys(String... keys); String setMultiKey(String... keys); String getEncoding(String key); Set<String> listAllKeys(int db); }### Answer: @Test public void createData1(){ for(int i=0;i<5000;i++){ redisKey.set("aaa"+i,"dfdfdfdf"); } } @Test public void createData2(){ for(int i=0;i<5000;i++){ redisKey.set("qq"+i,"dfdfdfdf"); } } @Test public void createData3(){ for(int i=0;i<5000;i++){ redisKey.set("pp"+i,"dfdfdfdf"); } } @Test public void testType() throws Exception { redisKey.set(key,"12"); String result = redisKey.type(key); Assert.assertEquals("string", result); }
### Question: RedisKey extends Commands { public String get(String key) { Jedis jedis = getJedis(); if ("string".equals(jedis.type(key))) { return jedis.get(key); } else { logger.error(ExceptionInfo.KEY_TYPE_NOT_STRING + " and type is " + jedis.type(key)); return null; } } private RedisKey(); synchronized static RedisKey getInstance(); String get(String key); String set(String key, String value); byte[] dump(String key); Long setExpire(String key, int second, String value); String setExpireMs(String key, long second, String value); long increaseKey(String key); long decreaseKey(String key); long append(String key, String value); List<String> getMultiKeys(String... keys); String setMultiKey(String... keys); String getEncoding(String key); Set<String> listAllKeys(int db); }### Answer: @Test public void testStatus(){ Map<String,String> map = redisKey.getStatus(); System.out.println(map.get("db0")); }
### Question: RedisKey extends Commands { public byte[] dump(String key) { return getJedis().dump(key); } private RedisKey(); synchronized static RedisKey getInstance(); String get(String key); String set(String key, String value); byte[] dump(String key); Long setExpire(String key, int second, String value); String setExpireMs(String key, long second, String value); long increaseKey(String key); long decreaseKey(String key); long append(String key, String value); List<String> getMultiKeys(String... keys); String setMultiKey(String... keys); String getEncoding(String key); Set<String> listAllKeys(int db); }### Answer: @Test public void testDump() throws Exception { byte[] result = redisKey.dump(key); Assert.assertArrayEquals(null, result); }
### Question: RedisKey extends Commands { public Long setExpire(String key, int second, String value) { Jedis jedis = getJedis(); jedis.set(key, value); return expire(key, second); } private RedisKey(); synchronized static RedisKey getInstance(); String get(String key); String set(String key, String value); byte[] dump(String key); Long setExpire(String key, int second, String value); String setExpireMs(String key, long second, String value); long increaseKey(String key); long decreaseKey(String key); long append(String key, String value); List<String> getMultiKeys(String... keys); String setMultiKey(String... keys); String getEncoding(String key); Set<String> listAllKeys(int db); }### Answer: @Test public void testSetExpire() throws Exception { Long result = redisKey.setExpire(key, 0, "value"); assert(1L == result); }
### Question: RedisKey extends Commands { public String setExpireMs(String key, long second, String value) { return getJedis().psetex(key, second, value); } private RedisKey(); synchronized static RedisKey getInstance(); String get(String key); String set(String key, String value); byte[] dump(String key); Long setExpire(String key, int second, String value); String setExpireMs(String key, long second, String value); long increaseKey(String key); long decreaseKey(String key); long append(String key, String value); List<String> getMultiKeys(String... keys); String setMultiKey(String... keys); String getEncoding(String key); Set<String> listAllKeys(int db); }### Answer: @Test public void testSetExpireMs() throws Exception { String result = redisKey.setExpireMs(key, 12L, "value"); Assert.assertEquals("OK", result); }
### Question: PoolManagement { public String createRedisPool(RedisPoolProperty property) throws Exception { int maxId = PropertyFile.getMaxId(); maxId++; property.setPoolId(maxId + ""); Map<String, ?> map = MythReflect.getFieldsValue(property); for (String key : map.keySet()) { PropertyFile.save(maxId + Configs.SEPARATE + key, map.get(key) + ""); } PropertyFile.delete(Configs.MAX_POOL_ID); PropertyFile.save(Configs.MAX_POOL_ID, maxId + ""); logger.info(NoticeInfo.CRETE_POOL + maxId); return maxId + ""; } private PoolManagement(); synchronized static PoolManagement getInstance(); RedisPools getRedisPool(); RedisPools getRedisPool(String poolId); RedisPools createRedisPoolAndConnection(RedisPoolProperty property); String createRedisPool(RedisPoolProperty property); boolean checkConnection(RedisPoolProperty property); boolean switchPool(String PoolId); String deleteRedisPool(String poolId); boolean clearAllPools(); boolean destroyRedisPool(String poolId); boolean destroyRedisPool(RedisPools redisPools); ConcurrentMap<String, RedisPools> getPoolMap(); }### Answer: @Test public void testCreateRedisPool() throws Exception { String result = poolManagement.createRedisPool(property); RedisPoolProperty getObject = RedisPoolProperty.initByIdFromConfig(result); Assert.assertEquals(getObject.toString(), property.toString()); }
### Question: RedisKey extends Commands { public long increaseKey(String key) throws TypeErrorException { checkIntValue(key); return getJedis().incr(key); } private RedisKey(); synchronized static RedisKey getInstance(); String get(String key); String set(String key, String value); byte[] dump(String key); Long setExpire(String key, int second, String value); String setExpireMs(String key, long second, String value); long increaseKey(String key); long decreaseKey(String key); long append(String key, String value); List<String> getMultiKeys(String... keys); String setMultiKey(String... keys); String getEncoding(String key); Set<String> listAllKeys(int db); }### Answer: @Test public void testIncreaseKey() throws Exception { redisKey.set(key,"1"); long result = redisKey.increaseKey(key); Assert.assertEquals(2L, result); testDeleteKey(); }
### Question: RedisKey extends Commands { public long decreaseKey(String key) throws TypeErrorException { checkIntValue(key); return getJedis().decr(key); } private RedisKey(); synchronized static RedisKey getInstance(); String get(String key); String set(String key, String value); byte[] dump(String key); Long setExpire(String key, int second, String value); String setExpireMs(String key, long second, String value); long increaseKey(String key); long decreaseKey(String key); long append(String key, String value); List<String> getMultiKeys(String... keys); String setMultiKey(String... keys); String getEncoding(String key); Set<String> listAllKeys(int db); }### Answer: @Test public void testDecreaseKey() throws Exception { redisKey.set(key,"1"); long result = redisKey.decreaseKey(key); Assert.assertEquals(0L, result); testDeleteKey(); }
### Question: RedisKey extends Commands { public long append(String key, String value) { return getJedis().append(key, value); } private RedisKey(); synchronized static RedisKey getInstance(); String get(String key); String set(String key, String value); byte[] dump(String key); Long setExpire(String key, int second, String value); String setExpireMs(String key, long second, String value); long increaseKey(String key); long decreaseKey(String key); long append(String key, String value); List<String> getMultiKeys(String... keys); String setMultiKey(String... keys); String getEncoding(String key); Set<String> listAllKeys(int db); }### Answer: @Test public void testAppend() throws Exception { redisKey.set(key,"1"); long result = redisKey.append(key, "value"); Assert.assertEquals(6L, result); }
### Question: RedisKey extends Commands { public List<String> getMultiKeys(String... keys) { return getJedis().mget(keys); } private RedisKey(); synchronized static RedisKey getInstance(); String get(String key); String set(String key, String value); byte[] dump(String key); Long setExpire(String key, int second, String value); String setExpireMs(String key, long second, String value); long increaseKey(String key); long decreaseKey(String key); long append(String key, String value); List<String> getMultiKeys(String... keys); String setMultiKey(String... keys); String getEncoding(String key); Set<String> listAllKeys(int db); }### Answer: @Test public void testGetMultiKeys() throws Exception { redisKey.set(key,"1"); redisKey.set("1","2"); List<String> result = redisKey.getMultiKeys(key,"1"); Assert.assertEquals(Arrays.<String>asList("1","2"), result); testDeleteKey(); redisKey.deleteKey("1"); }
### Question: RedisKey extends Commands { public String setMultiKey(String... keys) { return getJedis().mset(keys); } private RedisKey(); synchronized static RedisKey getInstance(); String get(String key); String set(String key, String value); byte[] dump(String key); Long setExpire(String key, int second, String value); String setExpireMs(String key, long second, String value); long increaseKey(String key); long decreaseKey(String key); long append(String key, String value); List<String> getMultiKeys(String... keys); String setMultiKey(String... keys); String getEncoding(String key); Set<String> listAllKeys(int db); }### Answer: @Test public void testSetMultiKey() throws Exception { String result = redisKey.setMultiKey("keys","a",key,"b"); Assert.assertEquals("OK", result); List<String> results = redisKey.getMultiKeys(key,"keys"); Assert.assertEquals(Arrays.<String>asList("b","a"), results); testDeleteKey(); redisKey.deleteKey("keys"); }
### Question: RedisKey extends Commands { public String getEncoding(String key) { return getJedis().objectEncoding(key); } private RedisKey(); synchronized static RedisKey getInstance(); String get(String key); String set(String key, String value); byte[] dump(String key); Long setExpire(String key, int second, String value); String setExpireMs(String key, long second, String value); long increaseKey(String key); long decreaseKey(String key); long append(String key, String value); List<String> getMultiKeys(String... keys); String setMultiKey(String... keys); String getEncoding(String key); Set<String> listAllKeys(int db); }### Answer: @Test public void testGetEncoding() throws Exception { redisKey.set(key,"78.89"); String result = redisKey.getEncoding(key); Assert.assertEquals("embstr", result); testDeleteKey(); }
### Question: RedisKey extends Commands { public Set<String> listAllKeys(int db) { logger.debug("RedisKey Management:" + this.getPools()); setDb(db); return getJedis().keys("*"); } private RedisKey(); synchronized static RedisKey getInstance(); String get(String key); String set(String key, String value); byte[] dump(String key); Long setExpire(String key, int second, String value); String setExpireMs(String key, long second, String value); long increaseKey(String key); long decreaseKey(String key); long append(String key, String value); List<String> getMultiKeys(String... keys); String setMultiKey(String... keys); String getEncoding(String key); Set<String> listAllKeys(int db); }### Answer: @Test public void testListKey(){ Set<String> sets = redisKey.listAllKeys(redisKey.getDb()); for(String d:sets){ System.out.println(d); } System.out.println(sets.size()); }
### Question: RedisHash extends Commands { public Long save(String key, String member, String value) { return getJedis().hset(key, member, value); } private RedisHash(); synchronized static RedisHash getInstance(); Long save(String key, String member, String value); String save(String key, Map<String, String> map); Long saveWhenNotExist(String key, String member, String value); String get(String key, String member); List<String> get(String key, String... member); Set<String> getMembers(String key); List<String> getValues(String key); Map<String, String> getAllMap(String key); Long increase(String key, String member, long value); Double increaseByFloat(String key, String member, double value); Long length(String key); Long remove(String key, String... members); }### Answer: @Test public void testSave() throws Exception { redisHash.save(key,"member","value"); Long result = redisHash.save(key, "member", "value2"); show(); Assert.assertEquals((Long)0L, result); } @Test public void testSave2() throws Exception { redisHash.save(key,"String","value"); String result = redisHash.save(key, new HashMap<String, String>() {{ put("String", "String"); put("String1","12"); }}); show(); Assert.assertEquals("OK", result); }