The following issues were found

python/docs/generate_docs.py
45 issues
Missing function or method docstring
Error

Line: 131 Column: 1

              """


def find_modules():
  modules = []
  for module_path in SOURCE_DIR.glob("**/*.py"):
    # Determine the (dotted) relative package and module names.
    package_path = module_path.parent.relative_to(PYTHON_DIR)
    if package_path == SOURCE_DIR:

            

Reported by Pylint.

Bad indentation. Found 2 spaces, expected 4
Style

Line: 132 Column: 1

              

def find_modules():
  modules = []
  for module_path in SOURCE_DIR.glob("**/*.py"):
    # Determine the (dotted) relative package and module names.
    package_path = module_path.parent.relative_to(PYTHON_DIR)
    if package_path == SOURCE_DIR:
      package_name = ""

            

Reported by Pylint.

Bad indentation. Found 2 spaces, expected 4
Style

Line: 133 Column: 1

              
def find_modules():
  modules = []
  for module_path in SOURCE_DIR.glob("**/*.py"):
    # Determine the (dotted) relative package and module names.
    package_path = module_path.parent.relative_to(PYTHON_DIR)
    if package_path == SOURCE_DIR:
      package_name = ""
      module_name = module_path.stem

            

Reported by Pylint.

Bad indentation. Found 4 spaces, expected 8
Style

Line: 135 Column: 1

                modules = []
  for module_path in SOURCE_DIR.glob("**/*.py"):
    # Determine the (dotted) relative package and module names.
    package_path = module_path.parent.relative_to(PYTHON_DIR)
    if package_path == SOURCE_DIR:
      package_name = ""
      module_name = module_path.stem
    else:
      package_name = package_path.as_posix().replace("/", ".")

            

Reported by Pylint.

Bad indentation. Found 4 spaces, expected 8
Style

Line: 136 Column: 1

                for module_path in SOURCE_DIR.glob("**/*.py"):
    # Determine the (dotted) relative package and module names.
    package_path = module_path.parent.relative_to(PYTHON_DIR)
    if package_path == SOURCE_DIR:
      package_name = ""
      module_name = module_path.stem
    else:
      package_name = package_path.as_posix().replace("/", ".")
      module_name = package_name + "." + module_path.stem

            

Reported by Pylint.

Bad indentation. Found 6 spaces, expected 12
Style

Line: 137 Column: 1

                  # Determine the (dotted) relative package and module names.
    package_path = module_path.parent.relative_to(PYTHON_DIR)
    if package_path == SOURCE_DIR:
      package_name = ""
      module_name = module_path.stem
    else:
      package_name = package_path.as_posix().replace("/", ".")
      module_name = package_name + "." + module_path.stem


            

Reported by Pylint.

Bad indentation. Found 6 spaces, expected 12
Style

Line: 138 Column: 1

                  package_path = module_path.parent.relative_to(PYTHON_DIR)
    if package_path == SOURCE_DIR:
      package_name = ""
      module_name = module_path.stem
    else:
      package_name = package_path.as_posix().replace("/", ".")
      module_name = package_name + "." + module_path.stem

    # Filter: first, accept anything in the whitelist; then, reject anything

            

Reported by Pylint.

Bad indentation. Found 4 spaces, expected 8
Style

Line: 139 Column: 1

                  if package_path == SOURCE_DIR:
      package_name = ""
      module_name = module_path.stem
    else:
      package_name = package_path.as_posix().replace("/", ".")
      module_name = package_name + "." + module_path.stem

    # Filter: first, accept anything in the whitelist; then, reject anything
    # at package level, then module name level.

            

Reported by Pylint.

Bad indentation. Found 6 spaces, expected 12
Style

Line: 140 Column: 1

                    package_name = ""
      module_name = module_path.stem
    else:
      package_name = package_path.as_posix().replace("/", ".")
      module_name = package_name + "." + module_path.stem

    # Filter: first, accept anything in the whitelist; then, reject anything
    # at package level, then module name level.
    if any(include == module_name for include in INCLUDED_MODULES):

            

Reported by Pylint.

Bad indentation. Found 6 spaces, expected 12
Style

Line: 141 Column: 1

                    module_name = module_path.stem
    else:
      package_name = package_path.as_posix().replace("/", ".")
      module_name = package_name + "." + module_path.stem

    # Filter: first, accept anything in the whitelist; then, reject anything
    # at package level, then module name level.
    if any(include == module_name for include in INCLUDED_MODULES):
      pass

            

Reported by Pylint.

java/core/src/main/java/com/google/protobuf/AbstractMessageLite.java
43 issues
Avoid throwing raw exception types.
Design

Line: 62

                    writeTo(out.getCodedOutput());
      return out.build();
    } catch (IOException e) {
      throw new RuntimeException(getSerializingExceptionMessage("ByteString"), e);
    }
  }

  @Override
  public byte[] toByteArray() {

            

Reported by PMD.

Avoid throwing raw exception types.
Design

Line: 75

                    output.checkNoSpaceLeft();
      return result;
    } catch (IOException e) {
      throw new RuntimeException(getSerializingExceptionMessage("byte array"), e);
    }
  }

  @Override
  public void writeTo(final OutputStream output) throws IOException {

            

Reported by PMD.

Avoid throwing raw exception types.
Design

Line: 192

                    } catch (InvalidProtocolBufferException e) {
        throw e;
      } catch (IOException e) {
        throw new RuntimeException(getReadingExceptionMessage("ByteString"), e);
      }
    }

    @Override
    public BuilderType mergeFrom(

            

Reported by PMD.

Avoid throwing raw exception types.
Design

Line: 208

                    } catch (InvalidProtocolBufferException e) {
        throw e;
      } catch (IOException e) {
        throw new RuntimeException(getReadingExceptionMessage("ByteString"), e);
      }
    }

    @Override
    public BuilderType mergeFrom(final byte[] data) throws InvalidProtocolBufferException {

            

Reported by PMD.

Avoid throwing raw exception types.
Design

Line: 228

                    } catch (InvalidProtocolBufferException e) {
        throw e;
      } catch (IOException e) {
        throw new RuntimeException(getReadingExceptionMessage("byte array"), e);
      }
    }

    @Override
    public BuilderType mergeFrom(final byte[] data, final ExtensionRegistryLite extensionRegistry)

            

Reported by PMD.

Avoid throwing raw exception types.
Design

Line: 253

                    } catch (InvalidProtocolBufferException e) {
        throw e;
      } catch (IOException e) {
        throw new RuntimeException(getReadingExceptionMessage("byte array"), e);
      }
    }

    @Override
    public BuilderType mergeFrom(final InputStream input) throws IOException {

            

Reported by PMD.

Avoid throwing null pointer exceptions.
Design

Line: 379

                        for (int i = list.size() - 1; i >= begin; i--) {
            list.remove(i);
          }
          throw new NullPointerException(message);
        }
        list.add(value);
      }
    }


            

Reported by PMD.

Avoid throwing null pointer exceptions.
Design

Line: 422

                          for (int i = lazyList.size() - 1; i >= begin; i--) {
              lazyList.remove(i);
            }
            throw new NullPointerException(message);
          }
          if (value instanceof ByteString) {
            lazyList.add((ByteString) value);
          } else {
            lazyList.add((String) value);

            

Reported by PMD.

Avoid reassigning parameters such as 'len'
Design

Line: 305

                    }

      @Override
      public int read(final byte[] b, final int off, int len) throws IOException {
        if (limit <= 0) {
          return -1;
        }
        len = Math.min(len, limit);
        final int result = super.read(b, off, len);

            

Reported by PMD.

Avoid using redundant field initializer for 'memoizedHashCode'
Performance

Line: 53

                      MessageType extends AbstractMessageLite<MessageType, BuilderType>,
        BuilderType extends AbstractMessageLite.Builder<MessageType, BuilderType>>
    implements MessageLite {
  protected int memoizedHashCode = 0;

  @Override
  public ByteString toByteString() {
    try {
      final ByteString.CodedBuilder out = ByteString.newCodedBuilder(getSerializedSize());

            

Reported by PMD.

ruby/src/main/java/com/google/protobuf/jruby/SentinelOuterClass.java
43 issues
Avoid throwing null pointer exceptions.
Design

Line: 568

                    public Builder setDefaultString(
          java.lang.String value) {
        if (value == null) {
    throw new NullPointerException();
  }

        defaultString_ = value;
        onChanged();
        return this;

            

Reported by PMD.

Avoid throwing null pointer exceptions.
Design

Line: 590

                    public Builder setDefaultStringBytes(
          com.google.protobuf.ByteString value) {
        if (value == null) {
    throw new NullPointerException();
  }

        defaultString_ = value;
        onChanged();
        return this;

            

Reported by PMD.

Avoid throwing null pointer exceptions.
Design

Line: 688

                     */
      public Builder setDefaultBytes(com.google.protobuf.ByteString value) {
        if (value == null) {
    throw new NullPointerException();
  }

        defaultBytes_ = value;
        onChanged();
        return this;

            

Reported by PMD.

This class has a bunch of public methods and attributes
Design

Line: 36

              // Generated by the protocol buffer compiler.  DO NOT EDIT!
// source: sentinel.proto

package com.google.protobuf.jruby;

public final class SentinelOuterClass {
  private SentinelOuterClass() {}
  public static void registerAllExtensions(
      com.google.protobuf.ExtensionRegistry registry) {

            

Reported by PMD.

Classes implementing Serializable should set a serialVersionUID
Error

Line: 100

                /**
   * Protobuf type {@code com.google.protobuf.jruby.Sentinel}
   */
  public  static final class Sentinel extends
      com.google.protobuf.GeneratedMessage implements
      // @@protoc_insertion_point(message_implements:com.google.protobuf.jruby.Sentinel)
      SentinelOrBuilder {
    // Use Sentinel.newBuilder() to construct.
    private Sentinel(com.google.protobuf.GeneratedMessage.Builder builder) {

            

Reported by PMD.

This class has too many methods, consider refactoring it.
Design

Line: 103

                public  static final class Sentinel extends
      com.google.protobuf.GeneratedMessage implements
      // @@protoc_insertion_point(message_implements:com.google.protobuf.jruby.Sentinel)
      SentinelOrBuilder {
    // Use Sentinel.newBuilder() to construct.
    private Sentinel(com.google.protobuf.GeneratedMessage.Builder builder) {
      super(builder);
    }
    private Sentinel() {

            

Reported by PMD.

Potential violation of Law of Demeter (static property access)
Design

Line: 123

                  @java.lang.Override
    public final com.google.protobuf.UnknownFieldSet
    getUnknownFields() {
      return com.google.protobuf.UnknownFieldSet.getDefaultInstance();
    }
    public static final com.google.protobuf.Descriptors.Descriptor
        getDescriptor() {
      return com.google.protobuf.jruby.SentinelOuterClass.internal_static_com_google_protobuf_jruby_Sentinel_descriptor;
    }

            

Reported by PMD.

Potential violation of Law of Demeter (static property access)
Design

Line: 132

              
    protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
        internalGetFieldAccessorTable() {
      return com.google.protobuf.jruby.SentinelOuterClass.internal_static_com_google_protobuf_jruby_Sentinel_fieldAccessorTable
          .ensureFieldAccessorsInitialized(
              com.google.protobuf.jruby.SentinelOuterClass.Sentinel.class, com.google.protobuf.jruby.SentinelOuterClass.Sentinel.Builder.class);
    }

    public static final com.google.protobuf.Parser<Sentinel> PARSER =

            

Reported by PMD.

New exception is thrown in catch block, original stack trace may be lost
Design

Line: 147

                      try {
          builder.mergeFrom(input, extensionRegistry);
        } catch (com.google.protobuf.InvalidProtocolBufferException e) {
          throw e.setUnfinishedMessage(builder.buildPartial());
        } catch (java.io.IOException e) {
          throw new com.google.protobuf.InvalidProtocolBufferException(
              e.getMessage()).setUnfinishedMessage(builder.buildPartial());
        }
        return builder.buildPartial();

            

Reported by PMD.

New exception is thrown in catch block, original stack trace may be lost
Design

Line: 149

                      } catch (com.google.protobuf.InvalidProtocolBufferException e) {
          throw e.setUnfinishedMessage(builder.buildPartial());
        } catch (java.io.IOException e) {
          throw new com.google.protobuf.InvalidProtocolBufferException(
              e.getMessage()).setUnfinishedMessage(builder.buildPartial());
        }
        return builder.buildPartial();
      }
    };

            

Reported by PMD.

python/google/protobuf/internal/enum_type_wrapper.py
42 issues
Class 'EnumTypeWrapper' inherits from object, can be safely removed from bases in python3
Error

Line: 43 Column: 1

              import six


class EnumTypeWrapper(object):
  """A utility for finding the names of enum values."""

  DESCRIPTOR = None

  def __init__(self, enum_type):

            

Reported by Pylint.

Bad indentation. Found 2 spaces, expected 4
Style

Line: 44 Column: 1

              

class EnumTypeWrapper(object):
  """A utility for finding the names of enum values."""

  DESCRIPTOR = None

  def __init__(self, enum_type):
    """Inits EnumTypeWrapper with an EnumDescriptor."""

            

Reported by Pylint.

Bad indentation. Found 2 spaces, expected 4
Style

Line: 46 Column: 1

              class EnumTypeWrapper(object):
  """A utility for finding the names of enum values."""

  DESCRIPTOR = None

  def __init__(self, enum_type):
    """Inits EnumTypeWrapper with an EnumDescriptor."""
    self._enum_type = enum_type
    self.DESCRIPTOR = enum_type  # pylint: disable=invalid-name

            

Reported by Pylint.

Bad indentation. Found 2 spaces, expected 4
Style

Line: 48 Column: 1

              
  DESCRIPTOR = None

  def __init__(self, enum_type):
    """Inits EnumTypeWrapper with an EnumDescriptor."""
    self._enum_type = enum_type
    self.DESCRIPTOR = enum_type  # pylint: disable=invalid-name

  def Name(self, number):  # pylint: disable=invalid-name

            

Reported by Pylint.

Bad indentation. Found 4 spaces, expected 8
Style

Line: 49 Column: 1

                DESCRIPTOR = None

  def __init__(self, enum_type):
    """Inits EnumTypeWrapper with an EnumDescriptor."""
    self._enum_type = enum_type
    self.DESCRIPTOR = enum_type  # pylint: disable=invalid-name

  def Name(self, number):  # pylint: disable=invalid-name
    """Returns a string containing the name of an enum value."""

            

Reported by Pylint.

Bad indentation. Found 4 spaces, expected 8
Style

Line: 50 Column: 1

              
  def __init__(self, enum_type):
    """Inits EnumTypeWrapper with an EnumDescriptor."""
    self._enum_type = enum_type
    self.DESCRIPTOR = enum_type  # pylint: disable=invalid-name

  def Name(self, number):  # pylint: disable=invalid-name
    """Returns a string containing the name of an enum value."""
    try:

            

Reported by Pylint.

Bad indentation. Found 4 spaces, expected 8
Style

Line: 51 Column: 1

                def __init__(self, enum_type):
    """Inits EnumTypeWrapper with an EnumDescriptor."""
    self._enum_type = enum_type
    self.DESCRIPTOR = enum_type  # pylint: disable=invalid-name

  def Name(self, number):  # pylint: disable=invalid-name
    """Returns a string containing the name of an enum value."""
    try:
      return self._enum_type.values_by_number[number].name

            

Reported by Pylint.

Bad indentation. Found 2 spaces, expected 4
Style

Line: 53 Column: 1

                  self._enum_type = enum_type
    self.DESCRIPTOR = enum_type  # pylint: disable=invalid-name

  def Name(self, number):  # pylint: disable=invalid-name
    """Returns a string containing the name of an enum value."""
    try:
      return self._enum_type.values_by_number[number].name
    except KeyError:
      pass  # fall out to break exception chaining

            

Reported by Pylint.

Bad indentation. Found 4 spaces, expected 8
Style

Line: 54 Column: 1

                  self.DESCRIPTOR = enum_type  # pylint: disable=invalid-name

  def Name(self, number):  # pylint: disable=invalid-name
    """Returns a string containing the name of an enum value."""
    try:
      return self._enum_type.values_by_number[number].name
    except KeyError:
      pass  # fall out to break exception chaining


            

Reported by Pylint.

Bad indentation. Found 4 spaces, expected 8
Style

Line: 55 Column: 1

              
  def Name(self, number):  # pylint: disable=invalid-name
    """Returns a string containing the name of an enum value."""
    try:
      return self._enum_type.values_by_number[number].name
    except KeyError:
      pass  # fall out to break exception chaining

    if not isinstance(number, six.integer_types):

            

Reported by Pylint.

python/google/protobuf/internal/proto_builder_test.py
41 issues
No name 'descriptor_pb2' in module 'google.protobuf'
Error

Line: 41 Column: 1

              except ImportError:
  import unittest

from google.protobuf import descriptor_pb2  # pylint: disable=g-import-not-at-top
from google.protobuf import descriptor
from google.protobuf import descriptor_pool
from google.protobuf import proto_builder
from google.protobuf import text_format


            

Reported by Pylint.

Bad option value 'g-import-not-at-top'
Error

Line: 41 Column: 1

              except ImportError:
  import unittest

from google.protobuf import descriptor_pb2  # pylint: disable=g-import-not-at-top
from google.protobuf import descriptor
from google.protobuf import descriptor_pool
from google.protobuf import proto_builder
from google.protobuf import text_format


            

Reported by Pylint.

Bad indentation. Found 2 spaces, expected 4
Style

Line: 37 Column: 1

              
import collections
try:
  import unittest2 as unittest
except ImportError:
  import unittest

from google.protobuf import descriptor_pb2  # pylint: disable=g-import-not-at-top
from google.protobuf import descriptor

            

Reported by Pylint.

Bad indentation. Found 2 spaces, expected 4
Style

Line: 39 Column: 1

              try:
  import unittest2 as unittest
except ImportError:
  import unittest

from google.protobuf import descriptor_pb2  # pylint: disable=g-import-not-at-top
from google.protobuf import descriptor
from google.protobuf import descriptor_pool
from google.protobuf import proto_builder

            

Reported by Pylint.

Missing class docstring
Error

Line: 48 Column: 1

              from google.protobuf import text_format


class ProtoBuilderTest(unittest.TestCase):

  def setUp(self):
    self.ordered_fields = collections.OrderedDict([
        ('foo', descriptor_pb2.FieldDescriptorProto.TYPE_INT64),
        ('bar', descriptor_pb2.FieldDescriptorProto.TYPE_STRING),

            

Reported by Pylint.

Bad indentation. Found 2 spaces, expected 4
Style

Line: 50 Column: 1

              
class ProtoBuilderTest(unittest.TestCase):

  def setUp(self):
    self.ordered_fields = collections.OrderedDict([
        ('foo', descriptor_pb2.FieldDescriptorProto.TYPE_INT64),
        ('bar', descriptor_pb2.FieldDescriptorProto.TYPE_STRING),
        ])
    self._fields = dict(self.ordered_fields)

            

Reported by Pylint.

Bad indentation. Found 4 spaces, expected 8
Style

Line: 51 Column: 1

              class ProtoBuilderTest(unittest.TestCase):

  def setUp(self):
    self.ordered_fields = collections.OrderedDict([
        ('foo', descriptor_pb2.FieldDescriptorProto.TYPE_INT64),
        ('bar', descriptor_pb2.FieldDescriptorProto.TYPE_STRING),
        ])
    self._fields = dict(self.ordered_fields)


            

Reported by Pylint.

Bad indentation. Found 4 spaces, expected 8
Style

Line: 55 Column: 1

                      ('foo', descriptor_pb2.FieldDescriptorProto.TYPE_INT64),
        ('bar', descriptor_pb2.FieldDescriptorProto.TYPE_STRING),
        ])
    self._fields = dict(self.ordered_fields)

  def testMakeSimpleProtoClass(self):
    """Test that we can create a proto class."""
    proto_cls = proto_builder.MakeSimpleProtoClass(
        self._fields,

            

Reported by Pylint.

Bad indentation. Found 2 spaces, expected 4
Style

Line: 57 Column: 1

                      ])
    self._fields = dict(self.ordered_fields)

  def testMakeSimpleProtoClass(self):
    """Test that we can create a proto class."""
    proto_cls = proto_builder.MakeSimpleProtoClass(
        self._fields,
        full_name='net.proto2.python.public.proto_builder_test.Test')
    proto = proto_cls()

            

Reported by Pylint.

Method name "testMakeSimpleProtoClass" doesn't conform to snake_case naming style
Error

Line: 57 Column: 3

                      ])
    self._fields = dict(self.ordered_fields)

  def testMakeSimpleProtoClass(self):
    """Test that we can create a proto class."""
    proto_cls = proto_builder.MakeSimpleProtoClass(
        self._fields,
        full_name='net.proto2.python.public.proto_builder_test.Test')
    proto = proto_cls()

            

Reported by Pylint.

java/core/src/test/java/com/google/protobuf/LazyFieldTest.java
41 issues
Unit tests should not contain more than 1 assert(s).
Design

Line: 46

              public class LazyFieldTest {

  @Test
  public void testHashCode() {
    MessageLite message = TestUtil.getAllSet();
    LazyField lazyField = createLazyFieldFromMessage(message);
    assertThat(message.hashCode()).isEqualTo(lazyField.hashCode());
    lazyField.getValue();
    assertThat(message.hashCode()).isEqualTo(lazyField.hashCode());

            

Reported by PMD.

Potential violation of Law of Demeter (object not created locally)
Design

Line: 49

                public void testHashCode() {
    MessageLite message = TestUtil.getAllSet();
    LazyField lazyField = createLazyFieldFromMessage(message);
    assertThat(message.hashCode()).isEqualTo(lazyField.hashCode());
    lazyField.getValue();
    assertThat(message.hashCode()).isEqualTo(lazyField.hashCode());
    changeValue(lazyField);
    // make sure two messages have different hash code
    assertNotEqual(message.hashCode(), lazyField.hashCode());

            

Reported by PMD.

Potential violation of Law of Demeter (object not created locally)
Design

Line: 49

                public void testHashCode() {
    MessageLite message = TestUtil.getAllSet();
    LazyField lazyField = createLazyFieldFromMessage(message);
    assertThat(message.hashCode()).isEqualTo(lazyField.hashCode());
    lazyField.getValue();
    assertThat(message.hashCode()).isEqualTo(lazyField.hashCode());
    changeValue(lazyField);
    // make sure two messages have different hash code
    assertNotEqual(message.hashCode(), lazyField.hashCode());

            

Reported by PMD.

Potential violation of Law of Demeter (method chain calls)
Design

Line: 49

                public void testHashCode() {
    MessageLite message = TestUtil.getAllSet();
    LazyField lazyField = createLazyFieldFromMessage(message);
    assertThat(message.hashCode()).isEqualTo(lazyField.hashCode());
    lazyField.getValue();
    assertThat(message.hashCode()).isEqualTo(lazyField.hashCode());
    changeValue(lazyField);
    // make sure two messages have different hash code
    assertNotEqual(message.hashCode(), lazyField.hashCode());

            

Reported by PMD.

Potential violation of Law of Demeter (object not created locally)
Design

Line: 50

                  MessageLite message = TestUtil.getAllSet();
    LazyField lazyField = createLazyFieldFromMessage(message);
    assertThat(message.hashCode()).isEqualTo(lazyField.hashCode());
    lazyField.getValue();
    assertThat(message.hashCode()).isEqualTo(lazyField.hashCode());
    changeValue(lazyField);
    // make sure two messages have different hash code
    assertNotEqual(message.hashCode(), lazyField.hashCode());
  }

            

Reported by PMD.

Potential violation of Law of Demeter (object not created locally)
Design

Line: 51

                  LazyField lazyField = createLazyFieldFromMessage(message);
    assertThat(message.hashCode()).isEqualTo(lazyField.hashCode());
    lazyField.getValue();
    assertThat(message.hashCode()).isEqualTo(lazyField.hashCode());
    changeValue(lazyField);
    // make sure two messages have different hash code
    assertNotEqual(message.hashCode(), lazyField.hashCode());
  }


            

Reported by PMD.

Potential violation of Law of Demeter (method chain calls)
Design

Line: 51

                  LazyField lazyField = createLazyFieldFromMessage(message);
    assertThat(message.hashCode()).isEqualTo(lazyField.hashCode());
    lazyField.getValue();
    assertThat(message.hashCode()).isEqualTo(lazyField.hashCode());
    changeValue(lazyField);
    // make sure two messages have different hash code
    assertNotEqual(message.hashCode(), lazyField.hashCode());
  }


            

Reported by PMD.

Potential violation of Law of Demeter (object not created locally)
Design

Line: 51

                  LazyField lazyField = createLazyFieldFromMessage(message);
    assertThat(message.hashCode()).isEqualTo(lazyField.hashCode());
    lazyField.getValue();
    assertThat(message.hashCode()).isEqualTo(lazyField.hashCode());
    changeValue(lazyField);
    // make sure two messages have different hash code
    assertNotEqual(message.hashCode(), lazyField.hashCode());
  }


            

Reported by PMD.

Potential violation of Law of Demeter (object not created locally)
Design

Line: 54

                  assertThat(message.hashCode()).isEqualTo(lazyField.hashCode());
    changeValue(lazyField);
    // make sure two messages have different hash code
    assertNotEqual(message.hashCode(), lazyField.hashCode());
  }

  @Test
  public void testHashCodeEx() throws Exception {
    TestAllExtensions message = TestUtil.getAllExtensionsSet();

            

Reported by PMD.

Potential violation of Law of Demeter (object not created locally)
Design

Line: 54

                  assertThat(message.hashCode()).isEqualTo(lazyField.hashCode());
    changeValue(lazyField);
    // make sure two messages have different hash code
    assertNotEqual(message.hashCode(), lazyField.hashCode());
  }

  @Test
  public void testHashCodeEx() throws Exception {
    TestAllExtensions message = TestUtil.getAllExtensionsSet();

            

Reported by PMD.

src/google/protobuf/stubs/strutil.cc
41 issues
snprintf - If format strings can be influenced by an attacker, they can be exploited, and note that sprintf variations do not always \0-terminate
Security

Line: 57 Column: 9 CWE codes: 134
Suggestion: Use a constant for the format specification

              // trailing zeros after the decimal point.  For some reason this bug only
// occurs with some input values, not all.  In any case, _snprintf does the
// right thing, so we use it.
#define snprintf _snprintf
#endif

namespace google {
namespace protobuf {


            

Reported by FlawFinder.

_snprintf - If format strings can be influenced by an attacker, they can be exploited, and note that sprintf variations do not always \0-terminate
Security

Line: 57 Column: 18 CWE codes: 134
Suggestion: Use a constant for the format specification

              // trailing zeros after the decimal point.  For some reason this bug only
// occurs with some input values, not all.  In any case, _snprintf does the
// right thing, so we use it.
#define snprintf _snprintf
#endif

namespace google {
namespace protobuf {


            

Reported by FlawFinder.

sprintf - Potential format string problem
Security

Line: 506 Column: 11 CWE codes: 134
Suggestion: Make format string constant

                           (last_hex_escape && isxdigit(*src)))) {
          if (dest_len - used < 4) // need space for 4 letter escape
            return -1;
          sprintf(dest + used, (use_hex ? "\\x%02x" : "\\%03o"),
                  static_cast<uint8>(*src));
          is_hex_escape = use_hex;
          used += 4;
        } else {
          dest[used++] = *src; break;

            

Reported by FlawFinder.

StrCat - Does not check for buffer overflows when concatenating to destination [MS-banned]
Security

Line: 1472 Column: 13 CWE codes: 120

                return out;
}

std::string StrCat(const AlphaNum &a, const AlphaNum &b) {
  std::string result;
  result.resize(a.size() + b.size());
  char *const begin = &*result.begin();
  char *out = Append2(begin, a, b);
  GOOGLE_DCHECK_EQ(out, begin + result.size());

            

Reported by FlawFinder.

StrCat - Does not check for buffer overflows when concatenating to destination [MS-banned]
Security

Line: 1481 Column: 13 CWE codes: 120

                return result;
}

std::string StrCat(const AlphaNum &a, const AlphaNum &b, const AlphaNum &c) {
  std::string result;
  result.resize(a.size() + b.size() + c.size());
  char *const begin = &*result.begin();
  char *out = Append2(begin, a, b);
  out = Append1(out, c);

            

Reported by FlawFinder.

StrCat - Does not check for buffer overflows when concatenating to destination [MS-banned]
Security

Line: 1491 Column: 13 CWE codes: 120

                return result;
}

std::string StrCat(const AlphaNum &a, const AlphaNum &b, const AlphaNum &c,
                   const AlphaNum &d) {
  std::string result;
  result.resize(a.size() + b.size() + c.size() + d.size());
  char *const begin = &*result.begin();
  char *out = Append4(begin, a, b, c, d);

            

Reported by FlawFinder.

StrCat - Does not check for buffer overflows when concatenating to destination [MS-banned]
Security

Line: 1501 Column: 13 CWE codes: 120

                return result;
}

std::string StrCat(const AlphaNum &a, const AlphaNum &b, const AlphaNum &c,
                   const AlphaNum &d, const AlphaNum &e) {
  std::string result;
  result.resize(a.size() + b.size() + c.size() + d.size() + e.size());
  char *const begin = &*result.begin();
  char *out = Append4(begin, a, b, c, d);

            

Reported by FlawFinder.

StrCat - Does not check for buffer overflows when concatenating to destination [MS-banned]
Security

Line: 1512 Column: 13 CWE codes: 120

                return result;
}

std::string StrCat(const AlphaNum &a, const AlphaNum &b, const AlphaNum &c,
                   const AlphaNum &d, const AlphaNum &e, const AlphaNum &f) {
  std::string result;
  result.resize(a.size() + b.size() + c.size() + d.size() + e.size() +
                f.size());
  char *const begin = &*result.begin();

            

Reported by FlawFinder.

StrCat - Does not check for buffer overflows when concatenating to destination [MS-banned]
Security

Line: 1524 Column: 13 CWE codes: 120

                return result;
}

std::string StrCat(const AlphaNum &a, const AlphaNum &b, const AlphaNum &c,
                   const AlphaNum &d, const AlphaNum &e, const AlphaNum &f,
                   const AlphaNum &g) {
  std::string result;
  result.resize(a.size() + b.size() + c.size() + d.size() + e.size() +
                f.size() + g.size());

            

Reported by FlawFinder.

StrCat - Does not check for buffer overflows when concatenating to destination [MS-banned]
Security

Line: 1538 Column: 13 CWE codes: 120

                return result;
}

std::string StrCat(const AlphaNum &a, const AlphaNum &b, const AlphaNum &c,
                   const AlphaNum &d, const AlphaNum &e, const AlphaNum &f,
                   const AlphaNum &g, const AlphaNum &h) {
  std::string result;
  result.resize(a.size() + b.size() + c.size() + d.size() + e.size() +
                f.size() + g.size() + h.size());

            

Reported by FlawFinder.

java/core/src/test/java/com/google/protobuf/WellKnownTypesTest.java
40 issues
JUnit 4 tests that execute tests should use the @Test annotation, JUnit 5 tests should use @Test, @RepeatedTest, @TestFactory, @TestTemplate or @ParameterizedTest
Design

Line: 51

               * runtime library.
 */
public class WellKnownTypesTest extends TestCase {
  public void testWellKnownTypes() {
    // The test passes if it compiles.
    TestWellKnownTypes message = TestWellKnownTypes.newBuilder().build();
    assertEquals(0, message.getAnyField().getSerializedSize());
    assertEquals(0, message.getApiField().getSerializedSize());
    assertEquals(0, message.getDurationField().getSerializedSize());

            

Reported by PMD.

Unit tests should not contain more than 1 assert(s).
Design

Line: 51

               * runtime library.
 */
public class WellKnownTypesTest extends TestCase {
  public void testWellKnownTypes() {
    // The test passes if it compiles.
    TestWellKnownTypes message = TestWellKnownTypes.newBuilder().build();
    assertEquals(0, message.getAnyField().getSerializedSize());
    assertEquals(0, message.getApiField().getSerializedSize());
    assertEquals(0, message.getDurationField().getSerializedSize());

            

Reported by PMD.

Potential violation of Law of Demeter (object not created locally)
Design

Line: 54

                public void testWellKnownTypes() {
    // The test passes if it compiles.
    TestWellKnownTypes message = TestWellKnownTypes.newBuilder().build();
    assertEquals(0, message.getAnyField().getSerializedSize());
    assertEquals(0, message.getApiField().getSerializedSize());
    assertEquals(0, message.getDurationField().getSerializedSize());
    assertEquals(0, message.getEmptyField().getSerializedSize());
    assertEquals(0, message.getFieldMaskField().getSerializedSize());
    assertEquals(0, message.getSourceContextField().getSerializedSize());

            

Reported by PMD.

JUnit assertions should include a message
Design

Line: 54

                public void testWellKnownTypes() {
    // The test passes if it compiles.
    TestWellKnownTypes message = TestWellKnownTypes.newBuilder().build();
    assertEquals(0, message.getAnyField().getSerializedSize());
    assertEquals(0, message.getApiField().getSerializedSize());
    assertEquals(0, message.getDurationField().getSerializedSize());
    assertEquals(0, message.getEmptyField().getSerializedSize());
    assertEquals(0, message.getFieldMaskField().getSerializedSize());
    assertEquals(0, message.getSourceContextField().getSerializedSize());

            

Reported by PMD.

Potential violation of Law of Demeter (method chain calls)
Design

Line: 54

                public void testWellKnownTypes() {
    // The test passes if it compiles.
    TestWellKnownTypes message = TestWellKnownTypes.newBuilder().build();
    assertEquals(0, message.getAnyField().getSerializedSize());
    assertEquals(0, message.getApiField().getSerializedSize());
    assertEquals(0, message.getDurationField().getSerializedSize());
    assertEquals(0, message.getEmptyField().getSerializedSize());
    assertEquals(0, message.getFieldMaskField().getSerializedSize());
    assertEquals(0, message.getSourceContextField().getSerializedSize());

            

Reported by PMD.

Potential violation of Law of Demeter (method chain calls)
Design

Line: 55

                  // The test passes if it compiles.
    TestWellKnownTypes message = TestWellKnownTypes.newBuilder().build();
    assertEquals(0, message.getAnyField().getSerializedSize());
    assertEquals(0, message.getApiField().getSerializedSize());
    assertEquals(0, message.getDurationField().getSerializedSize());
    assertEquals(0, message.getEmptyField().getSerializedSize());
    assertEquals(0, message.getFieldMaskField().getSerializedSize());
    assertEquals(0, message.getSourceContextField().getSerializedSize());
    assertEquals(0, message.getStructField().getSerializedSize());

            

Reported by PMD.

JUnit assertions should include a message
Design

Line: 55

                  // The test passes if it compiles.
    TestWellKnownTypes message = TestWellKnownTypes.newBuilder().build();
    assertEquals(0, message.getAnyField().getSerializedSize());
    assertEquals(0, message.getApiField().getSerializedSize());
    assertEquals(0, message.getDurationField().getSerializedSize());
    assertEquals(0, message.getEmptyField().getSerializedSize());
    assertEquals(0, message.getFieldMaskField().getSerializedSize());
    assertEquals(0, message.getSourceContextField().getSerializedSize());
    assertEquals(0, message.getStructField().getSerializedSize());

            

Reported by PMD.

Potential violation of Law of Demeter (object not created locally)
Design

Line: 55

                  // The test passes if it compiles.
    TestWellKnownTypes message = TestWellKnownTypes.newBuilder().build();
    assertEquals(0, message.getAnyField().getSerializedSize());
    assertEquals(0, message.getApiField().getSerializedSize());
    assertEquals(0, message.getDurationField().getSerializedSize());
    assertEquals(0, message.getEmptyField().getSerializedSize());
    assertEquals(0, message.getFieldMaskField().getSerializedSize());
    assertEquals(0, message.getSourceContextField().getSerializedSize());
    assertEquals(0, message.getStructField().getSerializedSize());

            

Reported by PMD.

Potential violation of Law of Demeter (method chain calls)
Design

Line: 56

                  TestWellKnownTypes message = TestWellKnownTypes.newBuilder().build();
    assertEquals(0, message.getAnyField().getSerializedSize());
    assertEquals(0, message.getApiField().getSerializedSize());
    assertEquals(0, message.getDurationField().getSerializedSize());
    assertEquals(0, message.getEmptyField().getSerializedSize());
    assertEquals(0, message.getFieldMaskField().getSerializedSize());
    assertEquals(0, message.getSourceContextField().getSerializedSize());
    assertEquals(0, message.getStructField().getSerializedSize());
    assertEquals(0, message.getTimestampField().getSerializedSize());

            

Reported by PMD.

Potential violation of Law of Demeter (object not created locally)
Design

Line: 56

                  TestWellKnownTypes message = TestWellKnownTypes.newBuilder().build();
    assertEquals(0, message.getAnyField().getSerializedSize());
    assertEquals(0, message.getApiField().getSerializedSize());
    assertEquals(0, message.getDurationField().getSerializedSize());
    assertEquals(0, message.getEmptyField().getSerializedSize());
    assertEquals(0, message.getFieldMaskField().getSerializedSize());
    assertEquals(0, message.getSourceContextField().getSerializedSize());
    assertEquals(0, message.getStructField().getSerializedSize());
    assertEquals(0, message.getTimestampField().getSerializedSize());

            

Reported by PMD.

java/core/src/test/java/com/google/protobuf/RopeByteStringSubstringTest.java
40 issues
Potential violation of Law of Demeter (method chain calls)
Design

Line: 54

                public void setUp() throws Exception {
    classUnderTest = "RopeByteString";
    byte[] sourceBytes = ByteStringTest.getTestBytes(22341, 22337766L);
    Iterator<ByteString> iter = ByteStringTest.makeConcretePieces(sourceBytes).iterator();
    ByteString sourceString = iter.next();
    while (iter.hasNext()) {
      sourceString = sourceString.concat(iter.next());
    }


            

Reported by PMD.

Potential violation of Law of Demeter (object not created locally)
Design

Line: 62

              
    int from = 1130;
    int to = sourceBytes.length - 5555;
    stringUnderTest = sourceString.substring(from, to);
    referenceBytes = new byte[to - from];
    System.arraycopy(sourceBytes, from, referenceBytes, 0, to - from);
    expectedHashCode = -1259260680;
  }


            

Reported by PMD.

Potential violation of Law of Demeter (method chain calls)
Design

Line: 71

                @Override
  @Test
  public void testGetTreeDepth() {
    assertWithMessage("%s must have the expected tree depth", classUnderTest)
        .that(stringUnderTest.getTreeDepth())
        .isEqualTo(3);
  }

  @Override

            

Reported by PMD.

Potential violation of Law of Demeter (method chain calls)
Design

Line: 71

                @Override
  @Test
  public void testGetTreeDepth() {
    assertWithMessage("%s must have the expected tree depth", classUnderTest)
        .that(stringUnderTest.getTreeDepth())
        .isEqualTo(3);
  }

  @Override

            

Reported by PMD.

Unit tests should not contain more than 1 assert(s).
Design

Line: 78

              
  @Override
  @Test
  public void testToString() throws UnsupportedEncodingException {
    String sourceString = "I love unicode \u1234\u5678 characters";
    ByteString sourceByteString = ByteString.copyFromUtf8(sourceString);
    int copies = 250;

    // By building the RopeByteString by concatenating, this is actually a fairly strenuous test.

            

Reported by PMD.

Potential violation of Law of Demeter (object not created locally)
Design

Line: 84

                  int copies = 250;

    // By building the RopeByteString by concatenating, this is actually a fairly strenuous test.
    StringBuilder builder = new StringBuilder(copies * sourceString.length());
    ByteString unicode = ByteString.EMPTY;
    for (int i = 0; i < copies; ++i) {
      builder.append(sourceString);
      unicode = RopeByteString.concatenate(unicode, sourceByteString);
    }

            

Reported by PMD.

Potential violation of Law of Demeter (object not created locally)
Design

Line: 93

                  String testString = builder.toString();

    // Do the substring part
    testString = testString.substring(2, testString.length() - 6);
    unicode = unicode.substring(2, unicode.size() - 6);

    assertWithMessage("%s from string must have the expected type", classUnderTest)
        .that(classUnderTest)
        .isEqualTo(getActualClassName(unicode));

            

Reported by PMD.

Potential violation of Law of Demeter (object not created locally)
Design

Line: 93

                  String testString = builder.toString();

    // Do the substring part
    testString = testString.substring(2, testString.length() - 6);
    unicode = unicode.substring(2, unicode.size() - 6);

    assertWithMessage("%s from string must have the expected type", classUnderTest)
        .that(classUnderTest)
        .isEqualTo(getActualClassName(unicode));

            

Reported by PMD.

Potential violation of Law of Demeter (object not created locally)
Design

Line: 94

              
    // Do the substring part
    testString = testString.substring(2, testString.length() - 6);
    unicode = unicode.substring(2, unicode.size() - 6);

    assertWithMessage("%s from string must have the expected type", classUnderTest)
        .that(classUnderTest)
        .isEqualTo(getActualClassName(unicode));
    String roundTripString = unicode.toString(UTF_8);

            

Reported by PMD.

Potential violation of Law of Demeter (object not created locally)
Design

Line: 94

              
    // Do the substring part
    testString = testString.substring(2, testString.length() - 6);
    unicode = unicode.substring(2, unicode.size() - 6);

    assertWithMessage("%s from string must have the expected type", classUnderTest)
        .that(classUnderTest)
        .isEqualTo(getActualClassName(unicode));
    String roundTripString = unicode.toString(UTF_8);

            

Reported by PMD.

conformance/text_format_conformance_suite.cc
39 issues
StrCat - Does not check for buffer overflows when concatenating to destination [MS-banned]
Security

Line: 88 Column: 23 CWE codes: 120

                  case ConformanceResponse::kProtobufPayload: {
      if (requested_output != conformance::PROTOBUF) {
        ReportFailure(test_name, level, request, response,
                      StrCat("Test was asked for ",
                                   WireFormatToString(requested_output),
                                   " output but provided PROTOBUF instead.")
                          .c_str());
        return false;
      }

            

Reported by FlawFinder.

StrCat - Does not check for buffer overflows when concatenating to destination [MS-banned]
Security

Line: 107 Column: 23 CWE codes: 120

                  case ConformanceResponse::kTextPayload: {
      if (requested_output != conformance::TEXT_FORMAT) {
        ReportFailure(test_name, level, request, response,
                      StrCat("Test was asked for ",
                                   WireFormatToString(requested_output),
                                   " output but provided TEXT_FORMAT instead.")
                          .c_str());
        return false;
      }

            

Reported by FlawFinder.

StrCat - Does not check for buffer overflows when concatenating to destination [MS-banned]
Security

Line: 144 Column: 7 CWE codes: 120

                const ConformanceRequest& request = setting.GetRequest();
  ConformanceResponse response;
  string effective_test_name =
      StrCat(setting.ConformanceLevelToString(level),
                   ".Proto3.TextFormatInput.", test_name);

  RunTest(effective_test_name, request, &response);
  if (response.result_case() == ConformanceResponse::kParseError) {
    ReportSuccess(effective_test_name);

            

Reported by FlawFinder.

StrCat - Does not check for buffer overflows when concatenating to destination [MS-banned]
Security

Line: 266 Column: 9 CWE codes: 120

                  const std::string field_name =
        field_type == "String" ? "optional_string" : "optional_bytes";
    RunValidTextFormatTest(
        StrCat("StringLiteralConcat", field_type), REQUIRED,
        StrCat(field_name, ": 'first' \"second\"\n'third'"));
    RunValidTextFormatTest(
        StrCat("StringLiteralBasicEscapes", field_type), REQUIRED,
        StrCat(field_name, ": '\\a\\b\\f\\n\\r\\t\\v\\?\\\\\\'\\\"'"));
    RunValidTextFormatTest(

            

Reported by FlawFinder.

StrCat - Does not check for buffer overflows when concatenating to destination [MS-banned]
Security

Line: 267 Column: 9 CWE codes: 120

                      field_type == "String" ? "optional_string" : "optional_bytes";
    RunValidTextFormatTest(
        StrCat("StringLiteralConcat", field_type), REQUIRED,
        StrCat(field_name, ": 'first' \"second\"\n'third'"));
    RunValidTextFormatTest(
        StrCat("StringLiteralBasicEscapes", field_type), REQUIRED,
        StrCat(field_name, ": '\\a\\b\\f\\n\\r\\t\\v\\?\\\\\\'\\\"'"));
    RunValidTextFormatTest(
        StrCat("StringLiteralOctalEscapes", field_type), REQUIRED,

            

Reported by FlawFinder.

StrCat - Does not check for buffer overflows when concatenating to destination [MS-banned]
Security

Line: 269 Column: 9 CWE codes: 120

                      StrCat("StringLiteralConcat", field_type), REQUIRED,
        StrCat(field_name, ": 'first' \"second\"\n'third'"));
    RunValidTextFormatTest(
        StrCat("StringLiteralBasicEscapes", field_type), REQUIRED,
        StrCat(field_name, ": '\\a\\b\\f\\n\\r\\t\\v\\?\\\\\\'\\\"'"));
    RunValidTextFormatTest(
        StrCat("StringLiteralOctalEscapes", field_type), REQUIRED,
        StrCat(field_name, ": '\\341\\210\\264'"));
    RunValidTextFormatTest(StrCat("StringLiteralHexEscapes", field_type),

            

Reported by FlawFinder.

StrCat - Does not check for buffer overflows when concatenating to destination [MS-banned]
Security

Line: 270 Column: 9 CWE codes: 120

                      StrCat(field_name, ": 'first' \"second\"\n'third'"));
    RunValidTextFormatTest(
        StrCat("StringLiteralBasicEscapes", field_type), REQUIRED,
        StrCat(field_name, ": '\\a\\b\\f\\n\\r\\t\\v\\?\\\\\\'\\\"'"));
    RunValidTextFormatTest(
        StrCat("StringLiteralOctalEscapes", field_type), REQUIRED,
        StrCat(field_name, ": '\\341\\210\\264'"));
    RunValidTextFormatTest(StrCat("StringLiteralHexEscapes", field_type),
                           REQUIRED,

            

Reported by FlawFinder.

StrCat - Does not check for buffer overflows when concatenating to destination [MS-banned]
Security

Line: 272 Column: 9 CWE codes: 120

                      StrCat("StringLiteralBasicEscapes", field_type), REQUIRED,
        StrCat(field_name, ": '\\a\\b\\f\\n\\r\\t\\v\\?\\\\\\'\\\"'"));
    RunValidTextFormatTest(
        StrCat("StringLiteralOctalEscapes", field_type), REQUIRED,
        StrCat(field_name, ": '\\341\\210\\264'"));
    RunValidTextFormatTest(StrCat("StringLiteralHexEscapes", field_type),
                           REQUIRED,
                           StrCat(field_name, ": '\\xe1\\x88\\xb4'"));
    RunValidTextFormatTest(

            

Reported by FlawFinder.

StrCat - Does not check for buffer overflows when concatenating to destination [MS-banned]
Security

Line: 273 Column: 9 CWE codes: 120

                      StrCat(field_name, ": '\\a\\b\\f\\n\\r\\t\\v\\?\\\\\\'\\\"'"));
    RunValidTextFormatTest(
        StrCat("StringLiteralOctalEscapes", field_type), REQUIRED,
        StrCat(field_name, ": '\\341\\210\\264'"));
    RunValidTextFormatTest(StrCat("StringLiteralHexEscapes", field_type),
                           REQUIRED,
                           StrCat(field_name, ": '\\xe1\\x88\\xb4'"));
    RunValidTextFormatTest(
        StrCat("StringLiteralShortUnicodeEscape", field_type),

            

Reported by FlawFinder.

StrCat - Does not check for buffer overflows when concatenating to destination [MS-banned]
Security

Line: 274 Column: 28 CWE codes: 120

                  RunValidTextFormatTest(
        StrCat("StringLiteralOctalEscapes", field_type), REQUIRED,
        StrCat(field_name, ": '\\341\\210\\264'"));
    RunValidTextFormatTest(StrCat("StringLiteralHexEscapes", field_type),
                           REQUIRED,
                           StrCat(field_name, ": '\\xe1\\x88\\xb4'"));
    RunValidTextFormatTest(
        StrCat("StringLiteralShortUnicodeEscape", field_type),
        RECOMMENDED, StrCat(field_name, ": '\\u1234'"));

            

Reported by FlawFinder.