FailOnError does not work in custom NAnt task - nant

I have custom NAnt task for test purposes and I would like to cancel NAnt build process if the task is failed.
I have created custom ErrorTask:
[NAnt.Core.Attributes.TaskName("errorTask")]
public class ErrorTask : NAnt.Core.Task
{
public ErrorTask()
{
FailOnError = true;
}
protected override void ExecuteTask()
{
Log(NAnt.Core.Level.Error, "Error!");
}
}
Here is what I have in NAnt build file:
<target name="errorTarget">
<errorTask failonerror="true" />
<errorTask failonerror="true" />
</target>
In the result (build.log) I have:
errorTarget:
[errorTask] Error!
[errorTask] Error!
BUILD SUCCEEDED - 2 non-fatal error(s), 0 warning(s)
Total time: 0 seconds.
So, I can see that second task is also run, but I would like to cancel it, because first call returns "Error!". Could you assist me to fix it?
Also, I assume, that it is not necessary to hardcode FailOnError value, it should be enough to use just failonerror attribute in build script, but it does not work for me in any case.
Thank you.

You need to let an exception bubble out of your ExecuteTask function. After your log statement, add this line:
throw new BuildException("Something terrible has happened!");

Related

How to capture the exception when Assert get failed either in Nunit or MsTest

How to capture Failed Assert exception message or state when using NUnit ir MeTest Assert method.
I was trying to capture "AssertionException" when my assert get failed, how can i capture that using either NUnit or MsTest. since Assert method doesn't return any type. My requirements are Test should continue even when assert get failed to finish remaining assertions, should capture the error and should fail this assert. I was using below code statement. When i use Nunit framework its failing and continuous to next assert buy not able to capture even when i use try.. catch block where as in MsTest its failing, capturing using try..catch block and not continuing to next assertion.
Much appreciated for any help!
public static void ResponseValueAssert(dynamic actualValue, dynamic expectedValue, string nameOfAssert)
{
//var ex = Assert.Throws<AssertionException>(() =>
//Assert.AreEqual(expectedValue, actualValue, "Actual value doesn't match with Expected value {0}", nameOfAssert));
if (ResponseValueAssertImplicit(actualValue, expectedValue, nameOfAssert))
{
Console.WriteLine("\r\nResponse Assert:- {0}: <PASS>", nameOfAssert);
}
else
{
Console.WriteLine("\r\nResponse Assert:- {0}: <<FAIL>>", nameOfAssert);
Console.Error.WriteLine("\r\nResponse Assert:- {0}: <<FAIL>>", nameOfAssert);
// Assert.Fail();
}
Console.WriteLine("Expected Value: {0}.\r\nActual Value: {1}.", actualValue, expectedValue);
}
public static bool ResponseValueAssertImplicit(dynamic actualValue, dynamic expectedValue, string nameOfAssert)
{
try
{
Assert.AreEqual(expectedValue, actualValue, "Actual value doesn't match with Expected value {0}", nameOfAssert);
return true;
}
catch (AssertionException ex)
{
return false;
}
}
It's not useful to ask a question about two completely different pieces of software as one thing. The answer would obviously be different for NUnit and MSTest, which are implemented quite differently these days.
So I'll answer only with respect to NUnit, since I have no idea what you would do with MSTest anyway.
In NUnit, if you want a test to continue so that more than one assertion can be reported on in the same test, you use multiple assertions. That is...
Assert.Multiple(() =>
{
// Put your various asserts here
};
NUnit will report all the failed asserts. At the end of the block, the test will be terminated if any of the asserts failed.
Note that many people will say that more than one assert in a test is a bad idea. I believe it is most of the time but that there are situations, like checking multiple properties of the same object, where it can be useful.
Also, for the record, you should never be catching exceptions that are used internally by the test framework. They are basically hidden implementation details and all your work can be lost in the next release of the software... as has happened already to some people in this case.

Nunit - Why single test with unique name is executing multiple times?

I have a test like
[Test]
[TestCase("Chrome", TestName = "One")]
[TestCase("Firefox", TestName = "Two")]
[TestCase("IE", TestName = "Three")]
public void MyTest(string Browser)
{
.............
}
I am calling this through programming as
SimpleNameFilter filter = new SimpleNameFilter() { };
Test = "SeleniumTests.Test.One";
filter.Add(Test);
CoreExtensions.Host.InitializeService();
TestPackage testPackage = new TestPackage(#"D:\Test.dll");
RemoteTestRunner remoteTestRunner = new RemoteTestRunner();
remoteTestRunner.Load(testPackage);
TestResult result = remoteTestRunner.Run(new NullListener(), filter, true, LoggingThreshold.All);
when i executed the above code, the test "one" is executing , but calling multiple time, can anybody tell why this is happening like this?
Thanks in advance,
Kishore.
First of in your case you don't need the first [Test], since you already have [TestCase(...)]. Just remove the attribute and see if this is going to make a difference.
Second of all, I believe what happens is, the Test class - One (is what I think you called it) get's picked up and executes all the tests within it the class. For example MyTest will run 3 times (for each TestCase).
I hope I understood you correct.

NUnit: Execute code upon assertion failure hook

Is there a hook in NUnit to execute code only when assertion fails without catching the exception itself. Basically, it should accept action delegate to be executed when assertion fails and then re-throw exception. Why do I need this?
I need to compare two objects and dump the result on the screen, for easier debugging, when assertion fails.
Something like this works but is a bad hack, The problem is that it eagerly evaluates ProcessCompareError so I have unnecessary overhead, plus it does it no matter if there is an error or not. So, is there overload that will accept the delegate that would be executed when assertion fails?
Assert.That(benefitLimitComparer.Compare(copyBenefitLimit, origBenefitLimit), Is.EqualTo(0),limitError, ProcessCompareError(origBenefitLimit, copyBenefitLimit));
}
}
}
private string ProcessCompareError(BenefitLimit origBenefitLimit, BenefitLimit copyBenefitLimit)
{
Console.WriteLine("Original: ");
ObjectDumper.Write(origBenefitLimit);
Console.WriteLine("Copy");
ObjectDumper.Write(copyBenefitLimit);
return "";
}
I'm not sure how it might be done through a delegate. One alternative is to store the result of the Compare. If the result is false, write out the contents of the objects and then call Assert.Fail()
There is a possibilty to wrap an assert as an Action in a try-catch. In the catch you can handle the additional compare:
public static void ExecuteAssert(Action assert)
{
if (assert == null) return;
try
{
assert();
}
catch (Exception ex)
{
// perform the compare
}
}
As remark: I use a similar method to continue test execution and avoid the entire test to stop, if some non-fatal checks fail. Actually I iterate through a number of actions:
private static void VerifyAll(params Action[] asserts)

No appropriate default constructor available?

I've got a peculiar error writing some C++/CLI code. I'm trying to make a copy of a class which holds some data.
The class is defined as:
public ref class RawDataPacket
{
protected:
float* m_internalData;
public:
RawDataPacket(const float* newInternalData);
RawDataPacket(const RawDataPacket^ rdp);
RawDataPacket(RawDataPacket^ rdp);
RawDataPacket();
};
When I try and make use of the class as follows:
void SomeClass::SomeFunction( RawDataPacket^ rdp )
{
// Send a copy of the packet to anyone interested.
RawDataPacket^ rdp1 = gcnew RawDataPacket( rdp );
ForwardData( rdp1 );
}
I get:
error C2512: 'RawDataPacket' : no appropriate default constructor available
I thought that RawDataPacket(); had that covered? ..or am I missing something really obvious there?
[Edit] The body of RawDataPacket() looks like this:
RawDataPacket::RawDataPacket()
{
m_internalData = nullptr;
}
[Edit2] The full compiler output looks like this:
1>------ Build started: Project: MySoftware, Configuration: Debug Win32 ------
1>Compiling...
1>RawDataPacket.cpp
1>Controller.cpp
1>.\Controller.cpp(452) : error C2512: 'MySoftware::RawDataPacket' : no appropriate default constructor available
1>Build log was saved at "file://c:\Projects\Experiments\MySoftware\Debug\BuildLog.htm"
1>MySoftware - 1 error(s), 0 warning(s)
========== Build: 0 succeeded, 1 failed, 1 up-to-date, 0 skipped ==========
Got it! It occurred to me that I'd forward-declared the RawDataPacket class in the header of the Controller class.
I tried including the header in there and removing the forward declaration and it worked. So it turns out that despite forward-declaring the class I'd forgotten to include the header in Controller.cpp
That could have been a nasty one to find.. cheers for the help all!
use explicit before the constructor if you are having parameters for constructor.

Changing the title of a Command (CMD) window from NANT

I would like to be able to change the title of the Command window at various points throughout my NAnt script.
I have tried to use the task to call 'title myTargetName' but it gives me the following error:
'title' failed to start.
The system cannot find the file specified
Is there a way to do this please? Thanks in advance!
You can set the console title in a custom task. If the task is defined in a script, the build file is self contained.
The console title will revert once nant finishes.
<project default="title">
<target name="title">
<consoletask title='step 1'/>
<sleep minutes="1" />
<consoletask title='step 2'/>
<sleep minutes="1" />
<consoletask title='step 3'/>
<sleep minutes="1" />
</target>
<script language="C#">
<code>
[TaskName("consoletask")]
public class TestTask : Task
{
private string title;
[TaskAttribute("title", Required=true)]
public string Title
{
get { return title; }
set { title = value; }
}
protected override void ExecuteTask() {
System.Console.Title = title;
}
}
</code>
</script>
</project>
If you compile this small program as a console app:
namespace SetTitle
{
internal static class Program
{
private static void Main(string[] args)
{
System.Console.Title = string.Join(" ", args);
}
}
}
Then this would work:
<exec>SetTitle.exe "Step One"</exec>
<!-- Do some stuff -->
<exec>SetTitle.exe "Step Two"</exec>
You could do the same with a custom NAnt task, but the work involved would be more complicated and you'd still have to make your NAnt task assembly discoverable during the script's execution.
Try this:
' In your command prompt
title foobar
' The title now should say 'foobar' without quotes
' Now issue this...
cmd /k fubar
' The title now should say 'fubar' without quotes
So I guess you need to change it to like this:
<exec>cmd /k title one </exec>
Edit: At the end of the script, invoke the exit command to exit the nested levels of the cmd.exe command line processor...Suppose you have three 'exec' for the 'cmd /k', you would need three 'exit' commands in order to get back to the original cmd.exe shell, think of it like popping cmd.exe off the stack for the duration of the nant script...
Edit#2: As per Brett's comment...just a thought - why not do it this way....
<exec>cmd /k title one </exec>
<exec>exit</exec>
Add the 'exit' command immediately after setting the title of the window...?
Hope this helps,
Best regards,
Tom.
You could use a cmd or batch file to run the nant script containing this:
title %1
%NANT_PATH%\nant.exe %1
This should work:
<exec>title Step One</exec>
<!-- Do some stuff -->
<exec>title Step Two</exec>
This uses a regular cmd.exe command.