PEP8: fix E302: expected 2 blank lines, found 1
[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
66     def test_newgroup(self):
67         """This tests the "group add" and "group delete" commands"""
68         # try to add all the groups again, this should fail
69         for group in self.groups:
70             (result, out, err) = self._create_group(group)
71             self.assertCmdFail(result, "Succeeded to create existing group")
72             self.assertIn("LDAP error 68 LDAP_ENTRY_ALREADY_EXISTS", err)
73
74         # try to delete all the groups we just added
75         for group in self.groups:
76             (result, out, err) = self.runsubcmd("group", "delete", group["name"])
77             self.assertCmdSuccess(result, out, err,
78                                   "Failed to delete group '%s'" % group["name"])
79             found = self._find_group(group["name"])
80             self.assertIsNone(found,
81                               "Deleted group '%s' still exists" % group["name"])
82
83         # test adding groups
84         for group in self.groups:
85             (result, out, err) = self.runsubcmd("group", "add", group["name"],
86                                                  "--description=%s" % group["description"],
87                                                  "-H", "ldap://%s" % os.environ["DC_SERVER"],
88                                                  "-U%s%%%s" % (os.environ["DC_USERNAME"],
89                                                                os.environ["DC_PASSWORD"]))
90
91             self.assertCmdSuccess(result, out, err)
92             self.assertEquals(err, "", "There shouldn't be any error message")
93             self.assertIn("Added group %s" % group["name"], out)
94
95             found = self._find_group(group["name"])
96
97             self.assertEquals("%s" % found.get("samaccountname"),
98                               "%s" % group["name"])
99
100
101     def test_list(self):
102         (result, out, err) = self.runsubcmd("group", "list",
103                                             "-H", "ldap://%s" % os.environ["DC_SERVER"],
104                                             "-U%s%%%s" % (os.environ["DC_USERNAME"],
105                                                           os.environ["DC_PASSWORD"]))
106         self.assertCmdSuccess(result, out, err, "Error running list")
107
108         search_filter = "(objectClass=group)"
109
110         grouplist = self.samdb.search(base=self.samdb.domain_dn(),
111                                       scope=ldb.SCOPE_SUBTREE,
112                                       expression=search_filter,
113                                       attrs=["samaccountname"])
114
115         self.assertTrue(len(grouplist) > 0, "no groups found in samdb")
116
117         for groupobj in grouplist:
118             name = groupobj.get("samaccountname", idx=0)
119             found = self.assertMatch(out, name,
120                                      "group '%s' not found" % name)
121
122     def test_listmembers(self):
123         (result, out, err) = self.runsubcmd("group", "listmembers", "Domain Users",
124                                             "-H", "ldap://%s" % os.environ["DC_SERVER"],
125                                             "-U%s%%%s" % (os.environ["DC_USERNAME"],
126                                                           os.environ["DC_PASSWORD"]))
127         self.assertCmdSuccess(result, out, err, "Error running listmembers")
128
129         search_filter = "(|(primaryGroupID=513)(memberOf=CN=Domain Users,CN=Users,%s))" % self.samdb.domain_dn()
130
131         grouplist = self.samdb.search(base=self.samdb.domain_dn(),
132                                       scope=ldb.SCOPE_SUBTREE,
133                                       expression=search_filter,
134                                       attrs=["samAccountName"])
135
136         self.assertTrue(len(grouplist) > 0, "no groups found in samdb")
137
138         for groupobj in grouplist:
139             name = groupobj.get("samAccountName", idx=0)
140             found = self.assertMatch(out, name, "group '%s' not found" % name)
141
142     def test_move(self):
143         full_ou_dn = str(self.samdb.normalize_dn_in_domain("OU=movetest"))
144         (result, out, err) = self.runsubcmd("ou", "create", full_ou_dn)
145         self.assertCmdSuccess(result, out, err)
146         self.assertEquals(err, "", "There shouldn't be any error message")
147         self.assertIn('Created ou "%s"' % full_ou_dn, out)
148
149         for group in self.groups:
150             (result, out, err) = self.runsubcmd(
151                 "group", "move", group["name"], full_ou_dn)
152             self.assertCmdSuccess(result, out, err, "Error running move")
153             self.assertIn('Moved group "%s" into "%s"' %
154                           (group["name"], full_ou_dn), out)
155
156         # Should fail as groups objects are in OU
157         (result, out, err) = self.runsubcmd("ou", "delete", full_ou_dn)
158         self.assertCmdFail(result)
159         self.assertIn(("subtree_delete: Unable to delete a non-leaf node "
160                        "(it has %d children)!") % len(self.groups), err)
161
162         for group in self.groups:
163             new_dn = "CN=Users,%s" % self.samdb.domain_dn()
164             (result, out, err) = self.runsubcmd(
165                 "group", "move", group["name"], new_dn)
166             self.assertCmdSuccess(result, out, err, "Error running move")
167             self.assertIn('Moved group "%s" into "%s"' %
168                           (group["name"], new_dn), out)
169
170         (result, out, err) = self.runsubcmd("ou", "delete", full_ou_dn)
171         self.assertCmdSuccess(result, out, err,
172                               "Failed to delete ou '%s'" % full_ou_dn)
173
174     def test_show(self):
175         """Assert that we can show a group correctly."""
176         (result, out, err) = self.runsubcmd("group", "show", "Domain Users",
177                                             "-H", "ldap://%s" % os.environ["DC_SERVER"],
178                                             "-U%s%%%s" % (os.environ["DC_USERNAME"],
179                                                           os.environ["DC_PASSWORD"]))
180         self.assertCmdSuccess(result, out, err)
181         self.assertEquals(err, "", "Shouldn't be any error messages")
182         self.assertIn("dn: CN=Domain Users,CN=Users,DC=samba,DC=example,DC=com", out)
183
184     def _randomGroup(self, base={}):
185         """create a group with random attribute values, you can specify base attributes"""
186         group = {
187             "name": self.randomName(),
188             "description": self.randomName(count=100),
189         }
190         group.update(base)
191         return group
192
193     def _create_group(self, group):
194         return self.runsubcmd("group", "add", group["name"],
195                               "--description=%s" % group["description"],
196                               "-H", "ldap://%s" % os.environ["DC_SERVER"],
197                               "-U%s%%%s" % (os.environ["DC_USERNAME"],
198                                             os.environ["DC_PASSWORD"]))
199
200     def _find_group(self, name):
201         search_filter = ("(&(sAMAccountName=%s)(objectCategory=%s,%s))" %
202                          (ldb.binary_encode(name),
203                           "CN=Group,CN=Schema,CN=Configuration",
204                           self.samdb.domain_dn()))
205         grouplist = self.samdb.search(base=self.samdb.domain_dn(),
206                                       scope=ldb.SCOPE_SUBTREE,
207                                       expression=search_filter,
208                                       attrs=[])
209         if grouplist:
210             return grouplist[0]
211         else:
212             return None