Commits

Tom Tanner committed 30e1518 Merge

resync to tip

  • Participants
  • Parent commits f4b736e, 672a2af

Comments (0)

Files changed (196)

 d958f66a48e51acfe0a9a175eba42f41fd49dfda 0.98.3
 e5e9f66add3c1b5cc95536628a61e4959533ab42 1.2.0
 6820de195f6c6e4c7ddf4b2eee89ae6a974c6d14 2.1.0.final.0
+38e9e6d0ba0ca64702b2504c32c68bb7bb88c630 2.3.0

QMTest/TestCmd.py

 
 re_space = re.compile('\s')
 
-_Cleanup = []
-
-def _clean():
-    global _Cleanup
-    cleanlist = [ c for c in _Cleanup if c ]
-    del _Cleanup[:]
-    cleanlist.reverse()
-    for test in cleanlist:
-        test.cleanup()
-
-atexit.register(_clean)
-
 def _caller(tblist, skip):
     string = ""
     arr = []
 
 
 
+import subprocess
+
 try:
-    import subprocess
-except ImportError:
-    # The subprocess module doesn't exist in this version of Python,
-    # so we're going to cobble up something that looks just enough
-    # like its API for our purposes below.
-    import popen2
-    subprocess = types.ModuleType('subprocess')
-
-    subprocess.PIPE = 'PIPE'
-    subprocess.STDOUT = 'STDOUT'
-    subprocess.mswindows = (sys.platform == 'win32')
-
-    class Popen(popen2.Popen3, popen2.Popen4):
-        universal_newlines = 1
-        def __init__(self, command, **kw):
-            if kw.get('stderr') == 'STDOUT':
-                popen2.Popen4.__init__(self, command, 1)
-            else:
-                popen2.Popen3.__init__(self, command, 1)
-            self.stdin = self.tochild
-            self.stdout = self.fromchild
-            self.stderr = self.childerr
-        def communicate(self, input=None):
-            if input:
-                self.stdin.write(input)
-            self.stdin.close()
-            out = self.stdout.read()
-            if self.stderr is None:
-                err = None
-            else:
-                err = self.stderr.read()
-            self.stdout.close()
-            if self.stderr is not None:
-                self.stderr.close()
-            self.returncode = self.wait()
-            return (out, err)
+    subprocess.Popen.terminate
+except AttributeError:
+    if sys.platform == 'win32':
+        import win32process
+        def terminate(self):
+            win32process.TerminateProcess(self._handle, 1)
+    else:
         def terminate(self):
             os.kill(self.pid, signal.SIGTERM)
-        def wait(self, *args, **kw):
-            resultcode = popen2.Popen3.wait(self, *args, **kw)
-            if os.WIFSIGNALED(resultcode):
-                return (- os.WTERMSIG(resultcode))
-            elif os.WIFEXITED(resultcode):
-                return os.WEXITSTATUS(resultcode)
-            else:
-                return None
-
-    subprocess.Popen = Popen
-else:
-    try:
-        subprocess.Popen.terminate
-    except AttributeError:
-        if sys.platform == 'win32':
-            import win32process
-            def terminate(self):
-                win32process.TerminateProcess(self._handle, 1)
-        else:
-            def terminate(self):
-                os.kill(self.pid, signal.SIGTERM)
-        method = types.MethodType(terminate, None, subprocess.Popen)
-        setattr(subprocess.Popen, 'terminate', method)
+    method = types.MethodType(terminate, None, subprocess.Popen)
+    setattr(subprocess.Popen, 'terminate', method)
 
 
 
             raise Exception(disconnect_message)
         data = memoryview(data)[sent:]
 
+_Cleanup = []
+
+def _clean():
+    global _Cleanup
+    cleanlist = [ c for c in _Cleanup if c ]
+    del _Cleanup[:]
+    cleanlist.reverse()
+    for test in cleanlist:
+        test.cleanup()
+
+atexit.register(_clean)
 
 
 class TestCmd(object):
                        combine = 0,
                        universal_newlines = 1,
                        timeout = None):
+        self.external = os.environ.get('SCONS_EXTERNAL_TEST', 0)
         self._cwd = os.getcwd()
         self.description_set(description)
         self.program_set(program)
         self.condition = 'no_result'
         self.workdir_set(workdir)
         self.subdir(subdir)
+        self.script_srcdir = None
 
     def __del__(self):
         self.cleanup()
                 shutil.rmtree(dir, ignore_errors = 1)
             self._dirlist = []
 
-        try:
             global _Cleanup
-            _Cleanup.remove(self)
-        except (AttributeError, ValueError):
-            pass
+            if self in _Cleanup:
+                _Cleanup.remove(self)
 
     def command_args(self, program = None,
                            interpreter = None,
                            arguments = None):
-        if program:
-            if isinstance(program, str) and not os.path.isabs(program):
-                program = os.path.join(self._cwd, program)
+        if not self.external:
+            if program:
+                if isinstance(program, str) and not os.path.isabs(program):
+                    program = os.path.join(self._cwd, program)
+            else:
+                program = self.program
+                if not interpreter:
+                    interpreter = self.interpreter
         else:
-            program = self.program
-            if not interpreter:
-                interpreter = self.interpreter
+            if not program:
+                program = self.program
+                if not interpreter:
+                    interpreter = self.interpreter
         if not isinstance(program, (list, tuple)):
             program = [program]
         cmd = list(program)
     def program_set(self, program):
         """Set the executable program or script to be tested.
         """
-        if program and not os.path.isabs(program):
-            program = os.path.join(self._cwd, program)
+        if not self.external:
+            if program and not os.path.isabs(program):
+                program = os.path.join(self._cwd, program)
         self.program = program
 
     def read(self, file, mode = 'rb'):
         self.timeout = timeout
         self.timer = None
 
+    def parse_path(self, path, suppress_current=False):
+        """Return a list with the single path components of path.
+        """
+        head, tail = os.path.split(path)
+        result = []
+        if not tail:
+            if head == path:
+                return [head]
+        else:
+            result.append(tail)
+        head, tail = os.path.split(head)
+        while head and tail:
+            result.append(tail)
+            head, tail = os.path.split(head)
+        result.append(head or tail)
+        result.reverse()
+        
+        return result        
+
+    def dir_fixture(self, srcdir, dstdir=None):
+        """Copies the contents of the specified folder srcdir from
+        the directory of the called  script, to the current
+        working directory.
+        The srcdir name may be a list, in which case the elements are
+        concatenated with the os.path.join() method.  The dstdir is
+        assumed to be under the temporary working directory, it gets
+        created automatically, if it does not already exist.
+        """
+        if srcdir and self.script_srcdir and not os.path.isabs(srcdir):
+            spath = os.path.join(self.script_srcdir, srcdir)
+        else:
+            spath = srcdir
+        if dstdir:
+            dstdir = self.canonicalize(dstdir)
+        else:
+            dstdir = '.'            
+
+        if dstdir != '.' and not os.path.exists(dstdir):
+            dstlist = self.parse_path(dstdir)
+            if len(dstlist) > 0 and dstlist[0] == ".":
+                dstlist = dstlist[1:]
+            for idx in range(len(dstlist)):
+                self.subdir(dstlist[:idx+1])
+
+        if dstdir and self.workdir:
+            dstdir = os.path.join(self.workdir, dstdir)
+
+        for entry in os.listdir(spath):
+            epath = os.path.join(spath, entry)
+            dpath = os.path.join(dstdir, entry)
+            if os.path.isdir(epath):
+                # Copy the subfolder
+                shutil.copytree(epath, dpath)
+            else:
+                shutil.copy(epath, dpath)
+
+    def file_fixture(self, srcfile, dstfile=None):
+        """Copies the file srcfile from the directory of
+        the called script, to the current working directory.
+        The dstfile is assumed to be under the temporary working
+        directory unless it is an absolute path name.
+        If dstfile is specified its target directory gets created
+        automatically, if it does not already exist.
+        """
+        srcpath, srctail = os.path.split(srcfile)
+        if srcpath:
+            if self.script_srcdir and not os.path.isabs(srcpath):
+                spath = os.path.join(self.script_srcdir, srcfile)
+            else:
+                spath = srcfile
+        else:
+            spath = os.path.join(self.script_srcdir, srcfile)
+        if not dstfile:
+            if srctail:
+                dpath = os.path.join(self.workdir, srctail)
+            else:
+                return
+        else:
+            dstpath, dsttail = os.path.split(dstfile)
+            if dstpath:
+                if not os.path.exists(os.path.join(self.workdir, dstpath)):
+                    dstlist = self.parse_path(dstpath)
+                    if len(dstlist) > 0 and dstlist[0] == ".":
+                        dstlist = dstlist[1:]
+                    for idx in range(len(dstlist)):
+                        self.subdir(dstlist[:idx+1])
+                    
+            dpath = os.path.join(self.workdir, dstfile)
+        shutil.copy(spath, dpath)
+
     def start(self, program = None,
                     interpreter = None,
                     arguments = None,
         The specified program will have the original directory
         prepended unless it is enclosed in a [list].
         """
+        if self.external:
+            if not program:
+                program = self.program
+            if not interpreter:
+                interpreter = self.interpreter
+        
         if chdir:
             oldcwd = os.getcwd()
             if not os.path.isabs(chdir):
 
         #
         self._dirlist.append(path)
+
         global _Cleanup
-        try:
-            _Cleanup.index(self)
-        except ValueError:
+        if self not in _Cleanup:
             _Cleanup.append(self)
 
         return path

QMTest/TestCmdTests.py

         except KeyError:
             pass
 
+import subprocess
+
 try:
-    import subprocess
-except ImportError:
-    # The subprocess module doesn't exist in this version of Python,
-    # so we're going to cobble up something that looks just enough
-    # like its API for our purposes below.
-    import popen2
-    subprocess = types.ModuleType('subprocess')
-
-    subprocess.PIPE = 'PIPE'
-    subprocess.STDOUT = 'STDOUT'
-    subprocess.mswindows = (sys.platform == 'win32')
-
-    class Popen(popen2.Popen3, popen2.Popen4):
-        universal_newlines = 1
-        def __init__(self, command, **kw):
-            if kw.get('stderr') == 'STDOUT':
-                popen2.Popen4.__init__(self, command, 1)
-            else:
-                popen2.Popen3.__init__(self, command, 1)
-            self.stdin = self.tochild
-            self.stdout = self.fromchild
-            self.stderr = self.childerr
-        def communicate(self, input=None):
-            if input:
-                self.stdin.write(input)
-            self.stdin.close()
-            out = self.stdout.read()
-            if self.stderr is None:
-                err = None
-            else:
-                err = self.stderr.read()
-            self.stdout.close()
-            if self.stderr is not None:
-                self.stderr.close()
-            self.returncode = self.wait()
-            return (out, err)
+    subprocess.Popen.terminate
+except AttributeError:
+    if sys.platform == 'win32':
+        import win32process
+        def terminate(self):
+            win32process.TerminateProcess(self._handle, 1)
+    else:
         def terminate(self):
             os.kill(self.pid, signal.SIGTERM)
-        def wait(self, *args, **kw):
-            resultcode = popen2.Popen3.wait(self, *args, **kw)
-            if os.WIFEXITED(resultcode):
-                return os.WEXITSTATUS(resultcode)
-            elif os.WIFSIGNALED(resultcode):
-                return os.WTERMSIG(resultcode)
-            else:
-                return None
-
-    subprocess.Popen = Popen
-else:
-    try:
-        subprocess.Popen.terminate
-    except AttributeError:
-        if sys.platform == 'win32':
-            import win32process
-            def terminate(self):
-                win32process.TerminateProcess(self._handle, 1)
-        else:
-            def terminate(self):
-                os.kill(self.pid, signal.SIGTERM)
-        method = types.MethodType(terminate, None, subprocess.Popen)
-        setattr(subprocess.Popen, 'terminate', method)
+    method = types.MethodType(terminate, None, subprocess.Popen)
+    setattr(subprocess.Popen, 'terminate', method)
 
 class ExitError(Exception):
     pass
                                       ['a\\n', 'c\\n', 'd\\n', 'e\\n', 'f2\\n'])
 result = list(result)
 expect = [
-    '***  \\n',
-    '---  \\n',
+    '*** \\n',
+    '--- \\n',
     '***************\\n',
     '*** 1,5 ****\\n',
     '  a\\n',
                                       ['a\\n', 'c\\n', 'd\\n', 'e\\n', 'f2\\n'])
 result = list(result)
 expect = [
-    '---  \\n',
-    '+++  \\n',
+    '--- \\n',
+    '+++ \\n',
     '@@ -1,5 +1,5 @@\\n',
     ' a\\n',
     '-b\\n',

QMTest/TestCommon.py

 import os
 import stat
 import sys
+import glob
 
 try:
     from collections import UserList
 def is_List(e):
     return isinstance(e, (list, UserList))
 
+def is_Tuple(e):
+    return isinstance(e, tuple)
+
+def is_Sequence(e):
+    return (not hasattr(e, "strip") and
+            hasattr(e, "__getitem__") or
+            hasattr(e, "__iter__"))
+
 def is_writable(f):
     mode = os.stat(f)[stat.ST_MODE]
     return mode & stat.S_IWUSR
             print "Unwritable files: `%s'" % "', `".join(unwritable)
         self.fail_test(missing + unwritable)
 
-    def must_contain(self, file, required, mode = 'rb'):
+    def must_contain(self, file, required, mode = 'rb', find = None):
         """Ensures that the specified file contains the required text.
         """
         file_contents = self.read(file, mode)
-        contains = (file_contents.find(required) != -1)
+        if find is None:
+            def find(o, l):
+                try:
+                    return o.index(l)
+                except ValueError:
+                    return None
+        contains = find(file_contents, required)
         if not contains:
             print "File `%s' does not contain required string." % file
             print self.banner('Required string ')
                 except ValueError:
                     return None
         missing = []
+        if is_List(output):
+            output = '\n'.join(output)
+
         for line in lines:
             if find(output, line) is None:
                 missing.append(line)
         sys.stdout.flush()
         self.fail_test()
 
-    def must_contain_lines(self, lines, output, title=None):
+    def must_contain_lines(self, lines, output, title=None, find = None):
         # Deprecated; retain for backwards compatibility.
-        return self.must_contain_all_lines(output, lines, title)
+        return self.must_contain_all_lines(output, lines, title, find)
 
     def must_exist(self, *files):
         """Ensures that the specified file(s) must exist.  An individual
             print "Missing files: `%s'" % "', `".join(missing)
             self.fail_test(missing)
 
-    def must_match(self, file, expect, mode = 'rb'):
+    def must_exist_one_of(self, files):
+        """Ensures that at least one of the specified file(s) exists.
+        The filenames can be given as a list, where each entry may be
+        a single path string, or a tuple of folder names and the final
+        filename that get concatenated.
+        Supports wildcard names like 'foo-1.2.3-*.rpm'.
+        Exits FAILED if none of the files exists.
+        """
+        missing = []
+        for x in files:
+            if is_List(x) or is_Tuple(x):
+                xpath = os.path.join(*x)
+            else:
+                xpath = is_Sequence(x) and os.path.join(x) or x
+            if glob.glob(xpath):
+                return
+            missing.append(xpath)
+        print "Missing one of: `%s'" % "', `".join(missing)
+        self.fail_test(missing)
+
+    def must_match(self, file, expect, mode = 'rb', match=None):
         """Matches the contents of the specified file (first argument)
         against the expected contents (second argument).  The expected
         contents are a list of lines or a string which will be split
         on newlines.
         """
         file_contents = self.read(file, mode)
+        if not match:
+            match = self.match
         try:
-            self.fail_test(not self.match(file_contents, expect))
+            self.fail_test(not match(file_contents, expect))
         except KeyboardInterrupt:
             raise
         except:
             self.diff(expect, file_contents, 'contents ')
             raise
 
-    def must_not_contain(self, file, banned, mode = 'rb'):
+    def must_not_contain(self, file, banned, mode = 'rb', find = None):
         """Ensures that the specified file doesn't contain the banned text.
         """
         file_contents = self.read(file, mode)
-        contains = (file_contents.find(banned) != -1)
+        if find is None:
+            def find(o, l):
+                try:
+                    return o.index(l)
+                except ValueError:
+                    return None
+        contains = find(file_contents, banned)
         if contains:
             print "File `%s' contains banned string." % file
             print self.banner('Banned string ')
             sys.stdout.write(output)
             self.fail_test()
 
-    def must_not_contain_lines(self, lines, output, title=None):
-        return self.must_not_contain_any_line(output, lines, title)
+    def must_not_contain_lines(self, lines, output, title=None, find=None):
+        return self.must_not_contain_any_line(output, lines, title, find)
 
     def must_not_exist(self, *files):
         """Ensures that the specified file(s) must not exist.
             print "Unexpected files exist: `%s'" % "', `".join(existing)
             self.fail_test(existing)
 
+    def must_not_exist_any_of(self, files):
+        """Ensures that none of the specified file(s) exists.
+        The filenames can be given as a list, where each entry may be
+        a single path string, or a tuple of folder names and the final
+        filename that get concatenated.
+        Supports wildcard names like 'foo-1.2.3-*.rpm'.
+        Exits FAILED if any of the files exists.
+        """
+        existing = []
+        for x in files:
+            if is_List(x) or is_Tuple(x):
+                xpath = os.path.join(*x)
+            else:
+                xpath = is_Sequence(x) and os.path.join(x) or x
+            if glob.glob(xpath):
+                existing.append(xpath)
+        if existing:
+            print "Unexpected files exist: `%s'" % "', `".join(existing)
+            self.fail_test(existing)
 
     def must_not_be_writable(self, *files):
         """Ensures that the specified file(s) exist and are not writable.

QMTest/TestCommonTests.py

         stderr = run_env.stderr()
         assert stderr == "PASSED\n", stderr
 
+class must_exist_one_of_TestCase(TestCommonTestCase):
+    def test_success(self):
+        """Test must_exist_one_of():  success"""
+        run_env = self.run_env
 
+        script = lstrip("""\
+        from TestCommon import TestCommon
+        tc = TestCommon(workdir='')
+        tc.write('file1', "file1\\n")
+        tc.must_exist_one_of(['file1'])
+        tc.pass_test()
+        """)
+        run_env.run(program=sys.executable, stdin=script)
+        stdout = run_env.stdout()
+        assert stdout == "", stdout
+        stderr = run_env.stderr()
+        assert stderr == "PASSED\n", stderr
+
+    def test_failure(self):
+        """Test must_exist_one_of():  failure"""
+        run_env = self.run_env
+
+        script = lstrip("""\
+        from TestCommon import TestCommon
+        tc = TestCommon(workdir='')
+        tc.must_exist_one_of(['file1'])
+        tc.pass_test()
+        """)
+        run_env.run(program=sys.executable, stdin=script)
+        stdout = run_env.stdout()
+        assert stdout == "Missing one of: `file1'\n", stdout
+        stderr = run_env.stderr()
+        assert stderr.find("FAILED") != -1, stderr
+
+    def test_files_specified_as_list(self):
+        """Test must_exist_one_of():  files specified as list"""
+        run_env = self.run_env
+
+        script = lstrip("""\
+        from TestCommon import TestCommon
+        tc = TestCommon(workdir='')
+        tc.write('file1', "file1\\n")
+        tc.must_exist_one_of(['file2', 'file1'])
+        tc.pass_test()
+        """)
+        run_env.run(program=sys.executable, stdin=script)
+        stdout = run_env.stdout()
+        assert stdout == "", stdout
+        stderr = run_env.stderr()
+        assert stderr == "PASSED\n", stderr
+
+    def test_files_specified_with_wildcards(self):
+        """Test must_exist_one_of():  files specified with wildcards"""
+        run_env = self.run_env
+
+        script = lstrip("""\
+        from TestCommon import TestCommon
+        tc = TestCommon(workdir='')
+        tc.write('file7', "file7\\n")
+        tc.must_exist_one_of(['file?'])
+        tc.pass_test()
+        """)
+        run_env.run(program=sys.executable, stdin=script)
+        stdout = run_env.stdout()
+        assert stdout == "", stdout
+        stderr = run_env.stderr()
+        assert stderr == "PASSED\n", stderr
+
+    def test_file_given_as_list(self):
+        """Test must_exist_one_of():  file given as list"""
+        run_env = self.run_env
+
+        script = lstrip("""\
+        from TestCommon import TestCommon
+        tc = TestCommon(workdir='')
+        tc.subdir('sub')
+        tc.write(['sub', 'file1'], "sub/file1\\n")
+        tc.must_exist_one_of(['file2',
+                              ['sub', 'file1']])
+        tc.pass_test()
+        """)
+        run_env.run(program=sys.executable, stdin=script)
+        stdout = run_env.stdout()
+        assert stdout == "", stdout
+        stderr = run_env.stderr()
+        assert stderr == "PASSED\n", stderr
+
+    def test_file_given_as_sequence(self):
+        """Test must_exist_one_of():  file given as sequence"""
+        run_env = self.run_env
+
+        script = lstrip("""\
+        from TestCommon import TestCommon
+        tc = TestCommon(workdir='')
+        tc.subdir('sub')
+        tc.write(['sub', 'file1'], "sub/file1\\n")
+        tc.must_exist_one_of(['file2',
+                              ('sub', 'file1')])
+        tc.pass_test()
+        """)
+        run_env.run(program=sys.executable, stdin=script)
+        stdout = run_env.stdout()
+        assert stdout == "", stdout
+        stderr = run_env.stderr()
+        assert stderr == "PASSED\n", stderr
 
 class must_match_TestCase(TestCommonTestCase):
     def test_success(self):
         stderr = run_env.stderr()
         assert stderr.find("FAILED") != -1, stderr
 
+class must_not_exist_any_of_TestCase(TestCommonTestCase):
+    def test_success(self):
+        """Test must_not_exist_any_of():  success"""
+        run_env = self.run_env
+
+        script = lstrip("""\
+        from TestCommon import TestCommon
+        tc = TestCommon(workdir='')
+        tc.must_not_exist_any_of(['file1'])
+        tc.pass_test()
+        """)
+        run_env.run(program=sys.executable, stdin=script)
+        stdout = run_env.stdout()
+        assert stdout == "", stdout
+        stderr = run_env.stderr()
+        assert stderr == "PASSED\n", stderr
+
+    def test_failure(self):
+        """Test must_not_exist_any_of():  failure"""
+        run_env = self.run_env
+
+        script = lstrip("""\
+        from TestCommon import TestCommon
+        tc = TestCommon(workdir='')
+        tc.write('file1', "file1\\n")
+        tc.must_not_exist_any_of(['file1'])
+        tc.pass_test()
+        """)
+        run_env.run(program=sys.executable, stdin=script)
+        stdout = run_env.stdout()
+        assert stdout == "Unexpected files exist: `file1'\n", stdout
+        stderr = run_env.stderr()
+        assert stderr.find("FAILED") != -1, stderr
+
+    def test_files_specified_as_list(self):
+        """Test must_not_exist_any_of():  files specified as list"""
+        run_env = self.run_env
+
+        script = lstrip("""\
+        from TestCommon import TestCommon
+        tc = TestCommon(workdir='')
+        tc.must_not_exist_any_of(['file2', 'file1'])
+        tc.pass_test()
+        """)
+        run_env.run(program=sys.executable, stdin=script)
+        stdout = run_env.stdout()
+        assert stdout == "", stdout
+        stderr = run_env.stderr()
+        assert stderr == "PASSED\n", stderr
+
+    def test_files_specified_with_wildcards(self):
+        """Test must_not_exist_any_of():  files specified with wildcards"""
+        run_env = self.run_env
+
+        script = lstrip("""\
+        from TestCommon import TestCommon
+        tc = TestCommon(workdir='')
+        tc.write('file7', "file7\\n")
+        tc.must_not_exist_any_of(['files?'])
+        tc.pass_test()
+        """)
+        run_env.run(program=sys.executable, stdin=script)
+        stdout = run_env.stdout()
+        assert stdout == "", stdout
+        stderr = run_env.stderr()
+        assert stderr == "PASSED\n", stderr
+
+    def test_file_given_as_list(self):
+        """Test must_not_exist_any_of():  file given as list"""
+        run_env = self.run_env
+
+        script = lstrip("""\
+        from TestCommon import TestCommon
+        tc = TestCommon(workdir='')
+        tc.subdir('sub')
+        tc.write(['sub', 'file1'], "sub/file1\\n")
+        tc.must_not_exist_any_of(['file2',
+                              ['sub', 'files*']])
+        tc.pass_test()
+        """)
+        run_env.run(program=sys.executable, stdin=script)
+        stdout = run_env.stdout()
+        assert stdout == "", stdout
+        stderr = run_env.stderr()
+        assert stderr == "PASSED\n", stderr
+
+    def test_file_given_as_sequence(self):
+        """Test must_not_exist_any_of():  file given as sequence"""
+        run_env = self.run_env
+
+        script = lstrip("""\
+        from TestCommon import TestCommon
+        tc = TestCommon(workdir='')
+        tc.subdir('sub')
+        tc.write(['sub', 'file1'], "sub/file1\\n")
+        tc.must_not_exist_any_of(['file2',
+                              ('sub', 'files?')])
+        tc.pass_test()
+        """)
+        run_env.run(program=sys.executable, stdin=script)
+        stdout = run_env.stdout()
+        assert stdout == "", stdout
+        stderr = run_env.stderr()
+        assert stderr == "PASSED\n", stderr
 
 class run_TestCase(TestCommonTestCase):
     def test_argument_handling(self):
         must_contain_exactly_lines_TestCase,
         must_contain_lines_TestCase,
         must_exist_TestCase,
+        must_exist_one_of_TestCase,
         must_match_TestCase,
         must_not_be_writable_TestCase,
         must_not_contain_TestCase,
         must_not_contain_any_line_TestCase,
         must_not_contain_lines_TestCase,
         must_not_exist_TestCase,
+        must_not_exist_any_of_TestCase,
         run_TestCase,
         start_TestCase,
         skip_test_TestCase,

QMTest/TestRuntest.py

 
         dirs = [os.environ.get('SCONS_RUNTEST_DIR', orig_cwd)]
         
-        spe = os.environ.get('SCONS_SOURCE_PATH_EXECUTABLE', orig_cwd)
-        for d in spe.split(os.pathsep):
-            dirs.append(os.path.join(d, 'build'))
-            dirs.append(d)
-
         for thing in things_to_copy:
             for dir in dirs:
                 t = os.path.join(dir, thing)
 
         self.program_set(self.workpath(kw['program']))
 
-        for key in os.environ.keys():
-            if key[:5] == 'AEGIS':
-                os.environ[key] = ''
-
         os.environ['PYTHONPATH'] = ''
-        os.environ['SCONS_SOURCE_PATH_EXECUTABLE'] = ''
 
     def write_fake_scons_source_tree(self):
         os.mkdir('src')

QMTest/TestSCons.py

 
     test = TestSCons()
 
-TestScons is a subclass of TestCommon, which is in turn is a subclass
+TestScons is a subclass of TestCommon, which in turn is a subclass
 of TestCmd), and hence has available all of the methods and attributes
 from those classes, as well as any overridden or additional methods or
 attributes defined in this subclass.
 from TestCommon import *
 from TestCommon import __all__
 
+from TestCmd import Popen
+from TestCmd import PIPE
+
 # Some tests which verify that SCons has been packaged properly need to
 # look for specific version file names.  Replicating the version number
 # here provides some independent verification that what we packaged
 # conforms to what we expect.
 
-default_version = '2.1.0.alpha.yyyymmdd'
+default_version = '2.3.1.alpha.yyyymmdd'
 
-copyright_years = '2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012'
+copyright_years = '2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013'
 
 python_version_unsupported = (2, 3, 0)
-python_version_deprecated = (2, 4, 0)
+python_version_deprecated = (2, 7, 0)
 
 # In the checked-in source, the value of SConsVersion in the following
 # line must remain "__ VERSION __" (without the spaces) so the built
 _dll = dll_suffix
 dll_ = dll_prefix
 
-def gccFortranLibs():
-    """Test which gcc Fortran startup libraries are required.
-    This should probably move into SCons itself, but is kind of hacky.
-    """
-
-    libs = ['g2c']
-    cmd = 'gcc -v'
-
-    try:
-        import subprocess
-    except ImportError:
-        try:
-            import popen2
-            stderr = popen2.popen3(cmd)[2].read()
-        except OSError:
-            return libs
-    else:
-        p = subprocess.Popen(cmd, shell=True, stderr=subprocess.PIPE)
-        stderr = p.stderr.read()
-    m = re.search('gcc version (\d\.\d)', stderr)
-    if m:
-        gcc_version = m.group(1)
-        if re.match('4.[^0]', gcc_version):
-            libs = ['gfortranbegin']
-        elif gcc_version in ('3.1', '4.0'):
-            libs = ['frtbegin'] + libs
-
-    return libs
-
 
 if sys.platform == 'cygwin':
     # On Cygwin, os.path.normcase() lies, so just report back the
         return (os.path.normcase(s1) != os.path.normcase(s2))
 
 
-if sys.platform == 'win32':
-    fortran_lib = gccFortranLibs()
-elif sys.platform == 'cygwin':
-    fortran_lib = gccFortranLibs()
-elif sys.platform.find('irix') != -1:
-    fortran_lib = ['ftn']
-else:
-    fortran_lib = gccFortranLibs()
-
-
 file_expr = r"""File "[^"]*", line \d+, in [^\n]+
 """
 
         str = str.replace(c, '\\' + c)
     return str
 
+#
+# Helper functions that we use as a replacement to the default re.match
+# when searching for special strings in stdout/stderr.
+#
+def search_re(out, l):
+    """ Search the regular expression 'l' in the output 'out'
+        and return the start index when successful.
+    """
+    m = re.search(l, out)
+    if m:
+        return m.start()
 
+    return None
+
+def search_re_in_list(out, l):
+    """ Search the regular expression 'l' in each line of
+        the given string list 'out' and return the line's index
+        when successful.
+    """
+    for idx, o in enumerate(out):
+        m = re.search(l, o)
+        if m:
+            return idx
+
+    return None
+
+#
+# Helpers for handling Python version numbers
+#
 def python_version_string():
     return sys.version.split()[0]
 
         is not necessary.
         """
         self.orig_cwd = os.getcwd()
-        try:
-            script_dir = os.environ['SCONS_SCRIPT_DIR']
-        except KeyError:
-            pass
-        else:
-            os.chdir(script_dir)
+        self.external = os.environ.get('SCONS_EXTERNAL_TEST', 0)
+
+        if not self.external:
+            try:
+                script_dir = os.environ['SCONS_SCRIPT_DIR']
+            except KeyError:
+                pass
+            else:
+                os.chdir(script_dir)
         if 'program' not in kw:
             kw['program'] = os.environ.get('SCONS')
             if not kw['program']:
-                if os.path.exists('scons'):
+                if not self.external:
+                    if os.path.exists('scons'):
+                        kw['program'] = 'scons'
+                    else:
+                        kw['program'] = 'scons.py'
+                else:
                     kw['program'] = 'scons'
-                else:
-                    kw['program'] = 'scons.py'
-            elif not os.path.isabs(kw['program']):
+                    kw['interpreter'] = ''
+            elif not self.external and not os.path.isabs(kw['program']):
                 kw['program'] = os.path.join(self.orig_cwd, kw['program'])
         if 'interpreter' not in kw and not os.environ.get('SCONS_EXEC'):
             kw['interpreter'] = [python, '-tt']
         # control character output on FC8
         # TERM can cause test failures due to control chars in prompts etc.
         os.environ['TERM'] = 'dumb'
-        
+
         self.ignore_python_version = kw.get('ignore_python_version',1)
         if kw.get('ignore_python_version', -1) != -1:
             del kw['ignore_python_version']
 
         TestCommon.__init__(self, **kw)
 
-        import SCons.Node.FS
-        if SCons.Node.FS.default_fs is None:
-            SCons.Node.FS.default_fs = SCons.Node.FS.FS()
+        if not self.external:
+            import SCons.Node.FS
+            if SCons.Node.FS.default_fs is None:
+                SCons.Node.FS.default_fs = SCons.Node.FS.FS()
+
+        try:
+            self.script_srcdir = os.environ['PYTHON_SCRIPT_DIR']
+        except KeyError:
+            pass
 
     def Environment(self, ENV=None, *args, **kw):
         """
         Return a construction Environment that optionally overrides
         the default external environment with the specified ENV.
         """
-        import SCons.Environment
-        import SCons.Errors
-        if not ENV is None:
-            kw['ENV'] = ENV
-        try:
-            return SCons.Environment.Environment(*args, **kw)
-        except (SCons.Errors.UserError, SCons.Errors.InternalError):
-            return None
+        if not self.external:
+            import SCons.Environment
+            import SCons.Errors
+            if not ENV is None:
+                kw['ENV'] = ENV
+            try:
+                return SCons.Environment.Environment(*args, **kw)
+            except (SCons.Errors.UserError, SCons.Errors.InternalError):
+                return None
+
+        return None
 
     def detect(self, var, prog=None, ENV=None, norm=None):
         """
         used as prog.
         """
         env = self.Environment(ENV)
-        v = env.subst('$'+var)
-        if not v:
-            return None
-        if prog is None:
-            prog = v
-        if v != prog:
-            return None
-        result = env.WhereIs(prog)
-        if norm and os.sep != '/':
-            result = result.replace(os.sep, '/')
-        return result
+        if env:
+            v = env.subst('$'+var)
+            if not v:
+                return None
+            if prog is None:
+                prog = v
+            if v != prog:
+                return None
+            result = env.WhereIs(prog)
+            if norm and os.sep != '/':
+                result = result.replace(os.sep, '/')
+            return result
+
+        return self.where_is(prog)
 
     def detect_tool(self, tool, prog=None, ENV=None):
         """
     def where_is(self, prog, path=None):
         """
         Given a program, search for it in the specified external PATH,
-        or in the actual external PATH is none is specified.
+        or in the actual external PATH if none is specified.
         """
-        import SCons.Environment
-        env = SCons.Environment.Environment()
         if path is None:
             path = os.environ['PATH']
-        return env.WhereIs(prog, path)
+        if self.external:
+            if isinstance(prog, str):
+                prog = [prog]
+            import stat
+            paths = path.split(os.pathsep)
+            for p in prog:
+                for d in paths:
+                    f = os.path.join(d, p)
+                    if os.path.isfile(f):
+                        try:
+                            st = os.stat(f)
+                        except OSError:
+                            # os.stat() raises OSError, not IOError if the file
+                            # doesn't exist, so in this case we let IOError get
+                            # raised so as to not mask possibly serious disk or
+                            # network issues.
+                            continue
+                        if stat.S_IMODE(st[stat.ST_MODE]) & 0111:
+                            return os.path.normpath(f)
+        else:
+            import SCons.Environment
+            env = SCons.Environment.Environment()
+            return env.WhereIs(prog, path)
+
+        return None
 
     def wrap_stdout(self, build_str = "", read_str = "", error = 0, cleaning = 0):
         """Wraps standard output string(s) in the normal
         Initialize with a default external environment that uses a local
         Java SDK in preference to whatever's found in the default PATH.
         """
-        try:
-            return self._java_env[version]['ENV']
-        except AttributeError:
-            self._java_env = {}
-        except KeyError:
-            pass
+        if not self.external:
+            try:
+                return self._java_env[version]['ENV']
+            except AttributeError:
+                self._java_env = {}
+            except KeyError:
+                pass
 
-        import SCons.Environment
-        env = SCons.Environment.Environment()
-        self._java_env[version] = env
+            import SCons.Environment
+            env = SCons.Environment.Environment()
+            self._java_env[version] = env
 
 
-        if version:
-            patterns = [
-                '/usr/java/jdk%s*/bin'    % version,
-                '/usr/lib/jvm/*-%s*/bin' % version,
-                '/usr/local/j2sdk%s*/bin' % version,
-            ]
-            java_path = self.paths(patterns) + [env['ENV']['PATH']]
-        else:
-            patterns = [
-                '/usr/java/latest/bin',
-                '/usr/lib/jvm/*/bin',
-                '/usr/local/j2sdk*/bin',
-            ]
-            java_path = self.paths(patterns) + [env['ENV']['PATH']]
+            if version:
+                patterns = [
+                    '/usr/java/jdk%s*/bin'    % version,
+                    '/usr/lib/jvm/*-%s*/bin' % version,
+                    '/usr/local/j2sdk%s*/bin' % version,
+                ]
+                java_path = self.paths(patterns) + [env['ENV']['PATH']]
+            else:
+                patterns = [
+                    '/usr/java/latest/bin',
+                    '/usr/lib/jvm/*/bin',
+                    '/usr/local/j2sdk*/bin',
+                ]
+                java_path = self.paths(patterns) + [env['ENV']['PATH']]
 
-        env['ENV']['PATH'] = os.pathsep.join(java_path)
-        return env['ENV']
+            env['ENV']['PATH'] = os.pathsep.join(java_path)
+            return env['ENV']
+
+        return None
 
     def java_where_includes(self,version=None):
         """
         import sys
         if not version:
             version=''
-            frame = '/System/Library/Frameworks/JavaVM.framework/Headers/jni.h'
+            jni_dirs = ['/System/Library/Frameworks/JavaVM.framework/Headers/jni.h',
+                        '/usr/lib/jvm/default-java/include/jni.h']
         else:
-            frame = '/System/Library/Frameworks/JavaVM.framework/Versions/%s*/Headers/jni.h'%version
-        jni_dirs = ['/usr/lib/jvm/java-*-sun-%s*/include/jni.h'%version,
-                    '/usr/java/jdk%s*/include/jni.h'%version,
-		    frame,
-                    ]
+            jni_dirs = ['/System/Library/Frameworks/JavaVM.framework/Versions/%s*/Headers/jni.h'%version]
+        jni_dirs.extend(['/usr/lib/jvm/java-*-sun-%s*/include/jni.h'%version,
+                         '/usr/lib/jvm/java-%s*-openjdk/include/jni.h'%version,
+                         '/usr/java/jdk%s*/include/jni.h'%version])
         dirs = self.paths(jni_dirs)
         if not dirs:
             return None
     # to use cygwin compilers on cmd.exe -> uncomment following line
     #Configure_lib = 'm'
 
+    def gccFortranLibs(self):
+        """Test which gcc Fortran startup libraries are required.
+        This should probably move into SCons itself, but is kind of hacky.
+        """
+        if sys.platform.find('irix') != -1:
+            return ['ftn']
+
+        libs = ['g2c']
+        cmd = ['gcc','-v']
+
+        try:
+            p = Popen(cmd, stdout=PIPE, stderr=PIPE)
+            stdout, stderr = p.communicate()
+        except:
+            return libs
+
+        m = re.search('(gcc\s+version|gcc-Version)\s+(\d\.\d)', stderr)
+        if m:
+            gcc_version = m.group(2)
+            if re.match('4.[^0]', gcc_version):
+                libs = ['gfortranbegin']
+            elif gcc_version in ('3.1', '4.0'):
+                libs = ['frtbegin'] + libs
+
+        return libs
+
+    def skip_if_not_msvc(self, check_platform=True):
+        """ Check whether we are on a Windows platform and skip the
+            test if not. This check can be omitted by setting
+            check_platform to False.
+            Then, for a win32 platform, additionally check
+            whether we have a MSVC toolchain installed
+            in the system, and skip the test if none can be
+            found (=MinGW is the only compiler available).
+        """
+        if check_platform:
+            if sys.platform != 'win32':
+                msg = "Skipping Visual C/C++ test on non-Windows platform '%s'\n" % sys.platform
+                self.skip_test(msg)
+                return
+
+        try:
+            import SCons.Tool.MSCommon as msc
+            if not msc.msvc_exists():
+                msg = "No MSVC toolchain found...skipping test\n"
+                self.skip_test(msg)
+        except:
+            pass
+
     def checkLogAndStdout(self, checks, results, cached,
                           logfile, sconf_dir, sconstruct,
                           doCheckLog=1, doCheckStdout=1):
                         if flag == self.CR:
                             # up to date
                             log=log + \
-                                 re.escape("scons: Configure: \"%s\" is up to date." 
+                                 re.escape("scons: Configure: \"%s\" is up to date."
                                            % file) + ls
                             log=log+re.escape("scons: Configure: The original builder "
                                               "output was:") + ls
             if doCheckLog: lastEnd = matchPart(ls, logfile, lastEnd)
             if doCheckLog and lastEnd != len(logfile):
                 raise NoMatch(lastEnd)
-            
+
         except NoMatch, m:
             print "Cannot match log file against log regexp."
             print "log file: "
                 source = os.path.join(root, filename)
                 destination = source.replace(source_dir, dest_dir)
                 shutil.copy2(source, destination)
-    
+
 
 # In some environments, $AR will generate a warning message to stderr
 # if the library doesn't previously exist and is being created.  One

QMTest/TestSCons_time.py

 
 from TestCommon import *
 from TestCommon import __all__
+# some of the scons_time tests may need regex-based matching:
+from TestSCons import search_re, search_re_in_list
 
 __all__.extend([ 'TestSCons_time',
                ])
 
         TestCommon.__init__(self, **kw)
 
-        # Now that the testing object has been set up, check if we should
-        # skip the test due to the Python version.  We need to be able to
-        # import __future__ (which scons-time.py uses for nested scopes)
-        # and to handle list comprehensions (just because we're avoiding
-        # the old map() and filter() idioms).
-
-        try:
-            import __future__
-        except ImportError:
-            version = sys.version.split()[0]
-            msg = 'scons-time does not work on Python version %s\n' % version
-            self.skip_test(msg)
-
-        try:
-            eval('[x for x in [1, 2]]')
-        except SyntaxError:
-            version = sys.version.split()[0]
-            msg = 'scons-time does not work on Python version %s\n' % version
-            self.skip_test(msg)
-
     def archive_split(self, path):
         if path[-7:] == '.tar.gz':
             return path[:-7], path[-7:]

QMTest/test-framework.rst

+=======================
+SCons Testing Framework
+=======================
+
+SCons uses extensive automated tests to try to ensure quality. The primary goal
+is that users should be able to upgrade from version to version without any surprise
+changes in behavior.
+
+In general, no change goes into SCons unless it has one or more new or modified
+tests that demonstrably exercise the bug being fixed or the feature being added.
+There are exceptions to this guideline, but they should be just that, ''exceptions''.
+When in doubt, make sure it's tested.
+
+Test Organization
+=================
+
+There are three types of SCons tests:
+
+*End-to-End Tests*
+  End-to-end tests of SCons are all Python scripts (``*.py``) underneath
+  the ``test/`` subdirectory.  They use the test infrastructure modules in the
+  ``QMTest`` subdirectory.
+
+*Unit Tests*
+  Unit tests for individual SCons modules live underneath the
+  ``src/engine/`` subdirectory and are the same base name as the module
+  with ``Tests.py`` appended--for example, the unit tests for the
+  ``Builder.py`` module are in the ``BuilderTests.py`` script.
+
+*External Tests*
+  For the support of external Tools (in the form of packages, preferably), the
+  testing framework got extended, such that it can run in standalone mode.
+  You can start it from the top-level folder of your Tool's source tree,
+  where it then finds all Python scripts (``*.py``) underneath the
+  local ``test/`` directory.
+  This implies that Tool tests have to be kept in a folder named ``test``,
+  like for the SCons core.
+  
+
+Contrasting End-to-End and Unit Tests
+#####################################
+
+In general, anything that we've put into an end-to-end test script should
+be considered a hardened part of the interface (that is, it's something
+that a user might do) and should not be broken.  Unit tests are now
+considered more malleable, more for testing internal interfaces that
+can change so long as we don't break users' ``SConscript`` files.  (This
+wasn't always the case, and there's a lot of meaty code in many of the
+unit test scripts that does, in fact, capture external interface
+behavior.  In general, we should try to move those things to end-to-end
+scripts as we find them.)
+
+It's more difficult to debug end-to-end tests.  You can actually go
+straight into the Python debugger on the unit test scripts by using the
+``runtest.py --pdb`` option, but the end-to-end tests treat an SCons
+invocation as a "black box" and just look for external effects.
+Simple ``print`` statements within the SCons code itself often don't help
+debug end-to-end because they end up in SCons output that gets compared
+against expected output and cause a test failure.  Probably the most
+effective technique is to use the internal ``SCons.Debug.Trace()`` function,
+which prints output to ``/dev/tty`` on Linux/UNIX systems and ``con`` on
+Windows systems, so you can see what's going on.
+
+Naming conventions
+##################
+
+The end-to-end tests, more or less, stick to the following naming conventions:
+
+1. All tests end with a .py suffix.
+
+2. In the *General* form we use
+
+   ``Feature.py``
+       for the test of a specified feature; try to
+       keep this description reasonably short
+
+   ``Feature-x.py``
+       for the test of a specified feature using
+       option ``x``
+
+3. The *command line option* tests take the form
+
+   ``option-x.py``
+       for a lower-case single-letter option
+
+   ``option--X.py``
+       upper-case single-letter option
+       (with an extra hyphen, so the file names will
+       be unique on case-insensitive systems)
+
+   ``option--lo.py``  
+       long option; abbreviate the long
+       option name to a few characters
+
+
+Running Tests
+=============
+
+The standard set of SCons tests are run from the top-level source directory
+by the ``runtest.py`` script.
+There is a ``--qmtest`` option that checks whether the ``QMTest`` package
+is installed on your system. If it can be found, then the ``runtest.py`` script
+will use it to carry out the tests.
+
+Help is available through the ``-h`` option:
+
+::
+
+  $ python runtest.py -h
+
+To simply run all the tests, use the ``-a`` option:
+
+::
+
+  $ python runtest.py -a
+
+By default, ``runtest.py`` prints a count and percentage message for each test
+case, along with the name of the test file.
+If you need the output to be more silent, have a look at the ``-q``, ``-s`` and
+``-k`` options.
+
+You may specifically list one or more tests to be run:
+
+::
+
+  $ python runtest.py src/engine/SCons/BuilderTests.py
+  $ python runtest.py test/option-j.py test/Program.py
+
+Folder names are allowed arguments as well, so you can do a
+
+::
+
+  $ python runtest.py test/SWIG
+
+to run all SWIG tests only.
+
+You can also use the ``-f`` option to execute just the tests listed in a specified
+text file:
+
+::
+
+  $ cat testlist.txt
+  test/option-j.py
+  test/Program.py
+  $ python runtest.py -f testlist.txt
+
+
+One test must be listed per line, and any lines that begin with '#'
+will be ignored (the intent being to allow you, for example,
+to comment out tests that
+are currently passing and then uncomment all of the tests in the file
+for a final validation run).
+
+If more than one test is run, the ``runtest.py`` script prints a summary
+of how many tests passed, failed, or yielded no result, and lists any
+unsuccessful tests.
+
+The above invocations all test directly the files underneath the ``src/``
+subdirectory, and do not require that a packaging build be performed first.
+The ``runtest.py`` script supports additional options to run tests against
+unpacked packages in the ``build/test-*/`` subdirectories.
+
+If you are testing a separate Tool outside of the SCons source tree, you have
+to call the ``runtest.py`` script in *external* (stand-alone) mode::
+
+  $ python ~/scons/runtest.py -e -a
+
+.  This ensures that the testing framework doesn't try to access SCons classes
+needed for some of the *internal* test cases.
+
+Note, that the actual tests are carried out in a temporary folder each, which gets
+deleted afterwards. This ensures that your source directories don't get clobbered
+with temporary files from the test runs. It also means that you can't simply change
+into a folder to "debug things" after a test has gone wrong. For a way around this,
+check out the ``PRESERVE`` environment variable. It can be seen in action in
+`How to convert old tests`_ below.
+
+Not Running Tests
+=================
+
+If you simply want to check which tests would get executed, you can call the
+``runtest.py`` script with the ``-l`` option::
+
+  $ python runtest.py -l
+
+Then there is also the ``-n`` option, which prints the command line for each
+single test, but doesn't actually execute them::
+
+  $ python runtest.py -n
+
+Finding Tests
+=============
+
+When started in *standard* mode
+
+::
+
+  $ python runtest.py -a
+
+
+, ``runtest.py`` assumes that it is run from the SCons top-level source directory.
+It then dives into the ``src`` and ``test`` folders, where it tries to find filenames
+
+    ``*Test.py``
+        for the ``src`` directory, and
+  
+    ``*.py``
+        for the ``test`` folder.
+
+When using fixtures, you may quickly end up in a position where you have supporting
+Python script files in a subfolder, but they shouldn't get picked up as test scripts.
+In this case you have two options:
+
+1. Add a file with the name ``sconstest.skip`` to your subfolder. This lets
+   ``runtest.py`` skip the contents of the directory completely.
+2. Create a file ``.exclude_tests`` in each folder in question, and in it list
+   line-by-line the files to get excluded from testing.
+
+The same rules apply when testing external Tools by using the ``-e`` option.
+
+
+"Hello, world!" SCons Test Script
+=================================
+
+To illustrate how the end-to-end test scripts work,
+let's walk through a simple "Hello, world!" example:
+
+::
+
+  #!python
+  import TestSCons
+
+  test = TestSCons.TestSCons()
+
+  test.write('SConstruct', """\
+  Program('hello.c')
+  """)
+
+  test.write('hello.c', """\
+  int
+  main(int argc, char *argv[])
+  {
+        printf("Hello, world!\\n");
+        exit (0);
+  }
+  """)
+
+  test.run()
+
+  test.run(program='./hello', stdout="Hello, world!\n")
+
+  test.pass_test()
+
+
+``import TestSCons``  
+  Imports the main infrastructure for writing SCons tests.  This is normally the only part of the infrastructure that needs importing.  Sometimes other Python modules are necessary or helpful, and get imported before this line.
+
+``test = TestSCons.TestSCons()``
+  This initializes an object for testing.  A fair amount happens under the covers when the object is created, including:
+
+    * A temporary directory is created for all the in-line files that will get created.
+    * The temporary directory's removal is arranged for when the test is finished.
+    * We ``os.chdir()`` to the temporary directory.
+
+``test.write('SConstruct', ...``
+  This line creates an ``SConstruct`` file in the temporary directory, to be used as input to the ``scons`` run(s) that we're testing.  Note the use of the Python triple-quote syntax for the contents of the ``SConstruct`` file.  Because input files for tests are all created from in-line data like this, the tests can sometimes get a little confusing to read, because some of the Python code is found
+
+``test.write('hello.c', ...``
+  This lines creates an ``hello.c`` file in the temporary directory.  Note that we have to escape the ``\\n`` in the ``"Hello, world!\\n"`` string so that it ends up as a single backslash in the ``hello.c`` file on disk.
+
+``test.run()``
+  This actually runs SCons.  Like the object initialization, things happen under the covers:
+
+    * The exit status is verified; the test exits with a failure if the exit status is not zero.
+    * The error output is examined, and the test exits with a failure if there is any
+
+``test.run(program='./hello', stdout="Hello, world!\n")``
+  This shows use of the ``TestSCons.run()`` method to execute a program other than ``scons``, in this case the ``hello`` program we just presumably built.  The ``stdout=`` keyword argument also tells the ``TestSCons.run()`` method to fail if the program output does not match the expected string ``"Hello, world!\n"``.  Like the previous ``test.run()`` line, it will also fail the test if the exit status is non-zero, or there is any error output.
+
+``test.pass_test()``
+  This is always the last line in a test script.  It prints ``PASSED`` on the screen and makes sure we exit with a ``0`` status to indicate the test passed.  As a side effect of destroying the ``test`` object, the created temporary directory will be removed.
+
+Working with fixtures
+=====================
+
+In the simple example above, we have seen how to create files in the temporary test directory.
+We give a filename to the ``TestSCons.write()`` method, together with its contents, and it gets
+written to the test folder right before its start.
+
+This technique can still be seen throughout most of the end-to-end tests, but there is a better
+way. It's much easier to edit, create and maintain real files, instead of copy/pasting
+content to/from a Python script. If the test files get longer, the test script
+gets longer and is harder to read.
+
+Against this, we now have the possibility to copy single files or the contents of a
+local folder to the test directory. Since we can reuse these files/folders to setup
+several tests, we call them *fixtures* in the following.
+
+Directory fixtures
+##################
+
+The function ``dir_fixture(self, srcdir, dstdir=None)`` in the ``TestCmd`` class
+copies the contents of the specified folder ``srcdir`` from
+the directory of the called test script, to the current
+temporary test directory.
+The ``srcdir`` name may be a list, in which case the elements are
+concatenated with the ``os.path.join()`` method.  The ``dstdir`` is
+assumed to be under the temporary working directory, it gets
+created automatically, if it does not already exist.
+
+A short syntax example::
+
+  test = TestSCons.TestSCons()
+  test.dir_fixture('image')
+  test.run()  
+
+would copy all files and subfolders from the local ``image`` folder, to
+the temporary directory for the current test.
+
+If you'd like to see a real example for this in action, refer to the test
+named ``test/packaging/convenience-functions/convenience-functions.py``.
+  
+File fixtures
+#############
+
+Like for directory fixtures, ``file_fixture(self, srcfile, dstfile=None)``
+copies the file ``srcfile`` from the directory of
+the called script, to the temporary test directory.
+The ``dstfile`` is assumed to be under the temporary working
+directory, unless it is an absolute path name.
+If ``dstfile`` is specified, its target directory gets created
+automatically if it doesn't already exist.
+
+With a::
+
+  test = TestSCons.TestSCons()
+  test.file_fixture('SConstruct')
+  test.file_fixture(['src','main.cpp'],['src','main.cpp'])
+  test.run()  
+
+you would copy the files ``SConstruct`` and ``src/main.cpp`` to the temporary
+test folder, prior to running the test itself.
+
+Again, a reference example can be found in the current *default* revision of
+SCons, it is ``test/packaging/sandbox-test/sandbox-test.py``.
+
+For even more examples you should check out one of the external Tools, e.g. the
+*Qt4* Tool at https://bitbucket.org/dirkbaechle/scons_qt4. Also visit the SCons
+Tools Index at http://www.scons.org/wiki/ToolsIndex for a complete
+list of available Tools, though not all may have tests yet.
+
+How to convert old tests
+########################
+
+We now show how to convert a test, still using the ``TestSCons.write()`` method, to
+the fixture based approach. For this, we need to get at the files as they
+are written to each temporary test folder.
+
+Luckily, ``runtest.py`` checks for the existence of an environment variable named
+``PRESERVE``. If it is set to a non-zero value, the testing framework doesn't delete
+the test folder as ususal, but prints its name to the screen.
+
+So, you should be able to give the commands 
+
+::
+
+  $ export PRESERVE=1
+  $ python runtest.py test/packaging/sandbox-test.py
+
+, assuming Linux and a bash-like shell.
+  
+The output should then look something like this::
+
+  1/1 (100.00%) /usr/bin/python -tt test/packaging/sandbox-test.py
+  PASSED
+  Preserved directory /tmp/testcmd.4060.twlYNI
+
+and you see that the test files have been kept in the folder ``/tmp/testcmd.4060.twlYNI``, 
+where you can now copy them from to your new *fixture* folder. Then, in the test
+script you simply remove all the tedious ``TestSCons.write()`` statements and
+replace them by a single ``TestSCons.dir_fixture()``.
+
+Finally, you shouldn't forget to clean up and remove the temporary test directory. ``;)``
+
+Test Infrastructure
+===================
+
+The test API is in ``QMTest/TestSCons.py``.  ``TestSCons`` is a subclass of
+``TestCommon``, which is a subclass of ``TestCmd``; all those python files are
+in ``QMTest``. Start in ``QMTest/TestCmd.py`` for the base API definitions,
+like how to create files (``test.write()``) and run commands (``test.run()``).
+
+You want to use ``TestSCons`` for the end-to-end tests in ``test``, but ``TestCmd``
+for the unit tests in the ``src`` folder.
+
+The match functions work like this:
+
+TestSCons.match_re:: match each line with a RE
+  * Splits the lines into a list (unless they already are)
+  * splits the REs at newlines (unless already a list) and puts ^..$ around each
+  * then each RE must match each line.  This means there must be as many REs as lines.
+
+TestSCons.match_re_dotall:: match all the lines against a single RE
+  * Joins the lines with newline (unless already a string)
+  * joins the REs with newline (unless it's a string) and puts ^..$ around the whole thing
+  * then whole thing must match with python re.DOTALL.
+
+Use them in a test like this::
+
+  test.run(..., match=TestSCons.match_re, ...)
+
+or::
+
+  test.must_match(..., match=TestSCons.match_re, ...)
+
+Avoiding Tests based on Tool existence
+======================================
+
+Here's an easy sample::
+
+  #!python
+  intelc = test.detect_tool('intelc', prog='icpc')
+  if not intelc:
+      test.skip_test("Could not load 'intelc' Tool; skipping test(s).\n")
+
+See ``QMTest/TestSCons.py`` for the ``detect_tool`` method.  It calls the tool's
+``generate()`` method, and then looks for the given prog (tool name by default) in
+``env['ENV']['PATH']``.
+
+

README

-                 SCons - a software construction tool
-
-Welcome to the SCons development tree.  The real purpose of this tree
-is to package SCons for production distribution in a variety of formats,
-not just to hack SCons code.
-
-If all you want to do is install and run SCons, it will be easier for you
-to download and install the scons-{version}.tar.gz or scons-{version}.zip
-package rather than to work with the packaging logic in this tree.
-
-To the extent that this tree is about building SCons packages, the *full*
-development cycle is not just to test the code directly, but to package
-SCons, unpack the package, "install" SCons in a test subdirectory,
-and then to run the tests against the unpacked and installed software.
-This helps eliminate problems caused by, for example, failure to update
-the list of files to be packaged.
-
-For just working on making an individual change to the SCons source,
-however, you don't actually need to build or install SCons; you
-*can* actually edit and execute SCons in-place.  See the following
-sections below for more information:
-
-    MAKING CHANGES
-        How to edit and execute SCons in-place.
-
-    DEBUGGING
-        Tips for debugging problems in SCons.
-
-    TESTING
-        How to use the automated regression tests.
-
-    DEVELOPMENT WORKFLOW
-        An example of how to put the edit/execute/test pieces
-        together in a reasonable development workflow.
-
-
-LATEST VERSION
-==============
-
-Before going further, you can check that this package you have is the
-latest version at the SCons download page:
-
-        http://www.scons.org/download.php
-
-
-EXECUTION REQUIREMENTS
-======================
-
-Running SCons requires Python version 2.4 or later.  There should be
-no other dependencies or requirements to run SCons.
-
-The default SCons configuration assumes use of the Microsoft Visual C++
-compiler suite on WIN32 systems, and assumes a C compiler named 'cc',
-a C++ compiler named 'c++', and a Fortran compiler named 'g77' (such
-as found in the GNU C compiler suite) on any other type of system.
-You may, of course, override these default values by appropriate
-configuration of Environment construction variables.
-
-By default, SCons knows how to search for available programming tools
-on various systems--see the SCons man page for details.  You may,
-of course, override the default SCons choices made by appropriate
-configuration of Environment construction variables.
-
-
-INSTALLATION REQUIREMENTS
-=========================
-
-Nothing special.
-
-
-EXECUTING SCONS WITHOUT INSTALLING
-==================================
-
-You can execute the local SCons directly from the src/ subdirectory by
-first setting the SCONS_LIB_DIR environment variable to the local
-src/engine subdirectory, and then executing the local src/script/scons.py
-script to populate the build/scons/ subdirectory.  You would do this as
-follows on a Linux or UNIX system (using sh or a derivative like bash or
-ksh):
-
-        $ setenv MYSCONS=`pwd`/src
-        $ setenv SCONS_LIB_DIR=$MYSCONS/engine
-        $ python $MYSCONS/script/scons.py [arguments]
-
-Or on Windows:
-
-        C:\scons>set MYSCONS=%cd%\src
-        C:\scons>set SCONS_LIB_DIR=%MYSCONS%\engine
-        C:\scons>python %MYSCONS%\script\scons.py [arguments]
-
-An alternative approach is to skip the above and use:
-
-        $ python bootstrap.py [arguments]
-
-bootstrap.py keeps the src/ subdirectory free of compiled Python (*.pyc or
-*.pyo) files by copying the necessary SCons files to a local bootstrap/
-subdirectory and executing it from there.
-
-You can use the -C option to have SCons change directory to another
-location where you already have a build configuration set up.
-
-    $ python bootstrap.py -C /some/other/location [arguments]
-
-For simplicity in the following examples, we will only show the
-bootstrap.py approach.
-
-
-INSTALLATION
-============