<commit_before>#!/usr/bin/env python
#
# Copyright 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

"""Tests for protorpc.messages."""
import six

__author__ = '<EMAIL> (<NAME>)'


import pickle
import re
import sys
import types
import unittest

from protorpc import descriptor
from protorpc import message_types
from protorpc import messages
from protorpc import test_util


class ModuleInterfaceTest(test_util.ModuleInterfaceTest,
                          test_util.TestCase):

  MODULE = messages


class ValidationErrorTest(test_util.TestCase):

  def testStr_NoFieldName(self):
    """Test string version of ValidationError when no name provided."""
    self.assertEquals('Validation error',
                      str(messages.ValidationError('Validation error')))

  def testStr_FieldName(self):
    """Test string version of ValidationError when no name provided."""
    validation_error = messages.ValidationError('Validation error')
    validation_error.field_name = 'a_field'
    self.assertEquals('Validation error', str(validation_error))


class EnumTest(test_util.TestCase):

  def setUp(self):
    """Set up tests."""
    # Redefine Color class in case so that changes to it (an error) in one test
    # does not affect other tests.
    global Color
    class Color(messages.Enum):
      RED = 20
      ORANGE = 2
      YELLOW = 40
      GREEN = 4
      BLUE = 50
      INDIGO = 5
      VIOLET = 80

  def testNames(self):
    """Test that names iterates over enum names."""
    self.assertEquals(
        set(['BLUE', 'GREEN', 'INDIGO', 'ORANGE', 'RED', 'VIOLET', 'YELLOW']),
        set(Color.names()))

  def testNumbers(self):
    """Tests that numbers iterates of enum numbers."""
    self.assertEquals(set([2, 4, 5, 20, 40, 50, 80]), set(Color.numbers()))

  def testIterate(self):
    """Test that __iter__ iterates over all enum values."""
    self.assertEquals(set(Color),
                      set([Color.RED,
                           Color.ORANGE,
                           Color.YELLOW,
                           Color.GREEN,
                           Color.BLUE,
                           Color.INDIGO,
                           Color.VIOLET]))

  def testNaturalOrder(self):
    """Test that natural order enumeration is in numeric order."""
    self.assertEquals([Color.ORANGE,
                       Color.GREEN,
                       Color.INDIGO,
                       Color.RED,
                       Color.YELLOW,
                       Color.BLUE,
                       Color.VIOLET],
                      sorted(Color))

  def testByName(self):
    """Test look-up by name."""
    self.assertEquals(Color.RED, Color.lookup_by_name('RED'))
    self.assertRaises(KeyError, Color.lookup_by_name, 20)
    self.assertRaises(KeyError, Color.lookup_by_name, Color.RED)

  def testByNumber(self):
    """Test look-up by number."""
    self.assertRaises(KeyError, Color.lookup_by_number, 'RED')
    self.assertEquals(Color.RED, Color.lookup_by_number(20))
    self.assertRaises(KeyError, Color.lookup_by_number, Color.RED)

  def testConstructor(self):
    """Test that constructor look-up by name or number."""
    self.assertEquals(Color.RED, Color('RED'))
    self.assertEquals(Color.RED, Color(u'RED'))
    self.assertEquals(Color.RED, Color(20))
    if six.PY2:
        self.assertEquals(Color.RED, Color(long(20)))
    self.assertEquals(Color.RED, Color(Color.RED))
    self.assertRaises(TypeError, Color, 'Not exists')
    self.assertRaises(TypeError, Color, 'Red')
    self.assertRaises(TypeError, Color, 100)
    self.assertRaises(TypeError, Color, 10.0)

  def testLen(self):
    """Test that len function works to count enums."""
    self.assertEquals(7, len(Color))

  def testNoSubclasses(self):
    """Test that it is not possible to sub-class enum classes."""
    def declare_subclass():
      class MoreColor(Color):
        pass
    self.assertRaises(messages.EnumDefinitionError,
                      declare_subclass)

  def testClassNotMutable(self):
    """Test that enum classes themselves are not mutable."""
    self.assertRaises(AttributeError,
                      setattr,
                      Color,
                      'something_new',
                      10)

  def testInstancesMutable(self):
    """Test that enum instances are not mutable."""
    self.assertRaises(TypeError,
                      setattr,
                      Color.RED,
                      'something_new',
                      10)

  def testDefEnum(self):
    """Test def_enum works by building enum class from dict."""
    WeekDay = messages.Enum.def_enum({'Monday': 1,
                                      'Tuesday': 2,
                                      'Wednesday': 3,
                                      'Thursday': 4,
                                      'Friday': 6,
                                      'Saturday': 7,
                                      'Sunday': 8},
                                     'WeekDay')
    self.assertEquals('Wednesday', WeekDay(3).name)
    self.assertEquals(6, WeekDay('Friday').number)
    self.assertEquals(WeekDay.Sunday, WeekDay('Sunday'))

  def testNonInt(self):
    """Test that non-integer values rejection by enum def."""
    self.assertRaises(messages.EnumDefinitionError,
                      messages.Enum.def_enum,
                      {'Bad': '1'},
                      'BadEnum')

  def testNegativeInt(self):
    """Test that negative numbers rejection by enum def."""
    self.assertRaises(messages.EnumDefinitionError,
                      messages.Enum.def_enum,
                      {'Bad': -1},
                      'BadEnum')

  def testLowerBound(self):
    """Test that zero is accepted by enum def."""
    class NotImportant(messages.Enum):
      """Testing for value zero"""
      VALUE = 0

    self.assertEquals(0, int(NotImportant.VALUE))

  def testTooLargeInt(self):
    """Test that numbers too large are rejected."""
    self.assertRaises(messages.EnumDefinitionError,
                      messages.Enum.def_enum,
                      {'Bad': (2 ** 29)},
                      'BadEnum')

  def testRepeatedInt(self):
    """Test duplicated numbers are forbidden."""
    self.assertRaises(messages.EnumDefinitionError,
                      messages.Enum.def_enum,
                      {'Ok': 1, 'Repeated': 1},
                      'BadEnum')

  def testStr(self):
    """Test converting to string."""
    self.assertEquals('RED', str(Color.RED))
    self.assertEquals('ORANGE', str(Color.ORANGE))

  def testInt(self):
    """Test converting to int."""
    self.assertEquals(20, int(Color.RED))
    self.assertEquals(2, int(Color.ORANGE))

  def testRepr(self):
    """Test enum representation."""
    self.assertEquals('Color(RED, 20)', repr(Color.RED))
    self.assertEquals('Color(YELLOW, 40)', repr(Color.YELLOW))

  def testDocstring(self):
    """Test that docstring is supported ok."""
    class NotImportant(messages.Enum):
      """I have a docstring."""

      VALUE1 = 1

    self.assertEquals('I have a docstring.', NotImportant.__doc__)

  def testDeleteEnumValue(self):
    """Test that enum values cannot be deleted."""
    self.assertRaises(TypeError, delattr, Color, 'RED')

  def testEnumName(self):
    """Test enum name."""
    module_name = test_util.get_module_name(EnumTest)
    self.assertEquals('%s.Color' % module_name, Color.definition_name())
    self.assertEquals(module_name, Color.outer_definition_name())
    self.assertEquals(module_name, Color.definition_package())

  def testDefinitionName_OverrideModule(self):
    """Test enum module is overriden by module package name."""
    global package
    try:
      package = 'my.package'
      self.assertEquals('my.package.Color', Color.definition_name())
      self.assertEquals('my.package', Color.outer_definition_name())
      self.assertEquals('my.package', Color.definition_package())
    finally:
      del package

  def testDefinitionName_NoModule(self):
    """Test what happens when there is no module for enum."""
    class Enum1(messages.Enum):
      pass

    original_modules = sys.modules
    sys.modules = dict(sys.modules)
    try:
      del sys.modules[__name__]
      self.assertEquals('Enum1', Enum1.definition_name())
      self.assertEquals(None, Enum1.outer_definition_name())
      self.assertEquals(None, Enum1.definition_package())
      self.assertEquals(unicode, type(Enum1.definition_name()))
    finally:
      sys.modules = original_modules

  def testDefinitionName_Nested(self):
    """Test nested Enum names."""
    class MyMessage(messages.Message):
<commit_msg>Overlooked 'unicode'.<commit_after>#!/usr/bin/env python
#
# Copyright 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

"""Tests for protorpc.messages."""
import six

__author__ = '<EMAIL> (<NAME>)'


import pickle
import re
import sys
import types
import unittest

from protorpc import descriptor
from protorpc import message_types
from protorpc import messages
from protorpc import test_util


class ModuleInterfaceTest(test_util.ModuleInterfaceTest,
                          test_util.TestCase):

  MODULE = messages


class ValidationErrorTest(test_util.TestCase):

  def testStr_NoFieldName(self):
    """Test string version of ValidationError when no name provided."""
    self.assertEquals('Validation error',
                      str(messages.ValidationError('Validation error')))

  def testStr_FieldName(self):
    """Test string version of ValidationError when no name provided."""
    validation_error = messages.ValidationError('Validation error')
    validation_error.field_name = 'a_field'
    self.assertEquals('Validation error', str(validation_error))


class EnumTest(test_util.TestCase):

  def setUp(self):
    """Set up tests."""
    # Redefine Color class in case so that changes to it (an error) in one test
    # does not affect other tests.
    global Color
    class Color(messages.Enum):
      RED = 20
      ORANGE = 2
      YELLOW = 40
      GREEN = 4
      BLUE = 50
      INDIGO = 5
      VIOLET = 80

  def testNames(self):
    """Test that names iterates over enum names."""
    self.assertEquals(
        set(['BLUE', 'GREEN', 'INDIGO', 'ORANGE', 'RED', 'VIOLET', 'YELLOW']),
        set(Color.names()))

  def testNumbers(self):
    """Tests that numbers iterates of enum numbers."""
    self.assertEquals(set([2, 4, 5, 20, 40, 50, 80]), set(Color.numbers()))

  def testIterate(self):
    """Test that __iter__ iterates over all enum values."""
    self.assertEquals(set(Color),
                      set([Color.RED,
                           Color.ORANGE,
                           Color.YELLOW,
                           Color.GREEN,
                           Color.BLUE,
                           Color.INDIGO,
                           Color.VIOLET]))

  def testNaturalOrder(self):
    """Test that natural order enumeration is in numeric order."""
    self.assertEquals([Color.ORANGE,
                       Color.GREEN,
                       Color.INDIGO,
                       Color.RED,
                       Color.YELLOW,
                       Color.BLUE,
                       Color.VIOLET],
                      sorted(Color))

  def testByName(self):
    """Test look-up by name."""
    self.assertEquals(Color.RED, Color.lookup_by_name('RED'))
    self.assertRaises(KeyError, Color.lookup_by_name, 20)
    self.assertRaises(KeyError, Color.lookup_by_name, Color.RED)

  def testByNumber(self):
    """Test look-up by number."""
    self.assertRaises(KeyError, Color.lookup_by_number, 'RED')
    self.assertEquals(Color.RED, Color.lookup_by_number(20))
    self.assertRaises(KeyError, Color.lookup_by_number, Color.RED)

  def testConstructor(self):
    """Test that constructor look-up by name or number."""
    self.assertEquals(Color.RED, Color('RED'))
    self.assertEquals(Color.RED, Color(u'RED'))
    self.assertEquals(Color.RED, Color(20))
    if six.PY2:
        self.assertEquals(Color.RED, Color(long(20)))
    self.assertEquals(Color.RED, Color(Color.RED))
    self.assertRaises(TypeError, Color, 'Not exists')
    self.assertRaises(TypeError, Color, 'Red')
    self.assertRaises(TypeError, Color, 100)
    self.assertRaises(TypeError, Color, 10.0)

  def testLen(self):
    """Test that len function works to count enums."""
    self.assertEquals(7, len(Color))

  def testNoSubclasses(self):
    """Test that it is not possible to sub-class enum classes."""
    def declare_subclass():
      class MoreColor(Color):
        pass
    self.assertRaises(messages.EnumDefinitionError,
                      declare_subclass)

  def testClassNotMutable(self):
    """Test that enum classes themselves are not mutable."""
    self.assertRaises(AttributeError,
                      setattr,
                      Color,
                      'something_new',
                      10)

  def testInstancesMutable(self):
    """Test that enum instances are not mutable."""
    self.assertRaises(TypeError,
                      setattr,
                      Color.RED,
                      'something_new',
                      10)

  def testDefEnum(self):
    """Test def_enum works by building enum class from dict."""
    WeekDay = messages.Enum.def_enum({'Monday': 1,
                                      'Tuesday': 2,
                                      'Wednesday': 3,
                                      'Thursday': 4,
                                      'Friday': 6,
                                      'Saturday': 7,
                                      'Sunday': 8},
                                     'WeekDay')
    self.assertEquals('Wednesday', WeekDay(3).name)
    self.assertEquals(6, WeekDay('Friday').number)
    self.assertEquals(WeekDay.Sunday, WeekDay('Sunday'))

  def testNonInt(self):
    """Test that non-integer values rejection by enum def."""
    self.assertRaises(messages.EnumDefinitionError,
                      messages.Enum.def_enum,
                      {'Bad': '1'},
                      'BadEnum')

  def testNegativeInt(self):
    """Test that negative numbers rejection by enum def."""
    self.assertRaises(messages.EnumDefinitionError,
                      messages.Enum.def_enum,
                      {'Bad': -1},
                      'BadEnum')

  def testLowerBound(self):
    """Test that zero is accepted by enum def."""
    class NotImportant(messages.Enum):
      """Testing for value zero"""
      VALUE = 0

    self.assertEquals(0, int(NotImportant.VALUE))

  def testTooLargeInt(self):
    """Test that numbers too large are rejected."""
    self.assertRaises(messages.EnumDefinitionError,
                      messages.Enum.def_enum,
                      {'Bad': (2 ** 29)},
                      'BadEnum')

  def testRepeatedInt(self):
    """Test duplicated numbers are forbidden."""
    self.assertRaises(messages.EnumDefinitionError,
                      messages.Enum.def_enum,
                      {'Ok': 1, 'Repeated': 1},
                      'BadEnum')

  def testStr(self):
    """Test converting to string."""
    self.assertEquals('RED', str(Color.RED))
    self.assertEquals('ORANGE', str(Color.ORANGE))

  def testInt(self):
    """Test converting to int."""
    self.assertEquals(20, int(Color.RED))
    self.assertEquals(2, int(Color.ORANGE))

  def testRepr(self):
    """Test enum representation."""
    self.assertEquals('Color(RED, 20)', repr(Color.RED))
    self.assertEquals('Color(YELLOW, 40)', repr(Color.YELLOW))

  def testDocstring(self):
    """Test that docstring is supported ok."""
    class NotImportant(messages.Enum):
      """I have a docstring."""

      VALUE1 = 1

    self.assertEquals('I have a docstring.', NotImportant.__doc__)

  def testDeleteEnumValue(self):
    """Test that enum values cannot be deleted."""
    self.assertRaises(TypeError, delattr, Color, 'RED')

  def testEnumName(self):
    """Test enum name."""
    module_name = test_util.get_module_name(EnumTest)
    self.assertEquals('%s.Color' % module_name, Color.definition_name())
    self.assertEquals(module_name, Color.outer_definition_name())
    self.assertEquals(module_name, Color.definition_package())

  def testDefinitionName_OverrideModule(self):
    """Test enum module is overriden by module package name."""
    global package
    try:
      package = 'my.package'
      self.assertEquals('my.package.Color', Color.definition_name())
      self.assertEquals('my.package', Color.outer_definition_name())
      self.assertEquals('my.package', Color.definition_package())
    finally:
      del package

  def testDefinitionName_NoModule(self):
    """Test what happens when there is no module for enum."""
    class Enum1(messages.Enum):
      pass

    original_modules = sys.modules
    sys.modules = dict(sys.modules)
    try:
      del sys.modules[__name__]
      self.assertEquals('Enum1', Enum1.definition_name())
      self.assertEquals(None, Enum1.outer_definition_name())
      self.assertEquals(None, Enum1.definition_package())
      self.assertEquals(six.text_type, type(Enum1.definition_name()))
    finally:
      sys.modules = original_modules

  def testDefinitionName_Nested(self):
    """Test nested Enum names."""
    class MyMessage(messages.Message):

{'fraction_non_alphanumeric': 0.11283451665756418, 'fraction_numerical': 0.009066084107045331, 'mean_word_length': 2.4238967838444276, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 7, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 14, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5868516', 'n_tokens_mistral': 5224, 'n_tokens_neox': 4855, 'n_words': 1315}