PEP8: fix E401: multiple imports on one line
[samba.git] / python / samba / tests / samba_tool / base.py
1 # Unix SMB/CIFS implementation.
2 # Copyright (C) Sean Dague <sdague@linux.vnet.ibm.com> 2011
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 # This provides a wrapper around the cmd interface so that tests can
18 # easily be built on top of it and have minimal code to run basic tests
19 # of the commands. A list of the environmental variables can be found in
20 # ~/selftest/selftest.pl
21 #
22 # These can all be accesses via os.environ["VARIBLENAME"] when needed
23
24 import random
25 import string
26 from samba.auth import system_session
27 from samba.samdb import SamDB
28 from cStringIO import StringIO
29 from samba.netcmd.main import cmd_sambatool
30 import samba.tests
31
32
33 def truncate_string(s, cutoff=100):
34     if len(s) < cutoff + 15:
35         return s
36     return s[:cutoff] + '[%d more characters]' % (len(s) - cutoff)
37
38
39 class SambaToolCmdTest(samba.tests.BlackboxTestCase):
40
41     def getSamDB(self, *argv):
42         """a convenience function to get a samdb instance so that we can query it"""
43
44         # We build a fake command to get the options created the same
45         # way the command classes do it. It would be better if the command
46         # classes had a way to more cleanly do this, but this lets us write
47         # tests for now
48         cmd = cmd_sambatool.subcommands["user"].subcommands["setexpiry"]
49         parser, optiongroups = cmd._create_parser("user")
50         opts, args = parser.parse_args(list(argv))
51         # Filter out options from option groups
52         args = args[1:]
53         kwargs = dict(opts.__dict__)
54         for option_group in parser.option_groups:
55             for option in option_group.option_list:
56                 if option.dest is not None:
57                     del kwargs[option.dest]
58         kwargs.update(optiongroups)
59
60         H = kwargs.get("H", None)
61         sambaopts = kwargs.get("sambaopts", None)
62         credopts = kwargs.get("credopts", None)
63
64         lp = sambaopts.get_loadparm()
65         creds = credopts.get_credentials(lp, fallback_machine=True)
66
67         samdb = SamDB(url=H, session_info=system_session(),
68                       credentials=creds, lp=lp)
69         return samdb
70
71     def runcmd(self, name, *args):
72         """run a single level command"""
73         cmd = cmd_sambatool.subcommands[name]
74         cmd.outf = StringIO()
75         cmd.errf = StringIO()
76         result = cmd._run("samba-tool %s" % name, *args)
77         return (result, cmd.outf.getvalue(), cmd.errf.getvalue())
78
79     def runsubcmd(self, name, sub, *args):
80         """run a command with sub commands"""
81         # The reason we need this function separate from runcmd is
82         # that the .outf StringIO assignment is overridden if we use
83         # runcmd, so we can't capture stdout and stderr
84         cmd = cmd_sambatool.subcommands[name].subcommands[sub]
85         cmd.outf = StringIO()
86         cmd.errf = StringIO()
87         result = cmd._run("samba-tool %s %s" % (name, sub), *args)
88         return (result, cmd.outf.getvalue(), cmd.errf.getvalue())
89
90     def runsublevelcmd(self, name, sublevels, *args):
91         """run a command with any number of sub command levels"""
92         # Same as runsubcmd, except this handles a varying number of sub-command
93         # levels, e.g. 'samba-tool domain passwordsettings pso set', whereas
94         # runsubcmd() only handles exactly one level of sub-commands.
95         # First, traverse the levels of sub-commands to get the actual cmd
96         # object we'll run, and construct the cmd string along the way
97         cmd = cmd_sambatool.subcommands[name]
98         cmd_str = "samba-tool %s" % name
99         for sub in sublevels:
100             cmd = cmd.subcommands[sub]
101             cmd_str += " %s" % sub
102         cmd.outf = StringIO()
103         cmd.errf = StringIO()
104         result = cmd._run(cmd_str, *args)
105         return (result, cmd.outf.getvalue(), cmd.errf.getvalue())
106
107     def assertCmdSuccess(self, exit, out, err, msg=""):
108         self.assertIsNone(exit, msg="exit[%s] stdout[%s] stderr[%s]: %s" % (
109                           exit, out, err, msg))
110
111     def assertCmdFail(self, val, msg=""):
112         self.assertIsNotNone(val, msg)
113
114     def assertMatch(self, base, string, msg=None):
115         # Note: we should stop doing this and just use self.assertIn()
116         if msg is None:
117             msg = "%r is not in %r" % (truncate_string(string),
118                                        truncate_string(base))
119         self.assertIn(string, base, msg)
120
121     def randomName(self, count=8):
122         """Create a random name, cap letters and numbers, and always starting with a letter"""
123         name = random.choice(string.ascii_uppercase)
124         name += ''.join(random.choice(string.ascii_uppercase + string.ascii_lowercase + string.digits) for x in range(count - 1))
125         return name
126
127     def randomPass(self, count=16):
128         name = random.choice(string.ascii_uppercase)
129         name += random.choice(string.digits)
130         name += random.choice(string.ascii_lowercase)
131         name += ''.join(random.choice(string.ascii_uppercase + string.ascii_lowercase + string.digits) for x in range(count - 3))
132         return name
133
134     def randomXid(self):
135         # pick some hopefully unused, high UID/GID range to avoid interference
136         # from the system the test runs on
137         xid = random.randint(4711000, 4799000)
138         return xid
139
140     def assertWithin(self, val1, val2, delta, msg=""):
141         """Assert that val1 is within delta of val2, useful for time computations"""
142         self.assertTrue(((val1 + delta) > val2) and ((val1 - delta) < val2), msg)