def test_expand_user(value, expect): struct = pwd.struct_passwd( ['tester', 'x', 1234, 1000, 'Test User', '/home/tester', '/bin/sh']) flexmock(os) \ .should_receive('geteuid') \ .and_return(1234) flexmock(pwd) \ .should_receive('getpwuid') \ .and_return(struct) flexmock(pwd) \ .should_receive('getpwnam') \ .and_return(struct) flexmock(grp) \ .should_receive('getgrnam') \ .and_return(grp.struct_group(['gx', 'x', 100, []])) flexmock(grp) \ .should_receive('getgrall') \ .and_return([ grp.struct_group(['g1', 'x', 101, []]), grp.struct_group(['g2', 'x', 102, ['tester']]), grp.struct_group(['.g-$ +3', 'x', 103, ['net+tester']]), grp.struct_group(['veryveryveryveryveryverylongname_thisnot', 'x', 104, ['tester']]), ]) result = expand_user({'global': {'user': value}}) assert result == expect
def getgrnam(name): if name == 'staff': return grp.struct_group(('staff', '*', 20, ['root'])) elif name == 'wheel': return grp.struct_group(('wheel', '*', 0, ['root'])) else: raise KeyError(f'getgrnam(): name not found: {name}')
def test_expand_user_non_posix(): longname = '[email protected]' shortname = longname[:32] posixname = 'This_is-not_a-posix-username.It-' struct = pwd.struct_passwd( [longname, 'x', 1234, 1000, 'Test User', '/home/tester', '/bin/sh']) flexmock(pwd) \ .should_receive('getpwnam') \ .and_return(struct) flexmock(grp) \ .should_receive('getgrnam') \ .and_return(grp.struct_group(['gx', 'x', 100, []])) flexmock(grp) \ .should_receive('getgrall') \ .and_return([ grp.struct_group(['g1', 'x', 101, [longname]]), grp.struct_group(['g2', 'x', 102, [shortname]]), grp.struct_group(['g3', 'x', 103, [posixname]]), ]) result = expand_user({'global': {'user': '******' + longname}}) expect = dict( name=posixname, uid=1234, system=False, sudo=False, comment=longname, groups=[{'name': 'gx', 'gid': 100}, {'name': 'g1', 'gid': 101}]) assert result == expect
def UserAdd_Group(User, GroupFile='/etc/group'): # 1. temporary file fd, TempGroupFile = mkstemp(prefix='group', dir='/tmp') # 2. add new group entry pw = pwd.getpwnam(User) gr = grp.struct_group( sequence = ( User, 'x', pw.pw_gid, ['www-data'])) grall = grp.getgrall() grall.append(gr) grall.sort(lambda a, b: cmp(a.gr_gid, b.gr_gid)) # 3. write groups to temporary file with fdopen(fd, 'w+') as fh: for gr in grall: if gr.gr_name in ['www-data', 'jail'] and User not in gr.gr_mem: gr.gr_mem.append(User) fh.write(':'.join(map(GroupItem, gr))+'\n') # 4. activate new group file rename(TempGroupFile, GroupFile) chown(GroupFile, 0, 0) chmod(GroupFile, 0644)
def _test_restore_vtpm( self, exists, mock_isdir, mock_exists, mock_chown, mock_move, mock_makedirs, mock_chmod, mock_getpwnam, mock_getgrnam, ): mock_exists.return_value = exists mock_isdir.return_value = True mock_getpwnam.return_value = pwd.struct_passwd( ('swtpm', '*', 1234, 1234, None, '/home/test', '/bin/bash')) mock_getgrnam.return_value = grp.struct_group(('swtpm', '*', 4321, [])) libvirt_utils.restore_vtpm_dir('dummy') if not exists: mock_makedirs.assert_called_once_with(libvirt_utils.VTPM_DIR) mock_chmod.assert_called_once_with(libvirt_utils.VTPM_DIR, 0o711) mock_getpwnam.assert_called_once_with(CONF.libvirt.swtpm_user) mock_getgrnam.assert_called_once_with(CONF.libvirt.swtpm_group) mock_chown.assert_called_with('dummy', 1234, 4321, recursive=True) mock_move.assert_called_with('dummy', libvirt_utils.VTPM_DIR)
def test_format_info(self): """ Tests the formatting of returned group information """ data = grp.struct_group(("wheel", "*", 0, ["root"])) ret = {"passwd": "*", "gid": 0, "name": "wheel", "members": ["root"]} self.assertEqual(mac_group._format_info(data), ret)
def test_format_info(self): ''' Tests the formatting of returned group information ''' data = grp.struct_group(('wheel', '*', 0, ['root'])) ret = {'passwd': '*', 'gid': 0, 'name': 'test', 'members': ['root']} self.assertDictEqual(groupadd._format_info(data), ret)
def load_groups(dirpath): # check if we need to reload cache group_file = os.path.join(dirpath, "etc/group") group_stamp = os.stat(group_file).st_mtime if group_stamp <= groups_lastupdate.get(dirpath, -1): return groups[dirpath] = group = {} gids[dirpath] = gid = {} f = open(group_file) for line in f: arr = line.rstrip().split(":") if len(arr) != 4: # Skip any line we can't make sense of. continue try: arr[2] = int(arr[2]) except ValueError: # Skip any line we can't make sense of. continue gr_entry = grp.struct_group(arr) group[gr_entry.gr_name] = gr_entry # Traditional systems allow multiple groups to have the same # group id, so only the first one should be mapped to the # current pw_entry. gid.setdefault(gr_entry.gr_gid, gr_entry) groups_lastupdate[dirpath] = group_stamp f.close()
def test_format_info(self): """ Tests the formatting of returned group information """ data = grp.struct_group(("wheel", "*", 0, ["root"])) ret = {"passwd": "*", "gid": 0, "name": "test", "members": ["root"]} self.assertDictEqual(groupadd._format_info(data), ret)
def load_groups(dirpath): # check if we need to reload cache group_file = os.path.join(dirpath, "etc/group") group_stamp = os.stat(group_file).st_mtime if group_stamp <= groups_lastupdate.get(dirpath, -1): return groups[dirpath] = group = {} gids[dirpath] = gid = {} f = file(group_file) for line in f: arr = line.rstrip().split(":") if len(arr) != 4: # Skip any line we can't make sense of. continue try: arr[2] = int(arr[2]) except ValueError: # Skip any line we can't make sense of. continue gr_entry = grp.struct_group(arr) group[gr_entry.gr_name] = gr_entry # Traditional systems allow multiple groups to have the same # group id, so only the first one should be mapped to the # current pw_entry. gid.setdefault(gr_entry.gr_gid, gr_entry) groups_lastupdate[dirpath] = group_stamp f.close()
def assert_create_user_and_group(mock_check_call, gid_exists, uid_exists): mock_pwent = pwd.struct_passwd(( 'someuser', # login name 'hunter2', # password 834, # uid 835, # gid 'Some User', # user name '/home/someuser', # home directory '/bin/sh')) # login shell mock_grent = grp.struct_group(( 'users', # group name '*', # password 835, # gid ['someuser'])) # members exception = subprocess.CalledProcessError( returncode=FileSystemImageSandbox._USER_OR_GROUP_ID_EXISTS, cmd='some command', output=None) mock_check_call.side_effect = [ None if gid_exists else exception, None if uid_exists else exception ] with temporary_dir() as d: with mock.patch.object(FileSystemImageSandbox, 'get_user_and_group', return_value=(mock_pwent, mock_grent)): sandbox = FileSystemImageSandbox(os.path.join(d, 'sandbox'), user='******') sandbox._create_user_and_group_in_taskfs() assert len(mock_check_call.mock_calls) == 2
class ConfigPermissions(unittest.TestCase): conf = {'dir': '', 'user': '', 'group': ''} pwd_root = pwd.struct_passwd( ('root', 'x', 0, 0, 'root', '/root', '/bin/bash')) grp_root = grp.struct_group(('root', 'x', 0, [])) def test_no_user(self): with patch.object(pwd, 'getpwnam', side_effect=KeyError()): with patch.object(grp, 'getgrnam', return_value=self.grp_root): res = test_manila.config_permission(self.conf) self.assertEqual(res.result, Result.SKIP) def test_no_group(self): with patch.object(pwd, 'getpwnam', return_value=self.pwd_root): with patch.object(grp, 'getgrnam', side_effect=KeyError()): res = test_manila.config_permission(self.conf) self.assertEqual(res.result, Result.SKIP) def test_good_perm(self): with patch.object(pwd, 'getpwnam', return_value=self.pwd_root): with patch.object(grp, 'getgrnam', return_value=self.grp_root): with patch.object(utils, 'validate_permissions', return_value=TestResult(Result.PASS)): res = test_manila.config_permission(self.conf) self.assertEqual(res.result, Result.PASS) def test_bad_perm(self): with patch.object(pwd, 'getpwnam', return_value=self.pwd_root): with patch.object(grp, 'getgrnam', return_value=self.grp_root): with patch.object(utils, 'validate_permissions', return_value=TestResult(Result.FAIL)): res = test_manila.config_permission(self.conf) self.assertEqual(res.result, Result.FAIL)
class MacGroupTestCase(TestCase): ''' TestCase for the salt.modules.mac_group module ''' mock_group = {'passwd': '*', 'gid': 0, 'name': 'wheel', 'members': ['root']} mock_getgrall = [grp.struct_group(('foo', '*', 20, ['test']))] # 'add' function tests: 4 # Only tested error handling # Full functionality tests covered in integration testing @patch('salt.modules.mac_group.info', MagicMock(return_value=mock_group)) def test_add_group_exists(self): ''' Tests if the group already exists or not ''' self.assertRaises(CommandExecutionError, mac_group.add, 'wheel') @patch('salt.modules.mac_group.info', MagicMock(return_value={})) def test_add_whitespace(self): ''' Tests if there is whitespace in the group name ''' self.assertRaises(SaltInvocationError, mac_group.add, 'white space') @patch('salt.modules.mac_group.info', MagicMock(return_value={})) def test_add_underscore(self): ''' Tests if the group name starts with an underscore or not ''' self.assertRaises(SaltInvocationError, mac_group.add, '_Test') @patch('salt.modules.mac_group.info', MagicMock(return_value={})) def test_add_gid_int(self): ''' Tests if the gid is an int or not ''' self.assertRaises(SaltInvocationError, mac_group.add, 'foo', 'foo') def test_info_whitespace(self): ''' Tests if there is whitespace in the group name ''' self.assertRaises(SaltInvocationError, mac_group.info, 'white space') @patch('grp.getgrall', MagicMock(return_value=mock_getgrall)) def test_info(self): ''' Tests the return of group information ''' ret = {'passwd': '*', 'gid': 20, 'name': 'foo', 'members': ['test']} self.assertEqual(mac_group.info('foo'), ret) def test_format_info(self): ''' Tests the formatting of returned group information ''' data = grp.struct_group(('wheel', '*', 0, ['root'])) ret = {'passwd': '*', 'gid': 0, 'name': 'wheel', 'members': ['root']} self.assertEqual(mac_group._format_info(data), ret)
def test_getent(self): """ Tests the return of information on all groups """ getgrnam = grp.struct_group(("foo", "*", 20, ["test"])) with patch("grp.getgrall", MagicMock(return_value=[getgrnam])): ret = [{"passwd": "*", "gid": 20, "name": "foo", "members": ["test"]}] self.assertEqual(groupadd.getent(), ret)
def test_info(self): ''' Tests the return of group information ''' getgrnam = grp.struct_group(('foo', '*', 20, ['test'])) with patch('grp.getgrnam', MagicMock(return_value=getgrnam)): ret = {'passwd': '*', 'gid': 20, 'name': 'foo', 'members': ['test']} self.assertEqual(groupadd.info('foo'), ret)
def test_info(self): """ Tests the return of group information """ mock_getgrall = [grp.struct_group(("foo", "*", 20, ["test"]))] with patch("grp.getgrall", MagicMock(return_value=mock_getgrall)): ret = {"passwd": "*", "gid": 20, "name": "foo", "members": ["test"]} self.assertEqual(mac_group.info("foo"), ret)
def test_info(self): """ Tests the return of group information """ getgrnam = grp.struct_group(("foo", "*", 20, ["test"])) with patch("grp.getgrnam", MagicMock(return_value=getgrnam)): ret = {"passwd": "*", "gid": 20, "name": "foo", "members": ["test"]} self.assertEqual(groupadd.info("foo"), ret)
def test_getent(self): ''' Tests the return of information on all groups ''' getgrnam = grp.struct_group(('foo', '*', 20, ['test'])) with patch('grp.getgrall', MagicMock(return_value=[getgrnam])): ret = [{'passwd': '*', 'gid': 20, 'name': 'foo', 'members': ['test']}] self.assertEqual(groupadd.getent(), ret)
def test_format_info(self): """ Tests the formatting of returned group information """ group = {"passwd": "*", "gid": 0, "name": "test", "members": ["root"]} with patch("salt.modules.groupadd._format_info", MagicMock(return_value=group)): data = grp.struct_group(("wheel", "*", 0, ["root"])) ret = {"passwd": "*", "gid": 0, "name": "test", "members": ["root"]} self.assertDictEqual(groupadd._format_info(data), ret)
def test_format_info(self): ''' Tests the formatting of returned group information ''' group = {'passwd': '*', 'gid': 0, 'name': 'test', 'members': ['root']} with patch('salt.modules.groupadd._format_info', MagicMock(return_value=group)): data = grp.struct_group(('wheel', '*', 0, ['root'])) ret = {'passwd': '*', 'gid': 0, 'name': 'test', 'members': ['root']} self.assertDictEqual(groupadd._format_info(data), ret)
def test_chugid_and_umask(self): running_user = this_user() running_group = grp.getgrgid(os.getgid()).gr_name gids = {30: "expectedgroup", 20: running_group} getgrnams = { "expectedgroup": grp.struct_group(("expectedgroup", "*", 30, ["expecteduser"])), running_group: grp.struct_group((running_group, "*", 20, [running_user])), } getpwnams = { "expecteduser": pwd.struct_passwd(("expecteduser", "x", 30, 30, "-", "-", "-")), running_user: pwd.struct_passwd((running_user, "x", 20, 20, "-", "-", "-")), } def getgrnam(group): return getgrnams[group] def getpwnam(user): return getpwnams[user] def getgrgid(gid): return getgrnams[gids[gid]] with patch("grp.getgrgid", getgrgid): with patch("grp.getgrnam", getgrnam): with patch("pwd.getpwnam", getpwnam): with patch("salt.utils.user.chugid") as chugid_mock: salt.utils.user.chugid_and_umask("expecteduser", umask=None, group=running_group) chugid_mock.assert_called_with("expecteduser", running_group) salt.utils.user.chugid_and_umask("expecteduser", umask=None, group=None) chugid_mock.assert_called_with("expecteduser", "expectedgroup")
def parseRecords(self): group_info = self.results[0].split(':') group_info[2] = int(group_info[2]) members = group_info[3] if members != '': members = members.split(',') else: members = [] group_info[3] = members self.group = struct_group(group_info)
def test_info(self): ''' Tests the return of group information ''' mock_getgrall = [grp.struct_group(('foo', '*', 20, ['test']))] with patch('grp.getgrall', MagicMock(return_value=mock_getgrall)): ret = { 'passwd': '*', 'gid': 20, 'name': 'foo', 'members': ['test'] } self.assertEqual(mac_group.info('foo'), ret)
def assert_create_user_and_group(mock_check_call, mock_verify, gid_exists, uid_exists, group_name_exists, user_name_exists): mock_pwent = pwd.struct_passwd(( 'someuser', # login name 'hunter2', # password 834, # uid 835, # gid 'Some User', # user name '/home/someuser', # home directory '/bin/sh')) # login shell mock_grent = grp.struct_group(( 'users', # group name '*', # password 835, # gid ['someuser'])) # members returncode = 0 if gid_exists or uid_exists: returncode = FileSystemImageSandbox._USER_OR_GROUP_ID_EXISTS elif group_name_exists or user_name_exists: returncode = FileSystemImageSandbox._USER_OR_GROUP_NAME_EXISTS exception = subprocess.CalledProcessError( returncode=returncode, cmd='some command', output=None) mock_check_call.side_effect = [ exception if gid_exists or group_name_exists else None, exception if uid_exists or user_name_exists else None] with temporary_dir() as d: with mock.patch.object( FileSystemImageSandbox, 'get_user_and_group', return_value=(mock_pwent, mock_grent)): sandbox = FileSystemImageSandbox( os.path.join(d, 'sandbox'), user='******', sandbox_mount_point='/some/path') sandbox._create_user_and_group_in_taskfs() assert len(mock_check_call.mock_calls) == 2 assert len(mock_verify.mock_calls) == 1
def test_06__get_group_from_host(self, mock_grgid, mock_grname): """Test06 NixAuthentication()._get_group_from_host().""" hgr = grp.struct_group(["root", "*", "0", str([])]) mock_grgid.return_value = hgr auth = NixAuthentication() (name, gid, mem) = auth._get_group_from_host(0) self.assertEqual(name, hgr.gr_name) self.assertEqual(gid, str(hgr.gr_gid)) self.assertEqual(mem, hgr.gr_mem) mock_grname.return_value = hgr auth = NixAuthentication() (name, gid, mem) = auth._get_group_from_host("root") self.assertEqual(name, hgr.gr_name) self.assertEqual(gid, str(hgr.gr_gid)) self.assertEqual(mem, hgr.gr_mem)
def _getgrall(root=None): """ Alternative implemetantion for getgrall, that use only /etc/group """ root = root or "/" passwd = os.path.join(root, "etc/group") with salt.utils.files.fopen(passwd) as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) comps = line.strip().split(":") if len(comps) < 4: log.debug("Ignoring group line: %s", line) continue # Generate a getgrall compatible output comps[2] = int(comps[2]) comps[3] = comps[3].split(",") if comps[3] else [] yield grp.struct_group(comps)
def _getgrnam(name, root=None): """ Alternative implementation for getgrnam, that use only /etc/group """ root = root or "/" passwd = os.path.join(root, "etc/group") with salt.utils.files.fopen(passwd) as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) comps = line.strip().split(":") if len(comps) < 4: log.debug("Ignoring group line: %s", line) continue if comps[0] == name: # Generate a getpwnam compatible output comps[2] = int(comps[2]) comps[3] = comps[3].split(",") if comps[3] else [] return grp.struct_group(comps) raise KeyError("getgrnam(): name not found: {}".format(name))
def get_group_map(self, key_by_gid=False): """ Returns dictionary where keys are remote group names and values are grp.struct_grp objects from the standard grp module key_by_gid=True will use the integer gid as the returned dictionary's keys instead of the group's name """ grp_file = self.ssh.remote_file('/etc/group', 'r') groups = [l.strip().split(':') for l in grp_file.readlines()] grp_file.close() grp_map = {} for group in groups: name, passwd, gid, mems = group gid = int(gid) mems = mems.split(',') key = name if key_by_gid: key = gid grp_map[key] = grp.struct_group([name, passwd, gid, mems]) return grp_map
def assert_create_user_and_group( mock_check_call, mock_verify, gid_exists, uid_exists, group_name_exists, user_name_exists ): mock_pwent = pwd.struct_passwd( ( "someuser", # login name "hunter2", # password 834, # uid 835, # gid "Some User", # user name "/home/someuser", # home directory "/bin/sh", ) ) # login shell mock_grent = grp.struct_group(("users", "*", 835, ["someuser"])) # group name # password # gid # members returncode = 0 if gid_exists or uid_exists: returncode = FileSystemImageSandbox._USER_OR_GROUP_ID_EXISTS elif group_name_exists or user_name_exists: returncode = FileSystemImageSandbox._USER_OR_GROUP_NAME_EXISTS exception = subprocess.CalledProcessError(returncode=returncode, cmd="some command", output=None) mock_check_call.side_effect = [ exception if gid_exists or group_name_exists else None, exception if uid_exists or user_name_exists else None, ] with temporary_dir() as d: with mock.patch.object(FileSystemImageSandbox, "get_user_and_group", return_value=(mock_pwent, mock_grent)): sandbox = FileSystemImageSandbox( os.path.join(d, "sandbox"), user="******", sandbox_mount_point="/some/path" ) sandbox._create_user_and_group_in_taskfs() assert len(mock_check_call.mock_calls) == 2 assert len(mock_verify.mock_calls) == 1
def get_groups(self): """Returns a list of groups on the computer. Each group is represented as a dict with the keys: C{name}, C{gid} and C{members}. """ user_names = set([x["username"] for x in self.get_users()]) groups = [] found_groupnames = set() for group in self.get_group_data(): if not isinstance(group, struct_group): group = struct_group(group) if group.gr_name in found_groupnames: continue member_names = user_names.intersection(group.gr_mem) groups.append({ "name": group.gr_name, "gid": group.gr_gid, "members": sorted(list(member_names)) }) found_groupnames.add(group.gr_name) return groups
def process(user_pks, pwall, spwall, grpall, set_sudo, user_ids): '''Generate the passwd, shadow, and sudo fragments for IAM users. :param user_pks: Mapping of username (``str``) to public keys (``list`` of ``str``) retrieved from IAM. :type user_pks: dict :param pwall: A list of ``pwd.struct_passwd`` including all password entries found by NSS. Should include those users identified by libnss-extrausers. :type pwall: list ''' username_index = dict( (user.pw_name, user) for user in pwall if is_iam_user(user)) susername_index = dict( (user[0], user) for user in spwall if user[0] in username_index) group_index = dict( (group[0], group) for group in grpall if is_iam_group(group)) next_uid = MIN_USER_UID passwd, shadow, sudo, group = [], [], [], [] # Users that have been removed from IAM will keep their UIDs around in the # event that user IDs have. In practice, I don't anticipate this behavior # to be problematic since there is an abundance of UIDs available in the # default configuration UID range for all but the largest admin user pools. #for old_username in set(username_index.keys()) - set(user_pks.keys()): # passwd.append(username_index[old_username]) # shadow.append(susername_index[old_username]) LOG.info("Not appending old users") for username in user_pks.keys(): next_uid = aws_to_unix_id(user_ids[username]) LOG.info("Calculated UID for %s is %s", next_uid, username) if set_sudo is True: sudo.append('{} ALL=(ALL) NOPASSWD:ALL'.format(username)) if username in username_index: passwd.append(username_index[username]) shadow.append(susername_index[username]) group.append(group_index[username]) else: passwd.append( pwd.struct_passwd(( username, 'x', next_uid, next_uid, 'IAM-USER', '/home/{}'.format(username), '/bin/bash', ))) shadow.append( spwd.struct_spwd(( username, '*', (datetime.datetime.utcnow() - EPOCH).days, 0, 99999, 7, -1, -1, -1, ))) group.append(grp.struct_group((username, 'x', next_uid, ''))) if set_sudo is True: sudo.sort() sudo.insert( 0, '# Created by {} on {}'.format(__file__, datetime.datetime.utcnow().ctime())) return (sorted(passwd_to_line(x) for x in passwd), sorted(shadow_to_line(x) for x in shadow), [x.encode('utf-8') for x in sudo], sorted(":".join( '' if isinstance(y, list) and len(y) == 0 else str(y) for y in x).encode('utf-8') for x in group))
class MacUserTestCase(TestCase): ''' TestCase for the salt.modules.mac_user modules ''' mac_user.__context__ = {} mac_user.__grains__ = {} mac_user.__salt__ = {} mock_pwall = [ pwd.struct_passwd(('_amavisd', '*', 83, 83, 'AMaViS Daemon', '/var/virusmails', '/usr/bin/false')), pwd.struct_passwd(('_appleevents', '*', 55, 55, 'AppleEvents Daemon', '/var/empty', '/usr/bin/false')), pwd.struct_passwd(('_appowner', '*', 87, 87, 'Application Owner', '/var/empty', '/usr/bin/false')) ] mock_pwnam = pwd.struct_passwd( ('_TEST_GROUP', '*', 83, 83, 'AMaViS Daemon', '/var/virusmails', '/usr/bin/false')) mock_getgrgid = grp.struct_group(('_TEST_GROUP', '*', 83, [])) mock_getgrall = [ grp.struct_group(('accessibility', '*', 90, [])), grp.struct_group(('admin', '*', 80, ['root', 'admin'])) ] mock_info_ret = { 'shell': '/bin/bash', 'name': 'test', 'gid': 4376, 'groups': ['TEST_GROUP'], 'home': '/var/test', 'fullname': 'TEST USER', 'uid': 4376 } def test_osmajor(self): ''' Tests version of OS X ''' with patch.dict(mac_user.__grains__, { 'kernel': 'Darwin', 'osrelease': '10.9.1' }): self.assertEqual(mac_user._osmajor(), 10.9) @skipIf(True, 'Waiting on some clarifications from bug report') def test_flush_dscl_cache(self): # TODO: Implement tests after clarifications come in pass def test_dscl(self): ''' Tests the creation of a dscl node ''' mac_mock = MagicMock(return_value={ 'pid': 4948, 'retcode': 0, 'stderr': '', 'stdout': '' }) with patch.dict(mac_user.__salt__, {'cmd.run_all': mac_mock}): with patch.dict(mac_user.__grains__, { 'kernel': 'Darwin', 'osrelease': '10.9.1' }): self.assertEqual(mac_user._dscl('username'), { 'pid': 4948, 'retcode': 0, 'stderr': '', 'stdout': '' }) @patch('pwd.getpwall', MagicMock(return_value=mock_pwall)) def test_first_avail_uid(self): ''' Tests the availability of the next uid ''' self.assertEqual(mac_user._first_avail_uid(), 501) @skipIf(True, 'Test not implemented yet') def test_add(self): # TODO: Implement this guy last pass @skipIf(True, 'Test not implemented yet') def test_delete(self): # TODO: Implement after chgroups is tested pass @patch('pwd.getpwall', MagicMock(return_value=mock_pwall)) @patch('salt.modules.mac_user.list_groups', MagicMock(return_value=['TEST_GROUP'])) def test_getent(self): ''' Tests the list of information for all users ''' ret = [{ 'shell': '/usr/bin/false', 'name': '_amavisd', 'gid': 83, 'groups': ['TEST_GROUP'], 'home': '/var/virusmails', 'fullname': 'AMaViS Daemon', 'uid': 83 }, { 'shell': '/usr/bin/false', 'name': '_appleevents', 'gid': 55, 'groups': ['TEST_GROUP'], 'home': '/var/empty', 'fullname': 'AppleEvents Daemon', 'uid': 55 }, { 'shell': '/usr/bin/false', 'name': '_appowner', 'gid': 87, 'groups': ['TEST_GROUP'], 'home': '/var/empty', 'fullname': 'Application Owner', 'uid': 87 }] self.assertEqual(mac_user.getent(), ret) def test_chuid_int(self): ''' Tests if the uid is an int ''' with self.assertRaises(SaltInvocationError): mac_user.chuid('foo', 'foo') @patch('salt.modules.mac_user.info', MagicMock(return_value={})) def test_chuid_user_exists(self): ''' Tests if the user exists or not ''' with self.assertRaises(CommandExecutionError): mac_user.chuid('foo', 4376) @patch('salt.modules.mac_user.info', MagicMock(return_value=mock_info_ret)) def test_chuid_same_uid(self): ''' Tests if the user's uid is the same as as the argument ''' self.assertTrue(mac_user.chuid('foo', 4376)) def test_chgid_int(self): ''' Tests if the gid is an int ''' with self.assertRaises(SaltInvocationError): mac_user.chgid('foo', 'foo') @patch('salt.modules.mac_user.info', MagicMock(return_value={})) def test_chgid_user_exists(self): ''' Tests if the user exists or not ''' with self.assertRaises(CommandExecutionError): mac_user.chgid('foo', 4376) @patch('salt.modules.mac_user.info', MagicMock(return_value=mock_info_ret)) def test_chgid_same_gid(self): ''' Tests if the user's gid is the same as as the argument ''' self.assertTrue(mac_user.chgid('foo', 4376)) @patch('salt.modules.mac_user.list_groups', MagicMock(return_value=['_TEST_GROUP'])) def test_info(self): ''' Tests the return of user information ''' mock_pwnam = pwd.struct_passwd( ('test', '*', 0, 0, 'TEST USER', '/var/test', '/bin/bash')) ret = { 'shell': '/bin/bash', 'name': 'test', 'gid': 0, 'groups': ['_TEST_GROUP'], 'home': '/var/test', 'fullname': 'TEST USER', 'uid': 0 } with patch('pwd.getpwnam', MagicMock(return_value=mock_pwnam)): self.assertEqual(mac_user.info('root'), ret) @patch('salt.modules.mac_user.list_groups', MagicMock(return_value=['_TEST_GROUP'])) def test_format_info(self): ''' Tests the formatting of returned user information ''' data = pwd.struct_passwd(('_TEST_GROUP', '*', 83, 83, 'AMaViS Daemon', '/var/virusmails', '/usr/bin/false')) ret = { 'shell': '/usr/bin/false', 'name': '_TEST_GROUP', 'gid': 83, 'groups': ['_TEST_GROUP'], 'home': '/var/virusmails', 'fullname': 'AMaViS Daemon', 'uid': 83 } self.assertEqual(mac_user._format_info(data), ret) @patch('pwd.getpwnam', MagicMock(return_value=mock_pwnam)) @patch('grp.getgrgid', MagicMock(return_value=mock_getgrgid)) @patch('grp.getgrall', MagicMock(return_value=mock_getgrall)) def test_list_groups(self): ''' Tests the list of groups the user belongs to ''' self.assertEqual(mac_user.list_groups('name'), ['_TEST_GROUP']) @patch('pwd.getpwall', MagicMock(return_value=mock_pwall)) def test_list_users(self): ''' Tests the list of all users ''' ret = ['_amavisd', '_appleevents', '_appowner'] self.assertEqual(mac_user.list_users(), ret)
class GroupAddTestCase(TestCase): ''' TestCase for salt.modules.groupadd ''' groupadd.__grains__ = {} groupadd.__salt__ = {} groupadd.__context__ = {} mock_group = {'passwd': '*', 'gid': 0, 'name': 'test', 'members': ['root']} mock_getgrnam = grp.struct_group(('foo', '*', 20, ['test'])) # 'add' function tests: 1 def test_add(self): ''' Tests if specified group was added ''' mock = MagicMock(return_value={'retcode': 0}) with patch.dict(groupadd.__salt__, {'cmd.run_all': mock}): self.assertTrue(groupadd.add('test', 100)) with patch.dict(groupadd.__grains__, {'kernel': 'Linux'}): with patch.dict(groupadd.__salt__, {'cmd.run_all': mock}): self.assertTrue(groupadd.add('test', 100, True)) # 'info' function tests: 1 @patch('grp.getgrnam', MagicMock(return_value=mock_getgrnam)) def test_info(self): ''' Tests the return of group information ''' ret = {'passwd': '*', 'gid': 20, 'name': 'foo', 'members': ['test']} self.assertEqual(groupadd.info('foo'), ret) # '_format_info' function tests: 1 @patch('salt.modules.groupadd._format_info', MagicMock(return_value=mock_group)) def test_format_info(self): ''' Tests the formatting of returned group information ''' data = grp.struct_group(('wheel', '*', 0, ['root'])) ret = {'passwd': '*', 'gid': 0, 'name': 'test', 'members': ['root']} self.assertDictEqual(groupadd._format_info(data), ret) # 'getent' function tests: 1 @patch('grp.getgrall', MagicMock(return_value=[mock_getgrnam])) def test_getent(self): ''' Tests the return of information on all groups ''' ret = [{'passwd': '*', 'gid': 20, 'name': 'foo', 'members': ['test']}] self.assertEqual(groupadd.getent(), ret) # 'chgid' function tests: 2 def test_chgid_gid_same(self): ''' Tests if the group id is the same as argument ''' mock_pre_gid = MagicMock(return_value=10) with patch.dict(groupadd.__salt__, {'file.group_to_gid': mock_pre_gid}): self.assertTrue(groupadd.chgid('test', 10)) def test_chgid(self): ''' Tests the gid for a named group was changed ''' mock_pre_gid = MagicMock(return_value=0) mock_cmdrun = MagicMock(return_value=0) with patch.dict(groupadd.__salt__, {'file.group_to_gid': mock_pre_gid}): with patch.dict(groupadd.__salt__, {'cmd.run': mock_cmdrun}): self.assertFalse(groupadd.chgid('test', 500)) # 'delete' function tests: 1 def test_delete(self): ''' Tests if the specified group was deleted ''' mock_ret = MagicMock(return_value={'retcode': 0}) with patch.dict(groupadd.__salt__, {'cmd.run_all': mock_ret}): self.assertTrue(groupadd.delete('test')) # 'adduser' function tests: 1 def test_adduser(self): ''' Tests if specified user gets added in the group. ''' mock = MagicMock(return_value={'retcode': 0}) with patch.dict(groupadd.__grains__, {'kernel': 'Linux'}): with patch.dict(groupadd.__salt__, {'cmd.retcode': mock}): self.assertFalse(groupadd.adduser('test', 'root')) with patch.dict(groupadd.__grains__, {'kernel': ''}): with patch.dict(groupadd.__salt__, {'cmd.retcode': mock}): self.assertFalse(groupadd.adduser('test', 'root')) # 'deluser' function tests: 1 def test_deluser(self): ''' Tests if specified user gets deleted from the group. ''' mock_ret = MagicMock(return_value={'retcode': 0}) mock_info = MagicMock(return_value={'passwd': '*', 'gid': 0, 'name': 'test', 'members': ['root']}) with patch.dict(groupadd.__grains__, {'kernel': 'Linux'}): with patch.dict(groupadd.__salt__, {'cmd.retcode': mock_ret, 'group.info': mock_info}): self.assertFalse(groupadd.deluser('test', 'root')) mock_stdout = MagicMock(return_value={'cmd.run_stdout': 1}) with patch.dict(groupadd.__grains__, {'kernel': 'OpenBSD'}): with patch.dict(groupadd.__salt__, {'cmd.retcode': mock_ret, 'group.info': mock_info, 'cmd.run_stdout': mock_stdout}): self.assertTrue(groupadd.deluser('foo', 'root')) # 'deluser' function tests: 1 def test_members(self): ''' Tests if members of the group, get replaced with a provided list. ''' mock_ret = MagicMock(return_value={'retcode': 0}) mock_info = MagicMock(return_value={'passwd': '*', 'gid': 0, 'name': 'test', 'members': ['root']}) with patch.dict(groupadd.__grains__, {'kernel': 'Linux'}): with patch.dict(groupadd.__salt__, {'cmd.retcode': mock_ret, 'group.info': mock_info}): self.assertFalse(groupadd.members('test', ['foo'])) mock_stdout = MagicMock(return_value={'cmd.run_stdout': 1}) mock = MagicMock() with patch.dict(groupadd.__grains__, {'kernel': 'OpenBSD'}): with patch.dict(groupadd.__salt__, {'cmd.retcode': mock_ret, 'group.info': mock_info, 'cmd.run_stdout': mock_stdout, 'cmd.run': mock}): self.assertFalse(groupadd.members('foo', ['root']))
class MacGroupTestCase(TestCase, LoaderModuleMockMixin): ''' TestCase for the salt.modules.mac_group module ''' def setup_loader_modules(self): return {mac_group: {}} mock_group = {'passwd': '*', 'gid': 0, 'name': 'test', 'members': ['root']} mock_getgrall = [grp.struct_group(('foo', '*', 20, ['test']))] @classmethod def tearDownClass(cls): for attrname in ('mock_group', 'mock_getgrall'): delattr(cls, attrname) # 'add' function tests: 6 @patch('salt.modules.mac_group.info', MagicMock(return_value=mock_group)) def test_add_group_exists(self): ''' Tests if the group already exists or not ''' self.assertRaises(CommandExecutionError, mac_group.add, 'test') @patch('salt.modules.mac_group.info', MagicMock(return_value={})) def test_add_whitespace(self): ''' Tests if there is whitespace in the group name ''' self.assertRaises(SaltInvocationError, mac_group.add, 'white space') @patch('salt.modules.mac_group.info', MagicMock(return_value={})) def test_add_underscore(self): ''' Tests if the group name starts with an underscore or not ''' self.assertRaises(SaltInvocationError, mac_group.add, '_Test') @patch('salt.modules.mac_group.info', MagicMock(return_value={})) def test_add_gid_int(self): ''' Tests if the gid is an int or not ''' self.assertRaises(SaltInvocationError, mac_group.add, 'foo', 'foo') @patch('salt.modules.mac_group.info', MagicMock(return_value={})) @patch('salt.modules.mac_group._list_gids', MagicMock(return_value=['3456'])) def test_add_gid_exists(self): ''' Tests if the gid is already in use or not ''' self.assertRaises(CommandExecutionError, mac_group.add, 'foo', 3456) @patch('salt.modules.mac_group.info', MagicMock(return_value={})) @patch('salt.modules.mac_group._list_gids', MagicMock(return_value=[])) def test_add(self): ''' Tests if specified group was added ''' mock_ret = MagicMock(return_value=0) with patch.dict(mac_group.__salt__, {'cmd.retcode': mock_ret}): self.assertTrue(mac_group.add('test', 500)) # 'delete' function tests: 4 def test_delete_whitespace(self): ''' Tests if there is whitespace in the group name ''' self.assertRaises(SaltInvocationError, mac_group.delete, 'white space') def test_delete_underscore(self): ''' Tests if the group name starts with an underscore or not ''' self.assertRaises(SaltInvocationError, mac_group.delete, '_Test') @patch('salt.modules.mac_group.info', MagicMock(return_value={})) def test_delete_group_exists(self): ''' Tests if the group to be deleted exists or not ''' self.assertTrue(mac_group.delete('test')) @patch('salt.modules.mac_group.info', MagicMock(return_value=mock_group)) def test_delete(self): ''' Tests if the specified group was deleted ''' mock_ret = MagicMock(return_value=0) with patch.dict(mac_group.__salt__, {'cmd.retcode': mock_ret}): self.assertTrue(mac_group.delete('test')) # 'info' function tests: 2 def test_info_whitespace(self): ''' Tests if there is whitespace in the group name ''' self.assertRaises(SaltInvocationError, mac_group.info, 'white space') @patch('grp.getgrall', MagicMock(return_value=mock_getgrall)) def test_info(self): ''' Tests the return of group information ''' ret = {'passwd': '*', 'gid': 20, 'name': 'foo', 'members': ['test']} self.assertEqual(mac_group.info('foo'), ret) # '_format_info' function tests: 1 def test_format_info(self): ''' Tests the formatting of returned group information ''' data = grp.struct_group(('wheel', '*', 0, ['root'])) ret = {'passwd': '*', 'gid': 0, 'name': 'wheel', 'members': ['root']} self.assertEqual(mac_group._format_info(data), ret) # 'getent' function tests: 1 @patch('grp.getgrall', MagicMock(return_value=mock_getgrall)) def test_getent(self): ''' Tests the return of information on all groups ''' ret = [{'passwd': '*', 'gid': 20, 'name': 'foo', 'members': ['test']}] self.assertEqual(mac_group.getent(), ret) # 'chgid' function tests: 4 def test_chgid_gid_int(self): ''' Tests if gid is an integer or not ''' self.assertRaises(SaltInvocationError, mac_group.chgid, 'foo', 'foo') @patch('salt.modules.mac_group.info', MagicMock(return_value={})) def test_chgid_group_exists(self): ''' Tests if the group id exists or not ''' mock_pre_gid = MagicMock(return_value='') with patch.dict(mac_group.__salt__, {'file.group_to_gid': mock_pre_gid}): self.assertRaises(CommandExecutionError, mac_group.chgid, 'foo', 4376) @patch('salt.modules.mac_group.info', MagicMock(return_value=mock_group)) def test_chgid_gid_same(self): ''' Tests if the group id is the same as argument ''' mock_pre_gid = MagicMock(return_value=0) with patch.dict(mac_group.__salt__, {'file.group_to_gid': mock_pre_gid}): self.assertTrue(mac_group.chgid('test', 0)) @patch('salt.modules.mac_group.info', MagicMock(return_value=mock_group)) def test_chgid(self): ''' Tests the gid for a named group was changed ''' mock_pre_gid = MagicMock(return_value=0) mock_ret = MagicMock(return_value=0) with patch.dict(mac_group.__salt__, {'file.group_to_gid': mock_pre_gid}): with patch.dict(mac_group.__salt__, {'cmd.retcode': mock_ret}): self.assertTrue(mac_group.chgid('test', 500))
def _getgrnam(self, real, name): return grp.struct_group((name, ) + self._groups[name])
line = salt.utils.stringutils.to_unicode(line) comps = line.strip().split(':') if len(comps) < 4: log.debug('Ignoring group line: %s', line) continue if comps[0] == name: # Generate a getpwnam compatible output comps[2] = int(comps[2]) comps[3] = comps[3].split(',') if comps[3] else [] return grp.struct_group(comps) raise KeyError('getgrnam(): name not found: {}'.format(name)) def _getgrall(root=None): ''' Alternative implemetantion for getgrall, that use only /etc/group ''' root = root or '/' passwd = os.path.join(root, 'etc/group') with salt.utils.files.fopen(passwd) as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) comps = line.strip().split(':') if len(comps) < 4: log.debug('Ignoring group line: %s', line) continue # Generate a getgrall compatible output comps[2] = int(comps[2]) comps[3] = comps[3].split(',') if comps[3] else [] yield grp.struct_group(comps)
class GroupAddTestCase(TestCase): ''' TestCase for salt.modules.groupadd ''' groupadd.__grains__ = {} groupadd.__salt__ = {} groupadd.__context__ = {} mock_group = {'passwd': '*', 'gid': 0, 'name': 'test', 'members': ['root']} mock_getgrnam = grp.struct_group(('foo', '*', 20, ['test'])) # 'add' function tests: 1 def test_add(self): ''' Tests if specified group was added ''' mock = MagicMock(return_value={'retcode': 0}) with patch.dict(groupadd.__salt__, {'cmd.run_all': mock}): self.assertTrue(groupadd.add('test', 100)) with patch.dict(groupadd.__grains__, {'kernel': 'Linux'}): with patch.dict(groupadd.__salt__, {'cmd.run_all': mock}): self.assertTrue(groupadd.add('test', 100, True)) # 'info' function tests: 1 @patch('grp.getgrnam', MagicMock(return_value=mock_getgrnam)) def test_info(self): ''' Tests the return of group information ''' ret = {'passwd': '*', 'gid': 20, 'name': 'foo', 'members': ['test']} self.assertEqual(groupadd.info('foo'), ret) # '_format_info' function tests: 1 @patch('salt.modules.groupadd._format_info', MagicMock(return_value=mock_group)) def test_format_info(self): ''' Tests the formatting of returned group information ''' data = grp.struct_group(('wheel', '*', 0, ['root'])) ret = {'passwd': '*', 'gid': 0, 'name': 'test', 'members': ['root']} self.assertDictEqual(groupadd._format_info(data), ret) # 'getent' function tests: 1 @patch('grp.getgrall', MagicMock(return_value=[mock_getgrnam])) def test_getent(self): ''' Tests the return of information on all groups ''' ret = [{'passwd': '*', 'gid': 20, 'name': 'foo', 'members': ['test']}] self.assertEqual(groupadd.getent(), ret) # 'chgid' function tests: 2 def test_chgid_gid_same(self): ''' Tests if the group id is the same as argument ''' mock_pre_gid = MagicMock(return_value=10) with patch.dict(groupadd.__salt__, {'file.group_to_gid': mock_pre_gid}): self.assertTrue(groupadd.chgid('test', 10)) def test_chgid(self): ''' Tests the gid for a named group was changed ''' mock_pre_gid = MagicMock(return_value=0) mock_cmdrun = MagicMock(return_value=0) with patch.dict(groupadd.__salt__, {'file.group_to_gid': mock_pre_gid}): with patch.dict(groupadd.__salt__, {'cmd.run': mock_cmdrun}): self.assertFalse(groupadd.chgid('test', 500)) # 'delete' function tests: 1 def test_delete(self): ''' Tests if the specified group was deleted ''' mock_ret = MagicMock(return_value={'retcode': 0}) with patch.dict(groupadd.__salt__, {'cmd.run_all': mock_ret}): self.assertTrue(groupadd.delete('test')) # 'adduser' function tests: 1 def test_adduser(self): ''' Tests if specified user gets added in the group. ''' os_version_list = [ { 'grains': { 'kernel': 'Linux', 'os_family': 'RedHat', 'osmajorrelease': '5' }, 'cmd': ('gpasswd', '-a', 'root', 'test') }, { 'grains': { 'kernel': 'Linux', 'os_family': 'Suse', 'osmajorrelease': '11' }, 'cmd': ('usermod', '-A', 'test', 'root') }, { 'grains': { 'kernel': 'Linux' }, 'cmd': ('gpasswd', '--add', 'root', 'test') }, { 'grains': { 'kernel': 'OTHERKERNEL' }, 'cmd': ('usermod', '-G', 'test', 'root') }, ] for os_version in os_version_list: mock = MagicMock(return_value={'retcode': 0}) with patch.dict(groupadd.__grains__, os_version['grains']): with patch.dict(groupadd.__salt__, {'cmd.retcode': mock}): self.assertFalse(groupadd.adduser('test', 'root')) groupadd.__salt__['cmd.retcode'].assert_called_once_with( os_version['cmd'], python_shell=False) # 'deluser' function tests: 1 def test_deluser(self): ''' Tests if specified user gets deleted from the group. ''' os_version_list = [ { 'grains': { 'kernel': 'Linux', 'os_family': 'RedHat', 'osmajorrelease': '5' }, 'cmd': ('gpasswd', '-d', 'root', 'test') }, { 'grains': { 'kernel': 'Linux', 'os_family': 'Suse', 'osmajorrelease': '11' }, 'cmd': ('usermod', '-R', 'test', 'root') }, { 'grains': { 'kernel': 'Linux' }, 'cmd': ('gpasswd', '--del', 'root', 'test') }, { 'grains': { 'kernel': 'OpenBSD' }, 'cmd': 'usermod -S foo root' }, ] for os_version in os_version_list: mock_ret = MagicMock(return_value={'retcode': 0}) mock_stdout = MagicMock(return_value='test foo') mock_info = MagicMock(return_value={ 'passwd': '*', 'gid': 0, 'name': 'test', 'members': ['root'] }) with patch.dict(groupadd.__grains__, os_version['grains']): with patch.dict( groupadd.__salt__, { 'cmd.retcode': mock_ret, 'group.info': mock_info, 'cmd.run_stdout': mock_stdout }): self.assertFalse(groupadd.deluser('test', 'root')) groupadd.__salt__['cmd.retcode'].assert_called_once_with( os_version['cmd'], python_shell=False) # 'deluser' function tests: 1 def test_members(self): ''' Tests if members of the group, get replaced with a provided list. ''' os_version_list = [ { 'grains': { 'kernel': 'Linux', 'os_family': 'RedHat', 'osmajorrelease': '5' }, 'cmd': ('gpasswd', '-M', 'foo', 'test') }, { 'grains': { 'kernel': 'Linux', 'os_family': 'Suse', 'osmajorrelease': '11' }, 'cmd': ('groupmod', '-A', 'foo', 'test') }, { 'grains': { 'kernel': 'Linux' }, 'cmd': ('gpasswd', '--members', 'foo', 'test') }, { 'grains': { 'kernel': 'OpenBSD' }, 'cmd': 'usermod -G test foo' }, ] for os_version in os_version_list: mock_ret = MagicMock(return_value={'retcode': 0}) mock_stdout = MagicMock(return_value={'cmd.run_stdout': 1}) mock_info = MagicMock(return_value={ 'passwd': '*', 'gid': 0, 'name': 'test', 'members': ['root'] }) mock = MagicMock(return_value=True) with patch.dict(groupadd.__grains__, os_version['grains']): with patch.dict( groupadd.__salt__, { 'cmd.retcode': mock_ret, 'group.info': mock_info, 'cmd.run_stdout': mock_stdout, 'cmd.run': mock }): self.assertFalse(groupadd.members('test', 'foo')) groupadd.__salt__['cmd.retcode'].assert_called_once_with( os_version['cmd'], python_shell=False)
class MacUserTestCase(TestCase): ''' TestCase for the salt.modules.mac_user modules ''' mac_user.__context__ = {} mac_user.__grains__ = {} mac_user.__salt__ = {} mock_pwall = [ pwd.struct_passwd(('_amavisd', '*', 83, 83, 'AMaViS Daemon', '/var/virusmails', '/usr/bin/false')), pwd.struct_passwd(('_appleevents', '*', 55, 55, 'AppleEvents Daemon', '/var/empty', '/usr/bin/false')), pwd.struct_passwd(('_appowner', '*', 87, 87, 'Application Owner', '/var/empty', '/usr/bin/false')) ] mock_pwnam = pwd.struct_passwd( ('_TEST_GROUP', '*', 83, 83, 'AMaViS Daemon', '/var/virusmails', '/usr/bin/false')) mock_getgrgid = grp.struct_group(('_TEST_GROUP', '*', 83, [])) mock_getgrall = [ grp.struct_group(('accessibility', '*', 90, [])), grp.struct_group(('admin', '*', 80, ['root', 'admin'])) ] mock_info_ret = { 'shell': '/bin/bash', 'name': 'test', 'gid': 4376, 'groups': ['TEST_GROUP'], 'home': '/Users/foo', 'fullname': 'TEST USER', 'uid': 4376 } @skipIf(True, 'Waiting on some clarifications from bug report #10594') def test_flush_dscl_cache(self): # TODO: Implement tests after clarifications come in pass def test_dscl(self): ''' Tests the creation of a dscl node ''' mac_mock = MagicMock(return_value={ 'pid': 4948, 'retcode': 0, 'stderr': '', 'stdout': '' }) with patch.dict(mac_user.__salt__, {'cmd.run_all': mac_mock}): with patch.dict( mac_user.__grains__, { 'kernel': 'Darwin', 'osrelease': '10.9.1', 'osrelease_info': (10, 9, 1) }): self.assertEqual(mac_user._dscl('username'), { 'pid': 4948, 'retcode': 0, 'stderr': '', 'stdout': '' }) @patch('pwd.getpwall', MagicMock(return_value=mock_pwall)) def test_first_avail_uid(self): ''' Tests the availability of the next uid ''' self.assertEqual(mac_user._first_avail_uid(), 501) # 'add' function tests: 4 # Only tested error handling # Full functionality tests covered in integration testing @patch('salt.modules.mac_user.info', MagicMock(return_value=mock_info_ret)) def test_add_user_exists(self): ''' Tests if the user exists or not ''' self.assertRaises(CommandExecutionError, mac_user.add, 'test') @patch('salt.modules.mac_user.info', MagicMock(return_value={})) def test_add_whitespace(self): ''' Tests if there is whitespace in the user name ''' self.assertRaises(SaltInvocationError, mac_user.add, 'foo bar') @patch('salt.modules.mac_user.info', MagicMock(return_value={})) def test_add_uid_int(self): ''' Tests if the uid is an int ''' self.assertRaises(SaltInvocationError, mac_user.add, 'foo', 'foo') @patch('salt.modules.mac_user.info', MagicMock(return_value={})) def test_add_gid_int(self): ''' Tests if the gid is an int ''' self.assertRaises(SaltInvocationError, mac_user.add, 'foo', 20, 'foo') # 'delete' function tests: 2 # Only tested pure logic of function # Full functionality tests covered in integration testing def test_delete_whitespace(self): ''' Tests if there is whitespace in the user name ''' self.assertRaises(SaltInvocationError, mac_user.delete, 'foo bar') @patch('salt.modules.mac_user.info', MagicMock(return_value={})) def test_delete_user_exists(self): ''' Tests if the user exists or not ''' self.assertTrue(mac_user.delete('foo')) @patch('pwd.getpwall', MagicMock(return_value=mock_pwall)) @patch('salt.modules.mac_user.list_groups', MagicMock(return_value=['TEST_GROUP'])) def test_getent(self): ''' Tests the list of information for all users ''' ret = [{ 'shell': '/usr/bin/false', 'name': '_amavisd', 'gid': 83, 'groups': ['TEST_GROUP'], 'home': '/var/virusmails', 'fullname': 'AMaViS Daemon', 'uid': 83 }, { 'shell': '/usr/bin/false', 'name': '_appleevents', 'gid': 55, 'groups': ['TEST_GROUP'], 'home': '/var/empty', 'fullname': 'AppleEvents Daemon', 'uid': 55 }, { 'shell': '/usr/bin/false', 'name': '_appowner', 'gid': 87, 'groups': ['TEST_GROUP'], 'home': '/var/empty', 'fullname': 'Application Owner', 'uid': 87 }] self.assertEqual(mac_user.getent(), ret) # 'chuid' function tests: 3 # Only tested pure logic of function # Full functionality tests covered in integration testing def test_chuid_int(self): ''' Tests if the uid is an int ''' self.assertRaises(SaltInvocationError, mac_user.chuid, 'foo', 'foo') @patch('salt.modules.mac_user.info', MagicMock(return_value={})) def test_chuid_user_exists(self): ''' Tests if the user exists or not ''' self.assertRaises(CommandExecutionError, mac_user.chuid, 'foo', 4376) @patch('salt.modules.mac_user.info', MagicMock(return_value=mock_info_ret)) def test_chuid_same_uid(self): ''' Tests if the user's uid is the same as as the argument ''' self.assertTrue(mac_user.chuid('foo', 4376)) # 'chgid' function tests: 3 # Only tested pure logic of function # Full functionality tests covered in integration testing def test_chgid_int(self): ''' Tests if the gid is an int ''' self.assertRaises(SaltInvocationError, mac_user.chgid, 'foo', 'foo') @patch('salt.modules.mac_user.info', MagicMock(return_value={})) def test_chgid_user_exists(self): ''' Tests if the user exists or not ''' self.assertRaises(CommandExecutionError, mac_user.chgid, 'foo', 4376) @patch('salt.modules.mac_user.info', MagicMock(return_value=mock_info_ret)) def test_chgid_same_gid(self): ''' Tests if the user's gid is the same as as the argument ''' self.assertTrue(mac_user.chgid('foo', 4376)) # 'chshell' function tests: 2 # Only tested pure logic of function # Full functionality tests covered in integration testing @patch('salt.modules.mac_user.info', MagicMock(return_value={})) def test_chshell_user_exists(self): ''' Tests if the user exists or not ''' self.assertRaises(CommandExecutionError, mac_user.chshell, 'foo', '/bin/bash') @patch('salt.modules.mac_user.info', MagicMock(return_value=mock_info_ret)) def test_chshell_same_shell(self): ''' Tests if the user's shell is the same as the argument ''' self.assertTrue(mac_user.chshell('foo', '/bin/bash')) # 'chhome' function tests: 2 # Only tested pure logic of function # Full functionality tests covered in integration testing @patch('salt.modules.mac_user.info', MagicMock(return_value={})) def test_chhome_user_exists(self): ''' Test if the user exists or not ''' self.assertRaises(CommandExecutionError, mac_user.chhome, 'foo', '/Users/foo') @patch('salt.modules.mac_user.info', MagicMock(return_value=mock_info_ret)) def test_chhome_same_home(self): ''' Tests if the user's home is the same as the argument ''' self.assertTrue(mac_user.chhome('foo', '/Users/foo')) # 'chfullname' function tests: 2 # Only tested pure logic of function # Full functionality tests covered in integration testing @patch('salt.modules.mac_user.info', MagicMock(return_value={})) def test_chfullname_user_exists(self): ''' Tests if the user exists or not ''' self.assertRaises(CommandExecutionError, mac_user.chfullname, 'test', 'TEST USER') @patch('salt.modules.mac_user.info', MagicMock(return_value=mock_info_ret)) def test_chfullname_same_name(self): ''' Tests if the user's full name is the same as the argument ''' self.assertTrue(mac_user.chfullname('test', 'TEST USER')) # 'chgroups' function tests: 3 # Only tested pure logic of function # Full functionality tests covered in integration testing @patch('salt.modules.mac_user.info', MagicMock(return_value={})) def test_chgroups_user_exists(self): ''' Tests if the user exists or not ''' self.assertRaises(CommandExecutionError, mac_user.chgroups, 'foo', 'wheel,root') @patch('salt.modules.mac_user.info', MagicMock(return_value=mock_info_ret)) def test_chgroups_bad_groups(self): ''' Test if there is white space in groups argument ''' self.assertRaises(SaltInvocationError, mac_user.chgroups, 'test', 'bad group') @patch('salt.modules.mac_user.info', MagicMock(return_value=mock_info_ret)) @patch('salt.modules.mac_user.list_groups', MagicMock(return_value=('wheel', 'root'))) def test_chgroups_same_desired(self): ''' Tests if the user's list of groups is the same as the arguments ''' mock_primary = MagicMock(return_value='wheel') with patch.dict(mac_user.__salt__, {'file.gid_to_group': mock_primary}): self.assertTrue(mac_user.chgroups('test', 'wheel,root')) @patch('salt.modules.mac_user.list_groups', MagicMock(return_value=['_TEST_GROUP'])) def test_info(self): ''' Tests the return of user information ''' mock_pwnam = pwd.struct_passwd( ('test', '*', 0, 0, 'TEST USER', '/var/test', '/bin/bash')) ret = { 'shell': '/bin/bash', 'name': 'test', 'gid': 0, 'groups': ['_TEST_GROUP'], 'home': '/var/test', 'fullname': 'TEST USER', 'uid': 0 } with patch('pwd.getpwnam', MagicMock(return_value=mock_pwnam)): self.assertEqual(mac_user.info('root'), ret) @patch('salt.modules.mac_user.list_groups', MagicMock(return_value=['_TEST_GROUP'])) def test_format_info(self): ''' Tests the formatting of returned user information ''' data = pwd.struct_passwd(('_TEST_GROUP', '*', 83, 83, 'AMaViS Daemon', '/var/virusmails', '/usr/bin/false')) ret = { 'shell': '/usr/bin/false', 'name': '_TEST_GROUP', 'gid': 83, 'groups': ['_TEST_GROUP'], 'home': '/var/virusmails', 'fullname': 'AMaViS Daemon', 'uid': 83 } self.assertEqual(mac_user._format_info(data), ret) @patch('pwd.getpwall', MagicMock(return_value=mock_pwall)) def test_list_users(self): ''' Tests the list of all users ''' ret = ['_amavisd', '_appleevents', '_appowner'] self.assertEqual(mac_user.list_users(), ret)
def setUp(self): import grp grp.getgrnam = minimock.Mock("grp.getgrnam", tracker=None) grp.getgrnam.mock_returns = grp.struct_group(("fakegroup", "x", -1, ["fakeuser"])) self.acl = AclFilter.ACL()