Back to index

python3.2  3.2.2
Public Member Functions
test.test_collections.TestNamedTuple Class Reference

List of all members.

Public Member Functions

def test_factory
def test_factory_doc_attr
def test_name_fixer
def test_instance
def test_tupleness
def test_odd_sizes
def test_pickle
def test_copy
def test_name_conflicts
def test_repr

Detailed Description

Definition at line 122 of file test_collections.py.


Member Function Documentation

Definition at line 276 of file test_collections.py.

00276 
00277     def test_copy(self):
00278         p = TestNT(x=10, y=20, z=30)
00279         for copier in copy.copy, copy.deepcopy:
00280             q = copier(p)
00281             self.assertEqual(p, q)
00282             self.assertEqual(p._fields, q._fields)

Here is the call graph for this function:

Definition at line 124 of file test_collections.py.

00124 
00125     def test_factory(self):
00126         Point = namedtuple('Point', 'x y')
00127         self.assertEqual(Point.__name__, 'Point')
00128         self.assertEqual(Point.__slots__, ())
00129         self.assertEqual(Point.__module__, __name__)
00130         self.assertEqual(Point.__getitem__, tuple.__getitem__)
00131         self.assertEqual(Point._fields, ('x', 'y'))
00132 
00133         self.assertRaises(ValueError, namedtuple, 'abc%', 'efg ghi')       # type has non-alpha char
00134         self.assertRaises(ValueError, namedtuple, 'class', 'efg ghi')      # type has keyword
00135         self.assertRaises(ValueError, namedtuple, '9abc', 'efg ghi')       # type starts with digit
00136 
00137         self.assertRaises(ValueError, namedtuple, 'abc', 'efg g%hi')       # field with non-alpha char
00138         self.assertRaises(ValueError, namedtuple, 'abc', 'abc class')      # field has keyword
00139         self.assertRaises(ValueError, namedtuple, 'abc', '8efg 9ghi')      # field starts with digit
00140         self.assertRaises(ValueError, namedtuple, 'abc', '_efg ghi')       # field with leading underscore
00141         self.assertRaises(ValueError, namedtuple, 'abc', 'efg efg ghi')    # duplicate field
00142 
00143         namedtuple('Point0', 'x1 y2')   # Verify that numbers are allowed in names
00144         namedtuple('_', 'a b c')        # Test leading underscores in a typename
00145 
00146         nt = namedtuple('nt', 'the quick brown fox')                       # check unicode input
00147         self.assertNotIn("u'", repr(nt._fields))
00148         nt = namedtuple('nt', ('the', 'quick'))                           # check unicode input
00149         self.assertNotIn("u'", repr(nt._fields))
00150 
00151         self.assertRaises(TypeError, Point._make, [11])                     # catch too few args
00152         self.assertRaises(TypeError, Point._make, [11, 22, 33])             # catch too many args

Here is the call graph for this function:

Definition at line 155 of file test_collections.py.

00155 
00156     def test_factory_doc_attr(self):
00157         Point = namedtuple('Point', 'x y')
00158         self.assertEqual(Point.__doc__, 'Point(x, y)')

Here is the call graph for this function:

Definition at line 170 of file test_collections.py.

00170 
00171     def test_instance(self):
00172         Point = namedtuple('Point', 'x y')
00173         p = Point(11, 22)
00174         self.assertEqual(p, Point(x=11, y=22))
00175         self.assertEqual(p, Point(11, y=22))
00176         self.assertEqual(p, Point(y=22, x=11))
00177         self.assertEqual(p, Point(*(11, 22)))
00178         self.assertEqual(p, Point(**dict(x=11, y=22)))
00179         self.assertRaises(TypeError, Point, 1)                              # too few args
00180         self.assertRaises(TypeError, Point, 1, 2, 3)                        # too many args
00181         self.assertRaises(TypeError, eval, 'Point(XXX=1, y=2)', locals())   # wrong keyword argument
00182         self.assertRaises(TypeError, eval, 'Point(x=1)', locals())          # missing keyword argument
00183         self.assertEqual(repr(p), 'Point(x=11, y=22)')
00184         self.assertNotIn('__weakref__', dir(p))
00185         self.assertEqual(p, Point._make([11, 22]))                          # test _make classmethod
00186         self.assertEqual(p._fields, ('x', 'y'))                             # test _fields attribute
00187         self.assertEqual(p._replace(x=1), (1, 22))                          # test _replace method
00188         self.assertEqual(p._asdict(), dict(x=11, y=22))                     # test _asdict method
00189         self.assertEqual(vars(p), p._asdict())                              # verify that vars() works
00190 
00191         try:
00192             p._replace(x=1, error=2)
00193         except ValueError:
00194             pass
00195         else:
00196             self._fail('Did not detect an incorrect fieldname')
00197 
00198         # verify that field string can have commas
00199         Point = namedtuple('Point', 'x, y')
00200         p = Point(x=11, y=22)
00201         self.assertEqual(repr(p), 'Point(x=11, y=22)')
00202 
00203         # verify that fieldspec can be a non-string sequence
00204         Point = namedtuple('Point', ('x', 'y'))
00205         p = Point(x=11, y=22)
00206         self.assertEqual(repr(p), 'Point(x=11, y=22)')

Here is the call graph for this function:

Definition at line 283 of file test_collections.py.

00283 
00284     def test_name_conflicts(self):
00285         # Some names like "self", "cls", "tuple", "itemgetter", and "property"
00286         # failed when used as field names.  Test to make sure these now work.
00287         T = namedtuple('T', 'itemgetter property self cls tuple')
00288         t = T(1, 2, 3, 4, 5)
00289         self.assertEqual(t, (1,2,3,4,5))
00290         newt = t._replace(itemgetter=10, property=20, self=30, cls=40, tuple=50)
00291         self.assertEqual(newt, (10,20,30,40,50))
00292 
00293         # Broader test of all interesting names in a template
00294         with support.captured_stdout() as template:
00295             T = namedtuple('T', 'x', verbose=True)
00296         words = set(re.findall('[A-Za-z]+', template.getvalue()))
00297         words -= set(keyword.kwlist)
00298         T = namedtuple('T', words)
00299         # test __new__
00300         values = tuple(range(len(words)))
00301         t = T(*values)
00302         self.assertEqual(t, values)
00303         t = T(**dict(zip(T._fields, values)))
00304         self.assertEqual(t, values)
00305         # test _make
00306         t = T._make(values)
00307         self.assertEqual(t, values)
00308         # exercise __repr__
00309         repr(t)
00310         # test _asdict
00311         self.assertEqual(t._asdict(), dict(zip(T._fields, values)))
00312         # test _replace
00313         t = T._make(values)
00314         newvalues = tuple(v*10 for v in values)
00315         newt = t._replace(**dict(zip(T._fields, newvalues)))
00316         self.assertEqual(newt, newvalues)
00317         # test _fields
00318         self.assertEqual(T._fields, tuple(words))
00319         # test __getnewargs__
00320         self.assertEqual(t.__getnewargs__(), values)

Here is the call graph for this function:

Definition at line 159 of file test_collections.py.

00159 
00160     def test_name_fixer(self):
00161         for spec, renamed in [
00162             [('efg', 'g%hi'),  ('efg', '_1')],                              # field with non-alpha char
00163             [('abc', 'class'), ('abc', '_1')],                              # field has keyword
00164             [('8efg', '9ghi'), ('_0', '_1')],                               # field starts with digit
00165             [('abc', '_efg'), ('abc', '_1')],                               # field with leading underscore
00166             [('abc', 'efg', 'efg', 'ghi'), ('abc', 'efg', '_2', 'ghi')],    # duplicate field
00167             [('abc', '', 'x'), ('abc', '_1', 'x')],                         # fieldname is a space
00168         ]:
00169             self.assertEqual(namedtuple('NT', spec, rename=True)._fields, renamed)

Here is the call graph for this function:

Definition at line 226 of file test_collections.py.

00226 
00227     def test_odd_sizes(self):
00228         Zero = namedtuple('Zero', '')
00229         self.assertEqual(Zero(), ())
00230         self.assertEqual(Zero._make([]), ())
00231         self.assertEqual(repr(Zero()), 'Zero()')
00232         self.assertEqual(Zero()._asdict(), {})
00233         self.assertEqual(Zero()._fields, ())
00234 
00235         Dot = namedtuple('Dot', 'd')
00236         self.assertEqual(Dot(1), (1,))
00237         self.assertEqual(Dot._make([1]), (1,))
00238         self.assertEqual(Dot(1).d, 1)
00239         self.assertEqual(repr(Dot(1)), 'Dot(d=1)')
00240         self.assertEqual(Dot(1)._asdict(), {'d':1})
00241         self.assertEqual(Dot(1)._replace(d=999), (999,))
00242         self.assertEqual(Dot(1)._fields, ('d',))
00243 
00244         # n = 5000
00245         n = 254 # SyntaxError: more than 255 arguments:
00246         import string, random
00247         names = list(set(''.join([random.choice(string.ascii_letters)
00248                                   for j in range(10)]) for i in range(n)))
00249         n = len(names)
00250         Big = namedtuple('Big', names)
00251         b = Big(*range(n))
00252         self.assertEqual(b, tuple(range(n)))
00253         self.assertEqual(Big._make(range(n)), tuple(range(n)))
00254         for pos, name in enumerate(names):
00255             self.assertEqual(getattr(b, name), pos)
00256         repr(b)                                 # make sure repr() doesn't blow-up
00257         d = b._asdict()
00258         d_expected = dict(zip(names, range(n)))
00259         self.assertEqual(d, d_expected)
00260         b2 = b._replace(**dict([(names[1], 999),(names[-5], 42)]))
00261         b2_expected = list(range(n))
00262         b2_expected[1] = 999
00263         b2_expected[-5] = 42
00264         self.assertEqual(b2, tuple(b2_expected))
00265         self.assertEqual(b._fields, tuple(names))

Here is the call graph for this function:

Definition at line 266 of file test_collections.py.

00266 
00267     def test_pickle(self):
00268         p = TestNT(x=10, y=20, z=30)
00269         for module in (pickle,):
00270             loads = getattr(module, 'loads')
00271             dumps = getattr(module, 'dumps')
00272             for protocol in -1, 0, 1, 2:
00273                 q = loads(dumps(p, protocol))
00274                 self.assertEqual(p, q)
00275                 self.assertEqual(p._fields, q._fields)

Here is the call graph for this function:

Definition at line 321 of file test_collections.py.

00321 
00322     def test_repr(self):
00323         with support.captured_stdout() as template:
00324             A = namedtuple('A', 'x', verbose=True)
00325         self.assertEqual(repr(A(1)), 'A(x=1)')
00326         # repr should show the name of the subclass
00327         class B(A):
00328             pass
00329         self.assertEqual(repr(B(1)), 'B(x=1)')
00330 

Here is the call graph for this function:

Definition at line 207 of file test_collections.py.

00207 
00208     def test_tupleness(self):
00209         Point = namedtuple('Point', 'x y')
00210         p = Point(11, 22)
00211 
00212         self.assertIsInstance(p, tuple)
00213         self.assertEqual(p, (11, 22))                                       # matches a real tuple
00214         self.assertEqual(tuple(p), (11, 22))                                # coercable to a real tuple
00215         self.assertEqual(list(p), [11, 22])                                 # coercable to a list
00216         self.assertEqual(max(p), 22)                                        # iterable
00217         self.assertEqual(max(*p), 22)                                       # star-able
00218         x, y = p
00219         self.assertEqual(p, (x, y))                                         # unpacks like a tuple
00220         self.assertEqual((p[0], p[1]), (11, 22))                            # indexable like a tuple
00221         self.assertRaises(IndexError, p.__getitem__, 3)
00222 
00223         self.assertEqual(p.x, x)
00224         self.assertEqual(p.y, y)
00225         self.assertRaises(AttributeError, eval, 'p.z', locals())

Here is the call graph for this function:


The documentation for this class was generated from the following file: