The following issues were found

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

Line: 54

                }

  @Test
  public void mergeOptionalMessageFields() throws Exception {
    Proto2Message message1 =
        newBuilder()
            .setFieldMessage10(newBuilder().setFieldInt643(123).clearFieldInt325().build())
            .build();
    Proto2Message message2 =

            

Reported by PMD.

A method/constructor should not explicitly throw java.lang.Exception
Design

Line: 54

                }

  @Test
  public void mergeOptionalMessageFields() throws Exception {
    Proto2Message message1 =
        newBuilder()
            .setFieldMessage10(newBuilder().setFieldInt643(123).clearFieldInt325().build())
            .build();
    Proto2Message message2 =

            

Reported by PMD.

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

Line: 68

                          .setFieldMessage10(newBuilder().setFieldInt643(789).clearFieldInt325().build())
            .build();
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    message1.writeTo(output);
    message2.writeTo(output);
    message3.writeTo(output);
    byte[] data = output.toByteArray();

    Proto2Message merged = ExperimentalSerializationUtil.fromByteArray(data, Proto2Message.class);

            

Reported by PMD.

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

Line: 69

                          .build();
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    message1.writeTo(output);
    message2.writeTo(output);
    message3.writeTo(output);
    byte[] data = output.toByteArray();

    Proto2Message merged = ExperimentalSerializationUtil.fromByteArray(data, Proto2Message.class);
    assertThat(merged.getFieldMessage10().getFieldInt643()).isEqualTo(789);

            

Reported by PMD.

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

Line: 70

                  ByteArrayOutputStream output = new ByteArrayOutputStream();
    message1.writeTo(output);
    message2.writeTo(output);
    message3.writeTo(output);
    byte[] data = output.toByteArray();

    Proto2Message merged = ExperimentalSerializationUtil.fromByteArray(data, Proto2Message.class);
    assertThat(merged.getFieldMessage10().getFieldInt643()).isEqualTo(789);
    assertThat(merged.getFieldMessage10().getFieldInt325()).isEqualTo(456);

            

Reported by PMD.

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

Line: 74

                  byte[] data = output.toByteArray();

    Proto2Message merged = ExperimentalSerializationUtil.fromByteArray(data, Proto2Message.class);
    assertThat(merged.getFieldMessage10().getFieldInt643()).isEqualTo(789);
    assertThat(merged.getFieldMessage10().getFieldInt325()).isEqualTo(456);
  }

  @Test
  public void oneofFieldsShouldRoundtrip() throws IOException {

            

Reported by PMD.

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

Line: 74

                  byte[] data = output.toByteArray();

    Proto2Message merged = ExperimentalSerializationUtil.fromByteArray(data, Proto2Message.class);
    assertThat(merged.getFieldMessage10().getFieldInt643()).isEqualTo(789);
    assertThat(merged.getFieldMessage10().getFieldInt325()).isEqualTo(456);
  }

  @Test
  public void oneofFieldsShouldRoundtrip() throws IOException {

            

Reported by PMD.

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

Line: 74

                  byte[] data = output.toByteArray();

    Proto2Message merged = ExperimentalSerializationUtil.fromByteArray(data, Proto2Message.class);
    assertThat(merged.getFieldMessage10().getFieldInt643()).isEqualTo(789);
    assertThat(merged.getFieldMessage10().getFieldInt325()).isEqualTo(456);
  }

  @Test
  public void oneofFieldsShouldRoundtrip() throws IOException {

            

Reported by PMD.

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

Line: 75

              
    Proto2Message merged = ExperimentalSerializationUtil.fromByteArray(data, Proto2Message.class);
    assertThat(merged.getFieldMessage10().getFieldInt643()).isEqualTo(789);
    assertThat(merged.getFieldMessage10().getFieldInt325()).isEqualTo(456);
  }

  @Test
  public void oneofFieldsShouldRoundtrip() throws IOException {
    roundtrip("Field 53", newBuilder().setFieldDouble53(100).build());

            

Reported by PMD.

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

Line: 75

              
    Proto2Message merged = ExperimentalSerializationUtil.fromByteArray(data, Proto2Message.class);
    assertThat(merged.getFieldMessage10().getFieldInt643()).isEqualTo(789);
    assertThat(merged.getFieldMessage10().getFieldInt325()).isEqualTo(456);
  }

  @Test
  public void oneofFieldsShouldRoundtrip() throws IOException {
    roundtrip("Field 53", newBuilder().setFieldDouble53(100).build());

            

Reported by PMD.

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

Line: 64

                public void setUp() throws Exception {
    classUnderTest = "RopeByteString";
    referenceBytes = ByteStringTest.getTestBytes(22341, 22337766L);
    Iterator<ByteString> iter = ByteStringTest.makeConcretePieces(referenceBytes).iterator();
    stringUnderTest = iter.next();
    while (iter.hasNext()) {
      stringUnderTest = stringUnderTest.concat(iter.next());
    }
    expectedHashCode = -1214197238;

            

Reported by PMD.

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

Line: 73

                }

  @Test
  public void testMinLength() {
    // minLength should match the Fibonacci sequence
    int a = 1;
    int b = 1;
    int i;
    for (i = 0; a > 0; i++) {

            

Reported by PMD.

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

Line: 79

                  int b = 1;
    int i;
    for (i = 0; a > 0; i++) {
      assertThat(a).isEqualTo(RopeByteString.minLength(i));
      int c = a + b;
      a = b;
      b = c;
    }
    assertThat(RopeByteString.minLength(i)).isEqualTo(Integer.MAX_VALUE);

            

Reported by PMD.

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

Line: 84

                    a = b;
      b = c;
    }
    assertThat(RopeByteString.minLength(i)).isEqualTo(Integer.MAX_VALUE);
    assertThat(RopeByteString.minLength(i + 1)).isEqualTo(Integer.MAX_VALUE);
    assertThat(RopeByteString.minLengthByDepth).hasLength(i + 1);
  }

  @Override

            

Reported by PMD.

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

Line: 85

                    b = c;
    }
    assertThat(RopeByteString.minLength(i)).isEqualTo(Integer.MAX_VALUE);
    assertThat(RopeByteString.minLength(i + 1)).isEqualTo(Integer.MAX_VALUE);
    assertThat(RopeByteString.minLengthByDepth).hasLength(i + 1);
  }

  @Override
  @Test

            

Reported by PMD.

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

Line: 86

                  }
    assertThat(RopeByteString.minLength(i)).isEqualTo(Integer.MAX_VALUE);
    assertThat(RopeByteString.minLength(i + 1)).isEqualTo(Integer.MAX_VALUE);
    assertThat(RopeByteString.minLengthByDepth).hasLength(i + 1);
  }

  @Override
  @Test
  public void testGetTreeDepth() {

            

Reported by PMD.

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

Line: 92

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

  @Test

            

Reported by PMD.

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

Line: 92

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

  @Test

            

Reported by PMD.

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

Line: 98

                }

  @Test
  public void testBalance() {
    int numberOfPieces = 10000;
    int pieceSize = 64;
    byte[] testBytes = ByteStringTest.getTestBytes(numberOfPieces * pieceSize, 113377L);

    // Build up a big ByteString from smaller pieces to force a rebalance

            

Reported by PMD.

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

Line: 109

                    concatenated = concatenated.concat(ByteString.copyFrom(testBytes, i * pieceSize, pieceSize));
    }

    assertWithMessage("%s from string must have the expected type", classUnderTest)
        .that(classUnderTest)
        .isEqualTo(getActualClassName(concatenated));
    assertWithMessage("%s underlying bytes must match after balancing", classUnderTest)
        .that(Arrays.equals(testBytes, concatenated.toByteArray()))
        .isTrue();

            

Reported by PMD.

python/google/protobuf/internal/testing_refleaks.py
67 issues
Module 'sys' has no 'gettotalrefcount' member
Error

Line: 111 Column: 12

                  gc.collect()
    gc.collect()
    gc.collect()
    return sys.gettotalrefcount()


if hasattr(sys, 'gettotalrefcount'):

  def TestCase(test_class):

            

Reported by Pylint.

Bad indentation. Found 2 spaces, expected 4
Style

Line: 45 Column: 1

              import sys

try:
  import copy_reg as copyreg  #PY26
except ImportError:
  import copyreg

try:
  import unittest2 as unittest  #PY26

            

Reported by Pylint.

Bad indentation. Found 2 spaces, expected 4
Style

Line: 47 Column: 1

              try:
  import copy_reg as copyreg  #PY26
except ImportError:
  import copyreg

try:
  import unittest2 as unittest  #PY26
except ImportError:
  import unittest

            

Reported by Pylint.

Bad indentation. Found 2 spaces, expected 4
Style

Line: 50 Column: 1

                import copyreg

try:
  import unittest2 as unittest  #PY26
except ImportError:
  import unittest


class LocalTestResult(unittest.TestResult):

            

Reported by Pylint.

Bad indentation. Found 2 spaces, expected 4
Style

Line: 52 Column: 1

              try:
  import unittest2 as unittest  #PY26
except ImportError:
  import unittest


class LocalTestResult(unittest.TestResult):
  """A TestResult which forwards events to a parent object, except for Skips."""


            

Reported by Pylint.

Bad indentation. Found 2 spaces, expected 4
Style

Line: 56 Column: 1

              

class LocalTestResult(unittest.TestResult):
  """A TestResult which forwards events to a parent object, except for Skips."""

  def __init__(self, parent_result):
    unittest.TestResult.__init__(self)
    self.parent_result = parent_result


            

Reported by Pylint.

Bad indentation. Found 2 spaces, expected 4
Style

Line: 58 Column: 1

              class LocalTestResult(unittest.TestResult):
  """A TestResult which forwards events to a parent object, except for Skips."""

  def __init__(self, parent_result):
    unittest.TestResult.__init__(self)
    self.parent_result = parent_result

  def addError(self, test, error):
    self.parent_result.addError(test, error)

            

Reported by Pylint.

Bad indentation. Found 4 spaces, expected 8
Style

Line: 59 Column: 1

                """A TestResult which forwards events to a parent object, except for Skips."""

  def __init__(self, parent_result):
    unittest.TestResult.__init__(self)
    self.parent_result = parent_result

  def addError(self, test, error):
    self.parent_result.addError(test, error)


            

Reported by Pylint.

Bad indentation. Found 4 spaces, expected 8
Style

Line: 60 Column: 1

              
  def __init__(self, parent_result):
    unittest.TestResult.__init__(self)
    self.parent_result = parent_result

  def addError(self, test, error):
    self.parent_result.addError(test, error)

  def addFailure(self, test, error):

            

Reported by Pylint.

Bad indentation. Found 2 spaces, expected 4
Style

Line: 62 Column: 1

                  unittest.TestResult.__init__(self)
    self.parent_result = parent_result

  def addError(self, test, error):
    self.parent_result.addError(test, error)

  def addFailure(self, test, error):
    self.parent_result.addFailure(test, error)


            

Reported by Pylint.

python/google/protobuf/internal/keywords_test.py
65 issues
No name 'more_messages_pb2' in module 'google.protobuf.internal'
Error

Line: 38 Column: 1

              import unittest


from google.protobuf.internal import more_messages_pb2
from google.protobuf import descriptor_pool


class KeywordsConflictTest(unittest.TestCase):


            

Reported by Pylint.

Missing class docstring
Error

Line: 42 Column: 1

              from google.protobuf import descriptor_pool


class KeywordsConflictTest(unittest.TestCase):

  def setUp(self):
    super(KeywordsConflictTest, self).setUp()
    self.pool = descriptor_pool.Default()


            

Reported by Pylint.

Bad indentation. Found 2 spaces, expected 4
Style

Line: 44 Column: 1

              
class KeywordsConflictTest(unittest.TestCase):

  def setUp(self):
    super(KeywordsConflictTest, self).setUp()
    self.pool = descriptor_pool.Default()

  def testMessage(self):
    message = getattr(more_messages_pb2, 'class')()

            

Reported by Pylint.

Bad indentation. Found 4 spaces, expected 8
Style

Line: 45 Column: 1

              class KeywordsConflictTest(unittest.TestCase):

  def setUp(self):
    super(KeywordsConflictTest, self).setUp()
    self.pool = descriptor_pool.Default()

  def testMessage(self):
    message = getattr(more_messages_pb2, 'class')()
    message.int_field = 123

            

Reported by Pylint.

Consider using Python 3 style super() without arguments
Error

Line: 45 Column: 5

              class KeywordsConflictTest(unittest.TestCase):

  def setUp(self):
    super(KeywordsConflictTest, self).setUp()
    self.pool = descriptor_pool.Default()

  def testMessage(self):
    message = getattr(more_messages_pb2, 'class')()
    message.int_field = 123

            

Reported by Pylint.

Bad indentation. Found 4 spaces, expected 8
Style

Line: 46 Column: 1

              
  def setUp(self):
    super(KeywordsConflictTest, self).setUp()
    self.pool = descriptor_pool.Default()

  def testMessage(self):
    message = getattr(more_messages_pb2, 'class')()
    message.int_field = 123
    self.assertEqual(message.int_field, 123)

            

Reported by Pylint.

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

Line: 48 Column: 3

                  super(KeywordsConflictTest, self).setUp()
    self.pool = descriptor_pool.Default()

  def testMessage(self):
    message = getattr(more_messages_pb2, 'class')()
    message.int_field = 123
    self.assertEqual(message.int_field, 123)
    des = self.pool.FindMessageTypeByName('google.protobuf.internal.class')
    self.assertEqual(des.name, 'class')

            

Reported by Pylint.

Bad indentation. Found 2 spaces, expected 4
Style

Line: 48 Column: 1

                  super(KeywordsConflictTest, self).setUp()
    self.pool = descriptor_pool.Default()

  def testMessage(self):
    message = getattr(more_messages_pb2, 'class')()
    message.int_field = 123
    self.assertEqual(message.int_field, 123)
    des = self.pool.FindMessageTypeByName('google.protobuf.internal.class')
    self.assertEqual(des.name, 'class')

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 48 Column: 3

                  super(KeywordsConflictTest, self).setUp()
    self.pool = descriptor_pool.Default()

  def testMessage(self):
    message = getattr(more_messages_pb2, 'class')()
    message.int_field = 123
    self.assertEqual(message.int_field, 123)
    des = self.pool.FindMessageTypeByName('google.protobuf.internal.class')
    self.assertEqual(des.name, 'class')

            

Reported by Pylint.

Bad indentation. Found 4 spaces, expected 8
Style

Line: 49 Column: 1

                  self.pool = descriptor_pool.Default()

  def testMessage(self):
    message = getattr(more_messages_pb2, 'class')()
    message.int_field = 123
    self.assertEqual(message.int_field, 123)
    des = self.pool.FindMessageTypeByName('google.protobuf.internal.class')
    self.assertEqual(des.name, 'class')


            

Reported by Pylint.

python/google/protobuf/internal/symbol_database_test.py
65 issues
No name 'unittest_pb2' in module 'google.protobuf'
Error

Line: 40 Column: 1

              except ImportError:
  import unittest

from google.protobuf import unittest_pb2
from google.protobuf import descriptor
from google.protobuf import descriptor_pool
from google.protobuf import symbol_database



            

Reported by Pylint.

Access to a protected member _USE_C_DESCRIPTORS of a client class
Error

Line: 49 Column: 8

              class SymbolDatabaseTest(unittest.TestCase):

  def _Database(self):
    if descriptor._USE_C_DESCRIPTORS:
      # The C++ implementation does not allow mixing descriptors from
      # different pools.
      db = symbol_database.SymbolDatabase(pool=descriptor_pool.Default())
    else:
      db = symbol_database.SymbolDatabase()

            

Reported by Pylint.

Access to a protected member _TESTSERVICE of a client class
Error

Line: 63 Column: 34

                  db.RegisterMessage(unittest_pb2.TestAllTypes.RepeatedGroup)
    db.RegisterEnumDescriptor(unittest_pb2.ForeignEnum.DESCRIPTOR)
    db.RegisterEnumDescriptor(unittest_pb2.TestAllTypes.NestedEnum.DESCRIPTOR)
    db.RegisterServiceDescriptor(unittest_pb2._TESTSERVICE)
    return db

  def testGetPrototype(self):
    instance = self._Database().GetPrototype(
        unittest_pb2.TestAllTypes.DESCRIPTOR)

            

Reported by Pylint.

Bad indentation. Found 2 spaces, expected 4
Style

Line: 36 Column: 1

              """Tests for google.protobuf.symbol_database."""

try:
  import unittest2 as unittest  #PY26
except ImportError:
  import unittest

from google.protobuf import unittest_pb2
from google.protobuf import descriptor

            

Reported by Pylint.

Bad indentation. Found 2 spaces, expected 4
Style

Line: 38 Column: 1

              try:
  import unittest2 as unittest  #PY26
except ImportError:
  import unittest

from google.protobuf import unittest_pb2
from google.protobuf import descriptor
from google.protobuf import descriptor_pool
from google.protobuf import symbol_database

            

Reported by Pylint.

Missing class docstring
Error

Line: 46 Column: 1

              from google.protobuf import symbol_database


class SymbolDatabaseTest(unittest.TestCase):

  def _Database(self):
    if descriptor._USE_C_DESCRIPTORS:
      # The C++ implementation does not allow mixing descriptors from
      # different pools.

            

Reported by Pylint.

Bad indentation. Found 2 spaces, expected 4
Style

Line: 48 Column: 1

              
class SymbolDatabaseTest(unittest.TestCase):

  def _Database(self):
    if descriptor._USE_C_DESCRIPTORS:
      # The C++ implementation does not allow mixing descriptors from
      # different pools.
      db = symbol_database.SymbolDatabase(pool=descriptor_pool.Default())
    else:

            

Reported by Pylint.

Method could be a function
Error

Line: 48 Column: 3

              
class SymbolDatabaseTest(unittest.TestCase):

  def _Database(self):
    if descriptor._USE_C_DESCRIPTORS:
      # The C++ implementation does not allow mixing descriptors from
      # different pools.
      db = symbol_database.SymbolDatabase(pool=descriptor_pool.Default())
    else:

            

Reported by Pylint.

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

Line: 48 Column: 3

              
class SymbolDatabaseTest(unittest.TestCase):

  def _Database(self):
    if descriptor._USE_C_DESCRIPTORS:
      # The C++ implementation does not allow mixing descriptors from
      # different pools.
      db = symbol_database.SymbolDatabase(pool=descriptor_pool.Default())
    else:

            

Reported by Pylint.

Bad indentation. Found 4 spaces, expected 8
Style

Line: 49 Column: 1

              class SymbolDatabaseTest(unittest.TestCase):

  def _Database(self):
    if descriptor._USE_C_DESCRIPTORS:
      # The C++ implementation does not allow mixing descriptors from
      # different pools.
      db = symbol_database.SymbolDatabase(pool=descriptor_pool.Default())
    else:
      db = symbol_database.SymbolDatabase()

            

Reported by Pylint.

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

Line: 48

              public class AnyTest {

  @Test
  public void testAnyGeneratedApi() throws Exception {
    TestAllTypes.Builder builder = TestAllTypes.newBuilder();
    TestUtil.setAllFields(builder);
    TestAllTypes message = builder.build();

    TestAny container = TestAny.newBuilder().setValue(Any.pack(message)).build();

            

Reported by PMD.

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

Line: 55

              
    TestAny container = TestAny.newBuilder().setValue(Any.pack(message)).build();

    assertThat(container.getValue().is(TestAllTypes.class)).isTrue();
    assertThat(container.getValue().is(TestAny.class)).isFalse();

    TestAllTypes result = container.getValue().unpack(TestAllTypes.class);
    TestUtil.assertAllFieldsSet(result);


            

Reported by PMD.

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

Line: 55

              
    TestAny container = TestAny.newBuilder().setValue(Any.pack(message)).build();

    assertThat(container.getValue().is(TestAllTypes.class)).isTrue();
    assertThat(container.getValue().is(TestAny.class)).isFalse();

    TestAllTypes result = container.getValue().unpack(TestAllTypes.class);
    TestUtil.assertAllFieldsSet(result);


            

Reported by PMD.

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

Line: 55

              
    TestAny container = TestAny.newBuilder().setValue(Any.pack(message)).build();

    assertThat(container.getValue().is(TestAllTypes.class)).isTrue();
    assertThat(container.getValue().is(TestAny.class)).isFalse();

    TestAllTypes result = container.getValue().unpack(TestAllTypes.class);
    TestUtil.assertAllFieldsSet(result);


            

Reported by PMD.

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

Line: 56

                  TestAny container = TestAny.newBuilder().setValue(Any.pack(message)).build();

    assertThat(container.getValue().is(TestAllTypes.class)).isTrue();
    assertThat(container.getValue().is(TestAny.class)).isFalse();

    TestAllTypes result = container.getValue().unpack(TestAllTypes.class);
    TestUtil.assertAllFieldsSet(result);



            

Reported by PMD.

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

Line: 56

                  TestAny container = TestAny.newBuilder().setValue(Any.pack(message)).build();

    assertThat(container.getValue().is(TestAllTypes.class)).isTrue();
    assertThat(container.getValue().is(TestAny.class)).isFalse();

    TestAllTypes result = container.getValue().unpack(TestAllTypes.class);
    TestUtil.assertAllFieldsSet(result);



            

Reported by PMD.

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

Line: 56

                  TestAny container = TestAny.newBuilder().setValue(Any.pack(message)).build();

    assertThat(container.getValue().is(TestAllTypes.class)).isTrue();
    assertThat(container.getValue().is(TestAny.class)).isFalse();

    TestAllTypes result = container.getValue().unpack(TestAllTypes.class);
    TestUtil.assertAllFieldsSet(result);



            

Reported by PMD.

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

Line: 58

                  assertThat(container.getValue().is(TestAllTypes.class)).isTrue();
    assertThat(container.getValue().is(TestAny.class)).isFalse();

    TestAllTypes result = container.getValue().unpack(TestAllTypes.class);
    TestUtil.assertAllFieldsSet(result);


    // Unpacking to a wrong type will throw an exception.
    try {

            

Reported by PMD.

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

Line: 58

                  assertThat(container.getValue().is(TestAllTypes.class)).isTrue();
    assertThat(container.getValue().is(TestAny.class)).isFalse();

    TestAllTypes result = container.getValue().unpack(TestAllTypes.class);
    TestUtil.assertAllFieldsSet(result);


    // Unpacking to a wrong type will throw an exception.
    try {

            

Reported by PMD.

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

Line: 64

              
    // Unpacking to a wrong type will throw an exception.
    try {
      container.getValue().unpack(TestAny.class);
      assertWithMessage("Exception is expected.").fail();
    } catch (InvalidProtocolBufferException e) {
      // expected.
    }


            

Reported by PMD.

java/core/src/main/java/com/google/protobuf/UnsafeUtil.java
62 issues
This class has a bunch of public methods and attributes
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 java.lang.reflect.Field;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;

            

Reported by PMD.

The class 'UnsafeUtil' has a total cyclomatic complexity of 103 (highest 15).
Design

Line: 43

              import java.util.logging.Logger;

/** Utility class for working with unsafe operations. */
final class UnsafeUtil {
  private static final sun.misc.Unsafe UNSAFE = getUnsafe();
  private static final Class<?> MEMORY_CLASS = Android.getMemoryClass();
  private static final boolean IS_ANDROID_64 = determineAndroidSupportByAddressSize(long.class);
  private static final boolean IS_ANDROID_32 = determineAndroidSupportByAddressSize(int.class);
  private static final MemoryAccessor MEMORY_ACCESSOR = getMemoryAccessor();

            

Reported by PMD.

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

Line: 43

              import java.util.logging.Logger;

/** Utility class for working with unsafe operations. */
final class UnsafeUtil {
  private static final sun.misc.Unsafe UNSAFE = getUnsafe();
  private static final Class<?> MEMORY_CLASS = Android.getMemoryClass();
  private static final boolean IS_ANDROID_64 = determineAndroidSupportByAddressSize(long.class);
  private static final boolean IS_ANDROID_32 = determineAndroidSupportByAddressSize(int.class);
  private static final MemoryAccessor MEMORY_ACCESSOR = getMemoryAccessor();

            

Reported by PMD.

Use equals() to compare object references.
Error

Line: 82

                private static final int BYTE_ARRAY_ALIGNMENT =
      (int) (BYTE_ARRAY_BASE_OFFSET & STRIDE_ALIGNMENT_MASK);

  static final boolean IS_BIG_ENDIAN = ByteOrder.nativeOrder() == ByteOrder.BIG_ENDIAN;

  private UnsafeUtil() {}

  static boolean hasUnsafeArrayOperations() {
    return HAS_UNSAFE_ARRAY_OPERATIONS;

            

Reported by PMD.

A catch statement should never catch throwable since it includes errors.
Error

Line: 310

                                return null;
                }
              });
    } catch (Throwable e) {
      // Catching Throwable here due to the fact that Google AppEngine raises NoClassDefFoundError
      // for Unsafe.
    }
    return unsafe;
  }

            

Reported by PMD.

Avoid empty catch blocks
Error

Line: 310

                                return null;
                }
              });
    } catch (Throwable e) {
      // Catching Throwable here due to the fact that Google AppEngine raises NoClassDefFoundError
      // for Unsafe.
    }
    return unsafe;
  }

            

Reported by PMD.

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

Line: 355

                  }
    try {
      Class<?> clazz = MEMORY_CLASS;
      clazz.getMethod("peekLong", addressClass, boolean.class);
      clazz.getMethod("pokeLong", addressClass, long.class, boolean.class);
      clazz.getMethod("pokeInt", addressClass, int.class, boolean.class);
      clazz.getMethod("peekInt", addressClass, boolean.class);
      clazz.getMethod("pokeByte", addressClass, byte.class);
      clazz.getMethod("peekByte", addressClass);

            

Reported by PMD.

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

Line: 356

                  try {
      Class<?> clazz = MEMORY_CLASS;
      clazz.getMethod("peekLong", addressClass, boolean.class);
      clazz.getMethod("pokeLong", addressClass, long.class, boolean.class);
      clazz.getMethod("pokeInt", addressClass, int.class, boolean.class);
      clazz.getMethod("peekInt", addressClass, boolean.class);
      clazz.getMethod("pokeByte", addressClass, byte.class);
      clazz.getMethod("peekByte", addressClass);
      clazz.getMethod("pokeByteArray", addressClass, byte[].class, int.class, int.class);

            

Reported by PMD.

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

Line: 357

                    Class<?> clazz = MEMORY_CLASS;
      clazz.getMethod("peekLong", addressClass, boolean.class);
      clazz.getMethod("pokeLong", addressClass, long.class, boolean.class);
      clazz.getMethod("pokeInt", addressClass, int.class, boolean.class);
      clazz.getMethod("peekInt", addressClass, boolean.class);
      clazz.getMethod("pokeByte", addressClass, byte.class);
      clazz.getMethod("peekByte", addressClass);
      clazz.getMethod("pokeByteArray", addressClass, byte[].class, int.class, int.class);
      clazz.getMethod("peekByteArray", addressClass, byte[].class, int.class, int.class);

            

Reported by PMD.

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

Line: 358

                    clazz.getMethod("peekLong", addressClass, boolean.class);
      clazz.getMethod("pokeLong", addressClass, long.class, boolean.class);
      clazz.getMethod("pokeInt", addressClass, int.class, boolean.class);
      clazz.getMethod("peekInt", addressClass, boolean.class);
      clazz.getMethod("pokeByte", addressClass, byte.class);
      clazz.getMethod("peekByte", addressClass);
      clazz.getMethod("pokeByteArray", addressClass, byte[].class, int.class, int.class);
      clazz.getMethod("peekByteArray", addressClass, byte[].class, int.class, int.class);
      return true;

            

Reported by PMD.

java/core/src/test/java/com/google/protobuf/ParserLiteTest.java
62 issues
A method/constructor should not explicitly throw java.lang.Exception
Design

Line: 49

              public class ParserLiteTest {

  private void assertRoundTripEquals(MessageLite message, ExtensionRegistryLite registry)
      throws Exception {
    final byte[] data = message.toByteArray();
    final int offset = 20;
    final int length = data.length;
    final int padding = 30;
    Parser<? extends MessageLite> parser = message.getParserForType();

            

Reported by PMD.

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

Line: 55

                  final int length = data.length;
    final int padding = 30;
    Parser<? extends MessageLite> parser = message.getParserForType();
    assertThat(message).isEqualTo(parser.parseFrom(data, registry));
    assertThat(message)
        .isEqualTo(
            parser.parseFrom(
                generatePaddingArray(data, offset, padding), offset, length, registry));
    assertThat(message).isEqualTo(parser.parseFrom(message.toByteString(), registry));

            

Reported by PMD.

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

Line: 55

                  final int length = data.length;
    final int padding = 30;
    Parser<? extends MessageLite> parser = message.getParserForType();
    assertThat(message).isEqualTo(parser.parseFrom(data, registry));
    assertThat(message)
        .isEqualTo(
            parser.parseFrom(
                generatePaddingArray(data, offset, padding), offset, length, registry));
    assertThat(message).isEqualTo(parser.parseFrom(message.toByteString(), registry));

            

Reported by PMD.

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

Line: 56

                  final int padding = 30;
    Parser<? extends MessageLite> parser = message.getParserForType();
    assertThat(message).isEqualTo(parser.parseFrom(data, registry));
    assertThat(message)
        .isEqualTo(
            parser.parseFrom(
                generatePaddingArray(data, offset, padding), offset, length, registry));
    assertThat(message).isEqualTo(parser.parseFrom(message.toByteString(), registry));
    assertThat(message).isEqualTo(parser.parseFrom(new ByteArrayInputStream(data), registry));

            

Reported by PMD.

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

Line: 58

                  assertThat(message).isEqualTo(parser.parseFrom(data, registry));
    assertThat(message)
        .isEqualTo(
            parser.parseFrom(
                generatePaddingArray(data, offset, padding), offset, length, registry));
    assertThat(message).isEqualTo(parser.parseFrom(message.toByteString(), registry));
    assertThat(message).isEqualTo(parser.parseFrom(new ByteArrayInputStream(data), registry));
    assertThat(message).isEqualTo(parser.parseFrom(CodedInputStream.newInstance(data), registry));
    assertThat(message)

            

Reported by PMD.

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

Line: 60

                      .isEqualTo(
            parser.parseFrom(
                generatePaddingArray(data, offset, padding), offset, length, registry));
    assertThat(message).isEqualTo(parser.parseFrom(message.toByteString(), registry));
    assertThat(message).isEqualTo(parser.parseFrom(new ByteArrayInputStream(data), registry));
    assertThat(message).isEqualTo(parser.parseFrom(CodedInputStream.newInstance(data), registry));
    assertThat(message)
        .isEqualTo(parser.parseFrom(message.toByteString().asReadOnlyByteBuffer(), registry));
  }

            

Reported by PMD.

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

Line: 60

                      .isEqualTo(
            parser.parseFrom(
                generatePaddingArray(data, offset, padding), offset, length, registry));
    assertThat(message).isEqualTo(parser.parseFrom(message.toByteString(), registry));
    assertThat(message).isEqualTo(parser.parseFrom(new ByteArrayInputStream(data), registry));
    assertThat(message).isEqualTo(parser.parseFrom(CodedInputStream.newInstance(data), registry));
    assertThat(message)
        .isEqualTo(parser.parseFrom(message.toByteString().asReadOnlyByteBuffer(), registry));
  }

            

Reported by PMD.

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

Line: 62

                              generatePaddingArray(data, offset, padding), offset, length, registry));
    assertThat(message).isEqualTo(parser.parseFrom(message.toByteString(), registry));
    assertThat(message).isEqualTo(parser.parseFrom(new ByteArrayInputStream(data), registry));
    assertThat(message).isEqualTo(parser.parseFrom(CodedInputStream.newInstance(data), registry));
    assertThat(message)
        .isEqualTo(parser.parseFrom(message.toByteString().asReadOnlyByteBuffer(), registry));
  }

  @SuppressWarnings("unchecked")

            

Reported by PMD.

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

Line: 62

                              generatePaddingArray(data, offset, padding), offset, length, registry));
    assertThat(message).isEqualTo(parser.parseFrom(message.toByteString(), registry));
    assertThat(message).isEqualTo(parser.parseFrom(new ByteArrayInputStream(data), registry));
    assertThat(message).isEqualTo(parser.parseFrom(CodedInputStream.newInstance(data), registry));
    assertThat(message)
        .isEqualTo(parser.parseFrom(message.toByteString().asReadOnlyByteBuffer(), registry));
  }

  @SuppressWarnings("unchecked")

            

Reported by PMD.

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

Line: 63

                  assertThat(message).isEqualTo(parser.parseFrom(message.toByteString(), registry));
    assertThat(message).isEqualTo(parser.parseFrom(new ByteArrayInputStream(data), registry));
    assertThat(message).isEqualTo(parser.parseFrom(CodedInputStream.newInstance(data), registry));
    assertThat(message)
        .isEqualTo(parser.parseFrom(message.toByteString().asReadOnlyByteBuffer(), registry));
  }

  @SuppressWarnings("unchecked")
  private void assertRoundTripEquals(MessageLite message) throws Exception {

            

Reported by PMD.

java/core/src/test/java/com/google/protobuf/Proto2UnknownEnumValueTest.java
61 issues
Found non-transient, non-static member. Please mark as transient or provide accessors.
Error

Line: 46

              /** Unit tests for proto2 that treats unknown enum values as unknown fields. */
@RunWith(JUnit4.class)
public class Proto2UnknownEnumValueTest {
  FieldDescriptor singularField =
      TestAllTypes.getDescriptor().findFieldByName("optional_nested_enum");
  FieldDescriptor repeatedField =
      TestAllTypes.getDescriptor().findFieldByName("repeated_nested_enum");
  byte[] payload = buildPayloadWithUnknownEnumValues();


            

Reported by PMD.

Found non-transient, non-static member. Please mark as transient or provide accessors.
Error

Line: 48

              public class Proto2UnknownEnumValueTest {
  FieldDescriptor singularField =
      TestAllTypes.getDescriptor().findFieldByName("optional_nested_enum");
  FieldDescriptor repeatedField =
      TestAllTypes.getDescriptor().findFieldByName("repeated_nested_enum");
  byte[] payload = buildPayloadWithUnknownEnumValues();

  private byte[] buildPayloadWithUnknownEnumValues() {
    // Builds a payload with unknown enum values.

            

Reported by PMD.

Found non-transient, non-static member. Please mark as transient or provide accessors.
Error

Line: 50

                    TestAllTypes.getDescriptor().findFieldByName("optional_nested_enum");
  FieldDescriptor repeatedField =
      TestAllTypes.getDescriptor().findFieldByName("repeated_nested_enum");
  byte[] payload = buildPayloadWithUnknownEnumValues();

  private byte[] buildPayloadWithUnknownEnumValues() {
    // Builds a payload with unknown enum values.
    UnknownFieldSet.Builder builder = UnknownFieldSet.newBuilder();
    builder.addField(

            

Reported by PMD.

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

Line: 57

                  UnknownFieldSet.Builder builder = UnknownFieldSet.newBuilder();
    builder.addField(
        singularField.getNumber(),
        UnknownFieldSet.Field.newBuilder()
            .addVarint(TestAllTypes.NestedEnum.BAR.getNumber())
            .addVarint(1901 /* unknown enum value */)
            .build());
    builder.addField(
        repeatedField.getNumber(),

            

Reported by PMD.

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

Line: 58

                  builder.addField(
        singularField.getNumber(),
        UnknownFieldSet.Field.newBuilder()
            .addVarint(TestAllTypes.NestedEnum.BAR.getNumber())
            .addVarint(1901 /* unknown enum value */)
            .build());
    builder.addField(
        repeatedField.getNumber(),
        UnknownFieldSet.Field.newBuilder()

            

Reported by PMD.

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

Line: 63

                          .build());
    builder.addField(
        repeatedField.getNumber(),
        UnknownFieldSet.Field.newBuilder()
            .addVarint(TestAllTypes.NestedEnum.FOO.getNumber())
            .addVarint(1902 /* unknown enum value */)
            .addVarint(TestAllTypes.NestedEnum.BAZ.getNumber())
            .addVarint(1903 /* unknown enum value */)
            .build());

            

Reported by PMD.

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

Line: 64

                  builder.addField(
        repeatedField.getNumber(),
        UnknownFieldSet.Field.newBuilder()
            .addVarint(TestAllTypes.NestedEnum.FOO.getNumber())
            .addVarint(1902 /* unknown enum value */)
            .addVarint(TestAllTypes.NestedEnum.BAZ.getNumber())
            .addVarint(1903 /* unknown enum value */)
            .build());
    return builder.build().toByteArray();

            

Reported by PMD.

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

Line: 66

                      UnknownFieldSet.Field.newBuilder()
            .addVarint(TestAllTypes.NestedEnum.FOO.getNumber())
            .addVarint(1902 /* unknown enum value */)
            .addVarint(TestAllTypes.NestedEnum.BAZ.getNumber())
            .addVarint(1903 /* unknown enum value */)
            .build());
    return builder.build().toByteArray();
  }


            

Reported by PMD.

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

Line: 69

                          .addVarint(TestAllTypes.NestedEnum.BAZ.getNumber())
            .addVarint(1903 /* unknown enum value */)
            .build());
    return builder.build().toByteArray();
  }

  @Test
  public void testUnknownEnumValues() throws Exception {
    TestAllTypes message = TestAllTypes.parseFrom(payload);

            

Reported by PMD.

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

Line: 73

                }

  @Test
  public void testUnknownEnumValues() throws Exception {
    TestAllTypes message = TestAllTypes.parseFrom(payload);

    // Known enum values should be preserved.
    assertThat(message.getOptionalNestedEnum()).isEqualTo(TestAllTypes.NestedEnum.BAR);
    assertThat(message.getRepeatedNestedEnumList().size()).isEqualTo(2);

            

Reported by PMD.

python/google/protobuf/message_factory.py
61 issues
Bad indentation. Found 2 spaces, expected 4
Style

Line: 47 Column: 1

              from google.protobuf import message

if api_implementation.Type() == 'cpp':
  from google.protobuf.pyext import cpp_message as message_impl
else:
  from google.protobuf.internal import python_message as message_impl


# The type of all Message classes.

            

Reported by Pylint.

Bad indentation. Found 2 spaces, expected 4
Style

Line: 49 Column: 1

              if api_implementation.Type() == 'cpp':
  from google.protobuf.pyext import cpp_message as message_impl
else:
  from google.protobuf.internal import python_message as message_impl


# The type of all Message classes.
_GENERATED_PROTOCOL_MESSAGE_TYPE = message_impl.GeneratedProtocolMessageType


            

Reported by Pylint.

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

Line: 53 Column: 1

              

# The type of all Message classes.
_GENERATED_PROTOCOL_MESSAGE_TYPE = message_impl.GeneratedProtocolMessageType


class MessageFactory(object):
  """Factory for creating Proto2 messages from descriptors in a pool."""


            

Reported by Pylint.

Class 'MessageFactory' inherits from object, can be safely removed from bases in python3
Error

Line: 56 Column: 1

              _GENERATED_PROTOCOL_MESSAGE_TYPE = message_impl.GeneratedProtocolMessageType


class MessageFactory(object):
  """Factory for creating Proto2 messages from descriptors in a pool."""

  def __init__(self, pool=None):
    """Initializes a new factory."""
    self.pool = pool or descriptor_pool.DescriptorPool()

            

Reported by Pylint.

Bad indentation. Found 2 spaces, expected 4
Style

Line: 57 Column: 1

              

class MessageFactory(object):
  """Factory for creating Proto2 messages from descriptors in a pool."""

  def __init__(self, pool=None):
    """Initializes a new factory."""
    self.pool = pool or descriptor_pool.DescriptorPool()


            

Reported by Pylint.

Bad indentation. Found 2 spaces, expected 4
Style

Line: 59 Column: 1

              class MessageFactory(object):
  """Factory for creating Proto2 messages from descriptors in a pool."""

  def __init__(self, pool=None):
    """Initializes a new factory."""
    self.pool = pool or descriptor_pool.DescriptorPool()

    # local cache of all classes built from protobuf descriptors
    self._classes = {}

            

Reported by Pylint.

Bad indentation. Found 4 spaces, expected 8
Style

Line: 60 Column: 1

                """Factory for creating Proto2 messages from descriptors in a pool."""

  def __init__(self, pool=None):
    """Initializes a new factory."""
    self.pool = pool or descriptor_pool.DescriptorPool()

    # local cache of all classes built from protobuf descriptors
    self._classes = {}


            

Reported by Pylint.

Bad indentation. Found 4 spaces, expected 8
Style

Line: 61 Column: 1

              
  def __init__(self, pool=None):
    """Initializes a new factory."""
    self.pool = pool or descriptor_pool.DescriptorPool()

    # local cache of all classes built from protobuf descriptors
    self._classes = {}

  def GetPrototype(self, descriptor):

            

Reported by Pylint.

Bad indentation. Found 4 spaces, expected 8
Style

Line: 64 Column: 1

                  self.pool = pool or descriptor_pool.DescriptorPool()

    # local cache of all classes built from protobuf descriptors
    self._classes = {}

  def GetPrototype(self, descriptor):
    """Obtains a proto2 message class based on the passed in descriptor.

    Passing a descriptor with a fully qualified name matching a previous

            

Reported by Pylint.

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

Line: 66 Column: 3

                  # local cache of all classes built from protobuf descriptors
    self._classes = {}

  def GetPrototype(self, descriptor):
    """Obtains a proto2 message class based on the passed in descriptor.

    Passing a descriptor with a fully qualified name matching a previous
    invocation will cause the same class to be returned.


            

Reported by Pylint.