Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Fuzzing doesn't generate test for package-private parameters
  • Loading branch information
Markoutte committed Jul 12, 2022
commit 77b51a9380cc065526ffd971a1ea16cb1b131616
Original file line number Diff line number Diff line change
Expand Up @@ -406,6 +406,8 @@ class UtBotSymbolicEngine(

val methodUnderTestDescription = FuzzedMethodDescription(executableId, collectConstantsForFuzzer(graph)).apply {
compilableName = if (methodUnderTest.isMethod) executableId.name else null
className = executableId.classId.simpleName
packageName = executableId.classId.packageName
val names = graph.body.method.tags.filterIsInstance<ParamNamesTag>().firstOrNull()?.names
parameterNameMap = { index -> names?.getOrNull(index) }
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,16 @@ class FuzzedMethodDescription(
*/
var compilableName: String? = null

/**
* Class Name
*/
var className: String? = null

/**
* Package Name
*/
var packageName: String? = null

/**
* Returns parameter name by its index in the signature
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,9 @@ import org.utbot.fuzzer.objectModelProviders
import org.utbot.fuzzer.providers.ConstantsModelProvider.fuzzed
import java.lang.reflect.Constructor
import java.lang.reflect.Field
import java.lang.reflect.Member
import java.lang.reflect.Method
import java.lang.reflect.Modifier
import java.lang.reflect.Modifier.*
import java.util.function.BiConsumer
import java.util.function.IntSupplier

Expand Down Expand Up @@ -67,7 +68,7 @@ class ObjectModelProvider : ModelProvider {
.filterNot { it == stringClassId || it.isPrimitiveWrapper }
.flatMap { classId ->
collectConstructors(classId) { javaConstructor ->
isPublic(javaConstructor)
isAccessible(javaConstructor, description.packageName)
}.sortedWith(
primitiveParameterizedConstructorsFirstAndThenByParameterCount
).take(limit)
Expand All @@ -81,7 +82,7 @@ class ObjectModelProvider : ModelProvider {
.flatMap { (constructorId, fuzzedParameters) ->
if (constructorId.parameters.isEmpty()) {
sequenceOf(assembleModel(idGenerator.asInt, constructorId, emptyList())) +
generateModelsWithFieldsInitialization(constructorId, concreteValues)
generateModelsWithFieldsInitialization(constructorId, description, concreteValues)
}
else {
fuzzedParameters.map { params ->
Expand All @@ -98,8 +99,8 @@ class ObjectModelProvider : ModelProvider {
}
}

private fun generateModelsWithFieldsInitialization(constructorId: ConstructorId, concreteValues: Collection<FuzzedConcreteValue>): Sequence<FuzzedValue> {
val fields = findSuitableFields(constructorId.classId)
private fun generateModelsWithFieldsInitialization(constructorId: ConstructorId, description: FuzzedMethodDescription, concreteValues: Collection<FuzzedConcreteValue>): Sequence<FuzzedValue> {
val fields = findSuitableFields(constructorId.classId, description)
val syntheticClassFieldsSetterMethodDescription = FuzzedMethodDescription(
"${constructorId.classId.simpleName}<syntheticClassFieldSetter>",
voidClassId,
Expand All @@ -115,16 +116,16 @@ class ObjectModelProvider : ModelProvider {
fieldValues.asSequence().mapIndexedNotNull { index, value ->
val field = fields[index]
when {
field.setter != null -> UtExecutableCallModel(
fuzzedModel.model,
MethodId(constructorId.classId, field.setter.name, field.setter.returnType.id, listOf(field.classId)),
listOf(value.model)
)
field.canBeSetDirectly -> UtDirectSetFieldModel(
fuzzedModel.model,
FieldId(constructorId.classId, field.name),
value.model
)
field.setter != null -> UtExecutableCallModel(
fuzzedModel.model,
MethodId(constructorId.classId, field.setter.name, field.setter.returnType.id, listOf(field.classId)),
listOf(value.model)
)
else -> null
}
}.forEach(modificationChain::add)
Expand All @@ -141,8 +142,16 @@ class ObjectModelProvider : ModelProvider {
}
}

private fun isPublic(javaConstructor: Constructor<*>): Boolean {
return javaConstructor.modifiers and Modifier.PUBLIC != 0
private fun isAccessible(member: Member, packageName: String?): Boolean {
return isPublic(member.modifiers) ||
(isPackagePrivate(member.modifiers) && member.declaringClass.`package`.name == packageName)
}

private fun isPackagePrivate(modifiers: Int): Boolean {
val hasAnyAccessModifier = isPrivate(modifiers)
|| isProtected(modifiers)
|| isProtected(modifiers)
return !hasAnyAccessModifier
}

private fun FuzzedMethodDescription.fuzzParameters(constructorId: ConstructorId, vararg modelProviders: ModelProvider): Sequence<List<FuzzedValue>> {
Expand All @@ -168,26 +177,26 @@ class ObjectModelProvider : ModelProvider {
}
}

private fun findSuitableFields(classId: ClassId): List<FieldDescription> {
private fun findSuitableFields(classId: ClassId, description: FuzzedMethodDescription): List<FieldDescription> {
val jClass = classId.jClass
return jClass.declaredFields.map { field ->
FieldDescription(
field.name,
field.type.id,
field.isPublic && !field.isFinal && !field.isStatic,
jClass.findPublicSetterIfHasPublicGetter(field)
isAccessible(field, description.packageName) && !isFinal(field.modifiers) && !isStatic(field.modifiers),
jClass.findPublicSetterIfHasPublicGetter(field, description)
)
}
}

private fun Class<*>.findPublicSetterIfHasPublicGetter(field: Field): Method? {
private fun Class<*>.findPublicSetterIfHasPublicGetter(field: Field, description: FuzzedMethodDescription): Method? {
val postfixName = field.name.capitalize()
val setterName = "set$postfixName"
val getterName = "get$postfixName"
val getter = try { getDeclaredMethod(getterName) } catch (_: NoSuchMethodException) { return null }
return if (getter has Modifier.PUBLIC && getter.returnType == field.type) {
return if (isAccessible(getter, description.packageName) && getter.returnType == field.type) {
declaredMethods.find {
it has Modifier.PUBLIC &&
isAccessible(it, description.packageName) &&
it.name == setterName &&
it.parameterCount == 1 &&
it.parameterTypes[0] == field.type
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Possibly we should enlarge StatementsStorage.isSetterOrDirectAccessor method with this type check.

Expand All @@ -196,18 +205,6 @@ class ObjectModelProvider : ModelProvider {
null
}
}
private val Field.isPublic
get() = has(Modifier.PUBLIC)

private val Field.isFinal
get() = has(Modifier.FINAL)

private val Field.isStatic
get() = has(Modifier.STATIC)

private infix fun Field.has(modifier: Int) = (modifiers and modifier) != 0

private infix fun Method.has(modifier: Int) = (modifiers and modifier) != 0

private val primitiveParameterizedConstructorsFirstAndThenByParameterCount =
compareByDescending<ConstructorId> { constructorId ->
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package org.utbot.framework.plugin.api.samples;

@SuppressWarnings("All")
public class PackagePrivateFieldAndClass {

volatile int pkgField = 0;

PackagePrivateFieldAndClass() {

}

PackagePrivateFieldAndClass(int value) {
pkgField = value;
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import org.utbot.fuzzer.providers.StringConstantModelProvider
import org.junit.jupiter.api.Assertions.*
import org.junit.jupiter.api.Test
import org.utbot.framework.plugin.api.samples.FieldSetterClass
import org.utbot.framework.plugin.api.samples.PackagePrivateFieldAndClass
import org.utbot.framework.plugin.api.util.primitiveByWrapper
import org.utbot.framework.plugin.api.util.primitiveWrappers
import org.utbot.framework.plugin.api.util.voidWrapperClassId
Expand Down Expand Up @@ -469,20 +470,50 @@ class ModelProviderTest {
assertEquals(expectedModificationSize, actualModificationSize) { "In target class there's only $expectedModificationSize fields that can be changed, but generated $actualModificationSize modifications" }

assertEquals("pubField", (modificationsChain[0] as UtDirectSetFieldModel).fieldId.name)
assertEquals("setPubFieldWithSetter", (modificationsChain[1] as UtExecutableCallModel).executable.name)
assertEquals("pubFieldWithSetter", (modificationsChain[1] as UtDirectSetFieldModel).fieldId.name)
assertEquals("setPrvFieldWithSetter", (modificationsChain[2] as UtExecutableCallModel).executable.name)
}
}

@Test
fun `test complex object is created with setters and package private field and constructor`() {
val j = PackagePrivateFieldAndClass::class.java
assertEquals(1, j.declaredFields.size)
assertTrue(
setOf(
"pkgField",
).containsAll(j.declaredFields.map { it.name })
)

withUtContext(UtContext(this::class.java.classLoader)) {
val result = collect(ObjectModelProvider { 0 }.apply {
modelProvider = PrimitiveDefaultsModelProvider
}, parameters = listOf(PackagePrivateFieldAndClass::class.java.id)) {
packageName = PackagePrivateFieldAndClass::class.java.`package`.name
}
assertEquals(1, result.size)
assertEquals(3, result[0]!!.size)
assertEquals(0, (result[0]!![0] as UtAssembleModel).modificationsChain.size) { "One of models must be without any modifications" }
assertEquals(0, (result[0]!![2] as UtAssembleModel).modificationsChain.size) { "Modification by constructor doesn't change fields" }
val expectedModificationSize = 1
val modificationsChain = (result[0]!![1] as UtAssembleModel).modificationsChain
val actualModificationSize = modificationsChain.size
assertEquals(expectedModificationSize, actualModificationSize) { "In target class there's only $expectedModificationSize fields that can be changed, but generated $actualModificationSize modifications" }

assertEquals("pkgField", (modificationsChain[0] as UtDirectSetFieldModel).fieldId.name)
}
}

private fun collect(
modelProvider: ModelProvider,
name: String = "testMethod",
returnType: ClassId = voidClassId,
parameters: List<ClassId>,
constants: List<FuzzedConcreteValue> = emptyList()
constants: List<FuzzedConcreteValue> = emptyList(),
block: FuzzedMethodDescription.() -> Unit = {}
): Map<Int, List<UtModel>> {
return mutableMapOf<Int, MutableList<UtModel>>().apply {
modelProvider.generate(FuzzedMethodDescription(name, returnType, parameters, constants)) { i, m ->
modelProvider.generate(FuzzedMethodDescription(name, returnType, parameters, constants).apply(block)) { i, m ->
computeIfAbsent(i) { mutableListOf() }.add(m.model)
}
}
Expand Down