PATCH: Boolean convenience function for Context

Mark Mitchell mark at codesourcery.com
Thu Nov 13 03:12:16 UTC 2003


This patch adds a convenience function for getting the values of boolean
context variables.

-- 
Mark Mitchell <mark at codesourcery.com>
CodeSourcery, LLC
-------------- next part --------------
2003-11-12  Mark Mitchell  <mark at codesourcery.com>

	* qm/common.py (parse_boolean): New function.
	* qm/fields.py (BooleanField.Validate): New method.
	* qm/test/context.py (ContextException.__init__): Generalize.
	(Context.GetBoolean): New method.
	* qm/test/result.py (Result.NoteException): Simplify.
	* qm/test/share/messages/diagnostics.txt (invalid boolean context
	var): New message.
	(missing context variable): Likewise.

Index: qm/common.py
===================================================================
RCS file: /home/sc/Repository/qm/qm/common.py,v
retrieving revision 1.76
diff -c -5 -p -r1.76 common.py
*** qm/common.py	13 Nov 2003 01:52:58 -0000	1.76
--- qm/common.py	13 Nov 2003 02:52:55 -0000
*************** def split_argument_list(command):
*** 680,689 ****
--- 680,710 ----
      # Split the command into argument list elements at spaces.
      argument_list = re.split(" +", command)
      return argument_list
  
  
+ def parse_boolean(value):
+     """Parse a boolean string.
+ 
+     'value' -- A string.
+ 
+     returns -- True if 'value' is a true string, false if 'value' is a
+     false string.
+ 
+     raises -- 'ValueError' if 'value' is neither a true string, nor a
+     false string."""
+ 
+     value = value.lower()
+     if value in ("1", "true", "yes", "on"):
+         return 1
+     elif value in ("0", "false", "no", "off"):
+         return 0
+     else:
+         raise ValueError, value
+ 
+     
+     
  # No 'time.strptime' on non-UNIX systems, so use this instead.  This
  # version is more forgiving, anyway, and uses our standardized timestamp
  # format. 
  
  def parse_time(time_string, default_local_time_zone=1):
Index: qm/fields.py
===================================================================
RCS file: /home/sc/Repository/qm/qm/fields.py,v
retrieving revision 1.79
diff -c -5 -p -r1.79 fields.py
*** qm/fields.py	15 Oct 2003 08:34:29 -0000	1.79
--- qm/fields.py	13 Nov 2003 02:52:55 -0000
*************** class BooleanField(EnumerationField):
*** 1583,1592 ****
--- 1583,1600 ----
  
          # Construct the base class.
          EnumerationField.__init__(self, name, default_value,
                                    ["true", "false"], **properties)
  
+ 
+     def Validate(self, value):
+ 
+         if qm.common.parse_boolean(value):
+             value = "true"
+         else:
+             value = "false"
+         return super(BooleanField, self).Validate(value)
          
  
  ########################################################################
  
  class TimeField(IntegerField):
Index: qm/test/context.py
===================================================================
RCS file: /home/sc/Repository/qm/qm/test/context.py,v
retrieving revision 1.12
diff -c -5 -p -r1.12 context.py
*** qm/test/context.py	9 Aug 2003 05:15:02 -0000	1.12
--- qm/test/context.py	13 Nov 2003 02:52:56 -0000
*************** import types
*** 24,42 ****
  ########################################################################
  # Classes
  ########################################################################
  
  class ContextException(qm.common.QMException):
!     """A 'ContextException' indicates a missing context variable."""
  
!     def __init__(self, key):
          """Construct a new 'ContextException'.
  
!         'key' -- A string giving the context key for which no value
!         was available."""
  
!         qm.common.QMException.__init__(self, "Missing context variable.")
          self.key = key
  
          
      
  class ContextWrapper:
--- 24,46 ----
  ########################################################################
  # Classes
  ########################################################################
  
  class ContextException(qm.common.QMException):
!     """A 'ContextException' indicates an invalid context variable."""
  
!     def __init__(self, key, msg = "missing context variable"):
          """Construct a new 'ContextException'.
  
!         'key' -- A string giving the context key for which no valid
!         value was available.
  
!         'msg' -- A diagnostic identifier explaining the problem.  The
!         message string may contain a fill-in for the key."""
! 
!         msg = qm.error(msg, key = key)
!         qm.common.QMException.__init__(self, msg)
          self.key = key
  
          
      
  class ContextWrapper:
*************** class Context(types.DictType):
*** 99,108 ****
--- 103,137 ----
              value = qm.rc.Get(option, None)
              assert value is not None
              self[option] = value
  
  
+     def GetBoolean(self, key, default = None):
+         """Return the boolean value associated with 'key'.
+ 
+         'key' -- A string.
+ 
+         'default' -- A default value, used if 'key' has no assicated
+         value.
+ 
+         returns -- The value associated with 'key' in the context,
+         interpreted as a boolean.
+ 
+         The value associated with 'key' must be a string.  If not, an
+         exception is raised.  If the value is a string, but does not
+         correspond to a boolean value, an exception is raised."""
+ 
+         valstr = self.get(key)
+         if valstr is None:
+             raise ContextException(key)
+ 
+         try:
+             return qm.common.parse_boolean(valstr)
+         except ValueError:
+             raise ContextException(key, "invalid boolean context var")
+         
+ 
      def GetTemporaryDirectory(self):
          """Return the path to the a temporary directory.
  
          returns -- The path to the a temporary directory.  The
          'Runnable' object may make free use of this temporary
*************** class Context(types.DictType):
*** 207,212 ****
--- 236,242 ----
              return {}
          
          added = self.__context.GetAddedProperties()
          added.update(self)
          return added
+ 
  
Index: qm/test/result.py
===================================================================
RCS file: /home/sc/Repository/qm/qm/test/result.py,v
retrieving revision 1.21
diff -c -5 -p -r1.21 result.py
*** qm/test/result.py	2 Oct 2003 16:23:22 -0000	1.21
--- qm/test/result.py	13 Nov 2003 02:52:56 -0000
*************** class Result:
*** 284,301 ****
          exception_type = exc_info[0]
          
          # If no cause was specified, use an appropriate message.
          if not cause:
              if exception_type is ContextException:
!                 cause = 'Missing context variable "%s".' % exc_info[1].key
              else:
                  cause = "An exception occurred."
  
          # For a 'ContextException', indicate which context variable
!         # was missing.
          if exception_type is ContextException:
!             self["qmtest.missing_variable"] = exc_info[1].key
              
          self.SetOutcome(outcome)
          self[Result.CAUSE] = cause
          self[Result.EXCEPTION] = "%s: %s" % exc_info[:2]
          self[Result.TRACEBACK] \
--- 284,301 ----
          exception_type = exc_info[0]
          
          # If no cause was specified, use an appropriate message.
          if not cause:
              if exception_type is ContextException:
!                 cause = str(exc_info[1])
              else:
                  cause = "An exception occurred."
  
          # For a 'ContextException', indicate which context variable
!         # was invalid.
          if exception_type is ContextException:
!             self["qmtest.context_variable"] = exc_info[1].key
              
          self.SetOutcome(outcome)
          self[Result.CAUSE] = cause
          self[Result.EXCEPTION] = "%s: %s" % exc_info[:2]
          self[Result.TRACEBACK] \
Index: qm/test/share/messages/diagnostics.txt
===================================================================
RCS file: /home/sc/Repository/qm/qm/test/share/messages/diagnostics.txt,v
retrieving revision 1.10
diff -c -5 -p -r1.10 diagnostics.txt
*** qm/test/share/messages/diagnostics.txt	24 Mar 2003 07:24:24 -0000	1.10
--- qm/test/share/messages/diagnostics.txt	13 Nov 2003 02:52:56 -0000
*************** should be a valid Python regular express
*** 70,79 ****
--- 70,82 ----
  
  @ file invalid substitution
  The substitution "%(substitution)s" is invalid.  A substitution should
  have the form "/*pattern*/*replacement*/".
  
+ @ invalid boolean context var
+ The value of "%(key)s" is not a valid boolean value.  
+ 
  @ invalid class
  There is no test class "%(class_name)s".
  
  @ invalid class name
  The class name "%(class_name)s" is invalid.  Specify the class name in
*************** form KEY=VALUE.
*** 117,126 ****
--- 120,132 ----
  @ missing arg for template
  Specify the name of the test class and the test ID of the new test.
  
  @ missing argument
  A value for the "%(title)s" parameter is missing.
+ 
+ @ missing context variable
+ The context variable "%(key)s" was not defined.
  
  @ missing test id
  There is no test with ID "%(test_id)s".
  
  @ module does not exist


More information about the qmtest mailing list