tests: SambaToolCmdTest.assertMatch() indicates what was asserted
[nivanova/samba-autobuild/.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
72     def runcmd(self, name, *args):
73         """run a single level command"""
74         cmd = cmd_sambatool.subcommands[name]
75         cmd.outf = StringIO()
76         cmd.errf = StringIO()
77         result = cmd._run("samba-tool %s" % name, *args)
78         return (result, cmd.outf.getvalue(), cmd.errf.getvalue())
79
80     def runsubcmd(self, name, sub, *args):
81         """run a command with sub commands"""
82         # The reason we need this function separate from runcmd is
83         # that the .outf StringIO assignment is overridden if we use
84         # runcmd, so we can't capture stdout and stderr
85         cmd = cmd_sambatool.subcommands[name].subcommands[sub]
86         cmd.outf = StringIO()
87         cmd.errf = StringIO()
88         result = cmd._run("samba-tool %s %s" % (name, sub), *args)
89         return (result, cmd.outf.getvalue(), cmd.errf.getvalue())
90
91     def assertCmdSuccess(self, exit, out, err, msg=""):
92         self.assertIsNone(exit, msg="exit[%s] stdout[%s] stderr[%s]: %s" % (
93                           exit, out, err, msg))
94
95     def assertCmdFail(self, val, msg=""):
96         self.assertIsNotNone(val, msg)
97
98     def assertMatch(self, base, string, msg=None):
99         if msg is None:
100             msg = "%r is not in %r" % (truncate_string(string),
101                                        truncate_string(base))
102         self.assertTrue(string in base, msg)
103
104     def randomName(self, count=8):
105         """Create a random name, cap letters and numbers, and always starting with a letter"""
106         name = random.choice(string.ascii_uppercase)
107         name += ''.join(random.choice(string.ascii_uppercase + string.ascii_lowercase+ string.digits) for x in range(count - 1))
108         return name
109
110     def randomPass(self, count=16):
111         name = random.choice(string.ascii_uppercase)
112         name += random.choice(string.digits)
113         name += random.choice(string.ascii_lowercase)
114         name += ''.join(random.choice(string.ascii_uppercase + string.ascii_lowercase+ string.digits) for x in range(count - 3))
115         return name
116
117     def randomXid(self):
118         # pick some hopefully unused, high UID/GID range to avoid interference
119         # from the system the test runs on
120         xid = random.randint(4711000, 4799000)
121         return xid
122
123     def assertWithin(self, val1, val2, delta, msg=""):
124         """Assert that val1 is within delta of val2, useful for time computations"""
125         self.assertTrue(((val1 + delta) > val2) and ((val1 - delta) < val2), msg)