method2testcases
stringlengths
118
3.08k
### Question: AbstractValueProvider implements ValueProvider { @Override public void setParameters(Map<String, Object> params) { parameterMap.clear(); params.forEach((k, v) -> parameterMap.put(k, v.toString())); } @Override void update(Request request, Response response); @Override String lookupValue(String key); @Override Map<String, Object> getParameters(); @Override void setParameters(Map<String, Object> params); }### Answer: @Test public void setParameters() { provider.setParameters(Collections.singletonMap("new-param", "val")); Map<String, Object> parameters = provider.getParameters(); assertThat(parameters, hasEntry("new-param", "val")); assertThat(parameters.keySet(), hasSize(1)); }
### Question: VelocityTemplateEngine implements TemplateEngine { @Override public String renderTemplate(String template, ValueProvider context) { StringWriter writer = new StringWriter(); contextAdapter.setValueProvider(context); Velocity.evaluate(contextAdapter, writer, "", template); return writer.toString(); } VelocityTemplateEngine(); @Override String renderTemplate(String template, ValueProvider context); }### Answer: @Test public void renderTemplate() { when(valProvider.lookupValue("name")).thenReturn("Noddy"); assertThat(engine.renderTemplate("Hello ${name}", valProvider), equalTo("Hello Noddy")); } @Test public void renderTemplate_undefinedValue() { assertThat(engine.renderTemplate("Hello ${name}", valProvider), equalTo("Hello ${name}")); }
### Question: SimpleTopicSelectorConfig extends AbstractConfig { public List<String> getTopics() { return this.getList(TOPIC_LIST_CONFIG); } protected SimpleTopicSelectorConfig(ConfigDef config, Map<String, ?> parsedConfig); SimpleTopicSelectorConfig(Map<String, ?> parsedConfig); static ConfigDef conf(); List<String> getTopics(); static final String TOPIC_LIST_CONFIG; }### Answer: @Test public void testConfig() { Map<String, String> props = new HashMap<>(); props.put("rest.source.destination.topics", "test_topic1, test_topic2"); SimpleTopicSelectorConfig config = new SimpleTopicSelectorConfig(props); List<String> expectedTopics = Arrays.asList("test_topic1", "test_topic2"); assertEquals(expectedTopics, config.getTopics()); }
### Question: StringToMap { public static Map<String, Object> update(String path, String update) { HashMap<String, Object> map = new HashMap<>(); update(path.split("\\."), 0, map, update); return map; } static Map<String, Object> update(String path, String update); static void update(String path, String update, Map<String, Object> map); static String extract(String path, Map<String, Object> map); static void remove(String path, Map<String, Object> map); }### Answer: @Test public void testUpdate() { Map<String, Object> converted = StringToMap.update("test.foo.bar", "value"); Map<String, Object> level3 = new HashMap<>(); level3.put("bar", "value"); Map<String, Object> level2 = new HashMap<>(); level2.put("foo", level3); Map<String, Object> expected = new HashMap<>(); expected.put("test", level2); assertEquals(expected, converted); }
### Question: StringToMap { public static String extract(String path, Map<String, Object> map) { return extract(path.split("\\."), 0, map); } static Map<String, Object> update(String path, String update); static void update(String path, String update, Map<String, Object> map); static String extract(String path, Map<String, Object> map); static void remove(String path, Map<String, Object> map); }### Answer: @Test public void testExtract() { Map<String, Object> level3 = new HashMap<>(); level3.put("bar", "value"); Map<String, Object> level2 = new HashMap<>(); level2.put("foo", level3); Map<String, Object> map = new HashMap<>(); map.put("test", level2); String extracted = StringToMap.extract("test.foo.bar", map); assertEquals("value", extracted); }
### Question: StringToMap { public static void remove(String path, Map<String, Object> map) { remove(path.split("\\."), 0, map); } static Map<String, Object> update(String path, String update); static void update(String path, String update, Map<String, Object> map); static String extract(String path, Map<String, Object> map); static void remove(String path, Map<String, Object> map); }### Answer: @Test public void testRemove() { Map<String, Object> level3 = new HashMap<>(); level3.put("bar", "value"); Map<String, Object> level2 = new HashMap<>(); level2.put("foo", level3); Map<String, Object> map = new HashMap<>(); map.put("test", level2); StringToMap.remove("test.foo.bar", map); Map<String, Object> level2Expected = new HashMap<>(); level2Expected.put("foo", new HashMap<>()); Map<String, Object> mapExpected = new HashMap<>(); mapExpected.put("test", level2Expected); assertEquals(mapExpected, map); }
### Question: InstanceOfValidator implements ConfigDef.Validator { @Override public void ensureValid(String name, Object obj) { if (obj instanceof Class && parent.isAssignableFrom((Class<?>) obj)) { return; } throw new ConfigException(name, obj, "Class must extend: " + parent); } InstanceOfValidator(Class<?> parent); @Override void ensureValid(String name, Object obj); @Override String toString(); }### Answer: @Test public void ensureValidTest_sameClass() { validator.ensureValid("test", TestClass.class); } @Test public void ensureValidTest_subclass() { validator.ensureValid("test", TestSubClass.class); } @Test(expected = ConfigException.class) public void ensureValidTest_wrongClass() { validator.ensureValid("test", Object.class); } @Test(expected = ConfigException.class) public void ensureValidTest_notAClass() { validator.ensureValid("test", new Object()); }
### Question: ConstantPayloadGenerator implements PayloadGenerator, Configurable { @Override public Map<String, String> getRequestParameters() { return requestParameters; } @Override void configure(Map<String, ?> props); @Override boolean update(Request request, Response response); @Override String getRequestBody(); @Override Map<String, String> getRequestParameters(); @Override Map<String, String> getRequestHeaders(); @Override Map<String, Object> getOffsets(); @Override void setOffsets(Map<String, Object> offsets); }### Answer: @Test public void testGetRequestParameters() { generator.configure(CONFIG_PROPS); assertThat(generator.getRequestParameters(), allOf(hasEntry("priority", "MAXIMUM"), hasEntry("paged", "FALSE"))); }
### Question: ServiceProviderInterfaceRecommender implements ConfigDef.Recommender { @Override public List<Object> validValues(String name, Map<String, Object> connectorConfigs) { return implementations; } ServiceProviderInterfaceRecommender(Class<T> clazz); @Override List<Object> validValues(String name, Map<String, Object> connectorConfigs); @Override boolean visible(String name, Map<String, Object> connectorConfigs); }### Answer: @Test public void validValuesTest_actualSPI() { ServiceProviderInterfaceRecommender<RequestExecutor> recommender = new ServiceProviderInterfaceRecommender<>(RequestExecutor.class); assertThat(recommender.validValues("test", Collections.emptyMap()), hasItem(OkHttpRequestExecutor.class)); } @Test public void validValuesTest_notSPI() { ServiceProviderInterfaceRecommender<ServiceProviderInterfaceRecommenderTest> recommender = new ServiceProviderInterfaceRecommender<>(ServiceProviderInterfaceRecommenderTest.class); assertThat(recommender.validValues("test", Collections.emptyMap()), emptyIterable()); }
### Question: ServiceProviderInterfaceRecommender implements ConfigDef.Recommender { @Override public boolean visible(String name, Map<String, Object> connectorConfigs) { return true; } ServiceProviderInterfaceRecommender(Class<T> clazz); @Override List<Object> validValues(String name, Map<String, Object> connectorConfigs); @Override boolean visible(String name, Map<String, Object> connectorConfigs); }### Answer: @Test public void visible() { ServiceProviderInterfaceRecommender<RequestExecutor> recommender = new ServiceProviderInterfaceRecommender<>(RequestExecutor.class); assertThat(recommender.visible("test", Collections.emptyMap()), equalTo(true)); }
### Question: RestSinkConnector extends SinkConnector { @Override public List<Map<String, String>> taskConfigs(int maxTasks) { Map<String, String> taskProps = new HashMap<>(config.originalsStrings()); List<Map<String, String>> taskConfigs = new ArrayList<>(maxTasks); for (int i = 0; i < maxTasks; ++i) { taskConfigs.add(taskProps); } return taskConfigs; } @Override String version(); @Override void start(Map<String, String> map); @Override Class<? extends Task> taskClass(); @Override List<Map<String, String>> taskConfigs(int maxTasks); @Override void stop(); @Override ConfigDef config(); }### Answer: @Test public void shouldReturnListOfConfigsOnStartup() { Map<String, String> props = new HashMap<>(); props.put("key", "val"); when(config.originalsStrings()).thenReturn(props); List<Map<String, String>> maps = subject.taskConfigs(3); assertEquals(maps.get(0), props); assertEquals(maps.get(1), props); assertEquals(maps.get(2), props); }
### Question: RestSinkConnector extends SinkConnector { @Override public String version() { return VersionUtil.getVersion(); } @Override String version(); @Override void start(Map<String, String> map); @Override Class<? extends Task> taskClass(); @Override List<Map<String, String>> taskConfigs(int maxTasks); @Override void stop(); @Override ConfigDef config(); }### Answer: @Test public void shouldReturnVersionWhenRequested() { PowerMockito.mockStatic(VersionUtil.class); when(VersionUtil.getVersion()).thenReturn("test"); String version = subject.version(); assertEquals("test", version); }
### Question: RestSourceConnector extends SourceConnector { @Override public List<Map<String, String>> taskConfigs(int maxTasks) { Map<String, String> taskProps = new HashMap<>(config.originalsStrings()); List<Map<String, String>> taskConfigs = new ArrayList<>(maxTasks); for (int i = 0; i < maxTasks; ++i) { taskConfigs.add(taskProps); } return taskConfigs; } @Override String version(); @Override void start(Map<String, String> map); @Override Class<? extends Task> taskClass(); @Override List<Map<String, String>> taskConfigs(int maxTasks); @Override void stop(); @Override ConfigDef config(); }### Answer: @Test public void shouldReturnListOfConfigsOnStartup() { Map<String, String> props = new HashMap<>(); props.put("key", "val"); when(config.originalsStrings()).thenReturn(props); List<Map<String, String>> maps = subject.taskConfigs(3); assertEquals(maps.get(0), props); assertEquals(maps.get(1), props); assertEquals(maps.get(2), props); }
### Question: RestSourceConnector extends SourceConnector { @Override public String version() { return VersionUtil.getVersion(); } @Override String version(); @Override void start(Map<String, String> map); @Override Class<? extends Task> taskClass(); @Override List<Map<String, String>> taskConfigs(int maxTasks); @Override void stop(); @Override ConfigDef config(); }### Answer: @Test public void shouldReturnVersionWhenRequested() { PowerMockito.mockStatic(VersionUtil.class); when(VersionUtil.getVersion()).thenReturn("test"); String version = subject.version(); assertEquals("test", version); }
### Question: ConstantPayloadGenerator implements PayloadGenerator, Configurable { @Override public Map<String, String> getRequestHeaders() { return requestHeaders; } @Override void configure(Map<String, ?> props); @Override boolean update(Request request, Response response); @Override String getRequestBody(); @Override Map<String, String> getRequestParameters(); @Override Map<String, String> getRequestHeaders(); @Override Map<String, Object> getOffsets(); @Override void setOffsets(Map<String, Object> offsets); }### Answer: @Test public void testGetRequestHeaders() { generator.configure(CONFIG_PROPS); assertThat(generator.getRequestHeaders(), allOf( hasEntry("Content-Type", "application/json"), hasEntry("Accept", "application/json"))); }
### Question: ConstantPayloadGenerator implements PayloadGenerator, Configurable { @Override public Map<String, Object> getOffsets() { return Collections.singletonMap("timestamp", currentTimeMillis()); } @Override void configure(Map<String, ?> props); @Override boolean update(Request request, Response response); @Override String getRequestBody(); @Override Map<String, String> getRequestParameters(); @Override Map<String, String> getRequestHeaders(); @Override Map<String, Object> getOffsets(); @Override void setOffsets(Map<String, Object> offsets); }### Answer: @Test public void testGetOffsets() { generator.configure(CONFIG_PROPS); assertThat(generator.getOffsets(), hasEntry(equalTo("timestamp"), instanceOf(Long.class))); }
### Question: ConstantPayloadGenerator implements PayloadGenerator, Configurable { @Override public void setOffsets(Map<String, Object> offsets) { } @Override void configure(Map<String, ?> props); @Override boolean update(Request request, Response response); @Override String getRequestBody(); @Override Map<String, String> getRequestParameters(); @Override Map<String, String> getRequestHeaders(); @Override Map<String, Object> getOffsets(); @Override void setOffsets(Map<String, Object> offsets); }### Answer: @Test public void testSetOffsets() { generator.configure(CONFIG_PROPS); generator.setOffsets(null); assertThat(generator.getOffsets(), notNullValue()); }
### Question: TemplatedPayloadGenerator implements PayloadGenerator, Configurable { @Override public boolean update(Request request, Response response) { valueProvider.update(request,response); populateValues(); return false; } @Override void configure(Map<String, ?> props); @Override boolean update(Request request, Response response); @Override String getRequestBody(); @Override Map<String, String> getRequestParameters(); @Override Map<String, String> getRequestHeaders(); @Override Map<String, Object> getOffsets(); @Override void setOffsets(Map<String, Object> offsets); }### Answer: @Test public void testUpdate() { generator.configure(CONFIG_PROPS); assertThat(generator.update(REQUEST, RESPONSE), Matchers.equalTo(false)); }
### Question: TemplatedPayloadGenerator implements PayloadGenerator, Configurable { @Override public String getRequestBody() { return requestBodyValue; } @Override void configure(Map<String, ?> props); @Override boolean update(Request request, Response response); @Override String getRequestBody(); @Override Map<String, String> getRequestParameters(); @Override Map<String, String> getRequestHeaders(); @Override Map<String, Object> getOffsets(); @Override void setOffsets(Map<String, Object> offsets); }### Answer: @Test public void testGetRequestBody() { System.setProperty("STAR_NAME", "Sol"); generator.configure(CONFIG_PROPS); assertThat(generator.getRequestBody(), Matchers.equalTo("{\"query\": \"select * from known_stars where name='Sol'\"")); }
### Question: TemplatedPayloadGenerator implements PayloadGenerator, Configurable { @Override public Map<String, String> getRequestParameters() { return requestParameterValues; } @Override void configure(Map<String, ?> props); @Override boolean update(Request request, Response response); @Override String getRequestBody(); @Override Map<String, String> getRequestParameters(); @Override Map<String, String> getRequestHeaders(); @Override Map<String, Object> getOffsets(); @Override void setOffsets(Map<String, Object> offsets); }### Answer: @Test public void testGetRequestParameters() { System.setProperty("PRIORITY", "MAXIMUM"); System.setProperty("PAGED", "FALSE"); generator.configure(CONFIG_PROPS); assertThat(generator.getRequestParameters(), allOf( hasEntry("priority", "MAXIMUM"), hasEntry("paged", "FALSE"))); }
### Question: TemplatedPayloadGenerator implements PayloadGenerator, Configurable { @Override public Map<String, String> getRequestHeaders() { return requestHeaderValues; } @Override void configure(Map<String, ?> props); @Override boolean update(Request request, Response response); @Override String getRequestBody(); @Override Map<String, String> getRequestParameters(); @Override Map<String, String> getRequestHeaders(); @Override Map<String, Object> getOffsets(); @Override void setOffsets(Map<String, Object> offsets); }### Answer: @Test public void testGetRequestHeaders() { System.setProperty("CONTENT_TYPE", "application/json"); System.setProperty("ACCEPT_TYPE", "application/json"); generator.configure(CONFIG_PROPS); assertThat(generator.getRequestHeaders(), allOf( hasEntry("Content-Type", "application/json"), hasEntry("Accept", "application/json"))); }
### Question: SyntacticEquivalence { public static boolean areEquivalent(@Nullable UastNode node1, @Nullable UastNode node2) { if (node1 == null && node2 == null) { return true; } if (node1 == null || node2 == null) { return false; } if (node1.token == null && node2.token != null) { return false; } if (node2.token != null && !node1.token.value.equals(node2.token.value)) { return false; } if (node1.is(UastNode.Kind.UNSUPPORTED) || node2.is(UastNode.Kind.UNSUPPORTED)) { return false; } CommentFilteredList list1 = new CommentFilteredList(node1.children); CommentFilteredList list2 = new CommentFilteredList(node2.children); if (list1.computeSize() != list2.computeSize()) { return false; } Iterator<UastNode> child1 = list1.iterator(); Iterator<UastNode> child2 = list2.iterator(); while (child1.hasNext()) { if (!areEquivalent(child1.next(), child2.next())) { return false; } } return true; } private SyntacticEquivalence(); static boolean areEquivalent(@Nullable UastNode node1, @Nullable UastNode node2); static boolean areEquivalent(List<UastNode> node1, List<UastNode> node2); }### Answer: @Test void syntactically_equivalent_of_unsupported_node() throws Exception { UastNode node1 = UastNode.from(new StringReader("{ children: [ { kinds: [ 'UNSUPPORTED' ] } ] }")); UastNode node2 = UastNode.from(new StringReader("{ children: [ { kinds: [ 'UNSUPPORTED' ] } ] }")); assertFalse(SyntacticEquivalence.areEquivalent(node1, node2)); }
### Question: IfValidator extends Validator { @Override public void validate(UastNode node) { is(UastNode.Kind.IF); hasKeyword("if"); singleChild(UastNode.Kind.CONDITION); singleChild(UastNode.Kind.THEN); zeroOrOneChild(UastNode.Kind.ELSE).ifPresent(elseNode -> singleChild(UastNode.Kind.ELSE_KEYWORD)); } IfValidator(); @Override void validate(UastNode node); }### Answer: @Test void missing_else_keyword() { UastNode ifNode = node(Kind.IF, keyword("if", Kind.IF_KEYWORD), node(Kind.CONDITION), node(Kind.THEN), node(Kind.ELSE)); Validator.ValidationException exception = assertThrows(Validator.ValidationException.class, () -> validate(ifNode)); assertThat(exception.getMessage()).isEqualTo("IfValidator at line 1: Should have one single child of kind 'ELSE_KEYWORD' but got none."); } @Test void expected() { UastNode ifNode = buildNode(Kind.IF).addChildren(keyword("if", Kind.IF_KEYWORD), node(Kind.CONDITION), node(Kind.THEN)).build(); UastNode ifElseNode = buildNode(Kind.IF).addChildren(keyword("if", Kind.IF_KEYWORD), node(Kind.CONDITION), node(Kind.THEN),keyword("if", Kind.ELSE_KEYWORD), node(Kind.ELSE)).build(); try { validate(ifNode); validate(ifElseNode); } catch (Exception e) { fail("should not have failed", e); } } @Test void missing_if_keyword() { UastNode ifNode = node(Kind.IF, keyword("label"), node(Kind.THEN)); Validator.ValidationException exception = assertThrows(Validator.ValidationException.class, () -> validate(ifNode)); assertThat(exception.getMessage()).isEqualTo("IfValidator at line 1: Expected 'if' as keyword but got 'label'."); }
### Question: SwitchValidator extends Validator { @Override public void validate(UastNode t) { is(UastNode.Kind.SWITCH); hasKeyword("switch"); } SwitchValidator(); @Override void validate(UastNode t); }### Answer: @Test public void expected() throws Exception { UastNode switchNode = node(Sets.newHashSet(UastNode.Kind.SWITCH), keyword("switch")); try { validate(switchNode); } catch (Exception e) { fail("should not have failed", e); } } @Test public void do_not_have_switch_keyword() throws Exception { UastNode switchNode = node(Sets.newHashSet(UastNode.Kind.SWITCH), keyword("label")); Validator.ValidationException exception = assertThrows(Validator.ValidationException.class, () -> validate(switchNode)); assertThat(exception.getMessage()).isEqualTo("SwitchValidator at line 1: Expected 'switch' as keyword but got 'label'."); }
### Question: BinaryExpressionValidator extends Validator { @Override public void validate(UastNode node) { is(UastNode.Kind.BINARY_EXPRESSION); singleChild(UastNode.Kind.LEFT_OPERAND); singleChild(UastNode.Kind.OPERATOR); singleChild(UastNode.Kind.RIGHT_OPERAND); } BinaryExpressionValidator(); @Override void validate(UastNode node); }### Answer: @Test void expected() { UastNode binaryOperator = node(Kind.BINARY_EXPRESSION, node(Kind.LEFT_OPERAND), node(Kind.OPERATOR), node(Kind.RIGHT_OPERAND)); try { validate(binaryOperator); } catch (Exception e) { fail("should not have failed", e); } } @Test void missing_left_or_right_operand_or_operator() { UastNode binaryOperator0 = node(Kind.BINARY_EXPRESSION, node(Kind.OPERATOR), node(Kind.RIGHT_OPERAND)); Validator.ValidationException exception = assertThrows(Validator.ValidationException.class, () -> validate(binaryOperator0)); assertThat(exception.getMessage()).isEqualTo("BinaryExpressionValidator at line N/A: Should have one single child of kind 'LEFT_OPERAND' but got none."); UastNode binaryOperator1 = node(Kind.BINARY_EXPRESSION, node(Kind.LEFT_OPERAND), node(Kind.OPERATOR)); exception = assertThrows(Validator.ValidationException.class, () -> validate(binaryOperator1)); assertThat(exception.getMessage()).isEqualTo("BinaryExpressionValidator at line N/A: Should have one single child of kind 'RIGHT_OPERAND' but got none."); UastNode binaryOperator2 = node(Kind.BINARY_EXPRESSION, node(Kind.LEFT_OPERAND), node(Kind.RIGHT_OPERAND)); exception = assertThrows(Validator.ValidationException.class, () -> validate(binaryOperator2)); assertThat(exception.getMessage()).isEqualTo("BinaryExpressionValidator at line N/A: Should have one single child of kind 'OPERATOR' but got none."); }
### Question: LiteralLike { public static LiteralLike from(UastNode node) { if (node.is(UastNode.Kind.LITERAL)) { return new LiteralLike(node); } if (node.children.size() == 1) { Optional<UastNode> childLiteral = node.getChild(UastNode.Kind.LITERAL); if (childLiteral.isPresent()) { return new LiteralLike(childLiteral.get()); } } return null; } private LiteralLike(UastNode node); static LiteralLike from(UastNode node); UastNode node(); String value(); }### Answer: @Test void multiple_literal_children() throws Exception { UastNode literal = UastNode.from(new StringReader( "{ \"kinds\": [], " + "\"children\": [" + "{ \"kinds\": [\"LITERAL\"], \"token\": {\"value\": \"foo\" , \"line\": 1, \"column\": 1} }," + "{ \"kinds\": [\"LITERAL\"], \"token\": {\"value\": \"bar\" , \"line\": 1, \"column\": 1 } }" + "]" + "}")); LiteralLike literalLike = LiteralLike.from(literal); assertThat(literalLike).isNull(); }
### Question: Issue { @Override public String toString() { return check.getClass().getSimpleName() + ": " + primaryMessage.toString() + " " + Arrays.stream(secondaryMessages).map(Message::toString).collect(Collectors.joining(" ")); } Issue(Check check, Message primaryMessage, @Nullable Double effortToFix, Message... secondaryMessages); static Issue issueOnFile(Check check, String message); static Issue issueOnLine(Check check, int line, String message); Check getCheck(); boolean hasNodeLocation(); boolean hasLineLocation(); String getMessage(); Message getPrimary(); Message[] getSecondaries(); @Nullable Double getEffortToFix(); @Override String toString(); }### Answer: @Test void message_to_string() { Set<UastNode.Kind> noKind = Collections.emptySet(); List<UastNode> noChild = Collections.emptyList(); UastNode node1 = new UastNode(noKind, "", new UastNode.Token(42, 7, "{"), noChild); UastNode node2 = new UastNode(noKind, "", new UastNode.Token(54, 3, "}"), noChild); Issue.Message message1 = new Issue.Message(node1, node2, "a message"); assertThat(message1.toString()).isEqualTo("([42:7 {], [54:3 }]) a message"); Issue.Message message2 = new Issue.Message(node1, node2, null); assertThat(message2.toString()).isEqualTo("([42:7 {], [54:3 }])"); }
### Question: Engine { public ScanResult scan(UastNode uast, InputFile inputFile) throws IOException { metricsVisitor.enterFile(uast); engineContext.enterFile(inputFile); visit(uast); return new ScanResult(engineContext.getIssues(), metricsVisitor.getMetrics()); } Engine(Collection<Check> rules); Engine(Collection<Check> rules, Collection<Validator> validators); ScanResult scan(UastNode uast, InputFile inputFile); }### Answer: @Test void visit_should_visit_all_nodes() throws Exception { NodeCounter nodeCounter = new NodeCounter(); Engine engine = new Engine(Collections.singletonList(nodeCounter)); InputFile inputFile = TestInputFileBuilder.create(".", "foo.go").setType(InputFile.Type.MAIN).build(); List<Issue> issues = engine.scan(uast, inputFile).issues; assertEquals(4, issues.size()); assertTrue(issues.stream().map(Issue::getCheck).allMatch(rule -> rule == nodeCounter)); }
### Question: FunctionCognitiveComplexityCheck extends Check { public void setMaxComplexity(int maxComplexity) { this.maxComplexity = maxComplexity; } FunctionCognitiveComplexityCheck(); @Override void enterFile(InputFile inputFile); void setMaxComplexity(int maxComplexity); @Override void visitNode(UastNode node); @Override void leaveNode(UastNode node); }### Answer: @Test void test_java() throws Exception { FunctionCognitiveComplexityCheck check = new FunctionCognitiveComplexityCheck(); check.setMaxComplexity(0); TestUtils.checkRuleOnJava(check); } @Test void test_go() throws Exception { FunctionCognitiveComplexityCheck check = new FunctionCognitiveComplexityCheck(); check.setMaxComplexity(0); TestUtils.checkRuleOnGo(check); }
### Question: DefaultCaseValidator extends Validator { @Override public void validate(UastNode node) { is(UastNode.Kind.DEFAULT_CASE); hasKeyword("default"); noChild(UastNode.Kind.CONDITION); } DefaultCaseValidator(); @Override void validate(UastNode node); }### Answer: @Test public void expected() throws Exception { UastNode caseNode = node(Sets.newHashSet(UastNode.Kind.DEFAULT_CASE, UastNode.Kind.CASE), keyword("default"), token(":")); UastNode node = node(UastNode.Kind.SWITCH, caseNode); try { validate(node); } catch (Exception e) { fail("should not have failed", e); } } @Test public void wrong_keyword() throws Exception { UastNode caseNode = node(Sets.newHashSet(UastNode.Kind.DEFAULT_CASE, UastNode.Kind.CASE), keyword("case"), token(":")); UastNode node = node(UastNode.Kind.SWITCH, caseNode); Validator.ValidationException exception = assertThrows(Validator.ValidationException.class, () -> validate(node)); assertThat(exception.getMessage()).isEqualTo("DefaultCaseValidator at line 1: Expected 'default' as keyword but got 'case'."); } @Test public void should_not_have_condition() throws Exception { UastNode caseNode = node(Sets.newHashSet(UastNode.Kind.DEFAULT_CASE, UastNode.Kind.CASE), keyword("default"), node(UastNode.Kind.CONDITION), token(":")); UastNode node = node(UastNode.Kind.SWITCH, caseNode); Validator.ValidationException exception = assertThrows(Validator.ValidationException.class, () -> validate(node)); assertThat(exception.getMessage()).isEqualTo("DefaultCaseValidator at line 1: Should not have any child of kind 'CONDITION'."); }
### Question: GoPathContext { String concat(String parentPath, String childPath) { if (parentPath.isEmpty() || parentPath.charAt(parentPath.length() - 1) == fileSeparator) { return parentPath + childPath; } return parentPath + fileSeparator + childPath; } GoPathContext(char fileSeparator, String pathSeparator, @Nullable String goPath); }### Answer: @Test void concat_linux() { GoPathContext context = new GoPathContext('/', ":", "/home/paul/go"); assertThat(context.concat("/home", "paul")).isEqualTo("/home/paul"); assertThat(context.concat("/home/", "paul")).isEqualTo("/home/paul"); assertThat(context.concat("/", "paul")).isEqualTo("/paul"); assertThat(context.concat("", "paul")).isEqualTo("paul"); } @Test void concat_windows() { GoPathContext context = new GoPathContext('\\', ";", "C:\\Users\\paul\\go"); assertThat(context.concat("C:\\Users", "paul")).isEqualTo("C:\\Users\\paul"); assertThat(context.concat("C:\\Users\\", "paul")).isEqualTo("C:\\Users\\paul"); assertThat(context.concat("C:\\", "paul")).isEqualTo("C:\\paul"); assertThat(context.concat("", "paul")).isEqualTo("paul"); }
### Question: SonarWayProfile implements BuiltInQualityProfilesDefinition { @Override public void define(Context context) { NewBuiltInQualityProfile profile = context.createBuiltInQualityProfile("Sonar way", GoLanguage.KEY); BuiltInQualityProfileJsonLoader.load(profile, GoRulesDefinition.REPOSITORY_KEY, "org/sonar/l10n/go/rules/go/Sonar_way_profile.json"); profile.setDefault(true); profile.done(); } @Override void define(Context context); }### Answer: @Test public void should_create_sonar_way_profile() { ValidationMessages validation = ValidationMessages.create(); BuiltInQualityProfilesDefinition.Context context = new BuiltInQualityProfilesDefinition.Context(); new SonarWayProfile().define(context); assertThat(context.profilesByLanguageAndName()).hasSize(1); BuiltInQualityProfilesDefinition.BuiltInQualityProfile profile = context.profile("go", "Sonar way"); assertThat(profile.language()).isEqualTo("go"); assertThat(profile.name()).isEqualTo("Sonar way"); assertThat(profile.rules()).extracting("repoKey").containsOnly(GoRulesDefinition.REPOSITORY_KEY); assertThat(validation.hasErrors()).isFalse(); assertThat(profile.rules()).extracting("ruleKey").contains("S2068"); assertThat(profile.rules()).extracting("ruleKey").doesNotContain("S3801"); }
### Question: GoSensor implements Sensor { @Override public void describe(SensorDescriptor descriptor) { descriptor.onlyOnLanguage(GoLanguage.KEY) .name("SonarGo"); } GoSensor(CheckFactory checkFactory, FileLinesContextFactory fileLinesContextFactory); @Override void describe(SensorDescriptor descriptor); @Override void execute(SensorContext context); }### Answer: @Test void test_description() { DefaultSensorDescriptor descriptor = new DefaultSensorDescriptor(); getSensor("S2068").describe(descriptor); assertThat(descriptor.name()).isEqualTo("SonarGo"); assertThat(descriptor.languages()).containsOnly("go"); } @Test void test_describe() { GoTestSensor goTestSensor = new GoTestSensor(); DefaultSensorDescriptor descriptor = new DefaultSensorDescriptor(); goTestSensor.describe(descriptor); assertThat(descriptor.name()).isEqualTo("Go Unit Test Report"); assertThat(descriptor.languages()).containsOnly("go"); }
### Question: GoLanguage extends AbstractLanguage { @Override public String[] getFileSuffixes() { String[] suffixes = configuration.getStringArray(FILE_SUFFIXES_KEY); if (suffixes == null || suffixes.length == 0) { suffixes = new String[] {FILE_SUFFIXES_DEFAULT_VALUE}; } return suffixes; } GoLanguage(Configuration configuration); @Override String[] getFileSuffixes(); static final String KEY; static final String FILE_SUFFIXES_KEY; static final String FILE_SUFFIXES_DEFAULT_VALUE; }### Answer: @Test void should_have_correct_file_extensions() { MapSettings mapSettings = new MapSettings(); GoLanguage typeScriptLanguage = new GoLanguage(mapSettings.asConfig()); assertThat(typeScriptLanguage.getFileSuffixes()).containsExactly(".go"); } @Test void can_override_file_extensions() { MapSettings mapSettings = new MapSettings(); mapSettings.setProperty("sonar.go.file.suffixes", ".go1,.go2"); GoLanguage typeScriptLanguage = new GoLanguage(mapSettings.asConfig()); assertThat(typeScriptLanguage.getFileSuffixes()).containsExactly(".go1",".go2"); }
### Question: Generator { public UastNode uast() { return uast; } Generator(String source); static void main(String[] args); static Set<String> allKindNames(); UastNode uast(); String json(); }### Answer: @Test void generate() { String source = "class A {\n" + " void foo() {\n" + " System.out.println(\"yolo\");\n" + " }\n" + "}"; Generator generator = new Generator(source); UastNode cutNode = generator.uast(); assertEquals("COMPILATION_UNIT", cutNode.nativeNode); assertEquals(null, cutNode.token); assertEquals(Collections.singleton(UastNode.Kind.COMPILATION_UNIT), cutNode.kinds); assertEquals(2, cutNode.children.size()); UastNode classNode = cutNode.children.get(0); assertEquals("CLASS", classNode.nativeNode); assertNull(classNode.token); assertEquals(EnumSet.of(CLASS, STATEMENT, TYPE), classNode.kinds); assertEquals(5, classNode.children.size()); UastNode eofToken = cutNode.children.get(1); assertEquals("TOKEN", eofToken.nativeNode); assertNotNull(eofToken.token); assertEquals(5, eofToken.token.line); assertEquals(2, eofToken.token.column); assertEquals("", eofToken.token.value); assertEquals(Collections.singleton(EOF), eofToken.kinds); assertEquals(0, eofToken.children.size()); }
### Question: Generator { public static void main(String[] args) throws IOException { Path path = Paths.get(args[0]); if (path.toFile().isDirectory()) { try (Stream<Path> files = Files.walk(path)) { files.filter(p -> p.toString().endsWith(".java")) .forEach(Generator::createUastFile); } } else { Generator.createUastFile(path); } } Generator(String source); static void main(String[] args); static Set<String> allKindNames(); UastNode uast(); String json(); }### Answer: @Test void test_generator_main() throws Exception { Generator.main(new String[] {"src/test/files/source.java"}); Path generatedFile = Paths.get("src/test/files/source.java.uast.json"); String generatedUast = new String(Files.readAllBytes(generatedFile), StandardCharsets.UTF_8); String expectedUast = new String(Files.readAllBytes(Paths.get("src/test/files/reference.java.uast.json")), StandardCharsets.UTF_8).trim(); assertEquals(expectedUast, generatedUast); Files.deleteIfExists(generatedFile); } @Test void test_generator_main_with_directory() throws Exception { Generator.main(new String[] {"src/test/files"}); Path generatedFile = Paths.get("src/test/files/source.java.uast.json"); String generatedUast = new String(Files.readAllBytes(generatedFile), StandardCharsets.UTF_8); String expectedUast = new String(Files.readAllBytes(Paths.get("src/test/files/reference.java.uast.json")), StandardCharsets.UTF_8).trim(); assertEquals(expectedUast, generatedUast); Files.deleteIfExists(generatedFile); }
### Question: AccountStatusDynaReport extends DynamicReportBase<AccountStatusFilter> { @Override public AccountStatusFilter buildFilter() { AccountStatusFilter result = new AccountStatusFilter(); result.setDate(new ReportDate(DateValueType.Today)); return result; } @Override AccountStatusFilter buildFilter(); }### Answer: @Test public void testExecReport() throws DRException { System.out.println("execReport"); AccountStatusDynaReport instance = new AccountStatusDynaReport(); instance.buildFilter(); instance.getFilter().setName("Deneme Şirketi"); JasperReportBuilder rb = instance.initReport(); rb.setDataSource(createDataSource()).show(false); System.out.println("execReport"); }
### Question: DateUtils { public static Date getDateAfterPeriod(String perStr, Date curDate) { Period pr = getPeriod(perStr); DateTime dt = new DateTime(curDate); return dt.plus(pr).toDate(); } static Period getPeriod( String perStr ); static Date getDateAfterPeriod(String perStr, Date curDate); static Date getDateBeforePeriod(String perStr, Date curDate); static ScheduleExpression getScheduleExpression( String cron ); static ScheduleExpression getHourlyScheduleExpression( Date date ); static ScheduleExpression getDailyScheduleExpression( Date date ); static ScheduleExpression getWeeklyScheduleExpression( Date date ); static ScheduleExpression getMonthlyScheduleExpression( Date date ); static DateTimeFormatter getDateTimeFormatter(); static String dateToStr( Date date); }### Answer: @Test public void testGetDateAfter() { DateTime dt = new DateTime(2015, 1, 1, 1, 1); Date expected = dt.plusHours(1).plusMinutes(5).toDate(); Date result = DateUtils.getDateAfterPeriod("1s5d", dt.toDate()); Assert.assertEquals(expected, result); result = DateUtils.getDateAfterPeriod("1h5M", dt.toDate()); Assert.assertEquals(expected, result); }
### Question: DateUtils { public static Date getDateBeforePeriod(String perStr, Date curDate) { Period pr = getPeriod(perStr); DateTime dt = new DateTime(curDate); return dt.minus(pr).toDate(); } static Period getPeriod( String perStr ); static Date getDateAfterPeriod(String perStr, Date curDate); static Date getDateBeforePeriod(String perStr, Date curDate); static ScheduleExpression getScheduleExpression( String cron ); static ScheduleExpression getHourlyScheduleExpression( Date date ); static ScheduleExpression getDailyScheduleExpression( Date date ); static ScheduleExpression getWeeklyScheduleExpression( Date date ); static ScheduleExpression getMonthlyScheduleExpression( Date date ); static DateTimeFormatter getDateTimeFormatter(); static String dateToStr( Date date); }### Answer: @Test public void testGetDateBefore() { DateTime dt = new DateTime(2015, 1, 1, 1, 1); Date expected = dt.minusHours(1).minusMinutes(5).toDate(); Date result = DateUtils.getDateBeforePeriod("1s5d", dt.toDate()); Assert.assertEquals(expected, result); result = DateUtils.getDateBeforePeriod("1h5M", dt.toDate()); Assert.assertEquals(expected, result); }
### Question: DateUtils { public static ScheduleExpression getScheduleExpression( String cron ){ List<String> ls = Splitter.on(' ').trimResults().omitEmptyStrings().splitToList(cron); ScheduleExpression result = new ScheduleExpression(); result.second(ls.get(0)); result.minute(ls.get(1)); result.hour(ls.get(2)); result.dayOfMonth(ls.get(3)); result.dayOfWeek(ls.get(4)); result.month(ls.get(5)); result.year(ls.get(6)); return result; } static Period getPeriod( String perStr ); static Date getDateAfterPeriod(String perStr, Date curDate); static Date getDateBeforePeriod(String perStr, Date curDate); static ScheduleExpression getScheduleExpression( String cron ); static ScheduleExpression getHourlyScheduleExpression( Date date ); static ScheduleExpression getDailyScheduleExpression( Date date ); static ScheduleExpression getWeeklyScheduleExpression( Date date ); static ScheduleExpression getMonthlyScheduleExpression( Date date ); static DateTimeFormatter getDateTimeFormatter(); static String dateToStr( Date date); }### Answer: @Test public void testScheduleExpression() { ScheduleExpression expected = new ScheduleExpression(); expected.hour("5"); expected.month("3"); ScheduleExpression result = DateUtils.getScheduleExpression("0 0 5 * * 3 *"); Assert.assertEquals(expected.getSecond(), result.getSecond()); Assert.assertEquals(expected.getMinute(), result.getMinute()); Assert.assertEquals(expected.getHour(), result.getHour()); Assert.assertEquals(expected.getDayOfMonth(), result.getDayOfMonth()); Assert.assertEquals(expected.getDayOfWeek(), result.getDayOfWeek()); Assert.assertEquals(expected.getYear(), result.getYear()); }
### Question: DynaFormUtils { public static String fieldValuestoJson( Map<String, Object> valueMap){ Gson gson = new Gson(); Type type = new TypeToken<Map<String,Object>>(){}.getType(); return gson.toJson(valueMap, type); } static String fieldValuestoJson( Map<String, Object> valueMap); static Map<String, Object> fieldValuesfromJson( String json, DynaForm form ); static Map<String, Object> fieldValuesfromJson( String json, Map<String,DynaField> fieldMap ); static Map<String,DynaField> resolveFieldMap( DynaForm form ); static String calcValuesToJson( Map<String, DynaCalcFieldValue> valueMap); static Map<String, DynaCalcFieldValue> calcValuesFromJson( String json ); }### Answer: @Test public void testToJson() { System.out.println("toJson"); Map<String, Object> valueMap = new HashMap<>(); valueMap.put("test:1:1", "Deneme"); valueMap.put("test:1:2", 5); valueMap.put("test:1:3", new Date()); valueMap.put("test:1:4", 11l); valueMap.put("test:1:5", BigDecimal.TEN); valueMap.put("test:1:6", Boolean.TRUE); valueMap.put("test:1:7", 3.2d); String expResult = ""; String result = DynaFormUtils.fieldValuestoJson(valueMap); System.out.println(result); }
### Question: DynaFormUtils { public static Map<String, Object> fieldValuesfromJson( String json, DynaForm form ){ return fieldValuesfromJson( json, resolveFieldMap(form)); } static String fieldValuestoJson( Map<String, Object> valueMap); static Map<String, Object> fieldValuesfromJson( String json, DynaForm form ); static Map<String, Object> fieldValuesfromJson( String json, Map<String,DynaField> fieldMap ); static Map<String,DynaField> resolveFieldMap( DynaForm form ); static String calcValuesToJson( Map<String, DynaCalcFieldValue> valueMap); static Map<String, DynaCalcFieldValue> calcValuesFromJson( String json ); }### Answer: @Test public void testFromJson2() { System.out.println("fromJson2"); Map<String, Serializable> valueMap = new HashMap<>(); String expResult = ""; TestFormBuilder fb = new TestFormBuilder(); DynaForm form = fb.buildTestForm(); Map<String,Object> result = DynaFormUtils.fieldValuesfromJson("{\"fld1\":\"test:1:5\"}", form); for( Map.Entry<String,Object> e : result.entrySet()){ System.out.print(e); System.out.println(" " + e.getValue().getClass().getName()); } System.out.println(result); }
### Question: KahveCriteria implements Serializable { public static KahveCriteria create() { return new KahveCriteria(); } protected KahveCriteria(); static KahveCriteria create(); KahveCriteria addScope(String scope); KahveCriteria addKey(String key); KahveCriteria addKey(KahveKey key); KahveCriteria addDefaultScope(String scope); KahveCriteria addDefaultValue(KahveEntry defVal); KahveCriteria addDefaultValue(String defVal); KahveCriteria addDefaultValue(Integer defVal); KahveCriteria addDefaultValue(Long defVal); KahveCriteria addDefaultValue(BigDecimal defVal); KahveCriteria addDefaultValue(Boolean defVal); KahveCriteria addDefaultValue(Date defVal); KahveCriteria addDefaultValue(KahveEntry defVal, String scope); List<String> getKeys(); List<String> getKeys(String identity); boolean hasDefaultValue(); KahveEntry getDefaultValue(); String getScopeKey( String identity ); String getScopeKey(); @Override String toString(); }### Answer: @Test public void testCreate() { System.out.println("create"); List<String> expResult = new ArrayList<>(); expResult.add("HAKAN::KEY"); expResult.add("admin::KEY"); expResult.add("merkez::KEY"); expResult.add("KEY"); KahveCriteria result = KahveCriteria.create() .addScope("admin") .addScope("merkez") .addKey("KEY") .addDefaultValue(new KahveEntry("BİŞİ")); Assert.assertEquals(expResult, result.getKeys("HAKAN")); System.out.println(result); System.out.println(result.getKeys( "HAKAN" )); }
### Question: KahveCriteria implements Serializable { public boolean hasDefaultValue() { return defVal != null; } protected KahveCriteria(); static KahveCriteria create(); KahveCriteria addScope(String scope); KahveCriteria addKey(String key); KahveCriteria addKey(KahveKey key); KahveCriteria addDefaultScope(String scope); KahveCriteria addDefaultValue(KahveEntry defVal); KahveCriteria addDefaultValue(String defVal); KahveCriteria addDefaultValue(Integer defVal); KahveCriteria addDefaultValue(Long defVal); KahveCriteria addDefaultValue(BigDecimal defVal); KahveCriteria addDefaultValue(Boolean defVal); KahveCriteria addDefaultValue(Date defVal); KahveCriteria addDefaultValue(KahveEntry defVal, String scope); List<String> getKeys(); List<String> getKeys(String identity); boolean hasDefaultValue(); KahveEntry getDefaultValue(); String getScopeKey( String identity ); String getScopeKey(); @Override String toString(); }### Answer: @Test public void testHasDefaultValue() { System.out.println("HasDefaultValue"); KahveCriteria result = KahveCriteria.create() .addScope("admin") .addScope("merkez") .addKey("KEY"); Assert.assertFalse(result.hasDefaultValue()); result.addDefaultValue(new KahveEntry("BİŞİ")); Assert.assertTrue(result.hasDefaultValue()); }
### Question: ReportDate implements Serializable { public Date getCalculatedValue() { value = null; return getValue(); } ReportDate(); ReportDate(Date date); ReportDate(DateValueType valueType); DateValueType getValueType(); void setValueType(DateValueType valueType); Date getDate(); void setDate(Date date); Date getValue(); void setValue(Date value); Date getCalculatedValue(); void calcDates(); List<DateValueType> getValueTypes(); }### Answer: @Test public void testSerialization() throws IOException, ClassNotFoundException { System.out.println("getValueType"); ReportDate instance = new ReportDate(DateValueType.Today); ByteArrayOutputStream os = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(os); oos.writeObject(instance); byte[] bytes = os.toByteArray(); ByteArrayInputStream is = new ByteArrayInputStream( bytes); ObjectInputStream ois = new ObjectInputStream(is); ReportDate si = (ReportDate) ois.readObject(); Date expResult = (new LocalDate()).toDate(); Date result = si.getCalculatedValue(); assertEquals(expResult, result); } @Test public void testGetToday() { System.out.println("getToDay"); ReportDate instance = new ReportDate(DateValueType.Today); Date expResult = (new LocalDate()).toDate(); Date result = instance.getCalculatedValue(); assertEquals(expResult, result); } @Test public void testGetTomorrow() { System.out.println("getTomorrow"); ReportDate instance = new ReportDate(DateValueType.Tomorrow); Date expResult = (new LocalDate()).plusDays(1).toDate(); Date result = instance.getCalculatedValue(); assertEquals(expResult, result); }
### Question: ReportDate implements Serializable { public Date getDate() { return date; } ReportDate(); ReportDate(Date date); ReportDate(DateValueType valueType); DateValueType getValueType(); void setValueType(DateValueType valueType); Date getDate(); void setDate(Date date); Date getValue(); void setValue(Date value); Date getCalculatedValue(); void calcDates(); List<DateValueType> getValueTypes(); }### Answer: @Test public void testGetDate() { System.out.println("getDate"); Date expResult = (new LocalDate()).plusDays(1).toDate(); ReportDate instance = new ReportDate(expResult); Date result = instance.getCalculatedValue(); assertEquals(expResult, result); }
### Question: ReportManager implements Serializable { public ReportFolder findOrCreateFolder( String path ){ return findOrCreateFolder(path, "report"); } void execReport(String report); List<ReportFolder> getFolderList(); List<ReportFolder> getParentFolderList( String path ); ReportFolder findOrCreateFolder( String path ); ReportFolder findOrCreateFolder( String path, String type ); void addReport( String path, String report ); ReportFolder getFolder( String path ); List<String> getReports( String path ); String getParentPath( String path ); String getFolderName( String path ); ReportFolder findSubfolder( ReportFolder folder, String folderName ); void sortReports(); }### Answer: @Test public void testFindOrCreateFolder_String_String() { System.out.println("findOrCreateFolder"); String path = "/folder1/folder2/folder3"; String type = "ABC"; ReportManager instance = new ReportManager(); ReportFolder expResult = new ReportFolder("/folder1/folder2", "/folder1/folder2/folder3", "folder3", "ABC"); ReportFolder result = instance.findOrCreateFolder(path, type); System.out.println(result); assertEquals(expResult, result); }
### Question: ReportManager implements Serializable { public void addReport( String path, String report ){ ReportFolder rf = findOrCreateFolder(path, "report"); rf.getReports().add(report); } void execReport(String report); List<ReportFolder> getFolderList(); List<ReportFolder> getParentFolderList( String path ); ReportFolder findOrCreateFolder( String path ); ReportFolder findOrCreateFolder( String path, String type ); void addReport( String path, String report ); ReportFolder getFolder( String path ); List<String> getReports( String path ); String getParentPath( String path ); String getFolderName( String path ); ReportFolder findSubfolder( ReportFolder folder, String folderName ); void sortReports(); }### Answer: @Test public void testAddReport() { System.out.println("addReport"); String path = "/folder1/folder2/folder3/"; String report = "Deneme"; ReportManager instance = new ReportManager(); instance.addReport(path, report); }
### Question: RomanNumeral { public String toString() { String roman = ""; int N = num; for (int i = 0; i < numbers.length; i++) { while (N >= numbers[i]) { roman += letters[i]; N -= numbers[i]; } } return roman; } RomanNumeral(int arabic); RomanNumeral(String roman); String toString(); int toInt(); static String integerToRomanNumeral( Integer i ); }### Answer: @Test public void testToString() { System.out.println("toString"); RomanNumeral instance = new RomanNumeral(123); String expResult = "CXXIII"; String result = instance.toString(); assertEquals(expResult, result); }
### Question: RomanNumeral { public int toInt() { return num; } RomanNumeral(int arabic); RomanNumeral(String roman); String toString(); int toInt(); static String integerToRomanNumeral( Integer i ); }### Answer: @Test public void testToInt() { System.out.println("toInt"); RomanNumeral instance = new RomanNumeral("CXXIII"); int expResult = 123; int result = instance.toInt(); assertEquals(expResult, result); }
### Question: RomanNumeral { public static String integerToRomanNumeral( Integer i ){ RomanNumeral instance = new RomanNumeral( i ); return instance.toString(); } RomanNumeral(int arabic); RomanNumeral(String roman); String toString(); int toInt(); static String integerToRomanNumeral( Integer i ); }### Answer: @Test public void testConverter() { System.out.println("converter"); String expResult = "CXXIII"; String result = RomanNumeral.integerToRomanNumeral(123); assertEquals(expResult, result); }
### Question: OverAnnotatedService { @RolesAllowed("USER") public String sec1a() { return "@RolesAllowed(\"USER\")"; } @PreFilter("filterObject.content.length() < 240 or hasRole('ADMIN')") @PostFilter("filterObject.author.name == authentication.name") List<ShortMessage> saveAndReturnAll(List<ShortMessage> posts); @RolesAllowed("USER") String sec1a(); @RolesAllowed("ROLE_USER") String sec1b(); @Secured("USER") String sec2a(); @Secured("ROLE_USER") String sec2b(); @PreAuthorize("hasRole('USER')") String sec3a(); @PreAuthorize("hasRole('ROLE_USER')") String sec3b(); @PreAuthorize("hasAuthority('USER')") String sec3c(); @PreAuthorize("hasAuthority('ROLE_USER')") String sec3d(); }### Answer: @Test @WithMockUser public void getMessageWithMockUserCustomAuthorities() { overAnnotatedService.sec1a(); } @Test @WithAnonymousUser public void getMessage() { try { overAnnotatedService.sec1a(); fail(); } catch (AccessDeniedException e) { } }
### Question: RegistrationForm { public boolean isNormalRegistration() { return signInProvider == null; } RegistrationForm(); boolean isNormalRegistration(); boolean isSocialSignIn(); String getEmail(); void setEmail(String email); String getFirstName(); void setFirstName(String firstName); String getLastName(); void setLastName(String lastName); String getPassword(); void setPassword(String password); String getPasswordVerification(); void setPasswordVerification(String passwordVerification); SocialMediaService getSignInProvider(); void setSignInProvider(SocialMediaService signInProvider); @Override String toString(); static final String FIELD_NAME_EMAIL; }### Answer: @Test public void isNormalRegistration_SocialProviderNotSet_ShouldReturnTrue() { RegistrationForm dto = new RegistrationFormBuilder().build(); boolean isNormalRegistration = dto.isNormalRegistration(); assertThat(isNormalRegistration).isTrue(); } @Test public void isNormalRegistration_SocialProviderSet_ShouldReturnFalse() { RegistrationForm dto = new RegistrationFormBuilder() .isSocialSignInViaSignInProvider(SIGN_IN_PROVIDER) .build(); boolean isNormalRegistration = dto.isNormalRegistration(); assertThat(isNormalRegistration).isFalse(); }
### Question: ExampleUserDetails extends SocialUser { public static Builder getBuilder() { return new Builder(); } ExampleUserDetails(String username, String password, Collection<? extends GrantedAuthority> authorities); static Builder getBuilder(); Long getId(); String getFirstName(); String getLastName(); Role getRole(); SocialMediaService getSocialSignInProvider(); @Override String toString(); }### Answer: @Test public void build_UserRegisteredByUsingFormRegistration_ShouldCreateNewObject() { ExampleUserDetails user = ExampleUserDetails.getBuilder() .firstName(FIRST_NAME) .id(ID) .lastName(LAST_NAME) .password(PASSWORD) .role(Role.ROLE_USER) .username(EMAIL) .build(); assertThat(user).hasFirstName(FIRST_NAME) .hasId(ID) .hasLastName(LAST_NAME) .hasPassword(PASSWORD) .hasUsername(EMAIL) .isActive() .isRegisteredUser() .isRegisteredByUsingFormRegistration(); } @Test public void build_UserUsingSocialSignIn_ShouldCreateNewObject() { ExampleUserDetails user = ExampleUserDetails.getBuilder() .firstName(FIRST_NAME) .id(ID) .lastName(LAST_NAME) .password(null) .role(Role.ROLE_USER) .socialSignInProvider(SocialMediaService.TWITTER) .username(EMAIL) .build(); assertThat(user) .hasFirstName(FIRST_NAME) .hasId(ID) .hasLastName(LAST_NAME) .hasPassword(SOCIAL_USER_DUMMY_PASSWORD) .hasUsername(EMAIL) .isActive() .isRegisteredUser() .isSignedInByUsingSocialSignInProvider(SocialMediaService.TWITTER); }
### Question: SecurityUtil { public static void logInUser(User user) { LOGGER.info("Logging in user: {}", user); ExampleUserDetails userDetails = ExampleUserDetails.getBuilder() .firstName(user.getFirstName()) .id(user.getId()) .lastName(user.getLastName()) .password(user.getPassword()) .role(user.getRole()) .socialSignInProvider(user.getSignInProvider()) .username(user.getEmail()) .build(); LOGGER.debug("Logging in principal: {}", userDetails); Authentication authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities()); SecurityContextHolder.getContext().setAuthentication(authentication); LOGGER.info("User: {} has been logged in.", userDetails); } static void logInUser(User user); }### Answer: @Test public void logInUser_UserRegisteredByUsingFormRegistration_ShouldAddUserDetailsToSecurityContext() { User user = new UserBuilder() .email(EMAIL) .firstName(FIRST_NAME) .id(ID) .lastName(LAST_NAME) .password(PASSWORD) .build(); SecurityUtil.logInUser(user); assertThat(SecurityContextHolder.getContext()) .loggedInUserIs(user) .loggedInUserHasPassword(PASSWORD) .loggedInUserIsRegisteredByUsingNormalRegistration(); } @Test public void logInUser_UserSignInByUsingSocialSignInProvider_ShouldAddUserDetailsToSecurityContext() { User user = new UserBuilder() .email(EMAIL) .firstName(FIRST_NAME) .id(ID) .lastName(LAST_NAME) .signInProvider(SocialMediaService.TWITTER) .build(); SecurityUtil.logInUser(user); assertThat(SecurityContextHolder.getContext()) .loggedInUserIs(user) .loggedInUserIsSignedInByUsingSocialProvider(SocialMediaService.TWITTER); }
### Question: SimpleSocialUserDetailsService implements SocialUserDetailsService { @Override public SocialUserDetails loadUserByUserId(String userId) throws UsernameNotFoundException, DataAccessException { LOGGER.debug("Loading user by user id: {}", userId); UserDetails userDetails = userDetailsService.loadUserByUsername(userId); LOGGER.debug("Found user details: {}", userDetails); return (SocialUserDetails) userDetails; } SimpleSocialUserDetailsService(UserDetailsService userDetailsService); @Override SocialUserDetails loadUserByUserId(String userId); }### Answer: @Test public void loadByUserId_UserDetailsNotFound_ShouldThrowException() { when(userDetailsServicemock.loadUserByUsername(USER_ID)).thenThrow(new UsernameNotFoundException("")); catchException(service).loadUserByUserId(USER_ID); assertThat(caughtException()) .isExactlyInstanceOf(UsernameNotFoundException.class) .hasNoCause(); verify(userDetailsServicemock, times(1)).loadUserByUsername(USER_ID); verifyNoMoreInteractions(userDetailsServicemock); } @Test public void loadByUserId_UserDetailsFound_ShouldReturnTheFoundUserDetails() { ExampleUserDetails found = ExampleUserDetails.getBuilder() .firstName(FIRST_NAME) .lastName(LAST_NAME) .password(PASSWORD) .username(USER_ID) .role(Role.ROLE_USER) .build(); when(userDetailsServicemock.loadUserByUsername(USER_ID)).thenReturn(found); UserDetails actual = service.loadUserByUserId(USER_ID); assertThat(actual).isEqualTo(found); verify(userDetailsServicemock, times(1)).loadUserByUsername(USER_ID); verifyNoMoreInteractions(userDetailsServicemock); }
### Question: BaseEntity { @PrePersist public void prePersist() { DateTime now = DateTime.now(); this.creationTime = now; this.modificationTime = now; } abstract ID getId(); DateTime getCreationTime(); DateTime getModificationTime(); long getVersion(); @PrePersist void prePersist(); @PreUpdate void preUpdate(); }### Answer: @Test public void prePersist_ShouldSetCreationAndModificationTime() { TestEntity entity = new TestEntity(); entity.prePersist(); assertThat(entity) .creationTimeIsSet() .modificationTimeIsSet() .creationTimeAndModificationTimeAreEqual(); }
### Question: BaseEntity { @PreUpdate public void preUpdate() { this.modificationTime = DateTime.now(); } abstract ID getId(); DateTime getCreationTime(); DateTime getModificationTime(); long getVersion(); @PrePersist void prePersist(); @PreUpdate void preUpdate(); }### Answer: @Test public void preUpdated_ShouldUpdateModificationTime() { DateTime yesterday = DateTime.now().minusDays(1); TestEntity entity = new TestEntityBuilder() .creationTime(yesterday) .modificationTime(yesterday) .build(); entity.preUpdate(); assertThat(entity) .creationTimeIsSet() .modificationTimeIsSet() .modificationTimeIsAfterCreationTime(); }
### Question: RegistrationForm { public boolean isSocialSignIn() { return signInProvider != null; } RegistrationForm(); boolean isNormalRegistration(); boolean isSocialSignIn(); String getEmail(); void setEmail(String email); String getFirstName(); void setFirstName(String firstName); String getLastName(); void setLastName(String lastName); String getPassword(); void setPassword(String password); String getPasswordVerification(); void setPasswordVerification(String passwordVerification); SocialMediaService getSignInProvider(); void setSignInProvider(SocialMediaService signInProvider); @Override String toString(); static final String FIELD_NAME_EMAIL; }### Answer: @Test public void isSocialSignIn_SocialProviderNotSet_ShouldReturnFalse() { RegistrationForm dto = new RegistrationFormBuilder().build(); boolean isSocialSignIn = dto.isSocialSignIn(); assertThat(isSocialSignIn).isFalse(); } @Test public void isSocialSignIn_SocialProviderSet_ShouldReturnTrue() { RegistrationForm dto = new RegistrationFormBuilder() .isSocialSignInViaSignInProvider(SIGN_IN_PROVIDER) .build(); boolean isSocialSignIn = dto.isSocialSignIn(); assertThat(isSocialSignIn).isTrue(); }
### Question: User extends BaseEntity<Long> { public static Builder getBuilder() { return new Builder(); } User(); static Builder getBuilder(); @Override Long getId(); String getEmail(); String getFirstName(); String getLastName(); String getPassword(); Role getRole(); SocialMediaService getSignInProvider(); @Override String toString(); }### Answer: @Test public void build_SignedInByUsingSocialMediaService_ShouldCreateUser() { User user = User.getBuilder() .email(EMAIL) .firstName(FIRST_NAME) .lastName(LAST_NAME) .signInProvider(SIGN_IN_PROVIDER) .build(); assertThat(user) .hasNoId() .hasEmail(EMAIL) .hasFirstName(FIRST_NAME) .hasLastName(LAST_NAME) .isRegisteredUser() .isRegisteredByUsingSignInProvider(SIGN_IN_PROVIDER); } @Test public void build_RegisteredViaNormalRegistration_ShouldCreateUser() { User user = User.getBuilder() .email(EMAIL) .firstName(FIRST_NAME) .lastName(LAST_NAME) .password(PASSWORD) .build(); assertThat(user) .hasNoId() .hasEmail(EMAIL) .hasFirstName(FIRST_NAME) .hasLastName(LAST_NAME) .hasPassword(PASSWORD) .isRegisteredUser() .isRegisteredByUsingNormalRegistration(); }
### Question: UrlUtils { public static String combine(final String... parts) { final StringBuilder sb = new StringBuilder(); for (final String part : parts) { if (isHttpUrl(part) || isHttpsUrl(part)) { sb.setLength(0); } else if (!part.startsWith("/")) { sb.append("/"); } final String path = sanitizePath(part); sb.append(path); } return sb.toString(); } static boolean isHttpUrl(final String url); static boolean isHttpsUrl(final String url); static String toBaseUrl(final String uriString); static String sanitizePath(final String path); static String combine(final String... parts); }### Answer: @Test public void testCombineBase() { final String result = UrlUtils.combine("http: assertThat(result).as("Combined Url").isEqualTo("http: } @Test public void testCombineBaseWithSlash() { final String result = UrlUtils.combine("http: assertThat(result).as("Combined Url").isEqualTo("http: } @Test public void testCombineWrap() { final String result = UrlUtils.combine("http: assertThat(result).as("Combined Url").isEqualTo("http: } @Test public void testCombineWrapWithSlash() { final String result = UrlUtils.combine("http: assertThat(result).as("Combined Url").isEqualTo("http: }
### Question: UrlUtils { public static boolean isHttpsUrl(final String url) { return StringUtils.startsWithIgnoreCase(url, "https: } static boolean isHttpUrl(final String url); static boolean isHttpsUrl(final String url); static String toBaseUrl(final String uriString); static String sanitizePath(final String path); static String combine(final String... parts); }### Answer: @Test public void shouldBeHttpsUrl() { final boolean result = UrlUtils.isHttpsUrl("https: assertThat(result).as("Is HTTPS URL").isTrue(); } @Test public void shouldNotBeHttpsUrl() { final boolean result = UrlUtils.isHttpsUrl("http: assertThat(result).as("Is HTTPS URL").isFalse(); }
### Question: UrlUtils { public static String toBaseUrl(final String uriString) { try { final URL url = new URL(uriString); return url.getProtocol() + ": } catch (final MalformedURLException e) { e.printStackTrace(); } return null; } static boolean isHttpUrl(final String url); static boolean isHttpsUrl(final String url); static String toBaseUrl(final String uriString); static String sanitizePath(final String path); static String combine(final String... parts); }### Answer: @Test public void testToBaseUrl() { final String result = UrlUtils.toBaseUrl("https: assertThat(result).as("Base Url").isEqualTo("https: } @Test public void shouldReturnBaseUrl() { final String result = UrlUtils.toBaseUrl("https: assertThat(result).as("Base Url").isEqualTo("https: } @Test public void shouldReturnBaseUrlFromSlash() { final String result = UrlUtils.toBaseUrl("https: assertThat(result).as("Base Url").isEqualTo("https: } @Test public void shouldReturnNullForNonUrl() { final String result = UrlUtils.toBaseUrl("some string"); assertThat(result).as("Base Url").isNull(); }
### Question: RequestFactory implements Serializable { public EntityRequest createLogoutRequest(final Store store) { final EntityRequest request = new EntityRequest( Method.POST, this.getUrl(store, URL_AUTH_LOGOUT)); return request; } RequestFactory(); EntityRequest createLoginRequest(final Store store); EntityRequest createLogoutRequest(final Store store); EntityRequest createLanguageRequest(final Store store); EntityRequest createAppStoreItemsRequest(final Store store); ZeroCopyFileRequest createUploadRequest(final Store store, final File file); ZeroCopyFileRequest createUploadAppRequest( final Store store, final String releaseStatus, final boolean archivePreviousVersion, final String environmentUuid); EntityRequest createAppFromFileRequest(final Store store, final JsonObject asset); EntityRequest createPersistApplicationRequest(final Store store, final JsonObject app); EntityRequest createPersistVersionRequest(final Store store, final JsonObject app, final JsonObject version); EntityRequest createDeleteVersionRequest(final Store store, final JsonObject version); }### Answer: @Test public void shouldCreateLogoutUrlFromHostName() { this.store.setUrl(URL_HOST_NAME); final EntityRequest request = this.requestFactory.createLogoutRequest(this.store); assertThat(request).isNotNull(); assertThat(request.getMethod()).isEqualTo(Method.POST); assertThat(request.getUri()).isEqualTo("https: } @Test public void shouldCreateLogoutUrlFromApiUrl() { this.store.setUrl(URL_API_URL); final EntityRequest request = this.requestFactory.createLogoutRequest(this.store); assertThat(request).isNotNull(); assertThat(request.getMethod()).isEqualTo(Method.POST); assertThat(request.getUri()).isEqualTo("https: }
### Question: RequestFactory implements Serializable { public EntityRequest createPersistApplicationRequest(final Store store, final JsonObject app) { final EntityRequest request = new EntityRequest( Method.POST, this.getUrl(store, URL_APPS)); final NStringEntity entity = new NStringEntity(app.toString(), CHARSET); request.setEntity(entity); request.setHeader(Headers.CONTENT_TYPE, APPLICATION_JSON); return request; } RequestFactory(); EntityRequest createLoginRequest(final Store store); EntityRequest createLogoutRequest(final Store store); EntityRequest createLanguageRequest(final Store store); EntityRequest createAppStoreItemsRequest(final Store store); ZeroCopyFileRequest createUploadRequest(final Store store, final File file); ZeroCopyFileRequest createUploadAppRequest( final Store store, final String releaseStatus, final boolean archivePreviousVersion, final String environmentUuid); EntityRequest createAppFromFileRequest(final Store store, final JsonObject asset); EntityRequest createPersistApplicationRequest(final Store store, final JsonObject app); EntityRequest createPersistVersionRequest(final Store store, final JsonObject app, final JsonObject version); EntityRequest createDeleteVersionRequest(final Store store, final JsonObject version); }### Answer: @Test public void shouldCreatePersistAppRequestFromHostName() { this.store.setUrl(URL_HOST_NAME); final JsonObject app = new JsonObject(); app.addProperty("appUuid", "{app-uuid}"); final EntityRequest request = this.requestFactory.createPersistApplicationRequest(this.store, app); assertThat(request).isNotNull(); assertThat(request.getMethod()).isEqualTo(Method.POST); assertThat(request.getUri()).isEqualTo("https: } @Test public void shouldCreatePersistAppRequestFromApiUrl() { this.store.setUrl(URL_API_URL); final JsonObject app = new JsonObject(); app.addProperty("uuid", "{app-uuid}"); final EntityRequest request = this.requestFactory.createPersistApplicationRequest(this.store, app); assertThat(request).isNotNull(); assertThat(request.getMethod()).isEqualTo(Method.POST); assertThat(request.getUri()).isEqualTo("https: }
### Question: RequestFactory implements Serializable { public EntityRequest createPersistVersionRequest(final Store store, final JsonObject app, final JsonObject version) { final String appUuid = Json.getString(app, ApiObject.UUID); final EntityRequest request = new EntityRequest( Method.POST, this.getUrl(store, URL_APPS, appUuid, VERSIONS)); final NStringEntity entity = new NStringEntity(version.toString(), CHARSET); request.setEntity(entity); request.setHeader(Headers.CONTENT_TYPE, APPLICATION_JSON); return request; } RequestFactory(); EntityRequest createLoginRequest(final Store store); EntityRequest createLogoutRequest(final Store store); EntityRequest createLanguageRequest(final Store store); EntityRequest createAppStoreItemsRequest(final Store store); ZeroCopyFileRequest createUploadRequest(final Store store, final File file); ZeroCopyFileRequest createUploadAppRequest( final Store store, final String releaseStatus, final boolean archivePreviousVersion, final String environmentUuid); EntityRequest createAppFromFileRequest(final Store store, final JsonObject asset); EntityRequest createPersistApplicationRequest(final Store store, final JsonObject app); EntityRequest createPersistVersionRequest(final Store store, final JsonObject app, final JsonObject version); EntityRequest createDeleteVersionRequest(final Store store, final JsonObject version); }### Answer: @Test public void shouldCreatePersistVersionRequestFromHostName() { this.store.setUrl(URL_HOST_NAME); final EntityRequest request = this.requestFactory.createPersistVersionRequest(this.store, this.app, this.version); assertThat(request).isNotNull(); assertThat(request.getMethod()).isEqualTo(Method.POST); assertThat(request.getUri()).isEqualTo("https: } @Test public void shouldCreatePersistVersionRequestFromApiUrl() { this.store.setUrl(URL_API_URL); final EntityRequest request = this.requestFactory.createPersistVersionRequest(this.store, this.app, this.version); assertThat(request).isNotNull(); assertThat(request.getMethod()).isEqualTo(Method.POST); assertThat(request.getUri()).isEqualTo("https: }
### Question: RequestFactory implements Serializable { public EntityRequest createDeleteVersionRequest(final Store store, final JsonObject version) { final String appUuid = Json.getString(version, Version.APP_UUID); final String uuid = Json.getString(version, ApiObject.UUID); final EntityRequest request = new EntityRequest( Method.DELETE, this.getUrl(store, URL_APPS, appUuid, VERSIONS, uuid)); return request; } RequestFactory(); EntityRequest createLoginRequest(final Store store); EntityRequest createLogoutRequest(final Store store); EntityRequest createLanguageRequest(final Store store); EntityRequest createAppStoreItemsRequest(final Store store); ZeroCopyFileRequest createUploadRequest(final Store store, final File file); ZeroCopyFileRequest createUploadAppRequest( final Store store, final String releaseStatus, final boolean archivePreviousVersion, final String environmentUuid); EntityRequest createAppFromFileRequest(final Store store, final JsonObject asset); EntityRequest createPersistApplicationRequest(final Store store, final JsonObject app); EntityRequest createPersistVersionRequest(final Store store, final JsonObject app, final JsonObject version); EntityRequest createDeleteVersionRequest(final Store store, final JsonObject version); }### Answer: @Test public void shouldCreateDeleteVersionRequestFromHostName() { this.store.setUrl(URL_HOST_NAME); final EntityRequest request = this.requestFactory.createDeleteVersionRequest(this.store, this.version); assertThat(request).isNotNull(); assertThat(request.getMethod()).isEqualTo(Method.DELETE); assertThat(request.getUri()).isEqualTo("https: } @Test public void shouldCreateDeleteVersionRequestFromApiUrl() { this.store.setUrl(URL_API_URL); final EntityRequest request = this.requestFactory.createDeleteVersionRequest(this.store, this.version); assertThat(request).isNotNull(); assertThat(request.getMethod()).isEqualTo(Method.DELETE); assertThat(request.getUri()).isEqualTo("https: }
### Question: UrlUtils { public static String sanitizePath(final String path) { if (StringUtils.isEmpty(path)) { return path; } if (path.endsWith("/")) { return path.substring(0, path.length() - 1); } return path; } static boolean isHttpUrl(final String url); static boolean isHttpsUrl(final String url); static String toBaseUrl(final String uriString); static String sanitizePath(final String path); static String combine(final String... parts); }### Answer: @Test public void testSanitizeUrl() { final String result = UrlUtils.sanitizePath("http: assertThat(result).as("Sanitized Path").isEqualTo("http: } @Test public void testSanitizeUrlWithSlash() { final String result = UrlUtils.sanitizePath("http: assertThat(result).as("Sanitized Path").isEqualTo("http: } @Test public void testSanitizePath() { final String result = UrlUtils.sanitizePath("/a/b/c"); assertThat(result).as("Sanitized Path").isEqualTo("/a/b/c"); } @Test public void testSanitizePathWithSlash() { final String result = UrlUtils.sanitizePath("/a/b/c/"); assertThat(result).as("Sanitized Path").isEqualTo("/a/b/c"); }
### Question: UrlUtils { public static boolean isHttpUrl(final String url) { return StringUtils.startsWithIgnoreCase(url, "http: } static boolean isHttpUrl(final String url); static boolean isHttpsUrl(final String url); static String toBaseUrl(final String uriString); static String sanitizePath(final String path); static String combine(final String... parts); }### Answer: @Test public void shouldBeHttpUrl() { final boolean result = UrlUtils.isHttpUrl("http: assertThat(result).as("Is HTTP URL").isTrue(); } @Test public void shouldNotBeHttpUrl() { final boolean result = UrlUtils.isHttpUrl("https: assertThat(result).as("Is HTTP URL").isFalse(); }
### Question: TemplateEngineRythmI18nMessageResolver implements II18nMessageResolver { @Override public String getMessage(ITemplate template, String key, Object... args) { Locale locale = null; if (args.length > 0) { Object arg0 = args[0]; if (arg0 instanceof Locale) { locale = (Locale) arg0; Object[] args0 = new Object[args.length - 1]; System.arraycopy(args, 1, args0, 0, args.length - 1); args = args0; } } if (locale == null && template != null) { locale = (template == null) ? RythmEngine.get().renderSettings.locale() : template.__curLocale(); } Optional<String> lang = Optional.absent(); if (locale != null) { lang = Optional.of(locale.toString().replace('_', '-')); } Optional<String> i18nMessage = Optional.absent(); i18nMessage = messages.get(key, lang, args); return i18nMessage.or(""); } TemplateEngineRythmI18nMessageResolver(Messages messages); @Override String getMessage(ITemplate template, String key, Object... args); }### Answer: @Test public void testGetMessage() { TemplateEngineRythmI18nMessageResolver resolver = new TemplateEngineRythmI18nMessageResolver( messages); Optional<String> lang = Optional.absent(); when(messages.get(Mockito.eq("key"), Mockito.eq(lang), Mockito.eq("arg1"))).thenReturn( Optional.of("i18n-Message")); Assert.assertEquals("i18n-Message", resolver.getMessage(template, "key", "arg1")); lang = Optional.of("de"); when(messages.get(Mockito.eq("key"), Mockito.eq(lang), Mockito.eq("arg1"))).thenReturn( Optional.of("i18n-Nachricht")); Assert.assertEquals("i18n-Nachricht", resolver.getMessage(template, "key", new Locale("de"), "arg1")); }
### Question: PersonController { public Result postPersonJson(Person person) { return Results.json().render(person); } Result getPersonJson(); Result postPersonJson(Person person); Result getPersonXml(); Result postPersonXml(Person person); }### Answer: @Test public void testPostPersonJson() throws Exception { Person person = new Person(); person.name = "zeeess name - and some utf8 => öäü"; String response = ninjaTestBrowser.postJson(getServerAddress() + "api/person.json", person); System.out.println("j: " + response); Person result = new ObjectMapper().readValue(response, Person.class); assertEquals(person.name, result.name); }
### Question: PersonController { public Result postPersonXml(Person person) { return Results.xml().render(person); } Result getPersonJson(); Result postPersonJson(Person person); Result getPersonXml(); Result postPersonXml(Person person); }### Answer: @Test public void testPostPersonXml() throws Exception { Person person = new Person(); person.name = "zeeess name - and some utf8 => öäü"; String response = ninjaTestBrowser .postXml(getServerAddress() + "api/person.xml", person); System.out.println("j: " + response); Person result = new XmlMapper().readValue(response, Person.class); assertEquals(person.name, result.name); }
### Question: InformationProperties { public URL getServer() throws MalformedURLException { String url = properties.getProperty(SERVER); return new URL(url); } InformationProperties(String propertiesFile); URL getServer(); static final String SERVER_DEFAULT; }### Answer: @Test public void shouldReturnTheValueFromThePropertyFile() throws IOException { String propertiesFile = "/server.properties"; InformationProperties ip = new InformationProperties(propertiesFile); assertThat(ip.getServer()).isEqualTo(new URL("http: } @Test public void shouldReturnDefaultValueIfPropertyFileDoesNotExists() throws IOException { String propertiesFile = "/test.properties"; InformationProperties ip = new InformationProperties(propertiesFile); assertThat(ip.getServer()).isEqualTo(new URL(InformationProperties.SERVER_DEFAULT)); }
### Question: BitMask { public boolean isBitSet(int bit) { long bitMask = Long.rotateLeft(1, bit); long result = this.bitMaskValue & bitMask; if (result != 0) { return true; } return false; } BitMask(); BitMask(long currentValue); long getBitMaskValue(); void setBit(int bit); void unsetBit(int bit); boolean isBitSet(int bit); }### Answer: @Test public void checkNumberBitTest() { for (int bitNumber = 0; bitNumber < 64; bitNumber++) { long bitMask = Long.rotateLeft(1, bitNumber); BitMask bm = new BitMask(bitMask); assertEquals(true, bm.isBitSet(bitNumber)); } } @Test public void checkFirstBitTest() { BitMask bm = new BitMask(0x8000000000000000L); assertEquals(true, bm.isBitSet(63)); }
### Question: Primes { public static IntStream primes(int max) { return IntStream .range(2, max + 1) .filter(candidate -> isPrimeStream(candidate)); } static IntStream primes(int max); static IntStream primes(int max, BiFunction<List<Integer>, Integer, Boolean> isPrime); static boolean isPrimeOpt2(List<Integer> primes, int candidate); static boolean isPrimeOpt(List<Integer> primes, int candidate); static boolean isPrimeStream(int candidate); static boolean isPrimeImperative(int candidate); }### Answer: @Test public void testPrimes() { for (int i = 0; i < 5; i++) { System.out.println("############################"); System.out.println(measurePerformance(() -> Primes.primes(10000, Primes::isPrimeOpt).count())); System.out.println(measurePerformance(() -> Primes.primes(10000, Primes::isPrimeOpt2).count())); } }
### Question: InstanceBucket { @NotNull List<T> getMany() { if (instance instanceof InjectedInstance) { return Collections.singletonList(((InjectedInstance<T>) instance).object); } else if (instance instanceof BoundInstance) { return Collections.singletonList(((BoundInstance<T>) instance).object); } return ((MultiObjectInstance<T>) instance).getMany(); } InstanceBucket( @NotNull MagnetScope scope, @Nullable InstanceFactory<T> factory, @NotNull Class<T> objectType, @NotNull T object, @NotNull String classifier, @NotNull OnInstanceListener listener ); boolean accept(Visitor visitor); }### Answer: @Test @SuppressWarnings("unchecked") public void test_getInstances_SingleItem() { InstanceBucket<Interface1> instances = new InstanceBucket( scope, factory1, Interface1.class, instance1, Classifier.NONE, listener ); List<Interface1> result = instances.getMany(); assertThat(result).containsExactly(instance1); }
### Question: InstanceBucket { @NotNull T getSingleInstance() { if (instance instanceof InjectedInstance) { return ((InjectedInstance<T>) instance).object; } else if (instance instanceof BoundInstance) { return ((BoundInstance<T>) instance).object; } MultiObjectInstance multiObjectInstance = (MultiObjectInstance) instance; throw new IllegalStateException( String.format( "Single instance requested, while many instances are stored: %s", multiObjectInstance.instances ) ); } InstanceBucket( @NotNull MagnetScope scope, @Nullable InstanceFactory<T> factory, @NotNull Class<T> objectType, @NotNull T object, @NotNull String classifier, @NotNull OnInstanceListener listener ); boolean accept(Visitor visitor); }### Answer: @Test @SuppressWarnings("unchecked") public void test_getSingleInstance() { InstanceBucket<Interface1> instances = new InstanceBucket( scope, factory1, Interface1.class, instance1, Classifier.NONE, listener ); Interface1 result = instances.getSingleInstance(); assertThat(result).isSameAs(instance1); }
### Question: InstanceBucket { @NotNull MagnetScope getScope() { return scope; } InstanceBucket( @NotNull MagnetScope scope, @Nullable InstanceFactory<T> factory, @NotNull Class<T> objectType, @NotNull T object, @NotNull String classifier, @NotNull OnInstanceListener listener ); boolean accept(Visitor visitor); }### Answer: @Test @SuppressWarnings("unchecked") public void test_getScope() { InstanceBucket<String> instances = new InstanceBucket( scope, factory1, Interface1.class, instance1, Classifier.NONE, listener ); assertThat(instances.getScope()).isSameAs(scope); }
### Question: BeanUtils { public static final String idFromName(String name) { Transliterator tr = Transliterator.getInstance("Any-Latin; Latin-ASCII"); return removeNonWord(tr.transliterate(name)); } private BeanUtils(); static final String idFromName(String name); static final boolean isValidVersion(String version); }### Answer: @SuppressWarnings("nls") @Test public void testIdFromName() { assertIdFromName("EricWittmann", "Eric Wittmann"); assertIdFromName("DeloitteTouche", "Deloitte & Touche"); assertIdFromName("JBoss_Overlord", "JBoss_Overlord"); assertIdFromName("Red--Hat", "!Red--Hat?"); assertIdFromName("Org.With.Periods", "Org.With.Periods"); assertIdFromName("my-project", "my-project"); assertIdFromName("MyInjectionimgsrca.fsdn.comsdtopicsspace_64.pngaltSpacetitleSpaceheight64width64", "My Injection: <img src=\\\" assertIdFromName("1.0.7-SNAPSHOT", "1.0.7-SNAPSHOT"); assertIdFromName("2.1.0_Final", "2.1.0_Final"); assertIdFromName("Teparados", "Té para dos"); assertIdFromName("Cajdladvoih", "Чай для двоих"); }
### Question: DdlParser { public List<String> parse(File ddlFile) { InputStream is = null; try { is = new FileInputStream(ddlFile); return parse(is); } catch (Exception e) { throw new RuntimeException(e); } finally { IOUtils.closeQuietly(is); } } DdlParser(); List<String> parse(File ddlFile); @SuppressWarnings("nls") List<String> parse(InputStream ddlStream); @SuppressWarnings("nls") static void main(String[] args); }### Answer: @Test public void testParseInputStream() { try (InputStream testDdlIS = getClass().getResourceAsStream("test.ddl")) { DdlParser parser = new DdlParser(); List<String> statements = parser.parse(testDdlIS); StringBuilder builder = new StringBuilder(); for (String statement : statements) { builder.append(statement).append("\n").append("---").append("\n"); } Assert.assertEquals(EXPECTED, builder.toString()); } catch (IOException e) { throw new RuntimeException(e); } }
### Question: PluginClassLoader extends ClassLoader { public List<URL> getPolicyDefinitionResources() { List<URL> resources = new ArrayList<>(); Enumeration<? extends ZipEntry> entries = this.pluginArtifactZip.entries(); while (entries.hasMoreElements()) { ZipEntry zipEntry = entries.nextElement(); if (zipEntry.getName().toLowerCase().startsWith("meta-inf/apiman/policydefs/") && zipEntry.getName().toLowerCase().endsWith(".json")) { try { resources.add(extractResource(zipEntry)); } catch (IOException e) { throw new RuntimeException(e); } } } return resources; } PluginClassLoader(File pluginArtifactFile); PluginClassLoader(File pluginArtifactFile, ClassLoader parent); void close(); List<URL> getPolicyDefinitionResources(); }### Answer: @Test public void testGetPolicyDefinitionResources() throws Exception { File file = new File("src/test/resources/plugin-with-policyDefs.war"); if (!file.exists()) { throw new Exception("Failed to find test WAR: plugin-with-policyDefs.war at: " + file.getAbsolutePath()); } PluginClassLoader classloader = new TestPluginClassLoader(file); List<URL> resources = classloader.getPolicyDefinitionResources(); Assert.assertNotNull(resources); Assert.assertEquals(2, resources.size()); URL url = resources.get(0); Assert.assertNotNull(url); Assert.assertTrue(url.toString().contains("META-INF/apiman/policyDefs")); }
### Question: QueryMap extends CaseInsensitiveStringMultiMap implements Serializable { @SuppressWarnings("nls") public String toQueryString() { List<Entry<String, String>> elems = getEntries(); Collections.reverse(elems); return elems.stream() .map(pair -> URLEnc(pair.getKey()) + "=" + URLEnc(pair.getValue())) .collect(Collectors.joining("&")); } QueryMap(); QueryMap(int sizeHint); @Override String toString(); @SuppressWarnings("nls") String toQueryString(); }### Answer: @Test public void emptyQuery() { QueryMap qm = new QueryMap(); assertEquals("", qm.toQueryString()); } @Test public void simpleQuery() { QueryMap qm = new QueryMap(); qm.add("q", "search").add("Q", "search again").add("x", "otherthing"); assertEquals("q=search&Q=search+again&x=otherthing", qm.toQueryString()); } @Test public void complexQuery() { QueryMap qm = new QueryMap(); qm.add("the query param", "the meaning of life: 42, according to Douglas Adams' Hitchiker's Guide to the Galaxy") .add("Q", "A & B & C & D * E @ F $ G % G ^ I & J ( K"); assertEquals("the+query+param=the+meaning+of+life%3A+42%2C+according+to+Douglas+Adams%27+Hitchiker%27s+Guide+to+the+Galaxy&" + "Q=A+%26+B+%26+C+%26+D+*+E+%40+F+%24+G+%25+G+%5E+I+%26+J+%28+K", qm.toQueryString()); }
### Question: SoapPayloadIO implements IPayloadIO<SOAPEnvelope> { @Override public byte[] marshall(SOAPEnvelope data) throws Exception { Transformer transformer = TransformerFactory.newInstance().newTransformer(); StreamResult result = new StreamResult(new StringWriter()); DOMSource source = new DOMSource(data); transformer.transform(source, result); String xml = result.getWriter().toString(); String enc = data.getOwnerDocument().getXmlEncoding(); if (enc == null) { enc = "UTF8"; } return xml.getBytes(enc); } SoapPayloadIO(); SOAPEnvelope parse(InputStream input); SOAPEnvelope parse(byte [] bytes); @Override SOAPEnvelope unmarshall(InputStream input); @Override SOAPEnvelope unmarshall(byte[] input); @Override byte[] marshall(SOAPEnvelope data); }### Answer: @Test public void testMarshall_Simple() throws Exception { MessageFactory msgFactory = MessageFactory.newInstance(); SOAPMessage message = msgFactory.createMessage(); SOAPEnvelope envelope = message.getSOAPPart().getEnvelope(); SOAPHeader header = envelope.getHeader(); SOAPHeaderElement cheader = header.addHeaderElement(new QName("urn:ns1", "CustomHeader")); cheader.setTextContent("CVALUE"); SoapPayloadIO io = new SoapPayloadIO(); byte[] data = io.marshall(envelope); String actual = new String(data); String expected = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http: Assert.assertEquals(expected, actual); }
### Question: XmlPayloadIO implements IPayloadIO<Document> { @Override public Document unmarshall(InputStream input) throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); factory.setValidating(false); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(input); return doc; } @Override Document unmarshall(InputStream input); @Override Document unmarshall(byte[] input); @Override byte[] marshall(Document data); }### Answer: @Test public void testUnmarshall_Simple() throws Exception { String xml = "<?xml version=\"1.0\"?>\r\n" + "<book xmlns=\"urn:ns1\">\r\n" + " <author>Gambardella, Matthew</author>\r\n" + " <title>XML Developer's Guide</title>\r\n" + " <genre>Computer</genre>\r\n" + " <price>44.95</price>\r\n" + " <publish_date>2000-10-01</publish_date>\r\n" + " <description>An in-depth look at creating applications with XML.</description>\r\n" + "</book>"; byte [] xmlBytes = xml.getBytes(); XmlPayloadIO io = new XmlPayloadIO(); try (InputStream is = new ByteArrayInputStream(xmlBytes)) { Document document = io.unmarshall(is); Assert.assertNotNull(document); Assert.assertEquals("book", document.getDocumentElement().getLocalName()); Assert.assertEquals("urn:ns1", document.getDocumentElement().getNamespaceURI()); } }
### Question: XmlPayloadIO implements IPayloadIO<Document> { @Override public byte[] marshall(Document data) throws Exception { Transformer transformer = TransformerFactory.newInstance().newTransformer(); StreamResult result = new StreamResult(new StringWriter()); DOMSource source = new DOMSource(data); transformer.transform(source, result); String xml = result.getWriter().toString(); String enc = data.getXmlEncoding(); if (enc == null) { enc = "UTF8"; } return xml.getBytes(enc); } @Override Document unmarshall(InputStream input); @Override Document unmarshall(byte[] input); @Override byte[] marshall(Document data); }### Answer: @Test public void testMarshall_Simple() throws Exception { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); DocumentBuilder builder = dbf.newDocumentBuilder(); Document document = builder.newDocument(); Element bookElem = document.createElementNS("urn:ns1", "book"); document.appendChild(bookElem); Element authorElem = document.createElementNS("urn:ns1", "author"); Element titleElem = document.createElementNS("urn:ns1", "title"); Element genreElem = document.createElementNS("urn:ns1", "genre"); authorElem.setTextContent("Gambardella, Matthew"); titleElem.setTextContent("title"); genreElem.setTextContent("Computer"); bookElem.appendChild(authorElem); bookElem.appendChild(titleElem); bookElem.appendChild(genreElem); XmlPayloadIO io = new XmlPayloadIO(); byte[] xmlBytes = io.marshall(document); String xml = new String(xmlBytes); String expected = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>" + "<book xmlns=\"urn:ns1\">" + "<author>Gambardella, Matthew</author>" + "<title>title</title>" + "<genre>Computer</genre>" + "</book>"; Assert.assertEquals(expected, xml); }
### Question: JsonPayloadIO implements IPayloadIO<Map> { @Override public byte[] marshall(Map data) throws Exception { String dataAsString = mapper.writeValueAsString(data); return dataAsString.getBytes("UTF8"); } JsonPayloadIO(); @Override Map unmarshall(InputStream input); @Override Map unmarshall(byte[] input); @Override byte[] marshall(Map data); }### Answer: @Test public void testMarshall_Simple() throws Exception { Map<String, Comparable> data = new LinkedHashMap<>(); data.put("hello", "world"); data.put("foo", "bar"); data.put("bool", true); JsonPayloadIO io = new JsonPayloadIO(); byte[] bytes = io.marshall(data); String actual = new String(bytes); String expected = "{\"hello\":\"world\",\"foo\":\"bar\",\"bool\":true}"; Assert.assertEquals(expected, actual); }
### Question: SoapHeaderScanner { public boolean scan(IApimanBuffer buffer) throws SoapEnvelopeNotFoundException { if (this.buffer == null) { this.buffer = buffer; } else { this.buffer.append(buffer); } boolean scanComplete = doScan(); if (!scanComplete && this.buffer.length() >= getMaxBufferLength()) { throw new SoapEnvelopeNotFoundException(); } return scanComplete; } SoapHeaderScanner(); boolean scan(IApimanBuffer buffer); int getMaxBufferLength(); void setMaxBufferLength(int maxBufferLength); boolean hasXmlPreamble(); String getXmlPreamble(); String getEnvelopeDeclaration(); String getHeaders(); byte[] getRemainingBytes(); }### Answer: @Test public void testScanNoSoap() throws SoapEnvelopeNotFoundException { String testData = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin finibus mauris " + "vel fermentum finibus. Proin lacus nulla, placerat in velit tristique, semper congue nisi. " + "Quisque ultricies metus felis, eu aliquet ligula gravida euismod. Integer et nulla eget " + "metus pretium consectetur eu id arcu. Fusce odio turpis, gravida sit amet finibus eu, " + "consequat in est. Nunc eu volutpat leo. Praesent sollicitudin est vitae lacus egestas, " + "iaculis dictum libero suscipit. Morbi vitae egestas diam. Nulla eu molestie urna."; IApimanBuffer buffer = new ByteBuffer(testData); SoapHeaderScanner scanner = new SoapHeaderScanner(); boolean done = scanner.scan(buffer); Assert.assertFalse("Expected the scan to *not* complete.", done); }
### Question: DefaultExecuteBlockingComponent implements IExecuteBlockingComponent { @Override public <T> void executeBlocking(IAsyncHandler<IAsyncFuture<T>> blockingCode, IAsyncResultHandler<T> resultHandler) { IAsyncFuture<T> wrapped = passthrough(resultHandler); try { blockingCode.handle(wrapped); } catch (Exception e) { wrapped.fail(e); } } @Override void executeBlocking(IAsyncHandler<IAsyncFuture<T>> blockingCode, IAsyncResultHandler<T> resultHandler); }### Answer: @Test public void testSuccessfulExecution() { executeBlockingComponent.executeBlocking(future -> { future.completed("Coëtivy"); }, result -> { Assert.assertTrue(result.isSuccess()); Assert.assertFalse(result.isError()); Assert.assertEquals(result.getResult(), "Coëtivy"); Assert.assertNull(result.getError()); }); } @Test public void testFailedExecution() { executeBlockingComponent.executeBlocking(future -> { future.fail(new ExampleException("Aldabra")); }, result -> { Assert.assertFalse(result.isSuccess()); Assert.assertTrue(result.isError()); Assert.assertTrue(result.getError() instanceof ExampleException); Assert.assertEquals(result.getError().getMessage(), "Aldabra"); Assert.assertNull(result.getResult()); }); } @Test public void testExceptionInExecuteBlock() { executeBlockingComponent.executeBlocking(future -> { throw new ExampleException("Cosmoledo"); }, result -> { Assert.assertFalse(result.isSuccess()); Assert.assertTrue(result.isError()); Assert.assertTrue(result.getError() instanceof ExampleException); Assert.assertEquals(result.getError().getMessage(), "Cosmoledo"); Assert.assertNull(result.getResult()); }); }
### Question: DefaultJdbcComponent implements IJdbcComponent { @Override public IJdbcClient createStandalone(JdbcOptionsBean config) { return createShared(dsNameFromConfig(config), config); } DefaultJdbcComponent(); @Override synchronized IJdbcClient createShared(String dsName, JdbcOptionsBean config); @Override IJdbcClient createStandalone(JdbcOptionsBean config); @Override IJdbcClient create(DataSource ds); }### Answer: @Test public void testStandalone() throws Throwable { DefaultJdbcComponent component = new DefaultJdbcComponent(); JdbcOptionsBean config = new JdbcOptionsBean(); config.setAutoCommit(true); config.setJdbcUrl("jdbc:h2:mem:testStandalone;DB_CLOSE_DELAY=-1"); config.setUsername("sa"); config.setPassword(""); IJdbcClient client = component.createStandalone(config); doAllTests(client); }
### Question: DefaultJdbcComponent implements IJdbcComponent { @Override public synchronized IJdbcClient createShared(String dsName, JdbcOptionsBean config) { if (clients.containsKey(dsName)) { return clients.get(dsName); } else { DataSource ds = datasourceFromConfig(config); DefaultJdbcClient client = new DefaultJdbcClient(ds); clients.put(dsName, client); return client; } } DefaultJdbcComponent(); @Override synchronized IJdbcClient createShared(String dsName, JdbcOptionsBean config); @Override IJdbcClient createStandalone(JdbcOptionsBean config); @Override IJdbcClient create(DataSource ds); }### Answer: @Test public void testShared() throws Throwable { DefaultJdbcComponent component = new DefaultJdbcComponent(); JdbcOptionsBean config = new JdbcOptionsBean(); config.setAutoCommit(true); config.setJdbcUrl("jdbc:h2:mem:testShared;DB_CLOSE_DELAY=-1"); config.setUsername("sa"); config.setPassword(""); IJdbcClient client = component.createShared("sharedDS", config); doAllTests(client); }
### Question: DefaultJdbcComponent implements IJdbcComponent { @Override public IJdbcClient create(DataSource ds) { return new DefaultJdbcClient(ds); } DefaultJdbcComponent(); @Override synchronized IJdbcClient createShared(String dsName, JdbcOptionsBean config); @Override IJdbcClient createStandalone(JdbcOptionsBean config); @Override IJdbcClient create(DataSource ds); }### Answer: @Test public void testDataSource() throws Throwable { DefaultJdbcComponent component = new DefaultJdbcComponent(); BasicDataSource ds = new BasicDataSource(); ds.setDriverClassName(Driver.class.getName()); ds.setUsername("sa"); ds.setPassword(""); ds.setUrl("jdbc:h2:mem:testDataSource;DB_CLOSE_DELAY=-1"); try { IJdbcClient client = component.create(ds); doAllTests(client); } finally { try { ds.close(); } catch (SQLException e) { e.printStackTrace(); } } }
### Question: AbstractConnectorConfig implements IConnectorConfig { @Override public Set<String> getSuppressedResponseHeaders() { return Collections.unmodifiableSet(suppressedResponseHeaders); } AbstractConnectorConfig(Set<String> suppressedRequestHeaders, Set<String> suppressedResponseHeaders); AbstractConnectorConfig(); @Override void suppressRequestHeader(String headerName); @Override void suppressResponseHeader(String headerName); @Override void permitRequestHeader(String headerName); @Override void permitResponseHeader(String headerName); @Override Set<String> getSuppressedRequestHeaders(); @Override Set<String> getSuppressedResponseHeaders(); }### Answer: @Test public void shouldContainInitialHeaders() { AbstractConnectorConfig connector = new AbstractConnectorConfig(REQUEST, RESPONSE) {}; Assert.assertTrue(connector.getSuppressedResponseHeaders().containsAll(RESPONSE)); }
### Question: AbstractConnectorConfig implements IConnectorConfig { @Override public Set<String> getSuppressedRequestHeaders() { return Collections.unmodifiableSet(suppressedRequestHeaders); } AbstractConnectorConfig(Set<String> suppressedRequestHeaders, Set<String> suppressedResponseHeaders); AbstractConnectorConfig(); @Override void suppressRequestHeader(String headerName); @Override void suppressResponseHeader(String headerName); @Override void permitRequestHeader(String headerName); @Override void permitResponseHeader(String headerName); @Override Set<String> getSuppressedRequestHeaders(); @Override Set<String> getSuppressedResponseHeaders(); }### Answer: @Test public void shouldEvaluateKeysCaseInsensitively() { AbstractConnectorConfig connector = new AbstractConnectorConfig(REQUEST, RESPONSE) {}; Assert.assertTrue("Must compare case insensitively", connector.getSuppressedRequestHeaders().contains("x-api-key")); }
### Question: AbstractConnectorConfig implements IConnectorConfig { @Override public void permitRequestHeader(String headerName) { if (suppressedRequestHeaders.contains(headerName)) { copyRequestMap(); suppressedRequestHeaders.remove(headerName); } } AbstractConnectorConfig(Set<String> suppressedRequestHeaders, Set<String> suppressedResponseHeaders); AbstractConnectorConfig(); @Override void suppressRequestHeader(String headerName); @Override void suppressResponseHeader(String headerName); @Override void permitRequestHeader(String headerName); @Override void permitResponseHeader(String headerName); @Override Set<String> getSuppressedRequestHeaders(); @Override Set<String> getSuppressedResponseHeaders(); }### Answer: @Test public void permitRequestHeader() { AbstractConnectorConfig connector = new AbstractConnectorConfig(REQUEST, RESPONSE) {}; connector.permitRequestHeader("Host"); Assert.assertFalse("Must unsuppress header", connector.getSuppressedRequestHeaders().contains("Host")); }
### Question: AbstractConnectorConfig implements IConnectorConfig { @Override public void permitResponseHeader(String headerName) { if (suppressedResponseHeaders.contains(headerName)) { copyResponseMap(); suppressedResponseHeaders.remove(headerName); } } AbstractConnectorConfig(Set<String> suppressedRequestHeaders, Set<String> suppressedResponseHeaders); AbstractConnectorConfig(); @Override void suppressRequestHeader(String headerName); @Override void suppressResponseHeader(String headerName); @Override void permitRequestHeader(String headerName); @Override void permitResponseHeader(String headerName); @Override Set<String> getSuppressedRequestHeaders(); @Override Set<String> getSuppressedResponseHeaders(); }### Answer: @Test public void permitResponseHeader() { AbstractConnectorConfig connector = new AbstractConnectorConfig(REQUEST, RESPONSE) {}; connector.permitResponseHeader("Host"); Assert.assertFalse("Must unsuppress header", connector.getSuppressedResponseHeaders().contains("Host")); }
### Question: JdbcMetrics extends AbstractJdbcComponent implements IMetrics { @Override public void record(RequestMetric metric) { try { queue.put(metric); } catch (Exception e) { e.printStackTrace(); } } JdbcMetrics(Map<String, String> config); @Override void record(RequestMetric metric); @Override void setComponentRegistry(IComponentRegistry registry); }### Answer: @Test public void testRecord() throws Exception { Map<String, String> config = new HashMap<>(); config.put("datasource.jndi-location", DB_JNDI_LOC); JdbcMetrics metrics = new JdbcMetrics(config); metrics.record(request( "2016-02-10T09:30:00Z", 300, "http: "GET", "TestOrg", "TestApi", "1.0", "Gold", "TestOrg", "TestClient", "1.0", "12345", "user1", 200, "OK", false, 0, null, false, null, 0, 1024)); Thread.sleep(200); assertRowCount(1, "SELECT * FROM gw_requests WHERE api_org_id = ?", "TestOrg"); metrics.stop(); }
### Question: PubkeyUtils { static String encodeHex(byte[] bytes) { final char[] hex = new char[bytes.length * 2]; int i = 0; for (byte b : bytes) { hex[i++] = HEX_DIGITS[(b >> 4) & 0x0f]; hex[i++] = HEX_DIGITS[b & 0x0f]; } return String.valueOf(hex); } private PubkeyUtils(); static String formatKey(Key key); static byte[] getEncodedPrivate(PrivateKey pk, String secret); static PrivateKey decodePrivate(byte[] encoded, String keyType); static PrivateKey decodePrivate(byte[] encoded, String keyType, String secret); static int getBitStrength(byte[] encoded, String keyType); static PublicKey decodePublic(byte[] encoded, String keyType); static KeyPair convertToKeyPair(PubkeyBean keybean, String password); static KeyPair recoverKeyPair(byte[] encoded); static String convertToOpenSSHFormat(PublicKey pk, String origNickname); static byte[] extractOpenSSHPublic(KeyPair pair); static String exportPEM(PrivateKey key, String secret); static final String PKCS8_START; static final String PKCS8_END; }### Answer: @Test public void encodeHex_Null_Failure() throws Exception { try { PubkeyUtils.encodeHex(null); fail("Should throw null pointer exception when argument is null"); } catch (NullPointerException e) { } } @Test public void encodeHex_Success() throws Exception { byte[] input = {(byte) 0xFF, 0x00, (byte) 0xA5, 0x5A, 0x12, 0x23}; String expected = "ff00a55a1223"; assertEquals("Encoded hex should match expected", PubkeyUtils.encodeHex(input), expected); }
### Question: PubkeyUtils { static BigInteger getRSAPublicExponentFromPkcs8Encoded(byte[] encoded) throws InvalidKeySpecException { if (encoded == null) { throw new InvalidKeySpecException("encoded key is null"); } try { SimpleDERReader reader = new SimpleDERReader(encoded); reader.resetInput(reader.readSequenceAsByteArray()); if (!reader.readInt().equals(BigInteger.ZERO)) { throw new InvalidKeySpecException("PKCS#8 is not version 0"); } reader.readSequenceAsByteArray(); reader.resetInput(reader.readOctetString()); reader.resetInput(reader.readSequenceAsByteArray()); if (!reader.readInt().equals(BigInteger.ZERO)) { throw new InvalidKeySpecException("RSA key is not version 0"); } reader.readInt(); return reader.readInt(); } catch (IOException e) { Log.w(TAG, "Could not read public exponent", e); throw new InvalidKeySpecException("Could not read key", e); } } private PubkeyUtils(); static String formatKey(Key key); static byte[] getEncodedPrivate(PrivateKey pk, String secret); static PrivateKey decodePrivate(byte[] encoded, String keyType); static PrivateKey decodePrivate(byte[] encoded, String keyType, String secret); static int getBitStrength(byte[] encoded, String keyType); static PublicKey decodePublic(byte[] encoded, String keyType); static KeyPair convertToKeyPair(PubkeyBean keybean, String password); static KeyPair recoverKeyPair(byte[] encoded); static String convertToOpenSSHFormat(PublicKey pk, String origNickname); static byte[] extractOpenSSHPublic(KeyPair pair); static String exportPEM(PrivateKey key, String secret); static final String PKCS8_START; static final String PKCS8_END; }### Answer: @Test public void getRSAPublicExponentFromPkcs8Encoded_Success() throws Exception { assertEquals(RSA_KEY_E, PubkeyUtils.getRSAPublicExponentFromPkcs8Encoded(RSA_KEY_PKCS8)); }
### Question: ResumptionTokenHelper { public static ResumptionToken decodeResumptionToken(String base64EncodedToken) { try { String decoded = new String(Base64.getUrlDecoder().decode(base64EncodedToken), StandardCharsets.UTF_8); String[] parts = tokenize(decoded); Date expirationDate = new Date(Long.valueOf(parts[EXPIRATION_TIME_INDEX])); long cursor = Long.parseLong(parts[CURSOR_INDEX]); long completeListSize = Long.parseLong(parts[COMPLETE_LIST_SIZE_INDEX]); return new ResumptionToken(decoded, completeListSize, expirationDate, cursor); } catch (Exception e) { throw new IllegalArgumentException(); } } private ResumptionTokenHelper(); static ResumptionToken createResumptionToken(String from, String until, String set, String format, Date expirationDate, long completeListSize, long cursor, String nextCursorMark); static ResumptionToken createResumptionToken(Date expirationDate, long completeListSize, long cursor); static ResumptionToken decodeResumptionToken(String base64EncodedToken); static String getFrom(String token); static String getUntil(String token); static String getSet(String token); static String getFormat(String token); static Date getExpirationDate(String token); static long getCompleteListSize(String token); static long getCursor(String token); static String getCursorMark(String token); }### Answer: @Test(expected = IllegalArgumentException.class) public void testDecodeIncorrectToken() { ResumptionTokenHelper.decodeResumptionToken(INCORRECT_TOKEN); }
### Question: RecordApi extends BaseProvider implements RecordProvider { @Override public Record getRecord(String id) throws OaiPmhException { ResponseEntity<String> response = getResponseForRecord(id); RDFMetadata rdf = new RDFMetadata(response.getBody()); Header header = new Header(); header.setIdentifier(id); header.setDatestamp(new Date()); return new Record(header, rdf); } @Override Record getRecord(String id); @Override void checkRecordExists(String id); @Override ListRecords listRecords(List<Header> identifiers); void close(); }### Answer: @Test public void getRecord() throws OaiPmhException, IOException { Record record = new Record(null, loadRecord()); given(recordApi.getRecord(TEST_RECORD_ID)).willReturn(record); Record xml = recordApi.getRecord(TEST_RECORD_ID); Assert.assertNotNull(xml); Assert.assertTrue(xml.getMetadata().getMetadata().contains("about=\"http: } @Test(expected=IdDoesNotExistException.class) public void getRecordNotExists() throws OaiPmhException { given(recordApi.getRecord("INCORRECT/ID")).willThrow(new IdDoesNotExistException("INCORRECT/ID")); recordApi.getRecord("INCORRECT/ID"); fail(); }