0001 import unittest 0002 from test import test_support 0003 0004 import pwd 0005 0006 class PwdTest(unittest.TestCase): 0007 0008 def test_values(self): 0009 entries = pwd.getpwall() 0010 entriesbyname = {} 0011 entriesbyuid = {} 0012 0013 for e in entries: 0014 self.assertEqual(len(e), 7) 0015 self.assertEqual(e[0], e.pw_name) 0016 self.assert_(isinstance(e.pw_name, basestring)) 0017 self.assertEqual(e[1], e.pw_passwd) 0018 self.assert_(isinstance(e.pw_passwd, basestring)) 0019 self.assertEqual(e[2], e.pw_uid) 0020 self.assert_(isinstance(e.pw_uid, int)) 0021 self.assertEqual(e[3], e.pw_gid) 0022 self.assert_(isinstance(e.pw_gid, int)) 0023 self.assertEqual(e[4], e.pw_gecos) 0024 self.assert_(isinstance(e.pw_gecos, basestring)) 0025 self.assertEqual(e[5], e.pw_dir) 0026 self.assert_(isinstance(e.pw_dir, basestring)) 0027 self.assertEqual(e[6], e.pw_shell) 0028 self.assert_(isinstance(e.pw_shell, basestring)) 0029 0030 # The following won't work, because of duplicate entries 0031 # for one uid 0032 # self.assertEqual(pwd.getpwuid(e.pw_uid), e) 0033 # instead of this collect all entries for one uid 0034 # and check afterwards 0035 entriesbyname.setdefault(e.pw_name, []).append(e) 0036 entriesbyuid.setdefault(e.pw_uid, []).append(e) 0037 0038 # check whether the entry returned by getpwuid() 0039 # for each uid is among those from getpwall() for this uid 0040 for e in entries: 0041 self.assert_(pwd.getpwnam(e.pw_name) in entriesbyname[e.pw_name]) 0042 self.assert_(pwd.getpwuid(e.pw_uid) in entriesbyuid[e.pw_uid]) 0043 0044 def test_errors(self): 0045 self.assertRaises(TypeError, pwd.getpwuid) 0046 self.assertRaises(TypeError, pwd.getpwnam) 0047 self.assertRaises(TypeError, pwd.getpwall, 42) 0048 0049 # try to get some errors 0050 bynames = {} 0051 byuids = {} 0052 for (n, p, u, g, gecos, d, s) in pwd.getpwall(): 0053 bynames[n] = u 0054 byuids[u] = n 0055 0056 allnames = bynames.keys() 0057 namei = 0 0058 fakename = allnames[namei] 0059 while fakename in bynames: 0060 chars = map(None, fakename) 0061 for i in xrange(len(chars)): 0062 if chars[i] == 'z': 0063 chars[i] = 'A' 0064 break 0065 elif chars[i] == 'Z': 0066 continue 0067 else: 0068 chars[i] = chr(ord(chars[i]) + 1) 0069 break 0070 else: 0071 namei = namei + 1 0072 try: 0073 fakename = allnames[namei] 0074 except IndexError: 0075 # should never happen... if so, just forget it 0076 break 0077 fakename = ''.join(map(None, chars)) 0078 0079 self.assertRaises(KeyError, pwd.getpwnam, fakename) 0080 0081 # Choose a non-existent uid. 0082 fakeuid = 4127 0083 while fakeuid in byuids: 0084 fakeuid = (fakeuid * 3) % 0x10000 0085 0086 self.assertRaises(KeyError, pwd.getpwuid, fakeuid) 0087 0088 def test_main(): 0089 test_support.run_unittest(PwdTest) 0090 0091 if __name__ == "__main__": 0092 test_main() 0093
Generated by PyXR 0.9.4