[SCM] Samba Shared Repository - branch master updated

Jelmer Vernooij jelmer at samba.org
Wed Oct 12 17:57:03 MDT 2011


The branch, master has been updated
       via  de9b3b6 samba-tools/testparm: Add really basic unit test, demonstrating how to write unit tests for samba-tool in Python.
       via  6f9a317 netcmd: Add Command.get_logger() method.
       via  63c9186 netcmd: Add errf stream to command instances.
       via  fba4b7a samba-tool/testparm: Fix traceback when checking client name/ip against hosts allowed.
       via  ba5b8a1 samba-tool/testparm: Fix handling of command-line options.
      from  7e9acf0 selftest: mark samba4.drs.delete_object.python knownfail

http://gitweb.samba.org/?p=samba.git;a=shortlog;h=master


- Log -----------------------------------------------------------------
commit de9b3b61906ae4f1862ccce81577b323fadbb27d
Author: Jelmer Vernooij <jelmer at samba.org>
Date:   Wed Oct 12 23:27:57 2011 +0200

    samba-tools/testparm: Add really basic unit test, demonstrating how to write unit tests for samba-tool in Python.
    
    Autobuild-User: Jelmer Vernooij <jelmer at samba.org>
    Autobuild-Date: Thu Oct 13 01:56:20 CEST 2011 on sn-devel-104

commit 6f9a3177d49d49d9a631cb1f2219761a4721b387
Author: Jelmer Vernooij <jelmer at samba.org>
Date:   Wed Oct 12 23:21:52 2011 +0200

    netcmd: Add Command.get_logger() method.

commit 63c9186e92ae2c7f1f7383352cc95d38b2efc45a
Author: Jelmer Vernooij <jelmer at samba.org>
Date:   Wed Oct 12 23:19:12 2011 +0200

    netcmd: Add errf stream to command instances.

commit fba4b7a5b9cba2c5319793fcf8bda9767836419e
Author: Jelmer Vernooij <jelmer at samba.org>
Date:   Wed Oct 12 23:11:14 2011 +0200

    samba-tool/testparm: Fix traceback when checking client name/ip against hosts allowed.

commit ba5b8a1056a1414d43120aec715c8e9a896c0290
Author: Jelmer Vernooij <jelmer at samba.org>
Date:   Wed Oct 12 23:10:14 2011 +0200

    samba-tool/testparm: Fix handling of command-line options.

-----------------------------------------------------------------------

Summary of changes:
 source4/scripting/bin/samba-tool                  |    3 +-
 source4/scripting/python/samba/netcmd/__init__.py |   20 +++++---
 source4/scripting/python/samba/netcmd/domain.py   |    3 +-
 source4/scripting/python/samba/netcmd/testparm.py |   61 +++++++++++----------
 source4/scripting/python/samba/tests/netcmd.py    |   29 ++++++++++
 5 files changed, 76 insertions(+), 40 deletions(-)


Changeset truncated at 500 lines:

diff --git a/source4/scripting/bin/samba-tool b/source4/scripting/bin/samba-tool
index f05fa3c..9f06e8d 100755
--- a/source4/scripting/bin/samba-tool
+++ b/source4/scripting/bin/samba-tool
@@ -45,7 +45,7 @@ from samba.netcmd.vampire import cmd_vampire
 
 class cmd_sambatool(SuperCommand):
     """samba-tool SuperCommand"""
-    
+
     subcommands = {}
     subcommands["dbcheck"] =  cmd_dbcheck()
     subcommands["delegation"] = cmd_delegation()
@@ -81,4 +81,5 @@ if __name__ == '__main__':
         retval = -1
     except Exception, e:
         cmd.show_command_error(e)
+        retval = 1
     sys.exit(retval)
diff --git a/source4/scripting/python/samba/netcmd/__init__.py b/source4/scripting/python/samba/netcmd/__init__.py
index 58d5660..49e0380 100644
--- a/source4/scripting/python/samba/netcmd/__init__.py
+++ b/source4/scripting/python/samba/netcmd/__init__.py
@@ -50,6 +50,7 @@ class Command(object):
         "versionopts": options.VersionOptions,
         }
     outf = sys.stdout
+    errf = sys.stderr
 
     def usage(self, *args):
         parser, _ = self._create_parser()
@@ -70,24 +71,23 @@ class Command(object):
 
         if isinstance(inner_exception, LdbError):
             (ldb_ecode, ldb_emsg) = inner_exception
-            print >>sys.stderr, "ERROR(ldb): %s - %s" % (message, ldb_emsg)
+            self.errf.write("ERROR(ldb): %s - %s\n" % (message, ldb_emsg))
         elif isinstance(inner_exception, AssertionError):
-            print >>sys.stderr, "ERROR(assert): %s" % message
+            self.errf.write("ERROR(assert): %s\n" % message)
             force_traceback = True
         elif isinstance(inner_exception, RuntimeError):
-            print >>sys.stderr, "ERROR(runtime): %s - %s" % (message, evalue)
+            self.errf.write("ERROR(runtime): %s - %s\n" % (message, evalue))
         elif type(inner_exception) is Exception:
-            print >>sys.stderr, "ERROR(exception): %s - %s" % (message, evalue)
+            self.errf.write("ERROR(exception): %s - %s\n" % (message, evalue))
             force_traceback = True
         elif inner_exception is None:
-            print >>sys.stderr, "ERROR: %s" % (message)
+            self.errf.write("ERROR: %s\n" % (message))
         else:
-            print >>sys.stderr, "ERROR(%s): %s - %s" % (str(etype), message, evalue)
+            self.errf.write("ERROR(%s): %s - %s\n" % (str(etype), message, evalue))
             force_traceback = True
 
         if force_traceback or samba.get_debug_level() >= 3:
             traceback.print_tb(etraceback)
-        sys.exit(1)
 
     def _create_parser(self):
         parser = optparse.OptionParser(usage=self.synopsis, 
@@ -141,6 +141,12 @@ class Command(object):
         """Run the command. This should be overriden by all subclasses."""
         raise NotImplementedError(self.run)
 
+    def get_logger(self, name="netcmd"):
+        """Get a logger object."""
+        import logging
+        logger = logging.getLogger(name)
+        logger.addHandler(logging.StreamHandler(self.outf))
+        return logger
 
 
 class SuperCommand(Command):
diff --git a/source4/scripting/python/samba/netcmd/domain.py b/source4/scripting/python/samba/netcmd/domain.py
index f1125b2..05e82b5 100644
--- a/source4/scripting/python/samba/netcmd/domain.py
+++ b/source4/scripting/python/samba/netcmd/domain.py
@@ -573,8 +573,7 @@ samba3 testparm utility (with --testparm)."""
             self.outf.write("warning: both libdir and testparm specified, ignoring libdir.\n")
             libdir = None
 
-        logger = logging.getLogger("upgrade")
-        logger.addHandler(logging.StreamHandler(sys.stdout))
+        logger = self.get_logger()
         if quiet:
             logger.setLevel(logging.WARNING)
         else:
diff --git a/source4/scripting/python/samba/netcmd/testparm.py b/source4/scripting/python/samba/netcmd/testparm.py
index 53d6d80..b997977 100755
--- a/source4/scripting/python/samba/netcmd/testparm.py
+++ b/source4/scripting/python/samba/netcmd/testparm.py
@@ -3,13 +3,14 @@
 #
 #   Unix SMB/CIFS implementation.
 #   Test validity of smb.conf
-#   Copyright (C) Karl Auer 1993, 1994-1998
-#   Copyright Giampaolo Lauria 2011 <lauria2 at yahoo.com>
+#   Copyright (C) 2010-2011 Jelmer Vernooij <jelmer at samba.org>
+#   Copyright (C) Giampaolo Lauria 2011 <lauria2 at yahoo.com>
 #
+# Based on the original in C:
+#   Copyright (C) Karl Auer 1993, 1994-1998
 #   Extensively modified by Andrew Tridgell, 1995
 #   Converted to popt by Jelmer Vernooij (jelmer at nl.linux.org), 2002
 #   Updated for Samba4 by Andrew Bartlett <abartlet at samba.org> 2006
-#   Converted to Python by Jelmer Vernooij <jelmer at samba.org> 2010
 #
 # This program is free software; you can redistribute it and/or modify
 # it under the terms of the GNU General Public License as published by
@@ -35,7 +36,6 @@
 
 import os
 import sys
-import logging
 
 import samba
 import samba.getopt as options
@@ -44,11 +44,11 @@ from samba.netcmd import Command, CommandError, Option
 class cmd_testparm(Command):
     """Syntax check the configuration file"""
 
-    synopsis = "%prog testparm [<hostname>] [<hostip>] [options]"
+    synopsis = "%prog testparm [options]"
 
     takes_optiongroups = {
         "sambaopts" : options.SambaOptions,
-        "versionops" : options.VersionOptions
+        "versionopts": options.VersionOptions
     }
 
     takes_options = [
@@ -72,43 +72,46 @@ class cmd_testparm(Command):
                help="Show the parameters, type, possible values")
         ]
 
-    takes_args = ["hostname?", "hostip?"]
-
-    def run(self, *args, **kwargs):
-        if kwargs.get('hostname', None) is not None and \
-           kwargs.get('hostip', None) is None:
-            raise CommandError("Both a DNS name and an IP address are " \
+    takes_args = []
+
+    def run(self, sambaopts, versionopts, 
+            section_name=None, parameter_name=None,
+            client_ip=None, client_name=None, verbose=False,
+            suppress_prompt=None,
+            show_all_parameters=False, server=None):
+        if server:
+            raise NotImplementedError("--server not yet implemented")
+        if show_all_parameters:
+            raise NotImplementedError("--show-all-parameters not yet implemented")
+        if client_name is not None and client_ip is None:
+            raise CommandError("Both a DNS name and an IP address are "
                                "required for the host access check")
 
-        lp = kwargs['sambaopts'].get_loadparm()
+        lp = sambaopts.get_loadparm()
 
         # We need this to force the output
         samba.set_debug_level(2)
 
-        logger = logging.getLogger("testparm")
-        logger.addHandler(logging.StreamHandler(sys.stdout))
+        logger = self.get_logger("testparm")
 
         logger.info("Loaded smb config files from %s", lp.configfile)
         logger.info("Loaded services file OK.")
 
         valid = self.do_global_checks(lp, logger)
         valid = valid and self.do_share_checks(lp, logger)
-        if kwargs.get('hostname', None) is not None and \
-           kwargs.get('hostip', None) is not None:
-            self.check_client_access(lp, kwargs['hostname'], kwargs['hostip'])
+        if client_name is not None and client_ip is not None:
+            self.check_client_access(lp, logger, client_name, client_ip)
         else:
-            if kwargs.get('section_name', None) is not None or \
-               kwargs.get('parameter_name', None) is not None:
-                if kwargs.get('parameter_name', None) is None:
-                    lp[kwargs['section_name']].dump(sys.stdout, lp.default_service,
-                                               kwargs['verbose'])
+            if section_name is not None or parameter_name is not None:
+                if parameter_name is None:
+                    lp[section_name].dump(sys.stdout, lp.default_service, verbose)
                 else:
-                    print lp.get(kwargs['parameter_name'], kwargs['section_name'])
+                    print lp.get(parameter_name, section_name)
             else:
-                if not kwargs['suppress_prompt']:
-                    print "Press enter to see a dump of your service definitions\n"
+                if not suppress_prompt:
+                    print "Press enter to see a dump of your service definitions"
                     sys.stdin.readline()
-                lp.dump(sys.stdout, kwargs['verbose'])
+                lp.dump(sys.stdout, verbose)
         if valid:
             return
         else:
@@ -155,11 +158,9 @@ class cmd_testparm(Command):
 
         return valid
 
-
     def allow_access(self, deny_list, allow_list, cname, caddr):
         raise NotImplementedError(self.allow_access)
 
-
     def do_share_checks(self, lp, logger):
         valid = True
         for s in lp.services():
@@ -188,7 +189,7 @@ class cmd_testparm(Command):
                         valid = False
         return valid
 
-    def check_client_access(self, lp, cname, caddr):
+    def check_client_access(self, lp, logger, cname, caddr):
         # this is totally ugly, a real `quick' hack
         for s in lp.services():
             if (self.allow_access(lp.get("hosts deny"), lp.get("hosts allow"), cname,
diff --git a/source4/scripting/python/samba/tests/netcmd.py b/source4/scripting/python/samba/tests/netcmd.py
index 7b53d53..4f06124 100644
--- a/source4/scripting/python/samba/tests/netcmd.py
+++ b/source4/scripting/python/samba/tests/netcmd.py
@@ -19,10 +19,39 @@
 
 """Tests for samba.netcmd."""
 
+from cStringIO import StringIO
 from samba.netcmd import Command
+from samba.netcmd.testparm import cmd_testparm
 import samba.tests
 
+class NetCmdTestCase(samba.tests.TestCase):
+
+    def run_netcmd(self, cmd_klass, args, retcode=0):
+        cmd = cmd_klass()
+        cmd.outf = StringIO()
+        cmd.errf = StringIO()
+        try:
+            retval = cmd._run(cmd_klass.__name__, *args)
+        except Exception, e:
+            cmd.show_command_error(e)
+            retval = 1
+        self.assertEquals(retcode, retval)
+        return cmd.outf.getvalue(), cmd.errf.getvalue()
+
+
+class TestParmTests(NetCmdTestCase):
+
+    def test_no_client_ip(self):
+        out, err = self.run_netcmd(cmd_testparm, ["--client-name=foo"],
+            retcode=-1)
+        self.assertEquals("", out)
+        self.assertEquals(
+            "ERROR: Both a DNS name and an IP address are "
+            "required for the host access check\n", err)
+
+
 class CommandTests(samba.tests.TestCase):
+
     def test_description(self):
         class cmd_foo(Command):
             """Mydescription"""


-- 
Samba Shared Repository


More information about the samba-cvs mailing list