Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add information about which required field was missing #1765

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
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
Original file line number Diff line number Diff line change
Expand Up @@ -110,8 +110,11 @@ private[compiler] class ParseFromGenerator(

private def usesBaseTypeInBuilder(field: FieldDescriptor) = field.isSingular

val requiredFieldMap: Map[FieldDescriptor, Int] =
message.fields.filter(fd => fd.isRequired || fd.noBoxRequired).zipWithIndex.toMap
private val requiredFields: Seq[(FieldDescriptor, Int)] =
message.fields.filter(fd => fd.isRequired || fd.noBoxRequired).zipWithIndex

private val requiredFieldMap: Map[FieldDescriptor, Int] =
requiredFields.toMap

val myFullScalaName = message.scalaType.fullNameWithMaybeRoot(message)

Expand Down Expand Up @@ -228,9 +231,22 @@ private[compiler] class ParseFromGenerator(
val r = (0 until (requiredFieldMap.size + 63) / 64)
.map(i => s"__requiredFields$i != 0L")
.mkString(" || ")
p.add(
s"""if (${r}) { throw new _root_.com.google.protobuf.InvalidProtocolBufferException("Message missing required fields.") } """
)
p.add(s"""if (${r}) {""")
.indent
.add("val __missingFields = Seq.newBuilder[_root_.scala.Predef.String]")
.print(requiredFields) { case (p, (fieldDescriptor, fieldNumber)) =>
val bitmask = f"${1L << fieldNumber}%#018xL"
val fieldVariable = s"__requiredFields${fieldNumber / 64}"
p.add(
s"""if (($fieldVariable & $bitmask) != 0L) __missingFields += "${fieldDescriptor.scalaName}""""
)
}
.add(
s"""val __message = s"Message missing required fields: $${__missingFields.result().mkString(", ")}"""",
s"""throw new _root_.com.google.protobuf.InvalidProtocolBufferException(__message)"""
)
.outdent
.add("}")
}
.add(s"$myFullScalaName(")
.indented(
Expand Down
2 changes: 1 addition & 1 deletion e2e/src/test/scala/NoBoxSpec.scala
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ class NoBoxSpec extends AnyFlatSpec with Matchers {
"RequiredCar" should "fail validation if required field is missing" in {
intercept[InvalidProtocolBufferException] {
RequiredCar.parseFrom(Array.empty[Byte])
}.getMessage must be("Message missing required fields.")
}.getMessage must be("Message missing required fields: tyre1")
}

"RequiredCar" should "fail parsing from text if field is empty" in {
Expand Down
51 changes: 50 additions & 1 deletion e2e/src/test/scala/RequiredFieldsSpec.scala
Original file line number Diff line number Diff line change
@@ -1,11 +1,60 @@
import com.google.protobuf.InvalidProtocolBufferException
import com.thesamet.proto.e2e.reqs.RequiredFields
import protobuf_unittest.unittest.TestEmptyMessage
import scalapb.UnknownFieldSet

import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.matchers.must.Matchers

class RequiredFieldsSpec extends AnyFlatSpec with Matchers {

private val descriptor = RequiredFields.javaDescriptor

private def partialMessage(fields: Map[Int, Int]): Array[Byte] = {
val fieldSet = fields.foldLeft(UnknownFieldSet.empty){ case (fieldSet, (field, value)) =>
fieldSet
.withField(field, UnknownFieldSet.Field(varint = Seq(value)))
}

TestEmptyMessage(fieldSet).toByteArray
}

private val allFieldsSet: Map[Int, Int] = (100 to 164).map(i => (i, i)).toMap

"RequiredMessage" should "throw InvalidProtocolBufferException for empty byte array" in {
intercept[InvalidProtocolBufferException](RequiredFields.parseFrom(Array[Byte]()))
val exception = intercept[InvalidProtocolBufferException](RequiredFields.parseFrom(Array[Byte]()))

exception.getMessage() must startWith("Message missing required fields")
}

it should "throw no exception when all fields are set correctly" in {
val parsed = RequiredFields.parseFrom(partialMessage(allFieldsSet))
parsed must be(a[RequiredFields])
parsed.f0 must be(100)
parsed.f64 must be(164)
}

it should "throw an exception if a field is missing and name the missing field" in {
val fields = allFieldsSet.removed(123)
val exception = intercept[InvalidProtocolBufferException](RequiredFields.parseFrom(partialMessage(fields)))

exception.getMessage() must be("Message missing required fields: f23")
}

it should "throw an exception if a multiple fields are missing and name those missing fields" in {
val fields = allFieldsSet.removed(123).removed(164).removed(130)
val exception = intercept[InvalidProtocolBufferException](RequiredFields.parseFrom(partialMessage(fields)))

exception.getMessage() must be("Message missing required fields: f23, f30, f64")
}

it should "sort the missing fields by field number" in {
val fields = Map.empty[Int, Int]
val exception = intercept[InvalidProtocolBufferException](RequiredFields.parseFrom(partialMessage(fields)))
val missingFields =exception.getMessage().stripPrefix("Message missing required fields: ").split(", ")

missingFields.sortBy[Int](field => descriptor.findFieldByName(field).getNumber()) must be(missingFields)

missingFields.toSeq mustBe Seq.tabulate(65)(i => s"f$i")
}
}