The following issues were found

python/google/protobuf/internal/well_known_types_test.py
758 issues
No name 'any_pb2' in module 'google.protobuf'
Error

Line: 51 Column: 1

              except ImportError:
  import unittest

from google.protobuf import any_pb2
from google.protobuf import duration_pb2
from google.protobuf import field_mask_pb2
from google.protobuf import struct_pb2
from google.protobuf import timestamp_pb2
from google.protobuf import map_unittest_pb2

            

Reported by Pylint.

No name 'duration_pb2' in module 'google.protobuf'
Error

Line: 52 Column: 1

                import unittest

from google.protobuf import any_pb2
from google.protobuf import duration_pb2
from google.protobuf import field_mask_pb2
from google.protobuf import struct_pb2
from google.protobuf import timestamp_pb2
from google.protobuf import map_unittest_pb2
from google.protobuf import unittest_pb2

            

Reported by Pylint.

No name 'field_mask_pb2' in module 'google.protobuf'
Error

Line: 53 Column: 1

              
from google.protobuf import any_pb2
from google.protobuf import duration_pb2
from google.protobuf import field_mask_pb2
from google.protobuf import struct_pb2
from google.protobuf import timestamp_pb2
from google.protobuf import map_unittest_pb2
from google.protobuf import unittest_pb2
from google.protobuf.internal import any_test_pb2

            

Reported by Pylint.

No name 'struct_pb2' in module 'google.protobuf'
Error

Line: 54 Column: 1

              from google.protobuf import any_pb2
from google.protobuf import duration_pb2
from google.protobuf import field_mask_pb2
from google.protobuf import struct_pb2
from google.protobuf import timestamp_pb2
from google.protobuf import map_unittest_pb2
from google.protobuf import unittest_pb2
from google.protobuf.internal import any_test_pb2
from google.protobuf.internal import test_util

            

Reported by Pylint.

No name 'timestamp_pb2' in module 'google.protobuf'
Error

Line: 55 Column: 1

              from google.protobuf import duration_pb2
from google.protobuf import field_mask_pb2
from google.protobuf import struct_pb2
from google.protobuf import timestamp_pb2
from google.protobuf import map_unittest_pb2
from google.protobuf import unittest_pb2
from google.protobuf.internal import any_test_pb2
from google.protobuf.internal import test_util
from google.protobuf.internal import well_known_types

            

Reported by Pylint.

No name 'map_unittest_pb2' in module 'google.protobuf'
Error

Line: 56 Column: 1

              from google.protobuf import field_mask_pb2
from google.protobuf import struct_pb2
from google.protobuf import timestamp_pb2
from google.protobuf import map_unittest_pb2
from google.protobuf import unittest_pb2
from google.protobuf.internal import any_test_pb2
from google.protobuf.internal import test_util
from google.protobuf.internal import well_known_types
from google.protobuf import descriptor

            

Reported by Pylint.

No name 'unittest_pb2' in module 'google.protobuf'
Error

Line: 57 Column: 1

              from google.protobuf import struct_pb2
from google.protobuf import timestamp_pb2
from google.protobuf import map_unittest_pb2
from google.protobuf import unittest_pb2
from google.protobuf.internal import any_test_pb2
from google.protobuf.internal import test_util
from google.protobuf.internal import well_known_types
from google.protobuf import descriptor
from google.protobuf import text_format

            

Reported by Pylint.

No name 'any_test_pb2' in module 'google.protobuf.internal'
Error

Line: 58 Column: 1

              from google.protobuf import timestamp_pb2
from google.protobuf import map_unittest_pb2
from google.protobuf import unittest_pb2
from google.protobuf.internal import any_test_pb2
from google.protobuf.internal import test_util
from google.protobuf.internal import well_known_types
from google.protobuf import descriptor
from google.protobuf import text_format


            

Reported by Pylint.

Using deprecated method assertRaisesRegexp()
Error

Line: 310 Column: 5

              
  def testInvalidTimestamp(self):
    message = timestamp_pb2.Timestamp()
    self.assertRaisesRegexp(
        ValueError,
        'Failed to parse timestamp: missing valid timezone offset.',
        message.FromJsonString,
        '')
    self.assertRaisesRegexp(

            

Reported by Pylint.

Using deprecated method assertRaisesRegexp()
Error

Line: 315 Column: 5

                      'Failed to parse timestamp: missing valid timezone offset.',
        message.FromJsonString,
        '')
    self.assertRaisesRegexp(
        ValueError,
        'Failed to parse timestamp: invalid trailing data '
        '1970-01-01T00:00:01Ztrail.',
        message.FromJsonString,
        '1970-01-01T00:00:01Ztrail')

            

Reported by Pylint.

python/google/protobuf/internal/descriptor_test.py
654 issues
No name 'unittest_custom_options_pb2' in module 'google.protobuf'
Error

Line: 45 Column: 1

              except ImportError:
  import unittest

from google.protobuf import unittest_custom_options_pb2
from google.protobuf import unittest_import_pb2
from google.protobuf import unittest_pb2
from google.protobuf import descriptor_pb2
from google.protobuf.internal import api_implementation
from google.protobuf.internal import test_util

            

Reported by Pylint.

No name 'unittest_import_pb2' in module 'google.protobuf'
Error

Line: 46 Column: 1

                import unittest

from google.protobuf import unittest_custom_options_pb2
from google.protobuf import unittest_import_pb2
from google.protobuf import unittest_pb2
from google.protobuf import descriptor_pb2
from google.protobuf.internal import api_implementation
from google.protobuf.internal import test_util
from google.protobuf import descriptor

            

Reported by Pylint.

No name 'unittest_pb2' in module 'google.protobuf'
Error

Line: 47 Column: 1

              
from google.protobuf import unittest_custom_options_pb2
from google.protobuf import unittest_import_pb2
from google.protobuf import unittest_pb2
from google.protobuf import descriptor_pb2
from google.protobuf.internal import api_implementation
from google.protobuf.internal import test_util
from google.protobuf import descriptor
from google.protobuf import descriptor_pool

            

Reported by Pylint.

No name 'descriptor_pb2' in module 'google.protobuf'
Error

Line: 48 Column: 1

              from google.protobuf import unittest_custom_options_pb2
from google.protobuf import unittest_import_pb2
from google.protobuf import unittest_pb2
from google.protobuf import descriptor_pb2
from google.protobuf.internal import api_implementation
from google.protobuf.internal import test_util
from google.protobuf import descriptor
from google.protobuf import descriptor_pool
from google.protobuf import symbol_database

            

Reported by Pylint.

Unused test_util imported from google.protobuf.internal
Error

Line: 50 Column: 1

              from google.protobuf import unittest_pb2
from google.protobuf import descriptor_pb2
from google.protobuf.internal import api_implementation
from google.protobuf.internal import test_util
from google.protobuf import descriptor
from google.protobuf import descriptor_pool
from google.protobuf import symbol_database
from google.protobuf import text_format


            

Reported by Pylint.

Redefining name 'descriptor' from outer scope (line 51)
Error

Line: 302 Column: 5

                      unittest_custom_options_pb2.double_opt])

  def testComplexExtensionOptions(self):
    descriptor =\
        unittest_custom_options_pb2.VariousComplexOptions.DESCRIPTOR
    options = descriptor.GetOptions()
    self.assertEqual(42, options.Extensions[
        unittest_custom_options_pb2.complex_opt1].foo)
    self.assertEqual(324, options.Extensions[

            

Reported by Pylint.

TODO(jieluo): Change __repr__ support for DescriptorSequence.
Error

Line: 566 Column: 3

                  self.assertRaises(StopIteration, next, reversed_iterator)
    expected_list[0] = 'change value'
    self.assertNotEqual(expected_list, sequence)
    # TODO(jieluo): Change __repr__ support for DescriptorSequence.
    if api_implementation.Type() == 'python':
      self.assertEqual(str(list(sequence)), str(sequence))
    else:
      self.assertEqual(str(sequence)[0], '<')


            

Reported by Pylint.

TODO(jieluo): Fix python and cpp extension diff.
Error

Line: 593 Column: 3

                  self.assertEqual(mapping.get(key), item)
    with self.assertRaises(TypeError):
      mapping.get()
    # TODO(jieluo): Fix python and cpp extension diff.
    if api_implementation.Type() == 'python':
      self.assertRaises(TypeError, mapping.get, [])
    else:
      self.assertEqual(None, mapping.get([]))
    # keys(), iterkeys() &co

            

Reported by Pylint.

TODO(jieluo): Add __repr__ support for DescriptorMapping.
Error

Line: 615 Column: 3

                  self.assertNotEqual(mapping, excepted_dict)
    self.assertRaises(KeyError, mapping.__getitem__, 'key_error')
    self.assertRaises(KeyError, mapping.__getitem__, len(mapping) + 1)
    # TODO(jieluo): Add __repr__ support for DescriptorMapping.
    if api_implementation.Type() == 'python':
      self.assertEqual(len(str(dict(mapping.items()))), len(str(mapping)))
    else:
      self.assertEqual(str(mapping)[0], '<')


            

Reported by Pylint.

TODO(jieluo): Fix pure python to check with the proto type.
Error

Line: 926 Column: 3

                @unittest.skipIf(
      api_implementation.Type() == 'python',
      'Pure python does not raise error.')
  # TODO(jieluo): Fix pure python to check with the proto type.
  def testCopyToProto_TypeError(self):
    file_proto = descriptor_pb2.FileDescriptorProto()
    self.assertRaises(TypeError,
                      unittest_pb2.TestEmptyMessage.DESCRIPTOR.CopyToProto,
                      file_proto)

            

Reported by Pylint.

python/google/protobuf/internal/well_known_types.py
649 issues
Assigning to attribute 'type_url' not defined in class slots
Error

Line: 76 Column: 7

                         deterministic=None):
    """Packs the specified message into current Any message."""
    if len(type_url_prefix) < 1 or type_url_prefix[-1] != '/':
      self.type_url = '%s/%s' % (type_url_prefix, msg.DESCRIPTOR.full_name)
    else:
      self.type_url = '%s%s' % (type_url_prefix, msg.DESCRIPTOR.full_name)
    self.value = msg.SerializeToString(deterministic=deterministic)

  def Unpack(self, msg):

            

Reported by Pylint.

Assigning to attribute 'type_url' not defined in class slots
Error

Line: 78 Column: 7

                  if len(type_url_prefix) < 1 or type_url_prefix[-1] != '/':
      self.type_url = '%s/%s' % (type_url_prefix, msg.DESCRIPTOR.full_name)
    else:
      self.type_url = '%s%s' % (type_url_prefix, msg.DESCRIPTOR.full_name)
    self.value = msg.SerializeToString(deterministic=deterministic)

  def Unpack(self, msg):
    """Unpacks the current Any message into specified message."""
    descriptor = msg.DESCRIPTOR

            

Reported by Pylint.

Assigning to attribute 'value' not defined in class slots
Error

Line: 79 Column: 5

                    self.type_url = '%s/%s' % (type_url_prefix, msg.DESCRIPTOR.full_name)
    else:
      self.type_url = '%s%s' % (type_url_prefix, msg.DESCRIPTOR.full_name)
    self.value = msg.SerializeToString(deterministic=deterministic)

  def Unpack(self, msg):
    """Unpacks the current Any message into specified message."""
    descriptor = msg.DESCRIPTOR
    if not self.Is(descriptor):

            

Reported by Pylint.

Assigning to attribute 'seconds' not defined in class slots
Error

Line: 197 Column: 5

                    else:
        seconds += (int(timezone[1:pos])*60+int(timezone[pos+1:]))*60
    # Set seconds and nanos
    self.seconds = int(seconds)
    self.nanos = int(nanos)

  def GetCurrentTime(self):
    """Get the current UTC into Timestamp."""
    self.FromDatetime(datetime.utcnow())

            

Reported by Pylint.

Assigning to attribute 'nanos' not defined in class slots
Error

Line: 198 Column: 5

                      seconds += (int(timezone[1:pos])*60+int(timezone[pos+1:]))*60
    # Set seconds and nanos
    self.seconds = int(seconds)
    self.nanos = int(nanos)

  def GetCurrentTime(self):
    """Get the current UTC into Timestamp."""
    self.FromDatetime(datetime.utcnow())


            

Reported by Pylint.

Assigning to attribute 'seconds' not defined in class slots
Error

Line: 224 Column: 5

              
  def FromNanoseconds(self, nanos):
    """Converts nanoseconds since epoch to Timestamp."""
    self.seconds = nanos // _NANOS_PER_SECOND
    self.nanos = nanos % _NANOS_PER_SECOND

  def FromMicroseconds(self, micros):
    """Converts microseconds since epoch to Timestamp."""
    self.seconds = micros // _MICROS_PER_SECOND

            

Reported by Pylint.

Assigning to attribute 'nanos' not defined in class slots
Error

Line: 225 Column: 5

                def FromNanoseconds(self, nanos):
    """Converts nanoseconds since epoch to Timestamp."""
    self.seconds = nanos // _NANOS_PER_SECOND
    self.nanos = nanos % _NANOS_PER_SECOND

  def FromMicroseconds(self, micros):
    """Converts microseconds since epoch to Timestamp."""
    self.seconds = micros // _MICROS_PER_SECOND
    self.nanos = (micros % _MICROS_PER_SECOND) * _NANOS_PER_MICROSECOND

            

Reported by Pylint.

Assigning to attribute 'seconds' not defined in class slots
Error

Line: 229 Column: 5

              
  def FromMicroseconds(self, micros):
    """Converts microseconds since epoch to Timestamp."""
    self.seconds = micros // _MICROS_PER_SECOND
    self.nanos = (micros % _MICROS_PER_SECOND) * _NANOS_PER_MICROSECOND

  def FromMilliseconds(self, millis):
    """Converts milliseconds since epoch to Timestamp."""
    self.seconds = millis // _MILLIS_PER_SECOND

            

Reported by Pylint.

Assigning to attribute 'nanos' not defined in class slots
Error

Line: 230 Column: 5

                def FromMicroseconds(self, micros):
    """Converts microseconds since epoch to Timestamp."""
    self.seconds = micros // _MICROS_PER_SECOND
    self.nanos = (micros % _MICROS_PER_SECOND) * _NANOS_PER_MICROSECOND

  def FromMilliseconds(self, millis):
    """Converts milliseconds since epoch to Timestamp."""
    self.seconds = millis // _MILLIS_PER_SECOND
    self.nanos = (millis % _MILLIS_PER_SECOND) * _NANOS_PER_MILLISECOND

            

Reported by Pylint.

Assigning to attribute 'seconds' not defined in class slots
Error

Line: 234 Column: 5

              
  def FromMilliseconds(self, millis):
    """Converts milliseconds since epoch to Timestamp."""
    self.seconds = millis // _MILLIS_PER_SECOND
    self.nanos = (millis % _MILLIS_PER_SECOND) * _NANOS_PER_MILLISECOND

  def FromSeconds(self, seconds):
    """Converts seconds since epoch to Timestamp."""
    self.seconds = seconds

            

Reported by Pylint.

python/google/protobuf/internal/decoder.py
641 issues
Bad option value 'g-import-not-at-top'
Error

Line: 91 Column: 1

              if six.PY3:
  long = int
else:
  import re    # pylint: disable=g-import-not-at-top
  _SURROGATE_PATTERN = re.compile(six.u(r'[\ud800-\udfff]'))

from google.protobuf.internal import containers
from google.protobuf.internal import encoder
from google.protobuf.internal import wire_format

            

Reported by Pylint.

Redefining name 'message' from outer scope (line 97)
Error

Line: 216 Column: 47

                                    clear_if_default=False):
    if is_packed:
      local_DecodeVarint = _DecodeVarint
      def DecodePackedField(buffer, pos, end, message, field_dict):
        value = field_dict.get(key)
        if value is None:
          value = field_dict.setdefault(key, new_default(message))
        (endpoint, pos) = local_DecodeVarint(buffer, pos)
        endpoint += pos

            

Reported by Pylint.

Redefining name 'message' from outer scope (line 97)
Error

Line: 235 Column: 49

                  elif is_repeated:
      tag_bytes = encoder.TagBytes(field_number, wire_type)
      tag_len = len(tag_bytes)
      def DecodeRepeatedField(buffer, pos, end, message, field_dict):
        value = field_dict.get(key)
        if value is None:
          value = field_dict.setdefault(key, new_default(message))
        while 1:
          (element, new_pos) = decode_value(buffer, pos)

            

Reported by Pylint.

Redefining name 'message' from outer scope (line 97)
Error

Line: 252 Column: 41

                          return new_pos
      return DecodeRepeatedField
    else:
      def DecodeField(buffer, pos, end, message, field_dict):
        (new_value, pos) = decode_value(buffer, pos)
        if pos > end:
          raise _DecodeError('Truncated message.')
        if clear_if_default and not new_value:
          field_dict.pop(key, None)

            

Reported by Pylint.

Unused argument 'message'
Error

Line: 252 Column: 41

                          return new_pos
      return DecodeRepeatedField
    else:
      def DecodeField(buffer, pos, end, message, field_dict):
        (new_value, pos) = decode_value(buffer, pos)
        if pos > end:
          raise _DecodeError('Truncated message.')
        if clear_if_default and not new_value:
          field_dict.pop(key, None)

            

Reported by Pylint.

Redefining built-in 'format'
Error

Line: 280 Column: 35

                return _SimpleDecoder(wire_type, InnerDecode)


def _StructPackDecoder(wire_type, format):
  """Return a constructor for a decoder for a fixed-width field.

  Args:
      wire_type:  The field's wire type.
      format:  The format string to pass to struct.unpack().

            

Reported by Pylint.

Redefining name 'message' from outer scope (line 97)
Error

Line: 396 Column: 45

                enum_type = key.enum_type
  if is_packed:
    local_DecodeVarint = _DecodeVarint
    def DecodePackedField(buffer, pos, end, message, field_dict):
      """Decode serialized packed enum to its value and a new position.

      Args:
        buffer: memoryview of the serialized bytes.
        pos: int, position in the memory view to start at.

            

Reported by Pylint.

Access to a protected member _unknown_fields of a client class
Error

Line: 439 Column: 15

                      if element in enum_type.values_by_number:
          del value[-1]   # Discard corrupt value.
        else:
          del message._unknown_fields[-1]
          # pylint: disable=protected-access
          del message._unknown_field_set._values[-1]
          # pylint: enable=protected-access
        raise _DecodeError('Packed element was truncated.')
      return pos

            

Reported by Pylint.

Redefining name 'message' from outer scope (line 97)
Error

Line: 449 Column: 47

                elif is_repeated:
    tag_bytes = encoder.TagBytes(field_number, wire_format.WIRETYPE_VARINT)
    tag_len = len(tag_bytes)
    def DecodeRepeatedField(buffer, pos, end, message, field_dict):
      """Decode serialized repeated enum to its value and a new position.

      Args:
        buffer: memoryview of the serialized bytes.
        pos: int, position in the memory view to start at.

            

Reported by Pylint.

Redefining name 'message' from outer scope (line 97)
Error

Line: 490 Column: 39

                        return new_pos
    return DecodeRepeatedField
  else:
    def DecodeField(buffer, pos, end, message, field_dict):
      """Decode serialized repeated enum to its value and a new position.

      Args:
        buffer: memoryview of the serialized bytes.
        pos: int, position in the memory view to start at.

            

Reported by Pylint.

python/google/protobuf/internal/encoder.py
637 issues
The raise statement is not inside an except clause
Error

Line: 567 Column: 9

                    elif value != value:           # NaN
        write(b'\x00\x00\xC0\x7F')
      else:
        raise
  elif value_size == 8:
    def EncodeNonFiniteOrRaise(write, value):
      if value == _POS_INF:
        write(b'\x00\x00\x00\x00\x00\x00\xF0\x7F')
      elif value == _NEG_INF:

            

Reported by Pylint.

The raise statement is not inside an except clause
Error

Line: 577 Column: 9

                    elif value != value:                         # NaN
        write(b'\x00\x00\x00\x00\x00\x00\xF8\x7F')
      else:
        raise
  else:
    raise ValueError('Can\'t encode floating-point values that are '
                     '%d bytes long (only 4 or 8)' % value_size)

  def SpecificEncoder(field_number, is_repeated, is_packed):

            

Reported by Pylint.

Unused argument 'value'
Error

Line: 203 Column: 21

                    return RepeatedFieldSize
    else:
      field_size = value_size + tag_size
      def FieldSize(value):
        return field_size
      return FieldSize

  return SpecificSizer


            

Reported by Pylint.

Access to a protected member _concrete_class of a client class
Error

Line: 360 Column: 19

                    # obvious way to avoid this within the current design without tons of code
      # duplication. For message map, value.ByteSize() should be called to
      # update the status.
      entry_msg = message_type._concrete_class(key=key, value=value)
      total += message_sizer(entry_msg)
      if is_message_map:
        value.ByteSize()
    return total


            

Reported by Pylint.

Redefining built-in 'format'
Error

Line: 506 Column: 35

                return SpecificEncoder


def _StructPackEncoder(wire_type, format):
  """Return a constructor for an encoder for a fixed-width field.

  Args:
      wire_type:  The field's wire type, for encoding tags.
      format:  The format string to pass to struct.pack().

            

Reported by Pylint.

Redefining built-in 'format'
Error

Line: 544 Column: 38

                return SpecificEncoder


def _FloatingPointEncoder(wire_type, format):
  """Return a constructor for an encoder for float fields.

  This is like StructPackEncoder, but catches errors that may be due to
  passing non-finite floating-point values to struct.pack, and makes a
  second attempt to encode those values.

            

Reported by Pylint.

Access to a protected member _InternalSerialize of a client class
Error

Line: 741 Column: 9

                  def EncodeRepeatedField(write, value, deterministic):
      for element in value:
        write(start_tag)
        element._InternalSerialize(write, deterministic)
        write(end_tag)
    return EncodeRepeatedField
  else:
    def EncodeField(write, value, deterministic):
      write(start_tag)

            

Reported by Pylint.

Access to a protected member _InternalSerialize of a client class
Error

Line: 747 Column: 7

                else:
    def EncodeField(write, value, deterministic):
      write(start_tag)
      value._InternalSerialize(write, deterministic)
      return write(end_tag)
    return EncodeField


def MessageEncoder(field_number, is_repeated, is_packed):

            

Reported by Pylint.

Access to a protected member _InternalSerialize of a client class
Error

Line: 763 Column: 9

                    for element in value:
        write(tag)
        local_EncodeVarint(write, element.ByteSize(), deterministic)
        element._InternalSerialize(write, deterministic)
    return EncodeRepeatedField
  else:
    def EncodeField(write, value, deterministic):
      write(tag)
      local_EncodeVarint(write, value.ByteSize(), deterministic)

            

Reported by Pylint.

Access to a protected member _InternalSerialize of a client class
Error

Line: 769 Column: 14

                  def EncodeField(write, value, deterministic):
      write(tag)
      local_EncodeVarint(write, value.ByteSize(), deterministic)
      return value._InternalSerialize(write, deterministic)
    return EncodeField


# --------------------------------------------------------------------
# As before, MessageSet is special.

            

Reported by Pylint.

java/core/src/test/java/com/google/protobuf/MapForProto2Test.java
630 issues
Possible God Class (WMC=93, ATFD=351, TCC=0.000%)
Design

Line: 60

              
/** Unit tests for map fields in proto2 protos. */
@RunWith(JUnit4.class)
public class MapForProto2Test {

  private void setMapValuesUsingMutableMap(TestMap.Builder builder) {
    builder.getMutableInt32ToInt32Field().put(1, 11);
    builder.getMutableInt32ToInt32Field().put(2, 22);
    builder.getMutableInt32ToInt32Field().put(3, 33);

            

Reported by PMD.

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

Line: 60

              
/** Unit tests for map fields in proto2 protos. */
@RunWith(JUnit4.class)
public class MapForProto2Test {

  private void setMapValuesUsingMutableMap(TestMap.Builder builder) {
    builder.getMutableInt32ToInt32Field().put(1, 11);
    builder.getMutableInt32ToInt32Field().put(2, 22);
    builder.getMutableInt32ToInt32Field().put(3, 33);

            

Reported by PMD.

The class 'MapForProto2Test' has a total cyclomatic complexity of 93 (highest 8).
Design

Line: 60

              
/** Unit tests for map fields in proto2 protos. */
@RunWith(JUnit4.class)
public class MapForProto2Test {

  private void setMapValuesUsingMutableMap(TestMap.Builder builder) {
    builder.getMutableInt32ToInt32Field().put(1, 11);
    builder.getMutableInt32ToInt32Field().put(2, 22);
    builder.getMutableInt32ToInt32Field().put(3, 33);

            

Reported by PMD.

Avoid really long classes.
Design

Line: 60

              
/** Unit tests for map fields in proto2 protos. */
@RunWith(JUnit4.class)
public class MapForProto2Test {

  private void setMapValuesUsingMutableMap(TestMap.Builder builder) {
    builder.getMutableInt32ToInt32Field().put(1, 11);
    builder.getMutableInt32ToInt32Field().put(2, 22);
    builder.getMutableInt32ToInt32Field().put(3, 33);

            

Reported by PMD.

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

Line: 63

              public class MapForProto2Test {

  private void setMapValuesUsingMutableMap(TestMap.Builder builder) {
    builder.getMutableInt32ToInt32Field().put(1, 11);
    builder.getMutableInt32ToInt32Field().put(2, 22);
    builder.getMutableInt32ToInt32Field().put(3, 33);
  //
    builder.getMutableInt32ToStringField().put(1, "11");
    builder.getMutableInt32ToStringField().put(2, "22");

            

Reported by PMD.

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

Line: 64

              
  private void setMapValuesUsingMutableMap(TestMap.Builder builder) {
    builder.getMutableInt32ToInt32Field().put(1, 11);
    builder.getMutableInt32ToInt32Field().put(2, 22);
    builder.getMutableInt32ToInt32Field().put(3, 33);
  //
    builder.getMutableInt32ToStringField().put(1, "11");
    builder.getMutableInt32ToStringField().put(2, "22");
    builder.getMutableInt32ToStringField().put(3, "33");

            

Reported by PMD.

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

Line: 65

                private void setMapValuesUsingMutableMap(TestMap.Builder builder) {
    builder.getMutableInt32ToInt32Field().put(1, 11);
    builder.getMutableInt32ToInt32Field().put(2, 22);
    builder.getMutableInt32ToInt32Field().put(3, 33);
  //
    builder.getMutableInt32ToStringField().put(1, "11");
    builder.getMutableInt32ToStringField().put(2, "22");
    builder.getMutableInt32ToStringField().put(3, "33");
  //

            

Reported by PMD.

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

Line: 67

                  builder.getMutableInt32ToInt32Field().put(2, 22);
    builder.getMutableInt32ToInt32Field().put(3, 33);
  //
    builder.getMutableInt32ToStringField().put(1, "11");
    builder.getMutableInt32ToStringField().put(2, "22");
    builder.getMutableInt32ToStringField().put(3, "33");
  //
    builder.getMutableInt32ToBytesField().put(1, TestUtil.toBytes("11"));
    builder.getMutableInt32ToBytesField().put(2, TestUtil.toBytes("22"));

            

Reported by PMD.

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

Line: 68

                  builder.getMutableInt32ToInt32Field().put(3, 33);
  //
    builder.getMutableInt32ToStringField().put(1, "11");
    builder.getMutableInt32ToStringField().put(2, "22");
    builder.getMutableInt32ToStringField().put(3, "33");
  //
    builder.getMutableInt32ToBytesField().put(1, TestUtil.toBytes("11"));
    builder.getMutableInt32ToBytesField().put(2, TestUtil.toBytes("22"));
    builder.getMutableInt32ToBytesField().put(3, TestUtil.toBytes("33"));

            

Reported by PMD.

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

Line: 69

                //
    builder.getMutableInt32ToStringField().put(1, "11");
    builder.getMutableInt32ToStringField().put(2, "22");
    builder.getMutableInt32ToStringField().put(3, "33");
  //
    builder.getMutableInt32ToBytesField().put(1, TestUtil.toBytes("11"));
    builder.getMutableInt32ToBytesField().put(2, TestUtil.toBytes("22"));
    builder.getMutableInt32ToBytesField().put(3, TestUtil.toBytes("33"));
  //

            

Reported by PMD.

java/core/src/test/java/com/google/protobuf/DescriptorsTest.java
620 issues
A high number of imports can indicate a high degree of coupling within an object.
Design

Line: 31

              // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

package com.google.protobuf;

import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth.assertWithMessage;

import com.google.protobuf.DescriptorProtos.DescriptorProto;

            

Reported by PMD.

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

Line: 76

              
/** Unit test for {@link Descriptors}. */
@RunWith(JUnit4.class)
public class DescriptorsTest {

  // Regression test for bug where referencing a FieldDescriptor.Type value
  // before a FieldDescriptorProto.Type value would yield a
  // ExceptionInInitializerError.
  @SuppressWarnings("unused")

            

Reported by PMD.

Possible God Class (WMC=49, ATFD=331, TCC=0.000%)
Design

Line: 76

              
/** Unit test for {@link Descriptors}. */
@RunWith(JUnit4.class)
public class DescriptorsTest {

  // Regression test for bug where referencing a FieldDescriptor.Type value
  // before a FieldDescriptorProto.Type value would yield a
  // ExceptionInInitializerError.
  @SuppressWarnings("unused")

            

Reported by PMD.

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

Line: 85

                private static final Object STATIC_INIT_TEST = FieldDescriptor.Type.BOOL;

  @Test
  public void testFieldTypeEnumMapping() throws Exception {
    assertThat(FieldDescriptor.Type.values()).hasLength(FieldDescriptorProto.Type.values().length);
    for (FieldDescriptor.Type type : FieldDescriptor.Type.values()) {
      FieldDescriptorProto.Type protoType = type.toProto();
      assertThat(protoType.name()).isEqualTo("TYPE_" + type.name());
      assertThat(FieldDescriptor.Type.valueOf(protoType)).isEqualTo(type);

            

Reported by PMD.

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

Line: 86

              
  @Test
  public void testFieldTypeEnumMapping() throws Exception {
    assertThat(FieldDescriptor.Type.values()).hasLength(FieldDescriptorProto.Type.values().length);
    for (FieldDescriptor.Type type : FieldDescriptor.Type.values()) {
      FieldDescriptorProto.Type protoType = type.toProto();
      assertThat(protoType.name()).isEqualTo("TYPE_" + type.name());
      assertThat(FieldDescriptor.Type.valueOf(protoType)).isEqualTo(type);
    }

            

Reported by PMD.

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

Line: 86

              
  @Test
  public void testFieldTypeEnumMapping() throws Exception {
    assertThat(FieldDescriptor.Type.values()).hasLength(FieldDescriptorProto.Type.values().length);
    for (FieldDescriptor.Type type : FieldDescriptor.Type.values()) {
      FieldDescriptorProto.Type protoType = type.toProto();
      assertThat(protoType.name()).isEqualTo("TYPE_" + type.name());
      assertThat(FieldDescriptor.Type.valueOf(protoType)).isEqualTo(type);
    }

            

Reported by PMD.

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

Line: 86

              
  @Test
  public void testFieldTypeEnumMapping() throws Exception {
    assertThat(FieldDescriptor.Type.values()).hasLength(FieldDescriptorProto.Type.values().length);
    for (FieldDescriptor.Type type : FieldDescriptor.Type.values()) {
      FieldDescriptorProto.Type protoType = type.toProto();
      assertThat(protoType.name()).isEqualTo("TYPE_" + type.name());
      assertThat(FieldDescriptor.Type.valueOf(protoType)).isEqualTo(type);
    }

            

Reported by PMD.

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

Line: 86

              
  @Test
  public void testFieldTypeEnumMapping() throws Exception {
    assertThat(FieldDescriptor.Type.values()).hasLength(FieldDescriptorProto.Type.values().length);
    for (FieldDescriptor.Type type : FieldDescriptor.Type.values()) {
      FieldDescriptorProto.Type protoType = type.toProto();
      assertThat(protoType.name()).isEqualTo("TYPE_" + type.name());
      assertThat(FieldDescriptor.Type.valueOf(protoType)).isEqualTo(type);
    }

            

Reported by PMD.

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

Line: 87

                @Test
  public void testFieldTypeEnumMapping() throws Exception {
    assertThat(FieldDescriptor.Type.values()).hasLength(FieldDescriptorProto.Type.values().length);
    for (FieldDescriptor.Type type : FieldDescriptor.Type.values()) {
      FieldDescriptorProto.Type protoType = type.toProto();
      assertThat(protoType.name()).isEqualTo("TYPE_" + type.name());
      assertThat(FieldDescriptor.Type.valueOf(protoType)).isEqualTo(type);
    }
  }

            

Reported by PMD.

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

Line: 89

                  assertThat(FieldDescriptor.Type.values()).hasLength(FieldDescriptorProto.Type.values().length);
    for (FieldDescriptor.Type type : FieldDescriptor.Type.values()) {
      FieldDescriptorProto.Type protoType = type.toProto();
      assertThat(protoType.name()).isEqualTo("TYPE_" + type.name());
      assertThat(FieldDescriptor.Type.valueOf(protoType)).isEqualTo(type);
    }
  }

  @Test

            

Reported by PMD.

python/google/protobuf/internal/test_util.py
617 issues
No name 'unittest_import_pb2' in module 'google.protobuf'
Error

Line: 43 Column: 1

              import operator
import os.path

from google.protobuf import unittest_import_pb2
from google.protobuf import unittest_pb2

try:
  long        # Python 2
except NameError:

            

Reported by Pylint.

No name 'unittest_pb2' in module 'google.protobuf'
Error

Line: 44 Column: 1

              import os.path

from google.protobuf import unittest_import_pb2
from google.protobuf import unittest_pb2

try:
  long        # Python 2
except NameError:
  long = int  # Python 3

            

Reported by Pylint.

Module 'operator' has no 'div' member
Error

Line: 754 Column: 31

                  return NonStandardInteger(operator.add(self.val, y))

  def __div__(self, y):
    return NonStandardInteger(operator.div(self.val, y))

  def __eq__(self, y):
    return operator.eq(self.val, y)

  def __floordiv__(self, y):

            

Reported by Pylint.

Module 'operator' has no 'div' member
Error

Line: 790 Column: 31

                  return NonStandardInteger(operator.add(y, self.val))

  def __rdiv__(self, y):
    return NonStandardInteger(operator.div(y, self.val))

  def __rmod__(self, y):
    return NonStandardInteger(operator.mod(y, self.val))

  def __rmul__(self, y):

            

Reported by Pylint.

Signature differs from overridden '__pow__' method
Error

Line: 780 Column: 3

                def __pos__(self):
    return NonStandardInteger(operator.pos(self.val))

  def __pow__(self, y):
    return NonStandardInteger(operator.pow(self.val, y))

  def __trunc__(self):
    return int(self.val)


            

Reported by Pylint.

Signature differs from overridden '__round__' method
Error

Line: 864 Column: 3

                    raise RuntimeError(self.error_string_on_conversion)
    return int(self.val)

  def __round__(self):
    return self

  def __repr__(self):
    return 'NonStandardInteger(%s)' % self.val

            

Reported by Pylint.

Bad indentation. Found 2 spaces, expected 4
Style

Line: 47 Column: 1

              from google.protobuf import unittest_pb2

try:
  long        # Python 2
except NameError:
  long = int  # Python 3


# Tests whether the given TestAllTypes message is proto2 or not.

            

Reported by Pylint.

Bad indentation. Found 2 spaces, expected 4
Style

Line: 49 Column: 1

              try:
  long        # Python 2
except NameError:
  long = int  # Python 3


# Tests whether the given TestAllTypes message is proto2 or not.
# This is used to gate several fields/features that only exist
# for the proto2 version of the message.

            

Reported by Pylint.

Class name "long" doesn't conform to PascalCase naming style
Error

Line: 49 Column: 3

              try:
  long        # Python 2
except NameError:
  long = int  # Python 3


# Tests whether the given TestAllTypes message is proto2 or not.
# This is used to gate several fields/features that only exist
# for the proto2 version of the message.

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 55 Column: 1

              # Tests whether the given TestAllTypes message is proto2 or not.
# This is used to gate several fields/features that only exist
# for the proto2 version of the message.
def IsProto2(message):
  return message.DESCRIPTOR.syntax == "proto2"


def SetAllNonLazyFields(message):
  """Sets every non-lazy field in the message to a unique value.

            

Reported by Pylint.

python/google/protobuf/descriptor.py
600 issues
No name '_message' in module 'google.protobuf.pyext'
Error

Line: 48 Column: 3

                # Used by MakeDescriptor in cpp mode
  import binascii
  import os
  from google.protobuf.pyext import _message
  _USE_C_DESCRIPTORS = True


class Error(Exception):
  """Base error for this module."""

            

Reported by Pylint.

No name 'descriptor_pb2' in module 'google.protobuf'
Error

Line: 167 Column: 5

                  if self._options:
      return self._options

    from google.protobuf import descriptor_pb2
    try:
      options_class = getattr(descriptor_pb2,
                              self._options_class_name)
    except AttributeError:
      raise RuntimeError('Unknown options class name %s!' %

            

Reported by Pylint.

No name 'descriptor_pb2' in module 'google.protobuf'
Error

Line: 927 Column: 7

                      arguments.
    """
    if self.containing_service is not None:
      from google.protobuf import descriptor_pb2
      service_proto = descriptor_pb2.ServiceDescriptorProto()
      self.containing_service.CopyToProto(service_proto)
      proto.CopyFrom(service_proto.method[self.index])
    else:
      raise Error('Descriptor does not contain a service.')

            

Reported by Pylint.

Bad option value 'g-explicit-bool-comparison'
Error

Line: 975 Column: 1

                              syntax=None, pool=None, create_key=None):
      # FileDescriptor() is called from various places, not only from generated
      # files, to register dynamic proto files and messages.
      # pylint: disable=g-explicit-bool-comparison
      if serialized_pb == b'':
        # Cpp generated code must be linked in if serialized_pb is ''
        try:
          return _message.default_pool.FindFileByName(name)
        except KeyError:

            

Reported by Pylint.

Super of 'FileDescriptor' has no '__new__' member
Error

Line: 985 Column: 16

                    elif serialized_pb:
        return _message.default_pool.AddSerializedFile(serialized_pb)
      else:
        return super(FileDescriptor, cls).__new__(cls)

  def __init__(self, name, package, options=None,
               serialized_options=None, serialized_pb=None,
               dependencies=None, public_dependencies=None,
               syntax=None, pool=None, create_key=None):

            

Reported by Pylint.

No name 'descriptor_pb2' in module 'google.protobuf'
Error

Line: 1102 Column: 5

                  # definition in the C++ descriptor pool. To do this, we build a
    # FileDescriptorProto with the same definition as this descriptor and build
    # it into the pool.
    from google.protobuf import descriptor_pb2
    file_descriptor_proto = descriptor_pb2.FileDescriptorProto()
    file_descriptor_proto.message_type.add().MergeFrom(desc_proto)

    # Generate a random name for this proto file to prevent conflicts with any
    # imported ones. We need to specify a file name so the descriptor pool

            

Reported by Pylint.

Consider explicitly re-raising using the 'from' keyword
Error

Line: 172 Column: 7

                    options_class = getattr(descriptor_pb2,
                              self._options_class_name)
    except AttributeError:
      raise RuntimeError('Unknown options class name %s!' %
                         (self._options_class_name))

    with _lock:
      if self._serialized_options is None:
        self._options = options_class()

            

Reported by Pylint.

TODO(falk): Add function to calculate full_name instead of having it in
Error

Line: 214 Column: 3

                      options, serialized_options, options_class_name)

    self.name = name
    # TODO(falk): Add function to calculate full_name instead of having it in
    #             memory?
    self.full_name = full_name
    self.file = file
    self.containing_type = containing_type


            

Reported by Pylint.

Unused argument 'name'
Error

Line: 292 Column: 9

              
    def __new__(
        cls,
        name=None,
        full_name=None,
        filename=None,
        containing_type=None,
        fields=None,
        nested_types=None,

            

Reported by Pylint.

Unused argument 'filename'
Error

Line: 294 Column: 9

                      cls,
        name=None,
        full_name=None,
        filename=None,
        containing_type=None,
        fields=None,
        nested_types=None,
        enum_types=None,
        extensions=None,

            

Reported by Pylint.

python/google/protobuf/descriptor_pool.py
587 issues
Bad option value 'g-import-not-at-top'
Error

Line: 212 Column: 1

                      :class:`FileDescriptorProto` to add.
    """

    # pylint: disable=g-import-not-at-top
    from google.protobuf import descriptor_pb2
    file_desc_proto = descriptor_pb2.FileDescriptorProto.FromString(
        serialized_file_desc_proto)
    self.Add(file_desc_proto)


            

Reported by Pylint.

No name 'descriptor_pb2' in module 'google.protobuf'
Error

Line: 213 Column: 5

                  """

    # pylint: disable=g-import-not-at-top
    from google.protobuf import descriptor_pb2
    file_desc_proto = descriptor_pb2.FileDescriptorProto.FromString(
        serialized_file_desc_proto)
    self.Add(file_desc_proto)

  # Add Descriptor to descriptor pool is dreprecated. Please use Add()

            

Reported by Pylint.

Bad option value 'g-complex-comprehension'
Error

Line: 867 Column: 1

                                                is_extension=True)
        for index, extension in enumerate(desc_proto.extension)]
    oneofs = [
        # pylint: disable=g-complex-comprehension
        descriptor.OneofDescriptor(desc.name, '.'.join((desc_name, desc.name)),
                                   index, None, [], desc.options,
                                   # pylint: disable=protected-access
                                   create_key=descriptor._internal_create_key)
        for index, desc in enumerate(desc_proto.oneof_decl)]

            

Reported by Pylint.

TODO(jieluo): Remove _file_desc_by_toplevel_extension after
Error

Line: 147 Column: 3

                  self._service_descriptors = {}
    self._file_descriptors = {}
    self._toplevel_extensions = {}
    # TODO(jieluo): Remove _file_desc_by_toplevel_extension after
    # maybe year 2020 for compatibility issue (with 3.4.1 only).
    self._file_desc_by_toplevel_extension = {}
    self._top_enum_values = {}
    # We store extensions in two two-level mappings: The first key is the
    # descriptor of the message being extended, the second key is the extension

            

Reported by Pylint.

TODO(jieluo): This is a temporary solution for FieldDescriptor.file.
Error

Line: 370 Column: 3

                  """

    self._AddFileDescriptor(file_desc)
    # TODO(jieluo): This is a temporary solution for FieldDescriptor.file.
    # FieldDescriptor.file is added in code gen. Remove this solution after
    # maybe 2020 for compatibility reason (with 3.4.1 only).
    for extension in file_desc.extensions_by_name.values():
      self._file_desc_by_toplevel_extension[
          extension.full_name] = file_desc

            

Reported by Pylint.

Consider explicitly re-raising using the 'from' keyword
Error

Line: 445 Column: 7

                    self._FindFileContainingSymbolInDb(symbol)
      return self._InternalFindFileContainingSymbol(symbol)
    except KeyError:
      raise KeyError('Cannot find a file containing %s' % symbol)

  def _InternalFindFileContainingSymbol(self, symbol):
    """Gets the already built FileDescriptor containing the specified symbol.

    Args:

            

Reported by Pylint.

Consider explicitly re-raising using the 'from' keyword
Error

Line: 494 Column: 7

                            sub_name in message.enum_values_by_name)
      return message.file
    except (KeyError, AssertionError):
      raise KeyError('Cannot find a file containing %s' % symbol)

  def FindMessageTypeByName(self, full_name):
    """Loads the named descriptor from the pool.

    Args:

            

Reported by Pylint.

No exception type(s) specified
Error

Line: 666 Column: 5

              
    try:
      self._ConvertFileProtoToFileDescriptor(file_proto)
    except:
      warn_msg = ('Unable to load proto file %s for extension number %d.' %
                  (file_proto.name, number))
      warnings.warn(warn_msg, RuntimeWarning)

  def FindServiceByName(self, full_name):

            

Reported by Pylint.

TODO(amauryfa): This pool could be constructed from Python code, when we
Error

Line: 1262 Column: 3

              

if _USE_C_DESCRIPTORS:
  # TODO(amauryfa): This pool could be constructed from Python code, when we
  # support a flag like 'use_cpp_generated_pool=True'.
  # pylint: disable=protected-access
  _DEFAULT = descriptor._message.default_pool
else:
  _DEFAULT = DescriptorPool()

            

Reported by Pylint.

Too many lines in module (1271/1000)
Error

Line: 1 Column: 1

              # Protocol Buffers - Google's data interchange format
# Copyright 2008 Google Inc.  All rights reserved.
# https://developers.google.com/protocol-buffers/
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
#     * Redistributions of source code must retain the above copyright

            

Reported by Pylint.