Captures console output to a string.
Used to capture the output so that it can be tested.
Inheritance: IDisposable
Example #1
0
        public void Test_BuildFileOption() {
            string filename = "file1.ha";
            string baseDirectory = TempDir.Create(Path.Combine(TempDirName, "foo"));
            string build1FileName = TempFile.CreateWithContents("<project/>", Path.Combine(baseDirectory, filename));

            string oldCurrDir = Environment.CurrentDirectory;
            Environment.CurrentDirectory = baseDirectory;
            using (ConsoleCapture c = new ConsoleCapture()) {
                bool errors = false;
                try {
                    //check filename only, should be resolvable via currentdirectory
                    Assert.IsTrue(0 == ConsoleDriver.Main(new string[] {"-buildfile:" + filename}), "Using filepath failed");
                    //check absolute
                    Assert.IsTrue(0 == ConsoleDriver.Main(new string[] {@"-buildfile:" + build1FileName}), "Using absolute filepath failed");
                    //check relative path, should be resolvable via currentdirectory
                    Assert.IsTrue(0 == ConsoleDriver.Main(new string[] {string.Format("-buildfile:.{0}{1}", Path.DirectorySeparatorChar, filename)}), "Using relative filepath failed #1");
                    //check relative path, should be resolvable via currentdirectory
                    Assert.IsTrue(0 == ConsoleDriver.Main(new string[] {string.Format("-buildfile:..{0}foo{0}{1}", Path.DirectorySeparatorChar, filename)}), "Using relative filepath failed #2");
                } catch (Exception e) {
                    e.ToString();
                    errors = true;
                    throw;
                }
                finally {
                    string results = c.Close();
                    if(errors)
                        System.Console.Write(results);
                }
            }
            Environment.CurrentDirectory = oldCurrDir;
        }
Example #2
0
        public void Test_DefineProperty() {
            string buildFileContents = @"<?xml version='1.0' ?>
                <project name='Test' default='test' basedir='.'>
                    <target name='test'>
                        <property name='project.name' value='Foo.Bar' overwrite='false' />
                        <echo message='project.name = ${project.name}'/>
                    </target>
                </project>";

            // write build file to temp file
            string buildFileName = CreateTempFile("buildfile.xml", buildFileContents);
            Assert.IsTrue(File.Exists(buildFileName), buildFileName + " does not exist.");

            string[] args = {
                "-D:project.name=MyCompany.MyProject",
                String.Format("-buildfile:{0}", buildFileName),
            };

            string result = null;
            using (ConsoleCapture c = new ConsoleCapture()) {
                ConsoleDriver.Main(args);
                result = c.Close();
            }

            // regular expression to look for expected output
            string expression = @"project.name = MyCompany.MyProject";
            Match match = Regex.Match(result, expression);
            Assert.IsTrue(match.Success, "Property 'project.name' appears to have been overridden by <property> task." + Environment.NewLine + result);

            // delete the build file
            File.Delete(buildFileName);
            Assert.IsFalse(File.Exists(buildFileName), buildFileName + " exists.");
        }
Example #3
0
        public void DoTestShowProjectHelp(string nantNamespace, string prefix) {
            string buildFileContents = @"<?xml version='1.0' ?>
                <{1}{2}project {0} name='Hello World' default='build' basedir='.'>

                    <{1}{2}property name='basename' value='HelloWorld'/>
                    <{1}{2}target name='init'/> <!-- fake subtarget for unit test -->

                    <{1}{2}target name='clean' description='cleans build directory'>
                        <{1}{2}delete file='${{basename}}.exe' failonerror='false'/>
                    </{1}{2}target>

                    <{1}{2}target name='build' description='compiles the source code'>
                        <{1}{2}csc target='exe' output='${{basename}}.exe'>
                            <{1}{2}sources>
                                <{1}{2}include name='${{basename}}.cs'/>
                            </{1}{2}sources>
                        </{1}{2}csc>
                    </{1}{2}target>

                    <{1}{2}target name='test' depends='build' description='run the program'>
                        <{1}{2}exec program='${{basename}}.exe'/>
                    </{1}{2}target>
                </{1}{2}project>";

            string colon = prefix.Length == 0? string.Empty: ":";
            string namespaceDecl = nantNamespace.Length == 0? string.Empty:
                string.Format("xmlns{2}{1}=\"{0}\"",nantNamespace,prefix,colon);
            // write build file to temp file
            string buildFileName = CreateTempFile("buildfile.xml", string.Format(buildFileContents,namespaceDecl,prefix,colon));
            Assert.IsTrue(File.Exists(buildFileName), buildFileName + " does not exist.");         

            X.XmlDocument document = new Project(buildFileName,Level.Warning,0).Document;
            Assert.AreEqual(nantNamespace,document.DocumentElement.NamespaceURI);
            string result = null;
            using (ConsoleCapture c = new ConsoleCapture()) {
                ConsoleDriver.ShowProjectHelp(document);
                result = c.Close();
            }
            /* expecting output in the form of"

                Default Target:

                 build         compiles the source code

                Main Targets:

                 clean         cleans build directory
                 build         compiles the source code
                 test          run the program

                Sub Targets:

                 init
            */

            // using a regular expression to look for valid output
            // expression created by RegEx http://www.organicbit.com/regex/
            string expression = @"Default Target:[\s]*(?<default>build)\s*compiles the source code[\s]*Main Targets:[\s]*(?<main1>build)\s*compiles the source code[\s]*(?<main2>clean)\s*cleans build directory[\s]*(?<main3>test)\s*run the program[\s]*Sub Targets:[\s]*(?<subtarget1>init)";

            Match match = Regex.Match(result, expression);
            if (match.Success) {
                Assert.AreEqual("build", match.Groups["default"].Value);
                Assert.AreEqual("build", match.Groups["main1"].Value);
                Assert.AreEqual("clean", match.Groups["main2"].Value);
                Assert.AreEqual("test", match.Groups["main3"].Value);
                Assert.AreEqual("init", match.Groups["subtarget1"].Value);
            } else {
                Assert.Fail("Project help text does not appear to be valid, see results for details:" + Environment.NewLine + result);
            }

            // delete the build file
            File.Delete(buildFileName);
            Assert.IsFalse(File.Exists(buildFileName), buildFileName + " exists.");
        }
Example #4
0
        public void Test_MissingValueForNameValuePair() {
            string[] args = {"-D:test", "-D:test"};

            string result = null;
            using (ConsoleCapture c = new ConsoleCapture()) {
                ConsoleDriver.Main(args);
                result = c.Close();
            }

            // using a regular expression to check for correct error message
            string expression = @"Expected name\/value pair \(<name>=<value>\).";

            Match match = Regex.Match(result, expression);
            Assert.IsTrue(match.Success, "Argument did not cause an error: " + result);
        }
Example #5
0
        public void Test_MissingNameForNameValuePair() {
            string[] args = {"-D:test=", "-D:test="};

            string result = null;
            using (ConsoleCapture c = new ConsoleCapture()) {
                ConsoleDriver.Main(args);
                result = c.Close();
            }

            // using a regular expression to check for correct error message
            string expression = @"Duplicate property named 'test' for command-line argument 'D'.";

            Match match = Regex.Match(result, expression);
            Assert.IsTrue(match.Success, "Argument did not cause an error: " + result);
        }
Example #6
0
        public void Test_DuplicateCollectionValue() {
            string[] args = {"-listener:test", "-listener:test"};

            string result = null;
            using (ConsoleCapture c = new ConsoleCapture()) {
                ConsoleDriver.Main(args);
                result = c.Close();
            }

            // using a regular expression to check for correct error message
            string expression = @"Duplicate value 'test' for command-line argument '-listener'.";

            Match match = Regex.Match(result, expression);
            Assert.IsTrue(match.Success, "Argument did not cause an error: " + result);
        }
Example #7
0
        public void Test_UnknownArgument() {
            string[] args = { "-asdf", "-help", "-verbose" };

            string result = null;
            using (ConsoleCapture c = new ConsoleCapture()) {
                ConsoleDriver.Main(args);
                result = c.Close();
            }

            // using a regular expression to check for correct error message
            string expression = @"Unknown argument '-asdf'";

            Match match = Regex.Match(result, expression);
            Assert.IsTrue(match.Success, "Argument did not cause an error: " + result);
        }
Example #8
0
        public void Test_ShowHelp() {
            string[] args = { "-help" };

            string result = null;
            using (ConsoleCapture c = new ConsoleCapture()) {
                ConsoleDriver.Main(args);
                result = c.Close();
            }

            // using a regular expression look for a plausible version number and valid copyright date
            string expression = @"^NAnt (?<infoMajor>[0-9]+).(?<infoMinor>[0-9]+) "
                 + @"\(Build (?<buildMajor>[0-9]+).(?<buildMinor>[0-9]+).(?<buildBuild>[0-9]+).(?<buildRevision>[0-9]+); "
                 + @"(?<configuration>.*); (?<releasedate>.*)\)"
                 + ".*\n" + @"Copyright \(C\) 2001-(?<year>20[0-9][0-9]) Gerry Shaw";

            Match match = Regex.Match(result, expression);
            Assert.IsTrue(match.Success, "Help text does not appear to be valid.");
            int infoMajor = Int32.Parse(match.Groups["infoMajor"].Value);
            int infoMinor = Int32.Parse(match.Groups["infoMinor"].Value);
            int buildMajor = Int32.Parse(match.Groups["buildMajor"].Value);
            int buildMinor = Int32.Parse(match.Groups["buildMinor"].Value);
            int buildBuild = Int32.Parse(match.Groups["buildBuild"].Value);
            int buildRevision = Int32.Parse(match.Groups["buildRevision"].Value);
            int year  = Int32.Parse(match.Groups["year"].Value);
            Assert.IsTrue(infoMajor >= 0, "Version numbers must be positive.");
            Assert.IsTrue(infoMinor >= 0, "Version numbers must be positive.");
            Assert.IsTrue(buildMajor >= 0, "Version numbers must be positive.");
            Assert.IsTrue(buildMinor >= 0, "Version numbers must be positive.");
            Assert.IsTrue(buildBuild >= 0, "Version numbers must be positive.");
            Assert.IsTrue(buildRevision >= 0, "Version numbers must be positive.");
            Assert.IsTrue(year <= DateTime.Now.Year, "Copyright year should be equal or less than current year.");
        }
Example #9
0
 /// <summary>
 /// Executes the project and returns the console output as a string.
 /// </summary>
 /// <param name="p">The project to execute.</param>
 /// <returns>
 /// The console output.
 /// </returns>
 /// <remarks>
 /// Any exception that is thrown as part of the execution of the 
 /// <see cref="Project" /> is wrapped in a <see cref="TestBuildException" />.
 /// </remarks>
 public static string ExecuteProject(Project p)
 {
     using (ConsoleCapture c = new ConsoleCapture()) {
         string output = null;
         try {
             p.Execute();
         } catch (BuildException e) {
             output = c.Close();
             throw new TestBuildException("Error Executing Project", output, e);
         } finally {
             if (output == null) {
                 output = c.Close();
             }
         }
         return output;
     }
 }
Example #10
0
 /// <summary>
 /// Executes a task and returns the console output as a string.
 /// </summary>
 /// <param name="task">The task to execute.</param>
 /// <returns>
 /// The console output.
 /// </returns>
 /// <remarks>
 /// Any exception that is thrown as part of the execution of the 
 /// <see cref="Task" /> is wrapped in a <see cref="TestBuildException" />.
 /// </remarks>
 public static string ExecuteTask(Task task)
 {
     using (ConsoleCapture c = new ConsoleCapture()) {
         string output = null;
         try {
             task.Execute();
         } catch (Exception e) {
             output = c.Close();
             throw new TestBuildException("Error Executing Task", output, e);
         } finally {
             if (output == null) {
                 output = c.Close();
             }
         }
         return output;
     }
 }