move sections
[python/dscho.git] / Lib / test / test_grp.py
blobb4701d5fac5d24600ca5fa7e48ae7334c0ca4aea
1 """Test script for the grp module."""
3 import unittest
4 from test import test_support
6 grp = test_support.import_module('grp')
8 class GroupDatabaseTestCase(unittest.TestCase):
10 def check_value(self, value):
11 # check that a grp tuple has the entries and
12 # attributes promised by the docs
13 self.assertEqual(len(value), 4)
14 self.assertEqual(value[0], value.gr_name)
15 self.assertIsInstance(value.gr_name, basestring)
16 self.assertEqual(value[1], value.gr_passwd)
17 self.assertIsInstance(value.gr_passwd, basestring)
18 self.assertEqual(value[2], value.gr_gid)
19 self.assertIsInstance(value.gr_gid, int)
20 self.assertEqual(value[3], value.gr_mem)
21 self.assertIsInstance(value.gr_mem, list)
23 def test_values(self):
24 entries = grp.getgrall()
26 for e in entries:
27 self.check_value(e)
29 if len(entries) > 1000: # Huge group file (NIS?) -- skip the rest
30 return
32 for e in entries:
33 e2 = grp.getgrgid(e.gr_gid)
34 self.check_value(e2)
35 self.assertEqual(e2.gr_gid, e.gr_gid)
36 e2 = grp.getgrnam(e.gr_name)
37 self.check_value(e2)
38 # There are instances where getgrall() returns group names in
39 # lowercase while getgrgid() returns proper casing.
40 # Discovered on Ubuntu 5.04 (custom).
41 self.assertEqual(e2.gr_name.lower(), e.gr_name.lower())
43 def test_errors(self):
44 self.assertRaises(TypeError, grp.getgrgid)
45 self.assertRaises(TypeError, grp.getgrnam)
46 self.assertRaises(TypeError, grp.getgrall, 42)
48 # try to get some errors
49 bynames = {}
50 bygids = {}
51 for (n, p, g, mem) in grp.getgrall():
52 if not n or n == '+':
53 continue # skip NIS entries etc.
54 bynames[n] = g
55 bygids[g] = n
57 allnames = bynames.keys()
58 namei = 0
59 fakename = allnames[namei]
60 while fakename in bynames:
61 chars = list(fakename)
62 for i in xrange(len(chars)):
63 if chars[i] == 'z':
64 chars[i] = 'A'
65 break
66 elif chars[i] == 'Z':
67 continue
68 else:
69 chars[i] = chr(ord(chars[i]) + 1)
70 break
71 else:
72 namei = namei + 1
73 try:
74 fakename = allnames[namei]
75 except IndexError:
76 # should never happen... if so, just forget it
77 break
78 fakename = ''.join(chars)
80 self.assertRaises(KeyError, grp.getgrnam, fakename)
82 # Choose a non-existent gid.
83 fakegid = 4127
84 while fakegid in bygids:
85 fakegid = (fakegid * 3) % 0x10000
87 self.assertRaises(KeyError, grp.getgrgid, fakegid)
89 def test_main():
90 test_support.run_unittest(GroupDatabaseTestCase)
92 if __name__ == "__main__":
93 test_main()