test_spwd.py 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. import os
  2. import unittest
  3. from test.support import import_helper
  4. import warnings
  5. with warnings.catch_warnings():
  6. warnings.simplefilter("ignore", DeprecationWarning)
  7. spwd = import_helper.import_module('spwd')
  8. @unittest.skipUnless(hasattr(os, 'geteuid') and os.geteuid() == 0,
  9. 'root privileges required')
  10. class TestSpwdRoot(unittest.TestCase):
  11. def test_getspall(self):
  12. entries = spwd.getspall()
  13. self.assertIsInstance(entries, list)
  14. for entry in entries:
  15. self.assertIsInstance(entry, spwd.struct_spwd)
  16. def test_getspnam(self):
  17. entries = spwd.getspall()
  18. if not entries:
  19. self.skipTest('empty shadow password database')
  20. random_name = entries[0].sp_namp
  21. entry = spwd.getspnam(random_name)
  22. self.assertIsInstance(entry, spwd.struct_spwd)
  23. self.assertEqual(entry.sp_namp, random_name)
  24. self.assertEqual(entry.sp_namp, entry[0])
  25. self.assertEqual(entry.sp_namp, entry.sp_nam)
  26. self.assertIsInstance(entry.sp_pwdp, str)
  27. self.assertEqual(entry.sp_pwdp, entry[1])
  28. self.assertEqual(entry.sp_pwdp, entry.sp_pwd)
  29. self.assertIsInstance(entry.sp_lstchg, int)
  30. self.assertEqual(entry.sp_lstchg, entry[2])
  31. self.assertIsInstance(entry.sp_min, int)
  32. self.assertEqual(entry.sp_min, entry[3])
  33. self.assertIsInstance(entry.sp_max, int)
  34. self.assertEqual(entry.sp_max, entry[4])
  35. self.assertIsInstance(entry.sp_warn, int)
  36. self.assertEqual(entry.sp_warn, entry[5])
  37. self.assertIsInstance(entry.sp_inact, int)
  38. self.assertEqual(entry.sp_inact, entry[6])
  39. self.assertIsInstance(entry.sp_expire, int)
  40. self.assertEqual(entry.sp_expire, entry[7])
  41. self.assertIsInstance(entry.sp_flag, int)
  42. self.assertEqual(entry.sp_flag, entry[8])
  43. with self.assertRaises(KeyError) as cx:
  44. spwd.getspnam('invalid user name')
  45. self.assertEqual(str(cx.exception), "'getspnam(): name not found'")
  46. self.assertRaises(TypeError, spwd.getspnam)
  47. self.assertRaises(TypeError, spwd.getspnam, 0)
  48. self.assertRaises(TypeError, spwd.getspnam, random_name, 0)
  49. try:
  50. bytes_name = os.fsencode(random_name)
  51. except UnicodeEncodeError:
  52. pass
  53. else:
  54. self.assertRaises(TypeError, spwd.getspnam, bytes_name)
  55. @unittest.skipUnless(hasattr(os, 'geteuid') and os.geteuid() != 0,
  56. 'non-root user required')
  57. class TestSpwdNonRoot(unittest.TestCase):
  58. def test_getspnam_exception(self):
  59. name = 'bin'
  60. try:
  61. with self.assertRaises(PermissionError) as cm:
  62. spwd.getspnam(name)
  63. except KeyError as exc:
  64. self.skipTest("spwd entry %r doesn't exist: %s" % (name, exc))
  65. if __name__ == "__main__":
  66. unittest.main()