method2testcases stringlengths 118 3.08k |
|---|
### Question:
InputParamUtil { public static String getRequiredParam(Map<String, String> parameters, String parameterKey) { if (parameters == null || parameters.get(parameterKey) == null || parameters.get(parameterKey).trim().isEmpty()) { throw new DMNRuntimeException("A '" + parameterKey + "' parameter is required."); } else { return parameters.get(parameterKey); } } static String getRequiredParam(Map<String, String> parameters, String parameterKey); static String getOptionalParam(Map<String, String> parameters, String parameterKey, String defaultValue); static String getOptionalParam(Map<String, String> parameters, String parameterKey); static boolean getOptionalBooleanParam(Map<String, String> parameters, String paramKey); static boolean getOptionalBooleanParam(Map<String, String> parameters, String paramKey, String defaultValue); }### Answer:
@Test public void testGetRequiredParamWherePresent() { Map<String, String> params = new HashMap<String, String>(){{ put("paramKey", "paramValue"); }}; assertEquals("paramValue", InputParamUtil.getRequiredParam(params, "paramKey")); }
@Test public void testGetRequiredParamWhereNotPresent() { Map<String, String> params = new HashMap<String, String>(){{ }}; try { InputParamUtil.getRequiredParam(params, "paramKey"); fail(); } catch (RuntimeException e) { assertEquals("A 'paramKey' parameter is required.", e.getMessage()); } } |
### Question:
InputParamUtil { public static String getOptionalParam(Map<String, String> parameters, String parameterKey, String defaultValue) { if (parameters == null || parameters.get(parameterKey) == null || parameters.get(parameterKey).trim().isEmpty()) { return defaultValue; } else { return parameters.get(parameterKey); } } static String getRequiredParam(Map<String, String> parameters, String parameterKey); static String getOptionalParam(Map<String, String> parameters, String parameterKey, String defaultValue); static String getOptionalParam(Map<String, String> parameters, String parameterKey); static boolean getOptionalBooleanParam(Map<String, String> parameters, String paramKey); static boolean getOptionalBooleanParam(Map<String, String> parameters, String paramKey, String defaultValue); }### Answer:
@Test public void testGetOptionalParamWherePresent() { Map<String, String> params = new HashMap<String, String>(){{ put("paramKey", "paramValue"); }}; assertEquals("paramValue", InputParamUtil.getOptionalParam(params, "paramKey")); }
@Test public void testGetOptionalParamWhereNotPresent() { Map<String, String> params = new HashMap<String, String>(){{ }}; assertNull(InputParamUtil.getOptionalParam(params, "paramKey")); } |
### Question:
InputParamUtil { public static boolean getOptionalBooleanParam(Map<String, String> parameters, String paramKey) { String param = InputParamUtil.getOptionalParam(parameters, paramKey); return Boolean.parseBoolean(param); } static String getRequiredParam(Map<String, String> parameters, String parameterKey); static String getOptionalParam(Map<String, String> parameters, String parameterKey, String defaultValue); static String getOptionalParam(Map<String, String> parameters, String parameterKey); static boolean getOptionalBooleanParam(Map<String, String> parameters, String paramKey); static boolean getOptionalBooleanParam(Map<String, String> parameters, String paramKey, String defaultValue); }### Answer:
@Test public void testGetOptionalBooleanParamWherePresent() { Map<String, String> params = new HashMap<String, String>(){{ put("paramKey", "true"); }}; assertTrue(InputParamUtil.getOptionalBooleanParam(params, "paramKey")); }
@Test public void testGetOptionalBooleanParamWhereNotPresent() { Map<String, String> params = new HashMap<String, String>(){{ }}; assertFalse(InputParamUtil.getOptionalBooleanParam(params, "paramKey")); } |
### Question:
JavaAssistCompiler extends JavaCompilerImpl { @Override public ClassData makeClassData(FunctionDefinition element, FEELContext context, BasicDMNToNativeTransformer dmnTransformer, FEELTranslator feelTranslator, String libClassName) { FunctionType functionType = (FunctionType) element.getType(); String signature = "Object[] args"; boolean convertToContext = true; String body = feelTranslator.expressionToNative(element.getBody(), context); NativeFactory nativeFactory = dmnTransformer.getNativeFactory(); String applyMethod = nativeFactory.applyMethod(functionType, signature, convertToContext, body); String bridgeMethodText = bridgeMethodText(); String packageName = "com.gs.dmn.runtime"; String className = "LambdaExpressionImpl" + System.currentTimeMillis(); return new JavaAssistClassData(packageName, className, applyMethod, bridgeMethodText); } @Override ClassData makeClassData(FunctionDefinition element, FEELContext context, BasicDMNToNativeTransformer dmnTransformer, FEELTranslator feelTranslator, String libClassName); @Override Class<?> compile(ClassData classData); }### Answer:
@Test public void testMakeClassData() { ClassData classData = makeClassData(); assertEquals(JavaAssistClassData.class.getName(), classData.getClass().getName()); assertTrue(classData.getClassName().startsWith("LambdaExpressionImpl")); assertEquals("com.gs.dmn.runtime", classData.getPackageName()); assertEquals("public Object apply(Object[] args) {\n return apply(args);\n}\n", ((JavaAssistClassData)classData).getBridgeMethodText()); assertEquals("public java.math.BigDecimal apply(Object[] args) {return number(\"123\");}", ((JavaAssistClassData)classData).getMethodText()); } |
### Question:
JavaAssistCompiler extends JavaCompilerImpl { @Override public Class<?> compile(ClassData classData) throws Exception { String packageName = classData.getPackageName(); String className = classData.getClassName(); String methodText = ((JavaAssistClassData)classData).getMethodText(); String bridgeMethodText = ((JavaAssistClassData)classData).getBridgeMethodText(); ClassPool classPool = new ClassPool(true); CtClass superClass = resolveClass(DefaultFEELLib.class); CtClass superInterface = resolveClass(LambdaExpression.class); CtClass lambdaImplClass = classPool.makeClass(packageName + "." + className); lambdaImplClass.setSuperclass(superClass); lambdaImplClass.addInterface(superInterface); CtMethod applyMethod = CtNewMethod.make(methodText, lambdaImplClass); applyMethod.setModifiers(applyMethod.getModifiers() | Modifier.VARARGS); lambdaImplClass.addMethod(applyMethod); CtMethod applyBridgeMethod = CtMethod.make(bridgeMethodText, lambdaImplClass); lambdaImplClass.addMethod(applyBridgeMethod); return lambdaImplClass.toClass(); } @Override ClassData makeClassData(FunctionDefinition element, FEELContext context, BasicDMNToNativeTransformer dmnTransformer, FEELTranslator feelTranslator, String libClassName); @Override Class<?> compile(ClassData classData); }### Answer:
@Override @Test public void testCompile() throws Exception { Class<?> cls = getCompiler().compile(makeClassData()); assertNotNull(cls); } |
### Question:
InterpretedRuleOutput extends RuleOutput { @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof InterpretedRuleOutput)) return false; InterpretedRuleOutput that = (InterpretedRuleOutput) o; return matched == that.matched && Objects.equals(result, that.result); } InterpretedRuleOutput(boolean matched, Object result); Object getResult(); @Override List<RuleOutput> sort(List<RuleOutput> matchedResults); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer:
@Test public void testEquals() { assertTrue(new InterpretedRuleOutput(true, "123").equals(new InterpretedRuleOutput(true, "123"))); assertFalse(new InterpretedRuleOutput(true, "1234").equals(new InterpretedRuleOutput(true, "123"))); Context c1 = new Context(); c1.put("Rate", new Pair<>("Best", null)); c1.put("Status", new Pair<>("Approved", null)); Context c2 = new Context(); c2.put("Rate", new Pair<>("Best", null)); c2.put("Status", new Pair<>("Approved", null)); assertTrue(new InterpretedRuleOutput(true, c1).equals(new InterpretedRuleOutput(true, c2))); } |
### Question:
Environment { public Declaration lookupVariableDeclaration(String name) { Declaration declaration = lookupLocalVariableDeclaration(name); if (declaration != null) { return declaration; } else { if (getParent() != null) { return getParent().lookupVariableDeclaration(name); } else { return null; } } } Environment(); Environment(Environment parent); Environment(Environment parent, Expression inputExpression); Environment getParent(); Expression getInputExpression(); Type getInputExpressionType(); void addDeclaration(Declaration declaration); void addDeclaration(String name, Declaration declaration); Declaration lookupVariableDeclaration(String name); List<Declaration> lookupFunctionDeclaration(String name); Declaration lookupFunctionDeclaration(String name, ParameterTypes parameterTypes); void updateVariableDeclaration(String name, Type type); }### Answer:
@Test public void testLookupVariableDeclaration() { Environment environment = environmentFactory.makeEnvironment(); String name = "x"; environment.addDeclaration(new VariableDeclaration(name, StringType.STRING)); assertEquals("x", environment.lookupVariableDeclaration(name).getName()); } |
### Question:
Environment { public List<Declaration> lookupFunctionDeclaration(String name) { List<Declaration> declarations = lookupLocalFunctionDeclaration(name); if (declarations == null) { declarations = new ArrayList<>(); } Environment environment = this.parent; while (environment != null) { List<Declaration> parentDeclarations = environment.lookupLocalFunctionDeclaration(name); if (parentDeclarations != null) { declarations.addAll(parentDeclarations); } environment = environment.parent; } return declarations; } Environment(); Environment(Environment parent); Environment(Environment parent, Expression inputExpression); Environment getParent(); Expression getInputExpression(); Type getInputExpressionType(); void addDeclaration(Declaration declaration); void addDeclaration(String name, Declaration declaration); Declaration lookupVariableDeclaration(String name); List<Declaration> lookupFunctionDeclaration(String name); Declaration lookupFunctionDeclaration(String name, ParameterTypes parameterTypes); void updateVariableDeclaration(String name, Type type); }### Answer:
@Test public void testLookupFunctionDeclaration() { Environment environment = environmentFactory.makeEnvironment(); String functionName = "date"; assertEquals(functionName, environment.lookupFunctionDeclaration(functionName, new PositionalParameterTypes(Arrays.asList(StringType.STRING))).getName()); } |
### Question:
NopBuildLogger implements BuildLogger { @Override public void debug(String charSequence) { } @Override void debug(String charSequence); @Override void info(String charSequence); @Override void warn(String charSequence); @Override void error(String charSequence); }### Answer:
@Test public void debug() { logger.debug(message); assertTrue(true); } |
### Question:
NopBuildLogger implements BuildLogger { @Override public void info(String charSequence) { } @Override void debug(String charSequence); @Override void info(String charSequence); @Override void warn(String charSequence); @Override void error(String charSequence); }### Answer:
@Test public void info() { logger.info(message); assertTrue(true); } |
### Question:
NopBuildLogger implements BuildLogger { @Override public void warn(String charSequence) { } @Override void debug(String charSequence); @Override void info(String charSequence); @Override void warn(String charSequence); @Override void error(String charSequence); }### Answer:
@Test public void warn() { logger.warn(message); assertTrue(true); } |
### Question:
NopBuildLogger implements BuildLogger { @Override public void error(String charSequence) { } @Override void debug(String charSequence); @Override void info(String charSequence); @Override void warn(String charSequence); @Override void error(String charSequence); }### Answer:
@Test public void error() { logger.info(message); assertTrue(true); } |
### Question:
LabelDuplicationDRGElementValidator extends LabelDuplicationValidator { @Override public List<String> validate(DMNModelRepository dmnModelRepository) { List<String> errors = new ArrayList<>(); if (dmnModelRepository == null) { return errors; } for (TDefinitions definitions: dmnModelRepository.getAllDefinitions()) { validateElements(dmnModelRepository.findDRGElements(definitions), errors); } return errors; } @Override List<String> validate(DMNModelRepository dmnModelRepository); }### Answer:
@Test public void testValidate() { String path = "dmn2java/exported/complex/input/"; String diagramName = "Linked Decision Test.dmn"; List<String> expectedErrors = Arrays.asList( "Found 2 Decision with duplicated label 'Assess applicant age'", "Label = 'Assess applicant age' Id = 'id-98f1b72e74edaaae8d7fd9043f7e1bc4' kind = 'TDecision'", "Label = 'Assess applicant age' Id = 'id-06eb38446e6385a69e74fcd503660971' kind = 'TDecision'", "Found 3 Decision with duplicated label 'Make credit decision'", "Label = 'Make credit decision' Id = 'id-5b83918d6fc820d73123e7ca0e6d3ca6' kind = 'TDecision'", "Label = 'Make credit decision' Id = 'id-53305251d2d6fb14173b439b019adeda' kind = 'TDecision'", "Label = 'Make credit decision' Id = 'id-75d5270913befc4881b90708206b1e9e' kind = 'TDecision'" ); validate(validator, path + diagramName, expectedErrors); } |
### Question:
RuleOutputList { public List<? extends RuleOutput> applyMultiple(HitPolicy hitPolicy) { List<RuleOutput> matchedRuleOutputs = this.getMatchedRuleResults(); if (hitPolicy == HitPolicy.COLLECT) { return matchedRuleOutputs; } else if (hitPolicy == HitPolicy.RULE_ORDER) { return matchedRuleOutputs; } else if (hitPolicy == HitPolicy.OUTPUT_ORDER) { return sort(matchedRuleOutputs); } else { throw new UnsupportedOperationException(String.format("Not supported multiple hit policy %s.", hitPolicy.name())); } } void add(RuleOutput result); List<RuleOutput> getMatchedRuleResults(); boolean noMatchedRules(); RuleOutput applySingle(HitPolicy hitPolicy); List<? extends RuleOutput> applyMultiple(HitPolicy hitPolicy); }### Answer:
@Test public void testApplyCollect() { assertEquals("[value1, value2]", makeRuleResultList(STRING_1, STRING_2).applyMultiple(COLLECT).toString()); }
@Test public void testApplyRuleOrder() { assertEquals("[value1, value2]", makeRuleResultList(STRING_1, STRING_2).applyMultiple(RULE_ORDER).toString()); }
@Test public void testApplyOutputOrder() { assertEquals("[value1, value2]", makeRuleResultList(STRING_1, STRING_2).applyMultiple(OUTPUT_ORDER).toString()); } |
### Question:
RuleDescriptionTransformer extends SimpleDMNTransformer<TestLab> { private DMNModelRepository cleanRuleDescription(DMNModelRepository repository, BuildLogger logger) { for (TDefinitions definitions: repository.getAllDefinitions()) { for(TDecision decision: repository.findDecisions(definitions)) { TExpression expression = repository.expression(decision); if (expression instanceof TDecisionTable) { logger.debug(String.format("Cleaning descriptions for '%s'", decision.getName())); List<TDecisionRule> rules = ((TDecisionTable) expression).getRule(); for (TDecisionRule rule: rules) { cleanRuleDescription(rule); } } } } return repository; } RuleDescriptionTransformer(); RuleDescriptionTransformer(BuildLogger logger); @Override DMNModelRepository transform(DMNModelRepository repository); @Override Pair<DMNModelRepository, List<TestLab>> transform(DMNModelRepository repository, List<TestLab> testLabList); }### Answer:
@Test public void testTransformForIncorrectLists() { TDecisionRule rule = makeRule("[ , string(\"\") , , string(\"\") , ]"); transformer.cleanRuleDescription(rule); assertEquals("[ string(\"\") , string(\"\") ]", rule.getDescription()); }
@Test public void testTransformForIllegalString() { TDecisionRule rule = makeRule("[ string(-) ]"); transformer.cleanRuleDescription(rule); assertEquals("[ \"\" ]", rule.getDescription()); }
@Test public void testTransformForIllegalCharacters() { TDecisionRule rule = makeRule("[ string(\"abc \u00A0 123\") ]"); transformer.cleanRuleDescription(rule); assertEquals("[ string(\"abc 123\") ]", rule.getDescription()); } |
### Question:
SimplifyTypesForMIDTransformer extends SimpleDMNTransformer<TestLab> { @Override public DMNModelRepository transform(DMNModelRepository repository) { this.inputDataClasses = new LinkedHashMap<>(); return removeDuplicateInformationRequirements(repository, logger); } SimplifyTypesForMIDTransformer(); SimplifyTypesForMIDTransformer(BuildLogger logger); @Override DMNModelRepository transform(DMNModelRepository repository); @Override Pair<DMNModelRepository, List<TestLab>> transform(DMNModelRepository repository, List<TestLab> testLabList); }### Answer:
@Test public void testTransform() throws Exception { String path = "dmn2java/exported/complex/input/"; File dmnFile = new File(resource(path + "IteratorExampleReturningMultiple.dmn")); Pair<TDefinitions, PrefixNamespaceMappings> pair = dmnReader.read(dmnFile); DMNModelRepository repository = new SignavioDMNModelRepository(pair, "http: DMNModelRepository actualRepository = transformer.transform(repository); checkDefinitions(actualRepository, "IteratorExampleReturningMultiple.dmn"); } |
### Question:
NormalizeDateTimeLiteralsTransformer extends SimpleDMNTransformer<TestLab> { private void normalize(TLiteralExpression exp) { if (exp != null) { String newText = normalize(exp.getText()); exp.setText(newText); } } NormalizeDateTimeLiteralsTransformer(); NormalizeDateTimeLiteralsTransformer(BuildLogger logger); @Override DMNModelRepository transform(DMNModelRepository repository); @Override Pair<DMNModelRepository, List<TestLab>> transform(DMNModelRepository repository, List<TestLab> testCases); }### Answer:
@Test public void testNormalize() { assertNull(transformer.normalize(null)); assertEquals("", transformer.normalize("")); assertEquals("date and time(\"1900-01-01T00:00:00Z\")", transformer.normalize("date and time(\"1899-12-31T19:00:00-0500\")")); assertEquals("time(\"00:00:00Z\")", transformer.normalize("time(\"T19:00:00-0500\")")); assertEquals("time(\"00:00:00Z\")", transformer.normalize("time(\"19:00:00-0500\")")); } |
### Question:
NormalizeDateTimeLiteralsTransformer extends SimpleDMNTransformer<TestLab> { @Override public DMNModelRepository transform(DMNModelRepository repository) { for (TDefinitions definitions: repository.getAllDefinitions()) { for (TDecision decision: repository.findDecisions(definitions)) { TExpression expression = repository.expression(decision); if (expression instanceof TDecisionTable) { logger.debug(String.format("Process decision table in decision '%s'", decision.getName())); transform((TDecisionTable) expression); } else if (expression instanceof TLiteralExpression) { logger.debug(String.format("Process literal expression in decision '%s'", decision.getName())); transform((TLiteralExpression) expression); } } } this.transformRepository = false; return repository; } NormalizeDateTimeLiteralsTransformer(); NormalizeDateTimeLiteralsTransformer(BuildLogger logger); @Override DMNModelRepository transform(DMNModelRepository repository); @Override Pair<DMNModelRepository, List<TestLab>> transform(DMNModelRepository repository, List<TestLab> testCases); }### Answer:
@Test public void testTransform() throws Exception { String path = "dmn/input/"; File dmnFile = new File(resource(path + "Null Safe Tests.dmn")); Pair<TDefinitions, PrefixNamespaceMappings> pair = dmnReader.read(dmnFile); DMNModelRepository repository = new SignavioDMNModelRepository(pair); DMNModelRepository actualRepository = transformer.transform(repository); checkDefinitions(actualRepository, "Normalized Null Safe Tests.dmn"); } |
### Question:
UniqueInformationRequirementTransformer extends SimpleDMNTransformer<TestLab> { @Override public DMNModelRepository transform(DMNModelRepository repository) { this.inputDataClasses = new LinkedHashMap<>(); return removeDuplicateInformationRequirements(repository, logger); } UniqueInformationRequirementTransformer(); UniqueInformationRequirementTransformer(BuildLogger logger); @Override DMNModelRepository transform(DMNModelRepository repository); @Override Pair<DMNModelRepository, List<TestLab>> transform(DMNModelRepository repository, List<TestLab> testLabList); }### Answer:
@Test public void testTransform() { String path = "dmn/input/"; File dmnFile = new File(resource(path + "simpleMID-with-ir-duplicates.dmn")); Pair<TDefinitions, PrefixNamespaceMappings> pair = dmnReader.read(dmnFile); DMNModelRepository repository = new SignavioDMNModelRepository(pair); DMNModelRepository actualRepository = transformer.transform(repository); checkDefinitions(actualRepository.getRootDefinitions(), "simpleMID-with-ir-duplicates.dmn"); } |
### Question:
AbstractMergeInputDataTransformer extends SimpleDMNTransformer<TestLab> { @Override public DMNModelRepository transform(DMNModelRepository repository) { this.inputDataClasses = new LinkedHashMap<>(); return mergeInputData(repository, logger); } AbstractMergeInputDataTransformer(); AbstractMergeInputDataTransformer(BuildLogger logger); @Override void configure(Map<String, Object> configuration); @Override DMNModelRepository transform(DMNModelRepository repository); @Override Pair<DMNModelRepository, List<TestLab>> transform(DMNModelRepository repository, List<TestLab> testLabList); }### Answer:
@Test public void testTransform() throws Exception { String path = "dmn/input/"; File dmnFile = new File(resource(path + getDMNFileName())); Pair<TDefinitions, PrefixNamespaceMappings> pair = dmnReader.read(dmnFile); DMNModelRepository repository = new SignavioDMNModelRepository(pair); Map<String, Object> config = new LinkedHashMap<>(); config.put("forceMerge", "false"); transformer.configure(config); DMNModelRepository actualRepository = transformer.transform(repository); File testLabFile = new File(resource(path + getTestLabFileName())); List<TestLab> testLabList = new ArrayList<>(); if (testLabFile.isFile()) { TestLab testLab = testReader.read(testLabFile); testLabList.add(testLab); } else { for (File child: testLabFile.listFiles()) { TestLab testLab = testReader.read(child); testLabList.add(testLab); } } List<TestLab> actualTestLabList = transformer.transform(actualRepository, testLabList).getRight(); TDefinitions definitions = actualRepository.getRootDefinitions(); check(definitions, actualTestLabList); } |
### Question:
DefaultDMNBaseDecision extends DefaultFEELLib implements DMNDecision<BigDecimal, XMLGregorianCalendar, XMLGregorianCalendar, XMLGregorianCalendar, Duration>, AnnotationTarget { @Override public DRGElement getDRGElementAnnotation() { return this.getClass().getAnnotation(DRGElement.class); } @Override DRGElement getDRGElementAnnotation(); @Override Rule getRuleAnnotation(int ruleIndex); }### Answer:
@Test public void testGetDRGElementAnnotation() { DRGElement drgElementAnnotation = baseDecision.getDRGElementAnnotation(); assertNull(drgElementAnnotation); } |
### Question:
DefaultDMNBaseDecision extends DefaultFEELLib implements DMNDecision<BigDecimal, XMLGregorianCalendar, XMLGregorianCalendar, XMLGregorianCalendar, Duration>, AnnotationTarget { @Override public Rule getRuleAnnotation(int ruleIndex) { String methodName = String.format("rule%d", ruleIndex); Class<? extends DefaultDMNBaseDecision> cls = this.getClass(); Method[] declaredMethods = cls.getDeclaredMethods(); for (Method method : declaredMethods) { if (methodName.equals(method.getName())) { return method.getAnnotation(Rule.class); } } return null; } @Override DRGElement getDRGElementAnnotation(); @Override Rule getRuleAnnotation(int ruleIndex); }### Answer:
@Test public void testGetRuleAnnotation() { Rule ruleAnnotation = baseDecision.getRuleAnnotation(0); assertNull(ruleAnnotation); } |
### Question:
CompositeListener implements EventListener { @Override public void startDRGElement(DRGElement element, Arguments arguments) { eventListeners.forEach(el -> el.startDRGElement(element, arguments)); } CompositeListener(EventListener... eventListeners); @Override void startDRGElement(DRGElement element, Arguments arguments); @Override void endDRGElement(DRGElement element, Arguments arguments, Object output, long duration); @Override void startRule(DRGElement element, Rule rule); @Override void matchRule(DRGElement element, Rule rule); @Override void endRule(DRGElement element, Rule rule, Object output); @Override void matchColumn(Rule rule, int columnIndex, Object result); }### Answer:
@Test public void testStartDRGElement() { listener.startDRGElement(null, null); assertTrue(true); } |
### Question:
CompositeListener implements EventListener { @Override public void endDRGElement(DRGElement element, Arguments arguments, Object output, long duration) { eventListeners.forEach(el -> el.endDRGElement(element, arguments, output, duration)); } CompositeListener(EventListener... eventListeners); @Override void startDRGElement(DRGElement element, Arguments arguments); @Override void endDRGElement(DRGElement element, Arguments arguments, Object output, long duration); @Override void startRule(DRGElement element, Rule rule); @Override void matchRule(DRGElement element, Rule rule); @Override void endRule(DRGElement element, Rule rule, Object output); @Override void matchColumn(Rule rule, int columnIndex, Object result); }### Answer:
@Test public void testEndDRGElement() { listener.endDRGElement(null, null, null, 0); assertTrue(true); } |
### Question:
CompositeListener implements EventListener { @Override public void startRule(DRGElement element, Rule rule) { eventListeners.forEach(el -> el.startRule(element, rule)); } CompositeListener(EventListener... eventListeners); @Override void startDRGElement(DRGElement element, Arguments arguments); @Override void endDRGElement(DRGElement element, Arguments arguments, Object output, long duration); @Override void startRule(DRGElement element, Rule rule); @Override void matchRule(DRGElement element, Rule rule); @Override void endRule(DRGElement element, Rule rule, Object output); @Override void matchColumn(Rule rule, int columnIndex, Object result); }### Answer:
@Test public void testStartRule() { listener.startRule(null, null); assertTrue(true); } |
### Question:
CompositeListener implements EventListener { @Override public void matchRule(DRGElement element, Rule rule) { eventListeners.forEach(el -> el.matchRule(element, rule)); } CompositeListener(EventListener... eventListeners); @Override void startDRGElement(DRGElement element, Arguments arguments); @Override void endDRGElement(DRGElement element, Arguments arguments, Object output, long duration); @Override void startRule(DRGElement element, Rule rule); @Override void matchRule(DRGElement element, Rule rule); @Override void endRule(DRGElement element, Rule rule, Object output); @Override void matchColumn(Rule rule, int columnIndex, Object result); }### Answer:
@Test public void testMatchRule() { listener.matchRule(null, null); assertTrue(true); } |
### Question:
CompositeListener implements EventListener { @Override public void endRule(DRGElement element, Rule rule, Object output) { eventListeners.forEach(el -> el.endRule(element, rule, output)); } CompositeListener(EventListener... eventListeners); @Override void startDRGElement(DRGElement element, Arguments arguments); @Override void endDRGElement(DRGElement element, Arguments arguments, Object output, long duration); @Override void startRule(DRGElement element, Rule rule); @Override void matchRule(DRGElement element, Rule rule); @Override void endRule(DRGElement element, Rule rule, Object output); @Override void matchColumn(Rule rule, int columnIndex, Object result); }### Answer:
@Test public void testEndRule() { listener.endRule(null, null, null); assertTrue(true); } |
### Question:
CompositeListener implements EventListener { @Override public void matchColumn(Rule rule, int columnIndex, Object result) { eventListeners.forEach(el -> el.matchColumn(rule,columnIndex, result)); } CompositeListener(EventListener... eventListeners); @Override void startDRGElement(DRGElement element, Arguments arguments); @Override void endDRGElement(DRGElement element, Arguments arguments, Object output, long duration); @Override void startRule(DRGElement element, Rule rule); @Override void matchRule(DRGElement element, Rule rule); @Override void endRule(DRGElement element, Rule rule, Object output); @Override void matchColumn(Rule rule, int columnIndex, Object result); }### Answer:
@Test public void testMatchColumn() { listener.matchColumn(null, 0, null); assertTrue(true); } |
### Question:
RDFToDMNMojo extends AbstractDMNMojo<NUMBER, DATE, TIME, DATE_TIME, DURATION, TEST> { @Override public void execute() throws MojoExecutionException { checkMandatoryField(inputFileDirectory, "inputFileDirectory"); checkMandatoryField(outputFileDirectory, "outputFileDirectory"); this.getLog().info(String.format("Transforming '%s' to '%s' ...", this.inputFileDirectory, this.outputFileDirectory)); MavenBuildLogger logger = new MavenBuildLogger(this.getLog()); FileTransformer transformer = new RDFToDMNTransformer( inputParameters, logger ); transformer.transform(inputFileDirectory.toPath(), outputFileDirectory.toPath()); try { this.project.addCompileSourceRoot(this.outputFileDirectory.getCanonicalPath()); } catch (IOException e) { throw new MojoExecutionException("", e); } } @Override void execute(); @Parameter(required = false)
public Map<String, String> inputParameters; @Parameter(required = true, defaultValue = "${project.basedir}/src/main/resources/signavio")
public File inputFileDirectory; @Parameter(required = true, defaultValue = "${project.build.directory}/generated-resources/dmn")
public File outputFileDirectory; }### Answer:
@Test(expected = IllegalArgumentException.class) public void testExecuteWhenMissingInput() throws Exception { mojo.inputParameters = makeParams(); mojo.execute(); assertTrue(true); }
@Test public void testExecute() throws Exception { String input = this.getClass().getClassLoader().getResource("input/NPEValidation2.xml").getFile(); mojo.project = project; mojo.inputFileDirectory = new File(input); mojo.outputFileDirectory = new File("target/output"); mojo.inputParameters = makeParams(); mojo.execute(); assertTrue(true); } |
### Question:
BaseDateTimeLib { protected boolean isTime(String literal) { if (literal == null) { return false; } return literal.length() > 3 && literal.charAt(2) == ':'; } static final DateTimeFormatter FEEL_DATE_FORMAT; static final DateTimeFormatter FEEL_TIME_FORMAT; static final DateTimeFormatter FEEL_DATE_TIME_FORMAT; }### Answer:
@Test public void testIsTime() { assertTrue(this.dateTimeLib.isTime("12:00:00")); assertTrue(this.dateTimeLib.isTime("12:00:00Z")); assertTrue(this.dateTimeLib.isTime("12:00:00[UTC]")); assertTrue(this.dateTimeLib.isTime("12:00:00@Europe/Paris")); assertTrue(this.dateTimeLib.isTime("12:00:00Z[UTC]")); assertTrue(this.dateTimeLib.isTime("12:00:00Z@Europe/Paris")); assertTrue(this.dateTimeLib.isTime("12:00:00+00:00[UTC]")); assertTrue(this.dateTimeLib.isTime("12:00:00+01:00@Europe/Paris")); assertFalse(this.dateTimeLib.isTime("2017-08-01")); assertFalse(this.dateTimeLib.isTime("2017-08-01T12:00:00Z")); assertFalse(this.dateTimeLib.isTime("2017-08-01T12:00:00+00:00[UTC]")); assertFalse(this.dateTimeLib.isTime("2017-08-01T12:00:00+00:00@Europe/Paris")); } |
### Question:
BaseDateTimeLib { protected boolean hasTime(String literal) { if (literal == null) { return false; } return literal.indexOf('T') != -1; } static final DateTimeFormatter FEEL_DATE_FORMAT; static final DateTimeFormatter FEEL_TIME_FORMAT; static final DateTimeFormatter FEEL_DATE_TIME_FORMAT; }### Answer:
@Test public void testHasTime() { assertTrue(this.dateTimeLib.hasTime("2017-06-01T12:00:00Z")); assertTrue(this.dateTimeLib.hasTime("9999999999-06-01T12:00:00Z")); assertTrue(this.dateTimeLib.hasTime("-9999999999-06-01T12:00:00Z")); assertTrue(this.dateTimeLib.hasTime("T12:00:00Z")); assertFalse(this.dateTimeLib.hasTime("2017-08-01")); assertFalse(this.dateTimeLib.hasTime("12:00:00Z")); } |
### Question:
BaseDateTimeLib { protected boolean timeHasOffset(String literal) { return literal.length() > 8 && (literal.charAt(8) == '+' || literal.charAt(8) == '-'); } static final DateTimeFormatter FEEL_DATE_FORMAT; static final DateTimeFormatter FEEL_TIME_FORMAT; static final DateTimeFormatter FEEL_DATE_TIME_FORMAT; }### Answer:
@Test public void testTimeHasOffset() { assertTrue(this.dateTimeLib.timeHasOffset("12:00:00+00:00")); assertTrue(this.dateTimeLib.timeHasOffset("12:00:00-00:00")); assertTrue(this.dateTimeLib.timeHasOffset("12:00:00-0000")); assertTrue(this.dateTimeLib.timeHasOffset("12:00:00+0000")); assertFalse(this.dateTimeLib.timeHasOffset("12:00:00")); assertFalse(this.dateTimeLib.timeHasOffset("12:00:00Z")); assertFalse(this.dateTimeLib.timeHasOffset("12:00:00[UTC]")); } |
### Question:
BaseDateTimeLib { protected LocalDate makeLocalDate(String literal) { if (StringUtils.isBlank(literal)) { return null; } if (hasTime(literal)) { return null; } if (invalidYear(literal)) { return null; } return LocalDate.parse(literal, FEEL_DATE_FORMAT); } static final DateTimeFormatter FEEL_DATE_FORMAT; static final DateTimeFormatter FEEL_TIME_FORMAT; static final DateTimeFormatter FEEL_DATE_TIME_FORMAT; }### Answer:
@Test public void testMakeLocalDate() { assertEquals("2017-08-10", this.dateTimeLib.makeLocalDate("2017-08-10").format(BaseDateTimeLib.FEEL_DATE_FORMAT)); assertEquals("9999-01-01", this.dateTimeLib.makeLocalDate("9999-01-01").format(BaseDateTimeLib.FEEL_DATE_FORMAT)); assertEquals("999999999-01-01", this.dateTimeLib.makeLocalDate("999999999-01-01").format(BaseDateTimeLib.FEEL_DATE_FORMAT)); assertEquals("-999999999-01-01", this.dateTimeLib.makeLocalDate("-999999999-01-01").format(BaseDateTimeLib.FEEL_DATE_FORMAT)); }
@Test(expected = DateTimeParseException.class) public void testMakeLocalDateWhenSign() { assertNotNull(this.dateTimeLib.makeLocalDate("+999999999-01-01")); } |
### Question:
DefaultSignavioBaseDecision extends DefaultSignavioLib implements SignavioDecision<BigDecimal, XMLGregorianCalendar, XMLGregorianCalendar, XMLGregorianCalendar, Duration>,
AnnotationTarget { @Override public DRGElement getDRGElementAnnotation() { return this.getClass().getAnnotation(DRGElement.class); } @Override DRGElement getDRGElementAnnotation(); @Override Rule getRuleAnnotation(int ruleIndex); }### Answer:
@Test public void testGetDRGElementAnnotation() throws Exception { DRGElement drgElementAnnotation = baseDecision.getDRGElementAnnotation(); assertNull(drgElementAnnotation); } |
### Question:
DefaultSignavioBaseDecision extends DefaultSignavioLib implements SignavioDecision<BigDecimal, XMLGregorianCalendar, XMLGregorianCalendar, XMLGregorianCalendar, Duration>,
AnnotationTarget { @Override public Rule getRuleAnnotation(int ruleIndex) { String methodName = String.format("rule%d", ruleIndex); Class<? extends DefaultSignavioBaseDecision> cls = this.getClass(); Method[] declaredMethods = cls.getDeclaredMethods(); for (Method method : declaredMethods) { if (methodName.equals(method.getName())) { return method.getAnnotation(Rule.class); } } return null; } @Override DRGElement getDRGElementAnnotation(); @Override Rule getRuleAnnotation(int ruleIndex); }### Answer:
@Test public void testGetRuleAnnotation() throws Exception { Rule ruleAnnotation = baseDecision.getRuleAnnotation(0); assertNull(ruleAnnotation); } |
### Question:
MixedJavaTimeSignavioBaseDecision extends MixedJavaTimeSignavioLib implements SignavioDecision<BigDecimal, XMLGregorianCalendar, XMLGregorianCalendar, XMLGregorianCalendar, Duration>,
AnnotationTarget { @Override public DRGElement getDRGElementAnnotation() { return this.getClass().getAnnotation(DRGElement.class); } @Override DRGElement getDRGElementAnnotation(); @Override Rule getRuleAnnotation(int ruleIndex); }### Answer:
@Test public void testGetDRGElementAnnotation() throws Exception { DRGElement drgElementAnnotation = baseDecision.getDRGElementAnnotation(); assertNull(drgElementAnnotation); } |
### Question:
MixedJavaTimeSignavioBaseDecision extends MixedJavaTimeSignavioLib implements SignavioDecision<BigDecimal, XMLGregorianCalendar, XMLGregorianCalendar, XMLGregorianCalendar, Duration>,
AnnotationTarget { @Override public Rule getRuleAnnotation(int ruleIndex) { String methodName = String.format("rule%d", ruleIndex); Class<? extends MixedJavaTimeSignavioBaseDecision> cls = this.getClass(); Method[] declaredMethods = cls.getDeclaredMethods(); for (Method method : declaredMethods) { if (methodName.equals(method.getName())) { return method.getAnnotation(Rule.class); } } return null; } @Override DRGElement getDRGElementAnnotation(); @Override Rule getRuleAnnotation(int ruleIndex); }### Answer:
@Test public void testGetRuleAnnotation() throws Exception { Rule ruleAnnotation = baseDecision.getRuleAnnotation(0); assertNull(ruleAnnotation); } |
### Question:
UnixPathParser { public static List<String> parse(String unixPath) { List<String> pathComponents = new ArrayList<>(); for (String component : unixPath.split("/", -1)) { if (!component.isEmpty()) { pathComponents.add(component); } } return pathComponents; } private UnixPathParser(); static List<String> parse(String unixPath); }### Answer:
@Test public void testParse() { Assert.assertEquals(ImmutableList.of("some", "path"), UnixPathParser.parse("/some/path")); Assert.assertEquals(ImmutableList.of("some", "path"), UnixPathParser.parse("some/path/")); Assert.assertEquals(ImmutableList.of("some", "path"), UnixPathParser.parse("some Assert.assertEquals( ImmutableList.of("\\windows\\path"), UnixPathParser.parse("\\windows\\path")); Assert.assertEquals(ImmutableList.of("T:\\dir"), UnixPathParser.parse("T:\\dir")); Assert.assertEquals( ImmutableList.of("T:\\dir", "real", "path"), UnixPathParser.parse("T:\\dir/real/path")); } |
### Question:
ProgressDisplayGenerator { public static List<String> generateProgressDisplay( double progress, List<String> unfinishedLeafTasks) { List<String> lines = new ArrayList<>(); lines.add(HEADER); lines.add(generateProgressBar(progress)); for (String task : unfinishedLeafTasks) { lines.add("> " + task); } return lines; } private ProgressDisplayGenerator(); static List<String> generateProgressDisplay(
double progress, List<String> unfinishedLeafTasks); }### Answer:
@Test public void testGenerateProgressDisplay_progressBar_0() { Assert.assertEquals( Arrays.asList("Executing tasks:", getBar("[ ]", 0.0)), ProgressDisplayGenerator.generateProgressDisplay(0, Collections.emptyList())); }
@Test public void testGenerateProgressDisplay_progressBar_50() { Assert.assertEquals( Arrays.asList("Executing tasks:", getBar("[=============== ]", 50.0)), ProgressDisplayGenerator.generateProgressDisplay(0.5, Collections.emptyList())); }
@Test public void testGenerateProgressDisplay_progressBar_100() { Assert.assertEquals( Arrays.asList("Executing tasks:", getBar("[==============================]", 100.0)), ProgressDisplayGenerator.generateProgressDisplay(1, Collections.emptyList())); }
@Test public void testGenerateProgressDisplay_unfinishedTasks() { Assert.assertEquals( Arrays.asList( "Executing tasks:", getBar("[=============== ]", 50.0), "> unfinished task", "> another task in progress", "> stalled"), ProgressDisplayGenerator.generateProgressDisplay( 0.5, Arrays.asList("unfinished task", "another task in progress", "stalled"))); } |
### Question:
FilePermissions { public static FilePermissions fromPosixFilePermissions( Set<PosixFilePermission> posixFilePermissions) { int permissionBits = 0; for (PosixFilePermission permission : posixFilePermissions) { permissionBits |= Objects.requireNonNull(PERMISSION_MAP.get(permission)); } return new FilePermissions(permissionBits); } FilePermissions(int permissionBits); static FilePermissions fromOctalString(String octalPermissions); static FilePermissions fromPosixFilePermissions(
Set<PosixFilePermission> posixFilePermissions); int getPermissionBits(); String toOctalString(); @Override boolean equals(Object other); @Override int hashCode(); @Override String toString(); static final FilePermissions DEFAULT_FILE_PERMISSIONS; static final FilePermissions DEFAULT_FOLDER_PERMISSIONS; }### Answer:
@Test public void testFromPosixFilePermissions() { Assert.assertEquals( new FilePermissions(0000), FilePermissions.fromPosixFilePermissions(ImmutableSet.of())); Assert.assertEquals( new FilePermissions(0110), FilePermissions.fromPosixFilePermissions( ImmutableSet.of(PosixFilePermission.OWNER_EXECUTE, PosixFilePermission.GROUP_EXECUTE))); Assert.assertEquals( new FilePermissions(0202), FilePermissions.fromPosixFilePermissions( ImmutableSet.of(PosixFilePermission.OWNER_WRITE, PosixFilePermission.OTHERS_WRITE))); Assert.assertEquals( new FilePermissions(0044), FilePermissions.fromPosixFilePermissions( ImmutableSet.of(PosixFilePermission.GROUP_READ, PosixFilePermission.OTHERS_READ))); Assert.assertEquals( new FilePermissions(0777), FilePermissions.fromPosixFilePermissions( ImmutableSet.copyOf(PosixFilePermission.values()))); } |
### Question:
AnsiLoggerWithFooter implements ConsoleLogger { @VisibleForTesting static List<String> truncateToMaxWidth(List<String> lines) { List<String> truncatedLines = new ArrayList<>(); for (String line : lines) { if (line.length() > MAX_FOOTER_WIDTH) { truncatedLines.add(line.substring(0, MAX_FOOTER_WIDTH - 3) + "..."); } else { truncatedLines.add(line); } } return truncatedLines; } AnsiLoggerWithFooter(
ImmutableMap<Level, Consumer<String>> messageConsumers,
SingleThreadedExecutor singleThreadedExecutor,
boolean enableTwoCursorUpJump); @Override void log(Level logLevel, String message); @Override void setFooter(List<String> newFooterLines); }### Answer:
@Test public void testTruncateToMaxWidth() { List<String> lines = Arrays.asList( "this line of text is way too long and will be truncated", "this line will not be truncated"); Assert.assertEquals( Arrays.asList( "this line of text is way too long and will be t...", "this line will not be truncated"), AnsiLoggerWithFooter.truncateToMaxWidth(lines)); } |
### Question:
ImageMetadataOutput implements JsonTemplate { @VisibleForTesting static ImageMetadataOutput fromJson(String json) throws IOException { return JsonTemplateMapper.readJson(json, ImageMetadataOutput.class); } @JsonCreator ImageMetadataOutput(
@JsonProperty(value = "image", required = true) String image,
@JsonProperty(value = "imageId", required = true) String imageId,
@JsonProperty(value = "imageDigest", required = true) String imageDigest,
@JsonProperty(value = "tags", required = true) List<String> tags); static ImageMetadataOutput fromJibContainer(JibContainer jibContainer); String getImage(); String getImageId(); String getImageDigest(); List<String> getTags(); String toJson(); }### Answer:
@Test public void testFromJson() throws IOException { ImageMetadataOutput output = ImageMetadataOutput.fromJson(TEST_JSON); Assert.assertEquals("gcr.io/project/image:tag", output.getImage()); Assert.assertEquals( "sha256:61bb3ec31a47cb730eb58a38bbfa813761a51dca69d10e39c24c3d00a7b2c7a9", output.getImageId()); Assert.assertEquals( "sha256:3f1be7e19129edb202c071a659a4db35280ab2bb1a16f223bfd5d1948657b6fc", output.getImageDigest()); Assert.assertEquals(ImmutableList.of("latest", "tag"), output.getTags()); } |
### Question:
ImageMetadataOutput implements JsonTemplate { public String toJson() throws IOException { return JsonTemplateMapper.toUtf8String(this); } @JsonCreator ImageMetadataOutput(
@JsonProperty(value = "image", required = true) String image,
@JsonProperty(value = "imageId", required = true) String imageId,
@JsonProperty(value = "imageDigest", required = true) String imageDigest,
@JsonProperty(value = "tags", required = true) List<String> tags); static ImageMetadataOutput fromJibContainer(JibContainer jibContainer); String getImage(); String getImageId(); String getImageDigest(); List<String> getTags(); String toJson(); }### Answer:
@Test public void testToJson() throws IOException { ImageMetadataOutput output = ImageMetadataOutput.fromJson(TEST_JSON); Assert.assertEquals(TEST_JSON, output.toJson()); } |
### Question:
AbsoluteUnixPath { public static AbsoluteUnixPath get(String unixPath) { if (!unixPath.startsWith("/")) { throw new IllegalArgumentException("Path does not start with forward slash (/): " + unixPath); } return new AbsoluteUnixPath(UnixPathParser.parse(unixPath)); } private AbsoluteUnixPath(List<String> pathComponents); static AbsoluteUnixPath get(String unixPath); static AbsoluteUnixPath fromPath(Path path); AbsoluteUnixPath resolve(RelativeUnixPath relativeUnixPath); AbsoluteUnixPath resolve(Path relativePath); AbsoluteUnixPath resolve(String relativeUnixPath); @Override String toString(); @Override boolean equals(Object other); @Override int hashCode(); }### Answer:
@Test public void testGet_notAbsolute() { try { AbsoluteUnixPath.get("not/absolute"); Assert.fail(); } catch (IllegalArgumentException ex) { Assert.assertEquals( "Path does not start with forward slash (/): not/absolute", ex.getMessage()); } } |
### Question:
SkaffoldFilesOutput { public String getJsonString() throws IOException { try (OutputStream outputStream = new ByteArrayOutputStream()) { new ObjectMapper().writeValue(outputStream, skaffoldFilesTemplate); return outputStream.toString(); } } SkaffoldFilesOutput(); @VisibleForTesting SkaffoldFilesOutput(String json); void addBuild(Path build); void addInput(Path inputFile); void addIgnore(Path ignoreFile); @VisibleForTesting List<String> getBuild(); @VisibleForTesting List<String> getInputs(); @VisibleForTesting List<String> getIgnore(); String getJsonString(); }### Answer:
@Test public void testGetJsonString() throws IOException { SkaffoldFilesOutput skaffoldFilesOutput = new SkaffoldFilesOutput(); skaffoldFilesOutput.addBuild(Paths.get("buildFile1")); skaffoldFilesOutput.addBuild(Paths.get("buildFile2")); skaffoldFilesOutput.addInput(Paths.get("input1")); skaffoldFilesOutput.addInput(Paths.get("input2")); skaffoldFilesOutput.addIgnore(Paths.get("ignore1")); skaffoldFilesOutput.addIgnore(Paths.get("ignore2")); Assert.assertEquals(TEST_JSON, skaffoldFilesOutput.getJsonString()); }
@Test public void testGetJsonString_empty() throws IOException { SkaffoldFilesOutput skaffoldFilesOutput = new SkaffoldFilesOutput(); Assert.assertEquals( "{\"build\":[],\"inputs\":[],\"ignore\":[]}", skaffoldFilesOutput.getJsonString()); } |
### Question:
SkaffoldSyncMapTemplate implements JsonTemplate { @VisibleForTesting public static SkaffoldSyncMapTemplate from(String jsonString) throws IOException { return new ObjectMapper().readValue(jsonString, SkaffoldSyncMapTemplate.class); } @VisibleForTesting static SkaffoldSyncMapTemplate from(String jsonString); void addGenerated(FileEntry layerEntry); void addDirect(FileEntry layerEntry); String getJsonString(); @VisibleForTesting List<FileTemplate> getGenerated(); @VisibleForTesting List<FileTemplate> getDirect(); }### Answer:
@Test public void testFrom_badPropertyName() throws IOException { try { SkaffoldSyncMapTemplate.from(FAIL_TEST_JSON_BAD_PROPERTY_NAME); Assert.fail(); } catch (UnrecognizedPropertyException ex) { Assert.assertTrue(ex.getMessage().contains("Unrecognized field \"jean-luc\"")); } }
@Test public void testFrom_missingField() throws IOException { try { SkaffoldSyncMapTemplate.from(FAIL_TEST_JSON_MISSING_FIELD); Assert.fail(); } catch (MismatchedInputException ex) { Assert.assertTrue(ex.getMessage().contains("Missing required creator property 'dest'")); } }
@Test public void testFrom_validEmpty() throws Exception { SkaffoldSyncMapTemplate.from(TEST_JSON_EMPTY_GENERATED); SkaffoldSyncMapTemplate.from(TEST_JSON_NO_GENERATED); } |
### Question:
AbsoluteUnixPath { public static AbsoluteUnixPath fromPath(Path path) { if (path.getRoot() == null) { throw new IllegalArgumentException( "Cannot create AbsoluteUnixPath from non-absolute Path: " + path); } List<String> pathComponents = new ArrayList<>(path.getNameCount()); path.forEach(component -> pathComponents.add(component.toString())); return new AbsoluteUnixPath(pathComponents); } private AbsoluteUnixPath(List<String> pathComponents); static AbsoluteUnixPath get(String unixPath); static AbsoluteUnixPath fromPath(Path path); AbsoluteUnixPath resolve(RelativeUnixPath relativeUnixPath); AbsoluteUnixPath resolve(Path relativePath); AbsoluteUnixPath resolve(String relativeUnixPath); @Override String toString(); @Override boolean equals(Object other); @Override int hashCode(); }### Answer:
@Test public void testFromPath() { Assert.assertEquals( "/absolute/path", AbsoluteUnixPath.fromPath(Paths.get("/absolute/path")).toString()); } |
### Question:
SkaffoldSyncMapTemplate implements JsonTemplate { public String getJsonString() throws IOException { try (OutputStream outputStream = new ByteArrayOutputStream()) { new ObjectMapper().writeValue(outputStream, this); return outputStream.toString(); } } @VisibleForTesting static SkaffoldSyncMapTemplate from(String jsonString); void addGenerated(FileEntry layerEntry); void addDirect(FileEntry layerEntry); String getJsonString(); @VisibleForTesting List<FileTemplate> getGenerated(); @VisibleForTesting List<FileTemplate> getDirect(); }### Answer:
@Test public void testGetJsonString() throws IOException { SkaffoldSyncMapTemplate ssmt = new SkaffoldSyncMapTemplate(); ssmt.addGenerated( new FileEntry( GEN_SRC, AbsoluteUnixPath.get("/genDest"), FilePermissions.DEFAULT_FILE_PERMISSIONS, FileEntriesLayer.DEFAULT_MODIFICATION_TIME)); ssmt.addDirect( new FileEntry( DIR_SRC_1, AbsoluteUnixPath.get("/dirDest1"), FilePermissions.DEFAULT_FILE_PERMISSIONS, FileEntriesLayer.DEFAULT_MODIFICATION_TIME)); ssmt.addDirect( new FileEntry( DIR_SRC_2, AbsoluteUnixPath.get("/dirDest2"), FilePermissions.DEFAULT_FILE_PERMISSIONS, FileEntriesLayer.DEFAULT_MODIFICATION_TIME)); Assert.assertEquals(TEST_JSON, ssmt.getJsonString()); } |
### Question:
AbsoluteUnixPath { @Override public boolean equals(Object other) { if (this == other) { return true; } if (!(other instanceof AbsoluteUnixPath)) { return false; } AbsoluteUnixPath otherAbsoluteUnixPath = (AbsoluteUnixPath) other; return unixPath.equals(otherAbsoluteUnixPath.unixPath); } private AbsoluteUnixPath(List<String> pathComponents); static AbsoluteUnixPath get(String unixPath); static AbsoluteUnixPath fromPath(Path path); AbsoluteUnixPath resolve(RelativeUnixPath relativeUnixPath); AbsoluteUnixPath resolve(Path relativePath); AbsoluteUnixPath resolve(String relativeUnixPath); @Override String toString(); @Override boolean equals(Object other); @Override int hashCode(); }### Answer:
@Test public void testEquals() { AbsoluteUnixPath absoluteUnixPath1 = AbsoluteUnixPath.get("/absolute/path"); AbsoluteUnixPath absoluteUnixPath2 = AbsoluteUnixPath.get("/absolute/path/"); AbsoluteUnixPath absoluteUnixPath3 = AbsoluteUnixPath.get("/another/path"); Assert.assertEquals(absoluteUnixPath1, absoluteUnixPath2); Assert.assertNotEquals(absoluteUnixPath1, absoluteUnixPath3); } |
### Question:
MainClassResolver { @VisibleForTesting static boolean isValidJavaClass(String className) { for (String part : Splitter.on('.').split(className)) { if (!SourceVersion.isIdentifier(part)) { return false; } } return true; } private MainClassResolver(); static String resolveMainClass(
@Nullable String configuredMainClass, ProjectProperties projectProperties); }### Answer:
@Test public void testValidJavaClassRegex() { Assert.assertTrue(MainClassResolver.isValidJavaClass("my.Class")); Assert.assertTrue(MainClassResolver.isValidJavaClass("my.java_Class$valid")); Assert.assertTrue(MainClassResolver.isValidJavaClass("multiple.package.items")); Assert.assertTrue(MainClassResolver.isValidJavaClass("is123.valid")); Assert.assertFalse(MainClassResolver.isValidJavaClass("${start-class}")); Assert.assertFalse(MainClassResolver.isValidJavaClass("123not.Valid")); Assert.assertFalse(MainClassResolver.isValidJavaClass("{class}")); Assert.assertFalse(MainClassResolver.isValidJavaClass("not valid")); } |
### Question:
ConfigurationPropertyValidator { public static List<String> parseListProperty(String property) { List<String> items = new ArrayList<>(); int startIndex = 0; for (int endIndex = 0; endIndex < property.length(); endIndex++) { if (property.charAt(endIndex) == ',') { items.add(property.substring(startIndex, endIndex)); startIndex = endIndex + 1; } else if (property.charAt(endIndex) == '\\') { endIndex++; } } items.add(property.substring(startIndex)); return items; } private ConfigurationPropertyValidator(); static Optional<Credential> getImageCredential(
Consumer<LogEvent> logger,
String usernameProperty,
String passwordProperty,
AuthProperty auth,
RawConfiguration rawConfiguration); static ImageReference getGeneratedTargetDockerTag(
@Nullable String targetImage,
ProjectProperties projectProperties,
HelpfulSuggestions helpfulSuggestions); static Map<String, String> parseMapProperty(String property); static List<String> parseListProperty(String property); }### Answer:
@Test public void testParseListProperty() { Assert.assertEquals( ImmutableList.of("abc"), ConfigurationPropertyValidator.parseListProperty("abc")); Assert.assertEquals( ImmutableList.of("abcd", "efg\\,hi\\\\", "", "\\jkl\\,", "\\\\\\,mnop", ""), ConfigurationPropertyValidator.parseListProperty( "abcd,efg\\,hi\\\\,,\\jkl\\,,\\\\\\,mnop,")); Assert.assertEquals(ImmutableList.of(""), ConfigurationPropertyValidator.parseListProperty("")); } |
### Question:
ConfigurationPropertyValidator { public static Map<String, String> parseMapProperty(String property) { Map<String, String> result = new LinkedHashMap<>(); List<String> entries = parseListProperty(property); for (String entry : entries) { Matcher matcher = KEY_VALUE_PATTERN.matcher(entry); if (!matcher.matches()) { throw new IllegalArgumentException("'" + entry + "' is not a valid key-value pair"); } result.put(matcher.group("name"), matcher.group("value")); } return result; } private ConfigurationPropertyValidator(); static Optional<Credential> getImageCredential(
Consumer<LogEvent> logger,
String usernameProperty,
String passwordProperty,
AuthProperty auth,
RawConfiguration rawConfiguration); static ImageReference getGeneratedTargetDockerTag(
@Nullable String targetImage,
ProjectProperties projectProperties,
HelpfulSuggestions helpfulSuggestions); static Map<String, String> parseMapProperty(String property); static List<String> parseListProperty(String property); }### Answer:
@Test public void testParseMapProperty() { Assert.assertEquals( ImmutableMap.of("abc", "def"), ConfigurationPropertyValidator.parseMapProperty("abc=def")); Assert.assertEquals( ImmutableMap.of("abc", "def", "gh\\,i", "j\\\\\\,kl", "mno", "", "pqr", "stu"), ConfigurationPropertyValidator.parseMapProperty("abc=def,gh\\,i=j\\\\\\,kl,mno=,pqr=stu")); try { ConfigurationPropertyValidator.parseMapProperty("not valid"); Assert.fail(); } catch (IllegalArgumentException ignored) { } } |
### Question:
ZipUtil { public static void unzip(Path archive, Path destination) throws IOException { String canonicalDestination = destination.toFile().getCanonicalPath(); try (InputStream fileIn = new BufferedInputStream(Files.newInputStream(archive)); ZipInputStream zipIn = new ZipInputStream(fileIn)) { for (ZipEntry entry = zipIn.getNextEntry(); entry != null; entry = zipIn.getNextEntry()) { Path entryPath = destination.resolve(entry.getName()); String canonicalTarget = entryPath.toFile().getCanonicalPath(); if (!canonicalTarget.startsWith(canonicalDestination + File.separator)) { String offender = entry.getName() + " from " + archive; throw new IOException("Blocked unzipping files outside destination: " + offender); } if (entry.isDirectory()) { Files.createDirectories(entryPath); } else { if (entryPath.getParent() != null) { Files.createDirectories(entryPath.getParent()); } try (OutputStream out = new BufferedOutputStream(Files.newOutputStream(entryPath))) { ByteStreams.copy(zipIn, out); } } } } } static void unzip(Path archive, Path destination); }### Answer:
@Test public void testUnzip() throws URISyntaxException, IOException { verifyUnzip(tempFolder.getRoot().toPath()); } |
### Question:
Instants { static Instant fromMillisOrIso8601(String time, String fieldName) { try { return Instant.ofEpochMilli(Long.parseLong(time)); } catch (NumberFormatException nfe) { try { DateTimeFormatter formatter = new DateTimeFormatterBuilder() .append(DateTimeFormatter.ISO_DATE_TIME) .optionalStart() .appendOffset("+HHmm", "+0000") .optionalEnd() .toFormatter(); return formatter.parse(time, Instant::from); } catch (DateTimeParseException dtpe) { throw new IllegalArgumentException( fieldName + " must be a number of milliseconds since epoch or an ISO 8601 formatted date"); } } } }### Answer:
@Test public void testFromMillisOrIso8601_millis() { Instant parsed = Instants.fromMillisOrIso8601("100", "ignored"); Assert.assertEquals(Instant.ofEpochMilli(100), parsed); }
@Test public void testFromMillisOrIso8601_iso8601() { Instant parsed = Instants.fromMillisOrIso8601("2020-06-08T14:54:36+00:00", "ignored"); Assert.assertEquals(Instant.parse("2020-06-08T14:54:36Z"), parsed); }
@Test public void testFromMillisOrIso8601_failed() { try { Instants.fromMillisOrIso8601("bad-time", "testFieldName"); Assert.fail(); } catch (IllegalArgumentException iae) { Assert.assertEquals( "testFieldName must be a number of milliseconds since epoch or an ISO 8601 formatted date", iae.getMessage()); } } |
### Question:
FileEntry { @Override public String toString() { return "{" + sourceFile + "," + extractionPath + "," + permissions + "," + modificationTime + "," + ownership + "}"; } FileEntry(
Path sourceFile,
AbsoluteUnixPath extractionPath,
FilePermissions permissions,
Instant modificationTime); FileEntry(
Path sourceFile,
AbsoluteUnixPath extractionPath,
FilePermissions permissions,
Instant modificationTime,
String ownership); Instant getModificationTime(); Path getSourceFile(); AbsoluteUnixPath getExtractionPath(); FilePermissions getPermissions(); String getOwnership(); @Override boolean equals(Object other); @Override int hashCode(); @Override String toString(); }### Answer:
@Test public void testToString() { Assert.assertEquals( "{a" + File.separator + "path,/an/absolute/unix/path,333,1970-01-01T00:00:00Z,0:0}", new FileEntry( Paths.get("a/path"), AbsoluteUnixPath.get("/an/absolute/unix/path"), FilePermissions.fromOctalString("333"), Instant.EPOCH, "0:0") .toString()); } |
### Question:
FilePropertiesStack { public void push(FilePropertiesSpec filePropertiesSpec) { Preconditions.checkState( stack.size() < 3, "Error in file properties stack push, stacking over 3"); stack.add(filePropertiesSpec); updateProperties(); } FilePropertiesStack(); void push(FilePropertiesSpec filePropertiesSpec); void pop(); FilePermissions getFilePermissions(); FilePermissions getDirectoryPermissions(); Instant getModificationTime(); String getOwnership(); }### Answer:
@Test public void testPush_tooMany() { FilePropertiesStack testStack = new FilePropertiesStack(); testStack.push(new FilePropertiesSpec("111", "111", "1", "1", "1")); testStack.push(new FilePropertiesSpec("111", "111", "1", "1", "1")); testStack.push(new FilePropertiesSpec("111", "111", "1", "1", "1")); try { testStack.push(new FilePropertiesSpec("111", "111", "1", "1", "1")); Assert.fail(); } catch (IllegalStateException ise) { Assert.assertEquals("Error in file properties stack push, stacking over 3", ise.getMessage()); } } |
### Question:
FilePropertiesStack { public void pop() { Preconditions.checkState(stack.size() > 0, "Error in file properties stack pop, popping at 0"); stack.remove(stack.size() - 1); updateProperties(); } FilePropertiesStack(); void push(FilePropertiesSpec filePropertiesSpec); void pop(); FilePermissions getFilePermissions(); FilePermissions getDirectoryPermissions(); Instant getModificationTime(); String getOwnership(); }### Answer:
@Test public void testPop_nothingToPop() { FilePropertiesStack testStack = new FilePropertiesStack(); try { testStack.pop(); Assert.fail(); } catch (IllegalStateException ise) { Assert.assertEquals("Error in file properties stack pop, popping at 0", ise.getMessage()); } } |
### Question:
Validator { public static void checkNullOrNotEmpty(@Nullable String value, String propertyName) { if (value == null) { return; } Preconditions.checkArgument( !value.trim().isEmpty(), "Property '" + propertyName + "' cannot be an empty string"); } static void checkNotNullAndNotEmpty(@Nullable String value, String propertyName); static void checkNullOrNotEmpty(@Nullable String value, String propertyName); static void checkNotNullAndNotEmpty(@Nullable Collection<?> value, String propertyName); static void checkNullOrNonNullNonEmptyEntries(
@Nullable Collection<String> values, String propertyName); static void checkNullOrNonNullNonEmptyEntries(
@Nullable Map<String, String> values, String propertyName); static void checkNullOrNonNullEntries(
@Nullable Collection<?> values, String propertyName); static void checkEquals(
@Nullable String value, String propertyName, String expectedValue); }### Answer:
@Test public void testCheckNullOrNotEmpty_valuePass() { Validator.checkNullOrNotEmpty("value", "test"); }
@Test public void testCheckNullOrNotEmpty_nullPass() { Validator.checkNullOrNotEmpty(null, "test"); }
@Test public void testCheckNullOrNotEmpty_fail() { try { Validator.checkNullOrNotEmpty(" ", "test"); Assert.fail(); } catch (IllegalArgumentException iae) { Assert.assertEquals("Property 'test' cannot be an empty string", iae.getMessage()); } } |
### Question:
Validator { public static void checkNullOrNonNullEntries( @Nullable Collection<?> values, String propertyName) { if (values == null) { return; } for (Object value : values) { Preconditions.checkNotNull( value, "Property '" + propertyName + "' cannot contain null entries"); } } static void checkNotNullAndNotEmpty(@Nullable String value, String propertyName); static void checkNullOrNotEmpty(@Nullable String value, String propertyName); static void checkNotNullAndNotEmpty(@Nullable Collection<?> value, String propertyName); static void checkNullOrNonNullNonEmptyEntries(
@Nullable Collection<String> values, String propertyName); static void checkNullOrNonNullNonEmptyEntries(
@Nullable Map<String, String> values, String propertyName); static void checkNullOrNonNullEntries(
@Nullable Collection<?> values, String propertyName); static void checkEquals(
@Nullable String value, String propertyName, String expectedValue); }### Answer:
@Test public void testCheckNullOrNonNullEntries_nullPass() { Validator.checkNullOrNonNullEntries(null, "test"); }
@Test public void testCheckNullOrNonNullEntries_emptyPass() { Validator.checkNullOrNonNullEntries(ImmutableList.of(), "test"); }
@Test public void testCheckNullOrNonNullEntries_valuesPass() { Validator.checkNullOrNonNullEntries(ImmutableList.of(new Object(), new Object()), "test"); }
@Test public void testCheckNullOrNonNullEntries_nullFail() { try { Validator.checkNullOrNonNullEntries(Arrays.asList(new Object(), null), "test"); Assert.fail(); } catch (NullPointerException npe) { Assert.assertEquals("Property 'test' cannot contain null entries", npe.getMessage()); } } |
### Question:
Validator { public static void checkEquals( @Nullable String value, String propertyName, String expectedValue) { Preconditions.checkNotNull(value, "Property '" + propertyName + "' cannot be null"); Preconditions.checkArgument( value.equals(expectedValue), "Property '" + propertyName + "' must be '" + expectedValue + "' but is '" + value + "'"); } static void checkNotNullAndNotEmpty(@Nullable String value, String propertyName); static void checkNullOrNotEmpty(@Nullable String value, String propertyName); static void checkNotNullAndNotEmpty(@Nullable Collection<?> value, String propertyName); static void checkNullOrNonNullNonEmptyEntries(
@Nullable Collection<String> values, String propertyName); static void checkNullOrNonNullNonEmptyEntries(
@Nullable Map<String, String> values, String propertyName); static void checkNullOrNonNullEntries(
@Nullable Collection<?> values, String propertyName); static void checkEquals(
@Nullable String value, String propertyName, String expectedValue); }### Answer:
@Test public void testCheckEquals_pass() { Validator.checkEquals("value", "ignored", "value"); }
@Test public void testCheckEquals_failsNull() { try { Validator.checkEquals(null, "test", "something"); Assert.fail(); } catch (NullPointerException npe) { Assert.assertEquals("Property 'test' cannot be null", npe.getMessage()); } }
@Test public void testCheckEquals_failsNotEquals() { try { Validator.checkEquals("somethingElse", "test", "something"); Assert.fail(); } catch (IllegalArgumentException iae) { Assert.assertEquals( "Property 'test' must be 'something' but is 'somethingElse'", iae.getMessage()); } } |
### Question:
BaseImageSpec { public List<PlatformSpec> getPlatforms() { return platforms; } @JsonCreator BaseImageSpec(
@JsonProperty(value = "image", required = true) String image,
@JsonProperty("platforms") List<PlatformSpec> platforms); String getImage(); List<PlatformSpec> getPlatforms(); }### Answer:
@Test public void testBaseImageSpec_nullCollections() throws JsonProcessingException { String data = "image: gcr.io/example/jib\n"; BaseImageSpec baseImageSpec = mapper.readValue(data, BaseImageSpec.class); Assert.assertEquals(ImmutableList.of(), baseImageSpec.getPlatforms()); } |
### Question:
FilePropertiesSpec { public Optional<Instant> getTimestamp() { return Optional.ofNullable(timestamp); } @JsonCreator FilePropertiesSpec(
@JsonProperty("filePermissions") String filePermissions,
@JsonProperty("directoryPermissions") String directoryPermissions,
@JsonProperty("user") String user,
@JsonProperty("group") String group,
@JsonProperty("timestamp") String timestamp); Optional<FilePermissions> getFilePermissions(); Optional<FilePermissions> getDirectoryPermissions(); Optional<String> getUser(); Optional<String> getGroup(); Optional<Instant> getTimestamp(); }### Answer:
@Test public void testFilePropertiesSpec_timestampSpecIso8601() throws JsonProcessingException { String data = "timestamp: 2020-06-08T14:54:36+00:00"; FilePropertiesSpec parsed = mapper.readValue(data, FilePropertiesSpec.class); Assert.assertEquals(Instant.parse("2020-06-08T14:54:36Z"), parsed.getTimestamp().get()); } |
### Question:
LayerDefinitionParser implements CommandLine.ITypeConverter<FileEntriesLayer> { @VisibleForTesting static ModificationTimeProvider parseTimestampsDirective(String directive) { if ("actual".equals(directive)) { return new ActualTimestampProvider(); } if (directive.matches("\\d+")) { long secondsSinceEpoch = Long.parseLong(directive); return new FixedTimestampProvider(Instant.ofEpochSecond(secondsSinceEpoch)); } return new FixedTimestampProvider( DateTimeFormatter.ISO_DATE_TIME.parse(directive, Instant::from)); } @Override FileEntriesLayer convert(String layerDefinition); }### Answer:
@Test public void testParseTimestampsDirective_actual() { MatcherAssert.assertThat( LayerDefinitionParser.parseTimestampsDirective("actual"), CoreMatchers.instanceOf(ActualTimestampProvider.class)); }
@Test public void testParseTimestampsDirective_secondsSinceEpoch() { ModificationTimeProvider provider = LayerDefinitionParser.parseTimestampsDirective("1"); MatcherAssert.assertThat(provider, CoreMatchers.instanceOf(FixedTimestampProvider.class)); Assert.assertEquals(Instant.ofEpochSecond(1), ((FixedTimestampProvider) provider).fixed); }
@Test public void testParseTimestampsDirective_is8601Date() { ModificationTimeProvider provider = LayerDefinitionParser.parseTimestampsDirective("1970-01-01T00:00:01.000Z"); MatcherAssert.assertThat(provider, CoreMatchers.instanceOf(FixedTimestampProvider.class)); Assert.assertEquals(Instant.ofEpochSecond(1), ((FixedTimestampProvider) provider).fixed); }
@Test public void testParseTimestampsDirective_invalid() { try { LayerDefinitionParser.parseTimestampsDirective("invalid"); Assert.fail(); } catch (RuntimeException ex) { MatcherAssert.assertThat(ex, CoreMatchers.instanceOf(DateTimeParseException.class)); } } |
### Question:
RelativeUnixPath { public static RelativeUnixPath get(String relativePath) { if (relativePath.startsWith("/")) { throw new IllegalArgumentException("Path starts with forward slash (/): " + relativePath); } return new RelativeUnixPath(UnixPathParser.parse(relativePath)); } private RelativeUnixPath(List<String> pathComponents); static RelativeUnixPath get(String relativePath); }### Answer:
@Test public void testGet_absolute() { try { RelativeUnixPath.get("/absolute"); Assert.fail(); } catch (IllegalArgumentException ex) { Assert.assertEquals("Path starts with forward slash (/): /absolute", ex.getMessage()); } }
@Test public void testGet() { Assert.assertEquals( ImmutableList.of("some", "relative", "path"), RelativeUnixPath.get("some/relative } |
### Question:
JarProcessor { public static JarType determineJarType(Path jarPath) throws IOException { JarFile jarFile = new JarFile(jarPath.toFile()); if (jarFile.getEntry("BOOT-INF") != null) { return JarType.SPRING_BOOT; } return JarType.STANDARD; } static JarType determineJarType(Path jarPath); }### Answer:
@Test public void testDetermineJarType_springBoot() throws IOException, URISyntaxException { Path springBootJar = Paths.get(Resources.getResource(SPRING_BOOT_RESOURCE_DIR).toURI()); JarType jarType = JarProcessor.determineJarType(springBootJar); assertThat(jarType).isEqualTo(JarType.SPRING_BOOT); }
@Test public void testDetermineJarType_standard() throws IOException, URISyntaxException { Path standardJar = Paths.get(Resources.getResource(STANDARD_RESOURCE_DIR).toURI()); JarType jarType = JarProcessor.determineJarType(standardJar); assertThat(jarType).isEqualTo(JarType.STANDARD); } |
### Question:
ActualTimestampProvider implements ModificationTimeProvider { @Override public Instant get(Path local, AbsoluteUnixPath inContainer) { try { return Files.getLastModifiedTime(local).toInstant(); } catch (IOException ex) { throw new RuntimeException(local.toString(), ex); } } @Override Instant get(Path local, AbsoluteUnixPath inContainer); }### Answer:
@Test public void testApply_file() { Assert.assertEquals( file.lastModified() / 1000, fixture.get(file.toPath(), AbsoluteUnixPath.get("/")).getEpochSecond()); }
@Test public void testApply_directory() { Assert.assertEquals( directory.lastModified() / 1000, fixture.get(directory.toPath(), AbsoluteUnixPath.get("/")).getEpochSecond()); } |
### Question:
FixedPermissionsProvider implements FilePermissionsProvider { @Override public FilePermissions get(Path local, AbsoluteUnixPath inContainer) { return Files.isDirectory(local) ? directoryPermissions : filePermissions; } FixedPermissionsProvider(FilePermissions filesPermission, FilePermissions directoriesPermission); @Override FilePermissions get(Path local, AbsoluteUnixPath inContainer); }### Answer:
@Test public void testApply_file() { FixedPermissionsProvider provider = new FixedPermissionsProvider(filesPermission, directoriesPermission); Assert.assertEquals(filesPermission, provider.get(file.toPath(), AbsoluteUnixPath.get("/"))); }
@Test public void testApply_directory() { FixedPermissionsProvider provider = new FixedPermissionsProvider(filesPermission, directoriesPermission); Assert.assertEquals( directoriesPermission, provider.get(directory.toPath(), AbsoluteUnixPath.get("/"))); } |
### Question:
FixedTimestampProvider implements ModificationTimeProvider { @Override public Instant get(Path local, AbsoluteUnixPath inContainer) { return fixed; } FixedTimestampProvider(Instant instant); @Override Instant get(Path local, AbsoluteUnixPath inContainer); }### Answer:
@Test public void testApply_file() { Assert.assertEquals( Instant.ofEpochSecond(1), fixture.get(file.toPath(), AbsoluteUnixPath.get("/"))); }
@Test public void testApply_directory() { Assert.assertEquals( Instant.ofEpochSecond(1), fixture.get(directory.toPath(), AbsoluteUnixPath.get("/"))); } |
### Question:
TaskCommon { @Nullable static TaskProvider<Task> getWarTaskProvider(Project project) { if (project.getPlugins().hasPlugin(WarPlugin.class)) { return project.getTasks().named(WarPlugin.WAR_TASK_NAME); } return null; } private TaskCommon(); static final String VERSION_URL; }### Answer:
@Test public void testGetWarTask_normalJavaProject() { Project project = ProjectBuilder.builder().build(); project.getPlugins().apply(JavaPlugin.class); TaskProvider<Task> warProviderTask = TaskCommon.getWarTaskProvider(project); Assert.assertNull(warProviderTask); }
@Test public void testGetWarTask_normalWarProject() { Project project = ProjectBuilder.builder().build(); project.getPlugins().apply(WarPlugin.class); TaskProvider<Task> warTask = TaskCommon.getWarTaskProvider(project); Assert.assertNotNull(warTask); Assert.assertNotNull(warTask instanceof War); } |
### Question:
TaskCommon { @Nullable static TaskProvider<Task> getBootWarTaskProvider(Project project) { if (project.getPlugins().hasPlugin("org.springframework.boot")) { try { return project.getTasks().named("bootWar"); } catch (UnknownTaskException ignored) { } } return null; } private TaskCommon(); static final String VERSION_URL; }### Answer:
@Test public void testGetBootWarTask_bootWarProject() { Project project = ProjectBuilder.builder().build(); project.getPlugins().apply(WarPlugin.class); project.getPlugins().apply(SpringBootPlugin.class); TaskProvider<Task> bootWarTask = TaskCommon.getBootWarTaskProvider(project); Assert.assertNotNull(bootWarTask); Assert.assertNotNull(bootWarTask instanceof BootWar); } |
### Question:
GradleProjectProperties implements ProjectProperties { @Override public boolean isWarProject() { return project.getPlugins().hasPlugin(WarPlugin.class); } @VisibleForTesting GradleProjectProperties(
Project project,
Logger logger,
TempDirectoryProvider tempDirectoryProvider,
Supplier<List<JibGradlePluginExtension<?>>> extensionLoader); static GradleProjectProperties getForProject(
Project project, Logger logger, TempDirectoryProvider tempDirectoryProvider); @Override JibContainerBuilder createJibContainerBuilder(
JavaContainerBuilder javaContainerBuilder, ContainerizingMode containerizingMode); @Override List<Path> getClassFiles(); @Override void waitForLoggingThread(); @Override void configureEventHandlers(Containerizer containerizer); @Override void log(LogEvent logEvent); @Override String getToolName(); @Override String getToolVersion(); @Override String getPluginName(); @Nullable @Override String getMainClassFromJarPlugin(); @Override Path getDefaultCacheDirectory(); @Override String getJarPluginName(); @Override boolean isWarProject(); @Override String getName(); @Override String getVersion(); @Override int getMajorJavaVersion(); @Override boolean isOffline(); @Override JibContainerBuilder runPluginExtensions(
List<? extends ExtensionConfiguration> extensionConfigs,
JibContainerBuilder jibContainerBuilder); }### Answer:
@Test public void testIsWarProject() { Mockito.when(mockProject.getPlugins().hasPlugin(WarPlugin.class)).thenReturn(true); Assert.assertTrue(gradleProjectProperties.isWarProject()); } |
### Question:
JibExtension { public void to(Action<? super TargetImageParameters> action) { action.execute(to); } JibExtension(Project project); void from(Action<? super BaseImageParameters> action); void to(Action<? super TargetImageParameters> action); void container(Action<? super ContainerParameters> action); void extraDirectories(Action<? super ExtraDirectoriesParameters> action); void dockerClient(Action<? super DockerClientParameters> action); void outputPaths(Action<? super OutputPathsParameters> action); void skaffold(Action<? super SkaffoldParameters> action); void pluginExtensions(Action<? super ExtensionParametersSpec> action); void setAllowInsecureRegistries(boolean allowInsecureRegistries); void setContainerizingMode(String containerizingMode); @Nested @Optional BaseImageParameters getFrom(); @Nested @Optional TargetImageParameters getTo(); @Nested @Optional ContainerParameters getContainer(); @Nested @Optional ExtraDirectoriesParameters getExtraDirectories(); @Nested @Optional DockerClientParameters getDockerClient(); @Nested @Optional OutputPathsParameters getOutputPaths(); @Nested @Optional SkaffoldParameters getSkaffold(); @Input @Optional String getContainerizingMode(); @Nested @Optional ListProperty<ExtensionParameters> getPluginExtensions(); }### Answer:
@Test public void testTo() { Assert.assertNull(testJibExtension.getTo().getImage()); Assert.assertNull(testJibExtension.getTo().getCredHelper()); testJibExtension.to( to -> { to.setImage("some image"); to.setCredHelper("some cred helper"); to.auth(auth -> auth.setUsername("some username")); to.auth(auth -> auth.setPassword("some password")); }); Assert.assertEquals("some image", testJibExtension.getTo().getImage()); Assert.assertEquals("some cred helper", testJibExtension.getTo().getCredHelper()); Assert.assertEquals("some username", testJibExtension.getTo().getAuth().getUsername()); Assert.assertEquals("some password", testJibExtension.getTo().getAuth().getPassword()); } |
### Question:
JibExtension { @Nested @Optional public TargetImageParameters getTo() { return to; } JibExtension(Project project); void from(Action<? super BaseImageParameters> action); void to(Action<? super TargetImageParameters> action); void container(Action<? super ContainerParameters> action); void extraDirectories(Action<? super ExtraDirectoriesParameters> action); void dockerClient(Action<? super DockerClientParameters> action); void outputPaths(Action<? super OutputPathsParameters> action); void skaffold(Action<? super SkaffoldParameters> action); void pluginExtensions(Action<? super ExtensionParametersSpec> action); void setAllowInsecureRegistries(boolean allowInsecureRegistries); void setContainerizingMode(String containerizingMode); @Nested @Optional BaseImageParameters getFrom(); @Nested @Optional TargetImageParameters getTo(); @Nested @Optional ContainerParameters getContainer(); @Nested @Optional ExtraDirectoriesParameters getExtraDirectories(); @Nested @Optional DockerClientParameters getDockerClient(); @Nested @Optional OutputPathsParameters getOutputPaths(); @Nested @Optional SkaffoldParameters getSkaffold(); @Input @Optional String getContainerizingMode(); @Nested @Optional ListProperty<ExtensionParameters> getPluginExtensions(); }### Answer:
@Test public void testToTags_noTagsPropertySet() { Assert.assertEquals(Collections.emptySet(), testJibExtension.getTo().getTags()); } |
### Question:
JibExtension { @Input @Optional public String getContainerizingMode() { String property = System.getProperty(PropertyNames.CONTAINERIZING_MODE); return property != null ? property : containerizingMode.get(); } JibExtension(Project project); void from(Action<? super BaseImageParameters> action); void to(Action<? super TargetImageParameters> action); void container(Action<? super ContainerParameters> action); void extraDirectories(Action<? super ExtraDirectoriesParameters> action); void dockerClient(Action<? super DockerClientParameters> action); void outputPaths(Action<? super OutputPathsParameters> action); void skaffold(Action<? super SkaffoldParameters> action); void pluginExtensions(Action<? super ExtensionParametersSpec> action); void setAllowInsecureRegistries(boolean allowInsecureRegistries); void setContainerizingMode(String containerizingMode); @Nested @Optional BaseImageParameters getFrom(); @Nested @Optional TargetImageParameters getTo(); @Nested @Optional ContainerParameters getContainer(); @Nested @Optional ExtraDirectoriesParameters getExtraDirectories(); @Nested @Optional DockerClientParameters getDockerClient(); @Nested @Optional OutputPathsParameters getOutputPaths(); @Nested @Optional SkaffoldParameters getSkaffold(); @Input @Optional String getContainerizingMode(); @Nested @Optional ListProperty<ExtensionParameters> getPluginExtensions(); }### Answer:
@Test public void testContainerizingMode() { Assert.assertEquals("exploded", testJibExtension.getContainerizingMode()); } |
### Question:
JibExtension { public void extraDirectories(Action<? super ExtraDirectoriesParameters> action) { action.execute(extraDirectories); } JibExtension(Project project); void from(Action<? super BaseImageParameters> action); void to(Action<? super TargetImageParameters> action); void container(Action<? super ContainerParameters> action); void extraDirectories(Action<? super ExtraDirectoriesParameters> action); void dockerClient(Action<? super DockerClientParameters> action); void outputPaths(Action<? super OutputPathsParameters> action); void skaffold(Action<? super SkaffoldParameters> action); void pluginExtensions(Action<? super ExtensionParametersSpec> action); void setAllowInsecureRegistries(boolean allowInsecureRegistries); void setContainerizingMode(String containerizingMode); @Nested @Optional BaseImageParameters getFrom(); @Nested @Optional TargetImageParameters getTo(); @Nested @Optional ContainerParameters getContainer(); @Nested @Optional ExtraDirectoriesParameters getExtraDirectories(); @Nested @Optional DockerClientParameters getDockerClient(); @Nested @Optional OutputPathsParameters getOutputPaths(); @Nested @Optional SkaffoldParameters getSkaffold(); @Input @Optional String getContainerizingMode(); @Nested @Optional ListProperty<ExtensionParameters> getPluginExtensions(); }### Answer:
@Test public void testExtraDirectories() { testJibExtension.extraDirectories( extraDirectories -> { extraDirectories.setPaths("test/path"); extraDirectories.setPermissions(ImmutableMap.of("file1", "123", "file2", "456")); }); Assert.assertEquals(1, testJibExtension.getExtraDirectories().getPaths().size()); Assert.assertEquals( Paths.get(fakeProject.getProjectDir().getPath(), "test", "path"), testJibExtension.getExtraDirectories().getPaths().get(0).getFrom()); Assert.assertEquals( ImmutableMap.of("file1", "123", "file2", "456"), testJibExtension.getExtraDirectories().getPermissions()); } |
### Question:
JibExtension { public void dockerClient(Action<? super DockerClientParameters> action) { action.execute(dockerClient); } JibExtension(Project project); void from(Action<? super BaseImageParameters> action); void to(Action<? super TargetImageParameters> action); void container(Action<? super ContainerParameters> action); void extraDirectories(Action<? super ExtraDirectoriesParameters> action); void dockerClient(Action<? super DockerClientParameters> action); void outputPaths(Action<? super OutputPathsParameters> action); void skaffold(Action<? super SkaffoldParameters> action); void pluginExtensions(Action<? super ExtensionParametersSpec> action); void setAllowInsecureRegistries(boolean allowInsecureRegistries); void setContainerizingMode(String containerizingMode); @Nested @Optional BaseImageParameters getFrom(); @Nested @Optional TargetImageParameters getTo(); @Nested @Optional ContainerParameters getContainer(); @Nested @Optional ExtraDirectoriesParameters getExtraDirectories(); @Nested @Optional DockerClientParameters getDockerClient(); @Nested @Optional OutputPathsParameters getOutputPaths(); @Nested @Optional SkaffoldParameters getSkaffold(); @Input @Optional String getContainerizingMode(); @Nested @Optional ListProperty<ExtensionParameters> getPluginExtensions(); }### Answer:
@Test public void testDockerClient() { testJibExtension.dockerClient( dockerClient -> { dockerClient.setExecutable("test-executable"); dockerClient.setEnvironment(ImmutableMap.of("key1", "val1", "key2", "val2")); }); Assert.assertEquals( Paths.get("test-executable"), testJibExtension.getDockerClient().getExecutablePath()); Assert.assertEquals( ImmutableMap.of("key1", "val1", "key2", "val2"), testJibExtension.getDockerClient().getEnvironment()); } |
### Question:
DockerHealthCheck { public static DockerHealthCheck.Builder fromCommand(List<String> command) { Preconditions.checkArgument(command.size() > 0, "command must not be empty"); Preconditions.checkArgument( command.stream().allMatch(Objects::nonNull), "command must not contain null elements"); return new Builder(ImmutableList.copyOf(command)); } private DockerHealthCheck(
ImmutableList<String> command,
@Nullable Duration interval,
@Nullable Duration timeout,
@Nullable Duration startPeriod,
@Nullable Integer retries); static DockerHealthCheck.Builder fromCommand(List<String> command); List<String> getCommand(); Optional<Duration> getInterval(); Optional<Duration> getTimeout(); Optional<Duration> getStartPeriod(); Optional<Integer> getRetries(); }### Answer:
@Test public void testBuild_invalidCommand() { try { DockerHealthCheck.fromCommand(ImmutableList.of()); Assert.fail(); } catch (IllegalArgumentException ex) { Assert.assertEquals("command must not be empty", ex.getMessage()); } try { DockerHealthCheck.fromCommand(Arrays.asList("CMD", null)); Assert.fail(); } catch (IllegalArgumentException ex) { Assert.assertEquals("command must not contain null elements", ex.getMessage()); } } |
### Question:
OciIndexTemplate implements ManifestTemplate { public void addManifest(BlobDescriptor descriptor, String imageReferenceName) { BuildableManifestTemplate.ContentDescriptorTemplate contentDescriptorTemplate = new BuildableManifestTemplate.ContentDescriptorTemplate( OciManifestTemplate.MANIFEST_MEDIA_TYPE, descriptor.getSize(), descriptor.getDigest()); contentDescriptorTemplate.setAnnotations( ImmutableMap.of("org.opencontainers.image.ref.name", imageReferenceName)); manifests.add(contentDescriptorTemplate); } @Override int getSchemaVersion(); @Override String getManifestMediaType(); void addManifest(BlobDescriptor descriptor, String imageReferenceName); @VisibleForTesting List<BuildableManifestTemplate.ContentDescriptorTemplate> getManifests(); static final String MEDIA_TYPE; }### Answer:
@Test public void testToJson() throws DigestException, IOException, URISyntaxException { Path jsonFile = Paths.get(Resources.getResource("core/json/ociindex.json").toURI()); String expectedJson = new String(Files.readAllBytes(jsonFile), StandardCharsets.UTF_8); OciIndexTemplate ociIndexJson = new OciIndexTemplate(); ociIndexJson.addManifest( new BlobDescriptor( 1000, DescriptorDigest.fromDigest( "sha256:8c662931926fa990b41da3c9f42663a537ccd498130030f9149173a0493832ad")), "regis.try/repo:tag"); Assert.assertEquals(expectedJson, JsonTemplateMapper.toUtf8String(ociIndexJson)); } |
### Question:
OciIndexTemplate implements ManifestTemplate { @VisibleForTesting public List<BuildableManifestTemplate.ContentDescriptorTemplate> getManifests() { return manifests; } @Override int getSchemaVersion(); @Override String getManifestMediaType(); void addManifest(BlobDescriptor descriptor, String imageReferenceName); @VisibleForTesting List<BuildableManifestTemplate.ContentDescriptorTemplate> getManifests(); static final String MEDIA_TYPE; }### Answer:
@Test public void testFromJson() throws IOException, URISyntaxException, DigestException { Path jsonFile = Paths.get(Resources.getResource("core/json/ociindex.json").toURI()); OciIndexTemplate ociIndexJson = JsonTemplateMapper.readJsonFromFile(jsonFile, OciIndexTemplate.class); BuildableManifestTemplate.ContentDescriptorTemplate manifest = ociIndexJson.getManifests().get(0); Assert.assertEquals( DescriptorDigest.fromDigest( "sha256:8c662931926fa990b41da3c9f42663a537ccd498130030f9149173a0493832ad"), manifest.getDigest()); Assert.assertEquals( "regis.try/repo:tag", manifest.getAnnotations().get("org.opencontainers.image.ref.name")); Assert.assertEquals(1000, manifest.getSize()); } |
### Question:
JsonToImageTranslator { @VisibleForTesting static ImmutableSet<AbsoluteUnixPath> volumeMapToSet(@Nullable Map<String, Map<?, ?>> volumeMap) throws BadContainerConfigurationFormatException { if (volumeMap == null) { return ImmutableSet.of(); } ImmutableSet.Builder<AbsoluteUnixPath> volumeList = ImmutableSet.builder(); for (String volume : volumeMap.keySet()) { try { volumeList.add(AbsoluteUnixPath.get(volume)); } catch (IllegalArgumentException exception) { throw new BadContainerConfigurationFormatException("Invalid volume path: " + volume); } } return volumeList.build(); } private JsonToImageTranslator(); static Image toImage(V21ManifestTemplate manifestTemplate); static Image toImage(
BuildableManifestTemplate manifestTemplate,
ContainerConfigurationTemplate containerConfigurationTemplate); }### Answer:
@Test public void testVolumeMapToList() throws BadContainerConfigurationFormatException { ImmutableSortedMap<String, Map<?, ?>> input = ImmutableSortedMap.of( "/var/job-result-data", ImmutableMap.of(), "/var/log/my-app-logs", ImmutableMap.of()); ImmutableSet<AbsoluteUnixPath> expected = ImmutableSet.of( AbsoluteUnixPath.get("/var/job-result-data"), AbsoluteUnixPath.get("/var/log/my-app-logs")); Assert.assertEquals(expected, JsonToImageTranslator.volumeMapToSet(input)); ImmutableList<Map<String, Map<?, ?>>> badInputs = ImmutableList.of( ImmutableMap.of("var/job-result-data", ImmutableMap.of()), ImmutableMap.of("log", ImmutableMap.of()), ImmutableMap.of("C:/udp", ImmutableMap.of())); for (Map<String, Map<?, ?>> badInput : badInputs) { try { JsonToImageTranslator.volumeMapToSet(badInput); Assert.fail(); } catch (BadContainerConfigurationFormatException ignored) { } } } |
### Question:
V22ManifestTemplate implements BuildableManifestTemplate { @Override public List<ContentDescriptorTemplate> getLayers() { return Collections.unmodifiableList(layers); } @Override int getSchemaVersion(); @Override String getManifestMediaType(); @Override @Nullable ContentDescriptorTemplate getContainerConfiguration(); @Override List<ContentDescriptorTemplate> getLayers(); @Override void setContainerConfiguration(long size, DescriptorDigest digest); @Override void addLayer(long size, DescriptorDigest digest); static final String MANIFEST_MEDIA_TYPE; }### Answer:
@Test public void testFromJson_optionalProperties() throws IOException, URISyntaxException { Path jsonFile = Paths.get(Resources.getResource("core/json/v22manifest_optional_properties.json").toURI()); V22ManifestTemplate manifestJson = JsonTemplateMapper.readJsonFromFile(jsonFile, V22ManifestTemplate.class); List<ContentDescriptorTemplate> layers = manifestJson.getLayers(); Assert.assertEquals(4, layers.size()); Assert.assertNull(layers.get(0).getUrls()); Assert.assertNull(layers.get(0).getAnnotations()); Assert.assertEquals(Arrays.asList("url-foo", "url-bar"), layers.get(1).getUrls()); Assert.assertNull(layers.get(1).getAnnotations()); Assert.assertNull(layers.get(2).getUrls()); Assert.assertEquals(ImmutableMap.of("key-foo", "value-foo"), layers.get(2).getAnnotations()); Assert.assertEquals(Arrays.asList("cool-url"), layers.get(3).getUrls()); Assert.assertEquals( ImmutableMap.of("key1", "value1", "key2", "value2"), layers.get(3).getAnnotations()); } |
### Question:
ImageToJsonTranslator { @VisibleForTesting @Nullable static Map<String, Map<?, ?>> portSetToMap(@Nullable Set<Port> exposedPorts) { return setToMap(exposedPorts, port -> port.getPort() + "/" + port.getProtocol()); } ImageToJsonTranslator(Image image); JsonTemplate getContainerConfiguration(); T getManifestTemplate(
Class<T> manifestTemplateClass, BlobDescriptor containerConfigurationBlobDescriptor); }### Answer:
@Test public void testPortListToMap() { ImmutableSet<Port> input = ImmutableSet.of(Port.tcp(1000), Port.udp(2000)); ImmutableSortedMap<String, Map<?, ?>> expected = ImmutableSortedMap.of("1000/tcp", ImmutableMap.of(), "2000/udp", ImmutableMap.of()); Assert.assertEquals(expected, ImageToJsonTranslator.portSetToMap(input)); } |
### Question:
ImageToJsonTranslator { @VisibleForTesting @Nullable static Map<String, Map<?, ?>> volumesSetToMap(@Nullable Set<AbsoluteUnixPath> volumes) { return setToMap(volumes, AbsoluteUnixPath::toString); } ImageToJsonTranslator(Image image); JsonTemplate getContainerConfiguration(); T getManifestTemplate(
Class<T> manifestTemplateClass, BlobDescriptor containerConfigurationBlobDescriptor); }### Answer:
@Test public void testVolumeListToMap() { ImmutableSet<AbsoluteUnixPath> input = ImmutableSet.of( AbsoluteUnixPath.get("/var/job-result-data"), AbsoluteUnixPath.get("/var/log/my-app-logs")); ImmutableSortedMap<String, Map<?, ?>> expected = ImmutableSortedMap.of( "/var/job-result-data", ImmutableMap.of(), "/var/log/my-app-logs", ImmutableMap.of()); Assert.assertEquals(expected, ImageToJsonTranslator.volumesSetToMap(input)); } |
### Question:
ImageToJsonTranslator { @VisibleForTesting @Nullable static ImmutableList<String> environmentMapToList(@Nullable Map<String, String> environment) { if (environment == null) { return null; } Preconditions.checkArgument( environment.keySet().stream().noneMatch(key -> key.contains("=")), "Illegal environment variable: name cannot contain '='"); return environment .entrySet() .stream() .map(entry -> entry.getKey() + "=" + entry.getValue()) .collect(ImmutableList.toImmutableList()); } ImageToJsonTranslator(Image image); JsonTemplate getContainerConfiguration(); T getManifestTemplate(
Class<T> manifestTemplateClass, BlobDescriptor containerConfigurationBlobDescriptor); }### Answer:
@Test public void testEnvironmentMapToList() { ImmutableMap<String, String> input = ImmutableMap.of("NAME1", "VALUE1", "NAME2", "VALUE2"); ImmutableList<String> expected = ImmutableList.of("NAME1=VALUE1", "NAME2=VALUE2"); Assert.assertEquals(expected, ImageToJsonTranslator.environmentMapToList(input)); } |
### Question:
Response implements Closeable { public InputStream getBody() throws IOException { return httpResponse.getContent(); } Response(HttpResponse httpResponse); int getStatusCode(); List<String> getHeader(String headerName); long getContentLength(); InputStream getBody(); GenericUrl getRequestUrl(); @Override void close(); }### Answer:
@Test public void testGetContent() throws IOException { byte[] expectedResponse = "crepecake\nis\ngood!".getBytes(StandardCharsets.UTF_8); ByteArrayInputStream responseInputStream = new ByteArrayInputStream(expectedResponse); Mockito.when(httpResponseMock.getContent()).thenReturn(responseInputStream); try (Response response = new Response(httpResponseMock)) { Assert.assertArrayEquals(expectedResponse, ByteStreams.toByteArray(response.getBody())); } } |
### Question:
FailoverHttpClient { public Response post(URL url, Request request) throws IOException { return call(HttpMethods.POST, url, request); } FailoverHttpClient(
boolean enableHttpAndInsecureFailover,
boolean sendAuthorizationOverHttp,
Consumer<LogEvent> logger); @VisibleForTesting FailoverHttpClient(
boolean enableHttpAndInsecureFailover,
boolean sendAuthorizationOverHttp,
Consumer<LogEvent> logger,
Supplier<HttpTransport> secureHttpTransportFactory,
Supplier<HttpTransport> insecureHttpTransportFactory); void shutDown(); Response get(URL url, Request request); Response post(URL url, Request request); Response put(URL url, Request request); Response call(String httpMethod, URL url, Request request); }### Answer:
@Test public void testPost() throws IOException { verifyCall(HttpMethods.POST, FailoverHttpClient::post); } |
### Question:
FailoverHttpClient { public Response put(URL url, Request request) throws IOException { return call(HttpMethods.PUT, url, request); } FailoverHttpClient(
boolean enableHttpAndInsecureFailover,
boolean sendAuthorizationOverHttp,
Consumer<LogEvent> logger); @VisibleForTesting FailoverHttpClient(
boolean enableHttpAndInsecureFailover,
boolean sendAuthorizationOverHttp,
Consumer<LogEvent> logger,
Supplier<HttpTransport> secureHttpTransportFactory,
Supplier<HttpTransport> insecureHttpTransportFactory); void shutDown(); Response get(URL url, Request request); Response post(URL url, Request request); Response put(URL url, Request request); Response call(String httpMethod, URL url, Request request); }### Answer:
@Test public void testPut() throws IOException { verifyCall(HttpMethods.PUT, FailoverHttpClient::put); } |
### Question:
FailoverHttpClient { public void shutDown() throws IOException { synchronized (transportsCreated) { while (!transportsCreated.isEmpty()) { transportsCreated.peekFirst().shutdown(); transportsCreated.removeFirst(); } } synchronized (responsesCreated) { while (!responsesCreated.isEmpty()) { responsesCreated.peekFirst().close(); responsesCreated.removeFirst(); } } } FailoverHttpClient(
boolean enableHttpAndInsecureFailover,
boolean sendAuthorizationOverHttp,
Consumer<LogEvent> logger); @VisibleForTesting FailoverHttpClient(
boolean enableHttpAndInsecureFailover,
boolean sendAuthorizationOverHttp,
Consumer<LogEvent> logger,
Supplier<HttpTransport> secureHttpTransportFactory,
Supplier<HttpTransport> insecureHttpTransportFactory); void shutDown(); Response get(URL url, Request request); Response post(URL url, Request request); Response put(URL url, Request request); Response call(String httpMethod, URL url, Request request); }### Answer:
@Test public void testShutDown() throws IOException { FailoverHttpClient secureHttpClient = newHttpClient(false, false); try (Response response = secureHttpClient.get(fakeUrl.toURL(), fakeRequest(null))) { secureHttpClient.shutDown(); secureHttpClient.shutDown(); Mockito.verify(mockHttpTransport, Mockito.times(1)).shutdown(); Mockito.verify(mockHttpResponse, Mockito.times(1)).disconnect(); } } |
### Question:
Request { @Nullable Integer getHttpTimeout() { return httpTimeout; } private Request(Builder builder); static Builder builder(); }### Answer:
@Test public void testGetHttpTimeout() { Request request = Request.builder().build(); Assert.assertNull(request.getHttpTimeout()); } |
### Question:
JsonTemplateMapper { public static <T extends JsonTemplate> T readJson(InputStream jsonStream, Class<T> templateClass) throws IOException { return objectMapper.readValue(jsonStream, templateClass); } private JsonTemplateMapper(); static T readJsonFromFile(Path jsonFile, Class<T> templateClass); static T readJsonFromFileWithLock(
Path jsonFile, Class<T> templateClass); static T readJson(InputStream jsonStream, Class<T> templateClass); static T readJson(String jsonString, Class<T> templateClass); static T readJson(byte[] jsonBytes, Class<T> templateClass); static List<T> readListOfJson(
String jsonString, Class<T> templateClass); static String toUtf8String(JsonTemplate template); static String toUtf8String(List<? extends JsonTemplate> templates); static byte[] toByteArray(JsonTemplate template); static byte[] toByteArray(List<? extends JsonTemplate> templates); static void writeTo(JsonTemplate template, OutputStream out); static void writeTo(List<? extends JsonTemplate> templates, OutputStream out); }### Answer:
@Test public void testReadJson_inputStream() throws IOException { String testJson = "{\"number\":3, \"text\":\"cool\"}"; ByteArrayInputStream in = new ByteArrayInputStream(testJson.getBytes(StandardCharsets.UTF_8)); TestJson json = JsonTemplateMapper.readJson(in, TestJson.class); Assert.assertEquals(3, json.number); Assert.assertEquals("cool", json.text); } |
### Question:
FileOperations { public static void copy(ImmutableList<Path> sourceFiles, Path destDir) throws IOException { for (Path sourceFile : sourceFiles) { PathConsumer copyPathConsumer = path -> { Path destPath = destDir.resolve(sourceFile.getParent().relativize(path)); if (Files.isDirectory(path)) { Files.createDirectories(destPath); } else { Files.copy(path, destPath); } }; if (Files.isDirectory(sourceFile)) { new DirectoryWalker(sourceFile).walk(copyPathConsumer); } else { copyPathConsumer.accept(sourceFile); } } } private FileOperations(); static void copy(ImmutableList<Path> sourceFiles, Path destDir); static OutputStream newLockingOutputStream(Path file); }### Answer:
@Test public void testCopy() throws IOException, URISyntaxException { Path destDir = temporaryFolder.newFolder().toPath(); Path libraryA = Paths.get(Resources.getResource("core/application/dependencies/libraryA.jar").toURI()); Path libraryB = Paths.get(Resources.getResource("core/application/dependencies/libraryB.jar").toURI()); Path dirLayer = Paths.get(Resources.getResource("core/layer").toURI()); FileOperations.copy(ImmutableList.of(libraryA, libraryB, dirLayer), destDir); assertFilesEqual(libraryA, destDir.resolve("libraryA.jar")); assertFilesEqual(libraryB, destDir.resolve("libraryB.jar")); Assert.assertTrue(Files.exists(destDir.resolve("layer").resolve("a").resolve("b"))); Assert.assertTrue(Files.exists(destDir.resolve("layer").resolve("c"))); assertFilesEqual( dirLayer.resolve("a").resolve("b").resolve("bar"), destDir.resolve("layer").resolve("a").resolve("b").resolve("bar")); assertFilesEqual( dirLayer.resolve("c").resolve("cat"), destDir.resolve("layer").resolve("c").resolve("cat")); assertFilesEqual(dirLayer.resolve("foo"), destDir.resolve("layer").resolve("foo")); } |
### Question:
LockFile implements Closeable { public static LockFile lock(Path lockFile) throws IOException { try { lockMap.computeIfAbsent(lockFile, key -> new ReentrantLock()).lockInterruptibly(); } catch (InterruptedException ex) { throw new IOException("Interrupted while trying to acquire lock", ex); } Files.createDirectories(lockFile.getParent()); FileOutputStream outputStream = new FileOutputStream(lockFile.toFile()); FileLock fileLock = null; try { fileLock = outputStream.getChannel().lock(); return new LockFile(lockFile, fileLock, outputStream); } finally { if (fileLock == null) { outputStream.close(); } } } private LockFile(Path lockFile, FileLock fileLock, OutputStream outputStream); static LockFile lock(Path lockFile); @Override void close(); }### Answer:
@Test public void testLockAndRelease() throws InterruptedException { AtomicInteger atomicInt = new AtomicInteger(0); Runnable procedure = () -> { try (LockFile ignored = LockFile.lock(temporaryFolder.getRoot().toPath().resolve("testLock"))) { Assert.assertTrue(Files.exists(temporaryFolder.getRoot().toPath().resolve("testLock"))); int valueBeforeSleep = atomicInt.intValue(); Thread.sleep(100); atomicInt.set(valueBeforeSleep + 1); } catch (InterruptedException | IOException ex) { throw new AssertionError(ex); } }; Thread thread = new Thread(procedure); thread.start(); procedure.run(); thread.join(); Assert.assertEquals(2, atomicInt.intValue()); } |
### Question:
DirectoryWalker { public ImmutableList<Path> walk(PathConsumer pathConsumer) throws IOException { ImmutableList<Path> files = walk(); for (Path path : files) { pathConsumer.accept(path); } return files; } DirectoryWalker(Path rootDir); DirectoryWalker filter(Predicate<Path> pathFilter); DirectoryWalker filterRoot(); ImmutableList<Path> walk(PathConsumer pathConsumer); ImmutableList<Path> walk(); }### Answer:
@Test public void testWalk() throws IOException { new DirectoryWalker(testDir).walk(addToWalkedPaths); Set<Path> expectedPaths = new HashSet<>( Arrays.asList( testDir, testDir.resolve("a"), testDir.resolve("a").resolve("b"), testDir.resolve("a").resolve("b").resolve("bar"), testDir.resolve("c"), testDir.resolve("c").resolve("cat"), testDir.resolve("foo"))); Assert.assertEquals(expectedPaths, walkedPaths); } |
### Question:
RegistryEndpointCaller { @VisibleForTesting static boolean isBrokenPipe(IOException original) { Throwable exception = original; while (exception != null) { String message = exception.getMessage(); if (message != null && message.toLowerCase(Locale.US).contains("broken pipe")) { return true; } exception = exception.getCause(); if (exception == original) { return false; } } return false; } @VisibleForTesting RegistryEndpointCaller(
EventHandlers eventHandlers,
@Nullable String userAgent,
RegistryEndpointProvider<T> registryEndpointProvider,
@Nullable Authorization authorization,
RegistryEndpointRequestProperties registryEndpointRequestProperties,
FailoverHttpClient httpClient); }### Answer:
@Test public void testIsBrokenPipe_notBrokenPipe() { Assert.assertFalse(RegistryEndpointCaller.isBrokenPipe(new IOException())); Assert.assertFalse(RegistryEndpointCaller.isBrokenPipe(new SocketException())); Assert.assertFalse(RegistryEndpointCaller.isBrokenPipe(new SSLException("mock"))); }
@Test public void testIsBrokenPipe_brokenPipe() { Assert.assertTrue(RegistryEndpointCaller.isBrokenPipe(new IOException("cool broken pipe !"))); Assert.assertTrue(RegistryEndpointCaller.isBrokenPipe(new SocketException("BROKEN PIPE"))); Assert.assertTrue(RegistryEndpointCaller.isBrokenPipe(new SSLException("calm BrOkEn PiPe"))); }
@Test public void testIsBrokenPipe_nestedBrokenPipe() { IOException exception = new IOException(new SSLException(new SocketException("Broken pipe"))); Assert.assertTrue(RegistryEndpointCaller.isBrokenPipe(exception)); }
@Test public void testIsBrokenPipe_terminatesWhenCauseIsOriginal() { IOException exception = Mockito.mock(IOException.class); Mockito.when(exception.getCause()).thenReturn(exception); Assert.assertFalse(RegistryEndpointCaller.isBrokenPipe(exception)); } |
### Question:
DockerConfig { @Nullable AuthTemplate getAuthFor(String registry) { Map.Entry<String, AuthTemplate> authEntry = findFirstInMapByKey(dockerConfigTemplate.getAuths(), getRegistryMatchersFor(registry)); return authEntry != null ? authEntry.getValue() : null; } DockerConfig(DockerConfigTemplate dockerConfigTemplate); }### Answer:
@Test public void testGetAuthFor_orderOfMatchPreference() throws URISyntaxException, IOException { Path json = Paths.get(Resources.getResource("core/json/dockerconfig_extra_matches.json").toURI()); DockerConfig dockerConfig = new DockerConfig(JsonTemplateMapper.readJsonFromFile(json, DockerConfigTemplate.class)); Assert.assertEquals( "my-registry: exact match", dockerConfig.getAuthFor("my-registry").getAuth()); Assert.assertEquals( "cool-registry: with https", dockerConfig.getAuthFor("cool-registry").getAuth()); Assert.assertEquals( "awesome-registry: starting with name", dockerConfig.getAuthFor("awesome-registry").getAuth()); Assert.assertEquals( "dull-registry: starting with name and with https", dockerConfig.getAuthFor("dull-registry").getAuth()); }
@Test public void testGetAuthFor_correctSuffixMatching() throws URISyntaxException, IOException { Path json = Paths.get(Resources.getResource("core/json/dockerconfig_extra_matches.json").toURI()); DockerConfig dockerConfig = new DockerConfig(JsonTemplateMapper.readJsonFromFile(json, DockerConfigTemplate.class)); Assert.assertNull(dockerConfig.getAuthFor("example")); } |
### Question:
RegistryAuthenticator { @VisibleForTesting String getAuthRequestParameters( @Nullable Credential credential, Map<String, String> repositoryScopes) { String serviceScope = getServiceScopeRequestParameters(repositoryScopes); return isOAuth2Auth(credential) ? serviceScope + "&client_id=jib.da031fe481a93ac107a95a96462358f9" + "&grant_type=refresh_token&refresh_token=" + Verify.verifyNotNull(credential).getPassword() : serviceScope; } private RegistryAuthenticator(
String realm,
String service,
RegistryEndpointRequestProperties registryEndpointRequestProperties,
@Nullable String userAgent,
FailoverHttpClient httpClient); Authorization authenticatePull(@Nullable Credential credential); Authorization authenticatePush(@Nullable Credential credential); }### Answer:
@Test public void testAuthRequestParameters_basicAuth() { Assert.assertEquals( "service=someservice&scope=repository:someimage:scope", registryAuthenticator.getAuthRequestParameters( null, Collections.singletonMap("someimage", "scope"))); }
@Test public void testAuthRequestParameters_oauth2() { Credential credential = Credential.from("<token>", "oauth2_access_token"); Assert.assertEquals( "service=someservice&scope=repository:someimage:scope" + "&client_id=jib.da031fe481a93ac107a95a96462358f9" + "&grant_type=refresh_token&refresh_token=oauth2_access_token", registryAuthenticator.getAuthRequestParameters( credential, Collections.singletonMap("someimage", "scope"))); } |
### Question:
RegistryAuthenticator { @VisibleForTesting boolean isOAuth2Auth(@Nullable Credential credential) { return credential != null && credential.isOAuth2RefreshToken(); } private RegistryAuthenticator(
String realm,
String service,
RegistryEndpointRequestProperties registryEndpointRequestProperties,
@Nullable String userAgent,
FailoverHttpClient httpClient); Authorization authenticatePull(@Nullable Credential credential); Authorization authenticatePush(@Nullable Credential credential); }### Answer:
@Test public void isOAuth2Auth_nullCredential() { Assert.assertFalse(registryAuthenticator.isOAuth2Auth(null)); }
@Test public void isOAuth2Auth_basicAuth() { Credential credential = Credential.from("name", "password"); Assert.assertFalse(registryAuthenticator.isOAuth2Auth(credential)); }
@Test public void isOAuth2Auth_oauth2() { Credential credential = Credential.from("<token>", "oauth2_token"); Assert.assertTrue(registryAuthenticator.isOAuth2Auth(credential)); } |
### Question:
RegistryAuthenticator { @VisibleForTesting URL getAuthenticationUrl(@Nullable Credential credential, Map<String, String> repositoryScopes) throws MalformedURLException { return isOAuth2Auth(credential) ? new URL(realm) : new URL(realm + "?" + getServiceScopeRequestParameters(repositoryScopes)); } private RegistryAuthenticator(
String realm,
String service,
RegistryEndpointRequestProperties registryEndpointRequestProperties,
@Nullable String userAgent,
FailoverHttpClient httpClient); Authorization authenticatePull(@Nullable Credential credential); Authorization authenticatePush(@Nullable Credential credential); }### Answer:
@Test public void getAuthenticationUrl_basicAuth() throws MalformedURLException { Assert.assertEquals( new URL("https: registryAuthenticator.getAuthenticationUrl( null, Collections.singletonMap("someimage", "scope"))); }
@Test public void istAuthenticationUrl_oauth2() throws MalformedURLException { Credential credential = Credential.from("<token>", "oauth2_token"); Assert.assertEquals( new URL("https: registryAuthenticator.getAuthenticationUrl(credential, Collections.emptyMap())); } |
### Question:
RegistryAuthenticator { public Authorization authenticatePush(@Nullable Credential credential) throws RegistryAuthenticationFailedException, RegistryCredentialsNotSentException { return authenticate(credential, "pull,push"); } private RegistryAuthenticator(
String realm,
String service,
RegistryEndpointRequestProperties registryEndpointRequestProperties,
@Nullable String userAgent,
FailoverHttpClient httpClient); Authorization authenticatePull(@Nullable Credential credential); Authorization authenticatePush(@Nullable Credential credential); }### Answer:
@Test public void testAuthorizationCleared() throws RegistryAuthenticationFailedException, IOException { ResponseException responseException = Mockito.mock(ResponseException.class); Mockito.when(responseException.getStatusCode()).thenReturn(401); Mockito.when(responseException.requestAuthorizationCleared()).thenReturn(true); Mockito.when(httpClient.call(Mockito.any(), Mockito.any(), Mockito.any())) .thenThrow(responseException); try { registryAuthenticator.authenticatePush(null); Assert.fail(); } catch (RegistryCredentialsNotSentException ex) { Assert.assertEquals( "Required credentials for someserver/someimage were not sent because the connection was " + "over HTTP", ex.getMessage()); } } |
### Question:
BlobChecker implements RegistryEndpointProvider<Optional<BlobDescriptor>> { @Override public Optional<BlobDescriptor> handleResponse(Response response) throws RegistryErrorException { long contentLength = response.getContentLength(); if (contentLength < 0) { throw new RegistryErrorExceptionBuilder(getActionDescription()) .addReason("Did not receive Content-Length header") .build(); } return Optional.of(new BlobDescriptor(contentLength, blobDigest)); } BlobChecker(
RegistryEndpointRequestProperties registryEndpointRequestProperties,
DescriptorDigest blobDigest); @Override Optional<BlobDescriptor> handleResponse(Response response); @Override Optional<BlobDescriptor> handleHttpResponseException(ResponseException responseException); @Override URL getApiRoute(String apiRouteBase); @Nullable @Override BlobHttpContent getContent(); @Override List<String> getAccept(); @Override String getHttpMethod(); @Override String getActionDescription(); }### Answer:
@Test public void testHandleResponse() throws RegistryErrorException { Mockito.when(mockResponse.getContentLength()).thenReturn(0L); BlobDescriptor expectedBlobDescriptor = new BlobDescriptor(0, fakeDigest); BlobDescriptor blobDescriptor = testBlobChecker.handleResponse(mockResponse).get(); Assert.assertEquals(expectedBlobDescriptor, blobDescriptor); }
@Test public void testHandleResponse_noContentLength() { Mockito.when(mockResponse.getContentLength()).thenReturn(-1L); try { testBlobChecker.handleResponse(mockResponse); Assert.fail("Should throw exception if Content-Length header is not present"); } catch (RegistryErrorException ex) { MatcherAssert.assertThat( ex.getMessage(), CoreMatchers.containsString("Did not receive Content-Length header")); } } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.