tests: Add test-case for 'group list --verbose'
[samba.git] / python / samba / tests / samba_tool / group.py
1 # Unix SMB/CIFS implementation.
2 # Copyright (C) Michael Adam 2012
3 #
4 # This program is free software; you can redistribute it and/or modify
5 # it under the terms of the GNU General Public License as published by
6 # the Free Software Foundation; either version 3 of the License, or
7 # (at your option) any later version.
8 #
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 # GNU General Public License for more details.
13 #
14 # You should have received a copy of the GNU General Public License
15 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
16 #
17
18 import os
19 import time
20 import ldb
21 from samba.tests.samba_tool.base import SambaToolCmdTest
22 from samba import (
23         nttime2unix,
24         dsdb
25         )
26
27
28 class GroupCmdTestCase(SambaToolCmdTest):
29     """Tests for samba-tool group subcommands"""
30     groups = []
31     samdb = None
32
33     def setUp(self):
34         super(GroupCmdTestCase, self).setUp()
35         self.samdb = self.getSamDB("-H", "ldap://%s" % os.environ["DC_SERVER"],
36                                    "-U%s%%%s" % (os.environ["DC_USERNAME"], os.environ["DC_PASSWORD"]))
37         self.groups = []
38         self.groups.append(self._randomGroup({"name": "testgroup1"}))
39         self.groups.append(self._randomGroup({"name": "testgroup2"}))
40         self.groups.append(self._randomGroup({"name": "testgroup3"}))
41         self.groups.append(self._randomGroup({"name": "testgroup4"}))
42
43         # setup the 4 groups and ensure they are correct
44         for group in self.groups:
45             (result, out, err) = self._create_group(group)
46
47             self.assertCmdSuccess(result, out, err)
48             self.assertEquals(err, "", "There shouldn't be any error message")
49             self.assertIn("Added group %s" % group["name"], out)
50
51             found = self._find_group(group["name"])
52
53             self.assertIsNotNone(found)
54
55             self.assertEquals("%s" % found.get("name"), group["name"])
56             self.assertEquals("%s" % found.get("description"), group["description"])
57
58     def tearDown(self):
59         super(GroupCmdTestCase, self).tearDown()
60         # clean up all the left over groups, just in case
61         for group in self.groups:
62             if self._find_group(group["name"]):
63                 self.runsubcmd("group", "delete", group["name"])
64
65     def test_newgroup(self):
66         """This tests the "group add" and "group delete" commands"""
67         # try to add all the groups again, this should fail
68         for group in self.groups:
69             (result, out, err) = self._create_group(group)
70             self.assertCmdFail(result, "Succeeded to create existing group")
71             self.assertIn("LDAP error 68 LDAP_ENTRY_ALREADY_EXISTS", err)
72
73         # try to delete all the groups we just added
74         for group in self.groups:
75             (result, out, err) = self.runsubcmd("group", "delete", group["name"])
76             self.assertCmdSuccess(result, out, err,
77                                   "Failed to delete group '%s'" % group["name"])
78             found = self._find_group(group["name"])
79             self.assertIsNone(found,
80                               "Deleted group '%s' still exists" % group["name"])
81
82         # test adding groups
83         for group in self.groups:
84             (result, out, err) = self.runsubcmd("group", "add", group["name"],
85                                                 "--description=%s" % group["description"],
86                                                 "-H", "ldap://%s" % os.environ["DC_SERVER"],
87                                                 "-U%s%%%s" % (os.environ["DC_USERNAME"],
88                                                               os.environ["DC_PASSWORD"]))
89
90             self.assertCmdSuccess(result, out, err)
91             self.assertEquals(err, "", "There shouldn't be any error message")
92             self.assertIn("Added group %s" % group["name"], out)
93
94             found = self._find_group(group["name"])
95
96             self.assertEquals("%s" % found.get("samaccountname"),
97                               "%s" % group["name"])
98
99     def test_list(self):
100         (result, out, err) = self.runsubcmd("group", "list",
101                                             "-H", "ldap://%s" % os.environ["DC_SERVER"],
102                                             "-U%s%%%s" % (os.environ["DC_USERNAME"],
103                                                           os.environ["DC_PASSWORD"]))
104         self.assertCmdSuccess(result, out, err, "Error running list")
105
106         search_filter = "(objectClass=group)"
107
108         grouplist = self.samdb.search(base=self.samdb.domain_dn(),
109                                       scope=ldb.SCOPE_SUBTREE,
110                                       expression=search_filter,
111                                       attrs=["samaccountname"])
112
113         self.assertTrue(len(grouplist) > 0, "no groups found in samdb")
114
115         for groupobj in grouplist:
116             name = str(groupobj.get("samaccountname", idx=0))
117             found = self.assertMatch(out, name,
118                                      "group '%s' not found" % name)
119
120     def test_list_verbose(self):
121         (result, out, err) = self.runsubcmd("group", "list", "--verbose",
122                                             "-H", "ldap://%s" % os.environ["DC_SERVER"],
123                                             "-U%s%%%s" % (os.environ["DC_USERNAME"],
124                                                           os.environ["DC_PASSWORD"]))
125         self.assertCmdSuccess(result, out, err, "Error running list --verbose")
126
127         # use the output to build a dictionary, where key=group-name,
128         # value=num-members
129         output_memberships = {}
130
131         # split the output by line, skipping the first 2 header lines
132         group_lines = out.split('\n')[2:-1]
133         for line in group_lines:
134             # split line by column whitespace (but keep the group name together
135             # if it contains spaces)
136             values = line.split("   ")
137             name = values[0]
138             num_members = int(values[-1])
139             output_memberships[name] = num_members
140
141         # build up a similar dict using an LDAP search
142         search_filter = "(objectClass=group)"
143         grouplist = self.samdb.search(base=self.samdb.domain_dn(),
144                                       scope=ldb.SCOPE_SUBTREE,
145                                       expression=search_filter,
146                                       attrs=["samaccountname", "member"])
147         self.assertTrue(len(grouplist) > 0, "no groups found in samdb")
148
149         ldap_memberships = {}
150         for groupobj in grouplist:
151             name = str(groupobj.get("samaccountname", idx=0))
152             num_members = len(groupobj.get("member", default=[]))
153             ldap_memberships[name] = num_members
154
155         # check the command output matches LDAP
156         self.assertTrue(output_memberships == ldap_memberships,
157                         "Command output doesn't match LDAP results.\n" +
158                         "Command='%s'\nLDAP='%s'" %(output_memberships,
159                                                     ldap_memberships))
160
161     def test_listmembers(self):
162         (result, out, err) = self.runsubcmd("group", "listmembers", "Domain Users",
163                                             "-H", "ldap://%s" % os.environ["DC_SERVER"],
164                                             "-U%s%%%s" % (os.environ["DC_USERNAME"],
165                                                           os.environ["DC_PASSWORD"]))
166         self.assertCmdSuccess(result, out, err, "Error running listmembers")
167
168         search_filter = "(|(primaryGroupID=513)(memberOf=CN=Domain Users,CN=Users,%s))" % self.samdb.domain_dn()
169
170         grouplist = self.samdb.search(base=self.samdb.domain_dn(),
171                                       scope=ldb.SCOPE_SUBTREE,
172                                       expression=search_filter,
173                                       attrs=["samAccountName"])
174
175         self.assertTrue(len(grouplist) > 0, "no groups found in samdb")
176
177         for groupobj in grouplist:
178             name = str(groupobj.get("samAccountName", idx=0))
179             found = self.assertMatch(out, name, "group '%s' not found" % name)
180
181     def test_move(self):
182         full_ou_dn = str(self.samdb.normalize_dn_in_domain("OU=movetest"))
183         (result, out, err) = self.runsubcmd("ou", "create", full_ou_dn)
184         self.assertCmdSuccess(result, out, err)
185         self.assertEquals(err, "", "There shouldn't be any error message")
186         self.assertIn('Created ou "%s"' % full_ou_dn, out)
187
188         for group in self.groups:
189             (result, out, err) = self.runsubcmd(
190                 "group", "move", group["name"], full_ou_dn)
191             self.assertCmdSuccess(result, out, err, "Error running move")
192             self.assertIn('Moved group "%s" into "%s"' %
193                           (group["name"], full_ou_dn), out)
194
195         # Should fail as groups objects are in OU
196         (result, out, err) = self.runsubcmd("ou", "delete", full_ou_dn)
197         self.assertCmdFail(result)
198         self.assertIn(("subtree_delete: Unable to delete a non-leaf node "
199                        "(it has %d children)!") % len(self.groups), err)
200
201         for group in self.groups:
202             new_dn = "CN=Users,%s" % self.samdb.domain_dn()
203             (result, out, err) = self.runsubcmd(
204                 "group", "move", group["name"], new_dn)
205             self.assertCmdSuccess(result, out, err, "Error running move")
206             self.assertIn('Moved group "%s" into "%s"' %
207                           (group["name"], new_dn), out)
208
209         (result, out, err) = self.runsubcmd("ou", "delete", full_ou_dn)
210         self.assertCmdSuccess(result, out, err,
211                               "Failed to delete ou '%s'" % full_ou_dn)
212
213     def test_show(self):
214         """Assert that we can show a group correctly."""
215         (result, out, err) = self.runsubcmd("group", "show", "Domain Users",
216                                             "-H", "ldap://%s" % os.environ["DC_SERVER"],
217                                             "-U%s%%%s" % (os.environ["DC_USERNAME"],
218                                                           os.environ["DC_PASSWORD"]))
219         self.assertCmdSuccess(result, out, err)
220         self.assertEquals(err, "", "Shouldn't be any error messages")
221         self.assertIn("dn: CN=Domain Users,CN=Users,DC=samba,DC=example,DC=com", out)
222
223     def _randomGroup(self, base={}):
224         """create a group with random attribute values, you can specify base attributes"""
225         group = {
226             "name": self.randomName(),
227             "description": self.randomName(count=100),
228         }
229         group.update(base)
230         return group
231
232     def _create_group(self, group):
233         return self.runsubcmd("group", "add", group["name"],
234                               "--description=%s" % group["description"],
235                               "-H", "ldap://%s" % os.environ["DC_SERVER"],
236                               "-U%s%%%s" % (os.environ["DC_USERNAME"],
237                                             os.environ["DC_PASSWORD"]))
238
239     def _find_group(self, name):
240         search_filter = ("(&(sAMAccountName=%s)(objectCategory=%s,%s))" %
241                          (ldb.binary_encode(name),
242                           "CN=Group,CN=Schema,CN=Configuration",
243                           self.samdb.domain_dn()))
244         grouplist = self.samdb.search(base=self.samdb.domain_dn(),
245                                       scope=ldb.SCOPE_SUBTREE,
246                                       expression=search_filter,
247                                       attrs=[])
248         if grouplist:
249             return grouplist[0]
250         else:
251             return None
252
253     def test_stats(self):
254         (result, out, err) = self.runsubcmd("group", "stats",
255                                             "-H", "ldap://%s" % os.environ["DC_SERVER"],
256                                             "-U%s%%%s" % (os.environ["DC_USERNAME"],
257                                                           os.environ["DC_PASSWORD"]))
258         self.assertCmdSuccess(result, out, err, "Error running stats")
259
260         # sanity-check the command reports 'total groups' correctly
261         search_filter = "(objectClass=group)"
262         grouplist = self.samdb.search(base=self.samdb.domain_dn(),
263                                       scope=ldb.SCOPE_SUBTREE,
264                                       expression=search_filter,
265                                       attrs=[])
266
267         total_groups = len(grouplist)
268         self.assertTrue("Total groups: {0}".format(total_groups) in out,
269                         "Total groups not reported correctly")