3 from test
import test_support
5 pwd
= test_support
.import_module('pwd')
7 class PwdTest(unittest
.TestCase
):
10 entries
= pwd
.getpwall()
15 self
.assertEqual(len(e
), 7)
16 self
.assertEqual(e
[0], e
.pw_name
)
17 self
.assertIsInstance(e
.pw_name
, basestring
)
18 self
.assertEqual(e
[1], e
.pw_passwd
)
19 self
.assertIsInstance(e
.pw_passwd
, basestring
)
20 self
.assertEqual(e
[2], e
.pw_uid
)
21 self
.assertIsInstance(e
.pw_uid
, int)
22 self
.assertEqual(e
[3], e
.pw_gid
)
23 self
.assertIsInstance(e
.pw_gid
, int)
24 self
.assertEqual(e
[4], e
.pw_gecos
)
25 self
.assertIsInstance(e
.pw_gecos
, basestring
)
26 self
.assertEqual(e
[5], e
.pw_dir
)
27 self
.assertIsInstance(e
.pw_dir
, basestring
)
28 self
.assertEqual(e
[6], e
.pw_shell
)
29 self
.assertIsInstance(e
.pw_shell
, basestring
)
31 # The following won't work, because of duplicate entries
33 # self.assertEqual(pwd.getpwuid(e.pw_uid), e)
34 # instead of this collect all entries for one uid
35 # and check afterwards
36 entriesbyname
.setdefault(e
.pw_name
, []).append(e
)
37 entriesbyuid
.setdefault(e
.pw_uid
, []).append(e
)
39 if len(entries
) > 1000: # Huge passwd file (NIS?) -- skip the rest
42 # check whether the entry returned by getpwuid()
43 # for each uid is among those from getpwall() for this uid
45 if not e
[0] or e
[0] == '+':
46 continue # skip NIS entries etc.
47 self
.assertIn(pwd
.getpwnam(e
.pw_name
), entriesbyname
[e
.pw_name
])
48 self
.assertIn(pwd
.getpwuid(e
.pw_uid
), entriesbyuid
[e
.pw_uid
])
50 def test_errors(self
):
51 self
.assertRaises(TypeError, pwd
.getpwuid
)
52 self
.assertRaises(TypeError, pwd
.getpwnam
)
53 self
.assertRaises(TypeError, pwd
.getpwall
, 42)
55 # try to get some errors
58 for (n
, p
, u
, g
, gecos
, d
, s
) in pwd
.getpwall():
62 allnames
= bynames
.keys()
64 fakename
= allnames
[namei
]
65 while fakename
in bynames
:
66 chars
= list(fakename
)
67 for i
in xrange(len(chars
)):
74 chars
[i
] = chr(ord(chars
[i
]) + 1)
79 fakename
= allnames
[namei
]
81 # should never happen... if so, just forget it
83 fakename
= ''.join(chars
)
85 self
.assertRaises(KeyError, pwd
.getpwnam
, fakename
)
87 # In some cases, byuids isn't a complete list of all users in the
88 # system, so if we try to pick a value not in byuids (via a perturbing
89 # loop, say), pwd.getpwuid() might still be able to find data for that
90 # uid. Using sys.maxint may provoke the same problems, but hopefully
91 # it will be a more repeatable failure.
93 self
.assertNotIn(fakeuid
, byuids
)
94 self
.assertRaises(KeyError, pwd
.getpwuid
, fakeuid
)
97 test_support
.run_unittest(PwdTest
)
99 if __name__
== "__main__":