1 """Test script for the grp module.""" 2 3 import unittest 4 from test import test_support 5 6 grp = test_support.import_module('grp') 7 8 class GroupDatabaseTestCase(unittest.TestCase): 9 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, (long, int)) 20 self.assertEqual(value[3], value.gr_mem) 21 self.assertIsInstance(value.gr_mem, list) 22 23 def test_values(self): 24 entries = grp.getgrall() 25 26 for e in entries: 27 self.check_value(e) 28 29 if len(entries) > 1000: # Huge group file (NIS?) -- skip the rest 30 return 31 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 name = e.gr_name 37 if name.startswith('+') or name.startswith('-'): 38 # NIS-related entry 39 continue 40 e2 = grp.getgrnam(name) 41 self.check_value(e2) 42 # There are instances where getgrall() returns group names in 43 # lowercase while getgrgid() returns proper casing. 44 # Discovered on Ubuntu 5.04 (custom). 45 self.assertEqual(e2.gr_name.lower(), name.lower()) 46 47 def test_errors(self): 48 self.assertRaises(TypeError, grp.getgrgid) 49 self.assertRaises(TypeError, grp.getgrnam) 50 self.assertRaises(TypeError, grp.getgrall, 42) 51 52 # try to get some errors 53 bynames = {} 54 bygids = {} 55 for (n, p, g, mem) in grp.getgrall(): 56 if not n or n == '+': 57 continue # skip NIS entries etc. 58 bynames[n] = g 59 bygids[g] = n 60 61 allnames = bynames.keys() 62 namei = 0 63 fakename = allnames[namei] 64 while fakename in bynames: 65 chars = list(fakename) 66 for i in xrange(len(chars)): 67 if chars[i] == 'z': 68 chars[i] = 'A' 69 break 70 elif chars[i] == 'Z': 71 continue 72 else: 73 chars[i] = chr(ord(chars[i]) + 1) 74 break 75 else: 76 namei = namei + 1 77 try: 78 fakename = allnames[namei] 79 except IndexError: 80 # should never happen... if so, just forget it 81 break 82 fakename = ''.join(chars) 83 84 self.assertRaises(KeyError, grp.getgrnam, fakename) 85 86 # Choose a non-existent gid. 87 fakegid = 4127 88 while fakegid in bygids: 89 fakegid = (fakegid * 3) % 0x10000 90 91 self.assertRaises(KeyError, grp.getgrgid, fakegid) 92 93 def test_main(): 94 test_support.run_unittest(GroupDatabaseTestCase) 95 96 if __name__ == "__main__": 97 test_main() 98