1 # Copyright 2017 The Chromium Authors. All rights reserved. 2 # Use of this source code is governed by a BSD-style license that can be 3 # found in the LICENSE file. 4 5 import unittest 6 7 from py_utils import slots_metaclass 8 9 class SlotsMetaclassUnittest(unittest.TestCase): 10 11 def testSlotsMetaclass(self): 12 class NiceClass(object): 13 __metaclass__ = slots_metaclass.SlotsMetaclass 14 __slots__ = '_nice', 15 16 def __init__(self, nice): 17 self._nice = nice 18 19 NiceClass(42) 20 21 with self.assertRaises(AssertionError): 22 class NaughtyClass(NiceClass): 23 def __init__(self, naughty): 24 super(NaughtyClass, self).__init__(42) 25 self._naughty = naughty 26 27 # Metaclasses are called when the class is defined, so no need to 28 # instantiate it. 29 30 with self.assertRaises(AttributeError): 31 class NaughtyClass2(NiceClass): 32 __slots__ = () 33 34 def __init__(self, naughty): 35 super(NaughtyClass2, self).__init__(42) 36 self._naughty = naughty # pylint: disable=assigning-non-slot 37 38 # SlotsMetaclass is happy that __slots__ is defined, but python won't be 39 # happy about assigning _naughty when the class is instantiated because it 40 # isn't listed in __slots__, even if you disable the pylint error. 41 NaughtyClass2(666) 42