Common Language Runtime detected an invalid program error in unit testing - clr

I have the following code
this.SafeUpdate(rate, Guid.Parse(import.myGuid), c => c.myGuid);
SafeUpdate basically takes the parsed guid value and applies it to the myGuid property on the rate object. This works fine from my front end, but throws the "CLR detected..." error when run in a unit test. What's odd is the same statement for DateTime.Parse and int.Parse works fine. It just fails for Guid and decimals. I don't believe the error is with the parsing (it has the correct parsed value when extracted into a separate variable). I don't believe it's the mocking either as the statement works fine for all other types other than guid and decimal. Any ideas?

We experienced a similar error yesterday on our build server. Our exception was thrown by the ReadObject() method of a DataContractSerializer.
System.InvalidProgramException: Common Language Runtime detected an invalid program.
at System.Xml.EncodingStreamWrapper..ctor(Stream stream, Encoding encoding)
at System.Xml.XmlUTF8TextReader.SetInput(Stream stream, Encoding encoding, XmlDictionaryReaderQuotas quotas, OnXmlDictionaryReaderClose onClose)
at System.Xml.XmlDictionaryReader.CreateTextReader(Stream stream, Encoding encoding, XmlDictionaryReaderQuotas quotas, OnXmlDictionaryReaderClose onClose)
at System.Xml.XmlDictionaryReader.CreateTextReader(Stream stream, XmlDictionaryReaderQuotas quotas)
at System.Runtime.Serialization.XmlObjectSerializer.ReadObject(Stream stream)
We've written a console app that does just this one thing. It runs without error, but fails in a simple unit test. We are using Gallio/MbUnit 3.4.11.0 for our test framework with a target of .net 4.0.
using System;
using System.IO;
using System.Runtime.Serialization;
using MbUnit.Framework;
namespace TestApp
{
[TestFixture]
class Program
{
static void Main()
{
FooBar();
Console.ReadKey();
}
public static void FooBar()
{
var type = typeof(string);
var foo = "foo";
using (var stream = new MemoryStream())
{
var serializer = new DataContractSerializer(type);
serializer.WriteObject(stream, foo);
stream.Seek(0, SeekOrigin.Begin);
var deserializer = new DataContractSerializer(type);
var bar = deserializer.ReadObject(stream);
Console.WriteLine(bar);
}
}
[Test]
public void Test()
{
FooBar();
}
}
}
The application runs fine, but the test throws. Strangely, this test passes on my dev box but fails on our build server as well as the dev box of a coworker. Clearly, there is something different about my dev box that allows the test to pass, but I have not located that difference yet.
Update 1
The version of System.dll on my dev box is 4.0.30319.296 but on the build server and the dev box of my coworker it is 4.0.30319.1001. System.Xml.dll and System.Runtime.Serialization.dll are identical at 4.0.30319.1, however.
Update 2
A quick google search for "4.0.30319.1001" returns this security update, http://support.microsoft.com/kb/2742595, which was applied to both our build server and the dev box of my coworker, but not my dev box. I uninstalled the update on the build server, rebooted, and the issue went away! I guess Microsoft doesn't have a unit test for this one yet. :-)

Related

Testing the compilation of cshtml files using RazorEngine

I want to unit test my cshtml files to ensure they compile successfully as recently I've had some issues where at run time there were failures due to the views expecting properties that weren't present. I am trying to use RazorEngine to check this, and here is my attempt at a unit test:
public void LayoutCshtml_AnyCase_ViewCompilesSuccessfully()
{
var model = new Model();
var templateName = File.ReadAllText("PathToView/_Layout.cshtml");
var result = Engine.Razor.RunCompile(templateName, "key", typeof(Model), model);
//Assertion will go here
}
I will add the assertion later but at the moment just want the view to compile. The templateName correctly picks up the right .cshtml but the result fails because of error:
The predefined type
'System.Runtime.CompilerServices.ExtensionAttribute' is defined in
multiple assemblies in the global alias;
Is anyone familiar with using RazorEngine to test please?

sun.org.mozilla.javascript.internal.NativeObject vs org.mozilla.javascript.NativeObject

I am really stuck at this now..
Essentially I have a Java Map, which I would like to pass it to a Javascript Code, so that in my JS code I can use dot notation to refer the keys in this Map. ( I know I can serialize the map into JSON and deserialize it back and pass it into JS, but I don't like that ) I have this piece of the unit code
#Test
public void mapToJsTest() throws Exception{
Map m = Maps.newHashMap();
m.put("name", "john");
NativeObject nobj = new NativeObject();
for (Object k : m.keySet()) {
nobj.defineProperty((String)k, m.get(k), NativeObject.READONLY);
}
engine.eval("function test(obj){ return obj.name;}");
Object obj = ((Invocable)engine).invokeFunction("test", nobj);
Assert.assertEquals(obj, "john");
}
If I am using
org.mozilla.javascript.NativeObject
then the test won't pass,
However, if I am using
sun.org.mozilla.javascript.internal.NativeObject
then the test will pass.
However, we all know that we shouldn't rely on these internal classes, and when I deploy my code on the server side, trying to access
this internal class will cause other problems.
So how do I achieve this with just "org.mozilla.javascript.NativeObject"?
BTW, I am using Rhino
ScriptEngine engine = new ScriptEngineManager().getEngineByName("JavaScript");
For Nashorn, it is much easier, I can pass Map directly into JS code.
Unless you're stuck with older JDK (jdk7 or below) for some reason, I'd recommend moving to jdk8u. You've ES 5.1 compliant JS implementation (Nashorn) that is bundled with JDK8+.

Switching from Rhino to Nashorn

I have a Java 7 project which makes a lot of use of Javascript for scripting various features. Until now I was using Rhino as script engine. I would now like to move to Java 8, which also means that I will replace Rhino by Nashorn.
How compatible is Nashorn to Rhino? Can I use it as a drop-in replacement, or can I expect that some of my scripts will not work anymore and will need to be ported to the new engine? Are there any commonly-used features of Rhino which are not supported by Nashorn?
One problem is that Nashorn can no longer by default import whole Java packages into the global scope by using importPackage(com.organization.project.package);
There is, however, a simple workaround: By adding this line to your script, you can enable the old behavior of Rhino:
load("nashorn:mozilla_compat.js");
Another problem I ran into is that certain type-conversions when passing data between java and javascript work differently. For example, the object which arrives when you pass a Javascript array to Java can no longer be cast to List, but it can be cast to a Map<String, Object>. As a workaround you can convert the Javascript array to a Java List in the Javascript code using Java.to(array, Java.type("java.util.List"))
To use the importClass method on JDK 8, we need to add the following command:
load("nashorn:mozilla_compat.js");
However, this change affect the execution on JDK 7 (JDK does not gives support to load method).
To maintain the compatibility for both SDKs, I solved this problem adding try/catch clause:
try{
load("nashorn:mozilla_compat.js");
}catch(e){
}
Nashorn can not access an inner class when that inner class is declared private, which Rhino was able to do:
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public class Test {
public static void main(String[] args) {
Test test = new Test();
test.run();
}
public void run() {
ScriptEngineManager factory = new ScriptEngineManager();
ScriptEngine engine = factory.getEngineByName("JavaScript");
Inner inner = new Inner();
engine.put("inner", inner);
try {
engine.eval("function run(inner){inner.foo(\"test\");} run(inner);");
} catch (ScriptException e) {
e.printStackTrace();
}
}
private class Inner {
public void foo(String msg) {
System.out.println(msg);
}
}
}
Under Java8 this code throws following exception:
javax.script.ScriptException: TypeError: kz.test.Test$Inner#117cd4b has no such function "foo" in <eval> at line number 1
at jdk.nashorn.api.scripting.NashornScriptEngine.throwAsScriptException(NashornScriptEngine.java:564)
at jdk.nashorn.api.scripting.NashornScriptEngine.evalImpl(NashornScriptEngine.java:548)
I noticed that Rhino didn't have a problem with a function called 'in()' (although 'in' is a reserved JavaScript keyword).
Nashorn however raise an error.
Nashorn cannot call static methods on instances! Rhino did this, therefore we had to backport Rhino to Java 8 (Here's a short summary: http://andreas.haufler.info/2015/04/using-rhino-with-java-8.html)
Nashorn on Java8 does not support AST. So if you have Java code that inspects the JS source tree using Rhino's AST mechanism , you may have to rewrite it (using regex maybe) once you port your code to use Nashorn.
I am talking about this API https://mozilla.github.io/rhino/javadoc/org/mozilla/javascript/ast/AstNode.html
Nashorn on Java9 supports AST though.
One feature that is in Rhino and not Nashorn: exposing static members through instances.
From http://nashorn-dev.openjdk.java.narkive.com/n0jtdHc9/bug-report-can-t-call-static-methods-on-a-java-class-instance : "
My conviction is that exposing static members through instances is a
sloppy mashing together of otherwise separate namespaces, hence I
chose not to enable it.
I think this is deeply wrong. As long as we have to use two different constructs to access the same java object and use package declarations unnecessarily in javascript, code becomes harder to read and write because cognitive load increases. I will rather stick to Rhino then.
I have not found a workaround for this obvious "design bug" yet.

AssertionError instead of failure

i have developed a test package using SWTbot and ant to build it , when i run it, it finds that there is a failure however in the test report it shows as an error instead of failure:
my code is :
public static void Check_TargetPack(final SWTWorkbenchBot bot,String configuration,
String targetpack) {
boolean exist=false;
String[] h=bot.comboBoxWithLabel("TargetPack").items();
int i=0;
for (i=0;i<h.length;i++){
if (h[i]==targetpack)exist=true;
assertTrue("target pack"+targetpack+" doesn't exist in targetpack list",exist);
};
bot.sleep(2000);
bot.button("Close").click();
}
and the result is
I can see one problem in your code.
You are matching Strings with "==" operator.
You should use following instead
h[i].equals(targetpack)

QTP 11 Extensibility developing (.NET sdk) - calling Record() on the recorder object fails

As far as I looked, there's no answered question about QTP's Ext. sdk on stackoverflow (and almost anywhere else on the net; there isn't even a appropriated tag for it...), so I'm aware it's unlikely I get my problem solved by asking , but whatever, it worth trying.
Anyway, before I lose the attention of anyone who never heard or used the Ext. sdk, maybe I will have more luck asking you to help me figure out how to locate the error log file QTP produces at run-time. I know such a file exists in the new UFT 11.5 version, but I couldn't locate it in QTP 10 or 11 (For the record, I don't talk about QTP's Log Tracking feature, but about the "meta" error log of errors/exceptions produced by QTP itself).
Now for the question:
I'm developing an extension for QTP to support native record and run tests on my application.
I'm currently able to import an object repository, and write test steps using The COM object testing agent I developed.
Problem started when I was trying to implement the IRecordable interface; I'm getting the IRecorder object from qtp, and even able to use it as ISuppressor object to exclude redundant steps from being recorded, but all my attempts to record a step (that is, to add new recorded objects to the repository, and add steps to the test) simply failed.
This is the code that I'm using:
public class MyTestingAgent :
AutInterface.ITestable,
AutInterface.IRecordable
{
QTPInterface.IRecorder recorder;
...
public void AutInterface.IRecordable.BeginRecording(object recorder)
{
IRecordSuppressor recordSuppressor = recorder as IRecordSuppressor;
recordSuppressor.Suppress(MyTestingAgentId,
"<Suppress><Item type=\"HWND\" value=\"[#HWND]\" /></Suppress>".Replace("[#HWND]", getMyAppHWND().ToString()));
this.recorder = recorder as QTPInterface.IRecorder;
...
}
public void recordNewObjStep(string parentName, string objName, string method, Object[] arguments)
{
object[] objectHyrarchy = new object[] { findObjectId(objName), findObjectId(parentName) };
string externalParent = null;
string appDescriptionXml = getDescriptionXml(parentName, objName);
try
{
recorder.Record(MyTestingAgentId, objectHyrarchy , appDescriptionXml, externalParent, method, arguments);
Trace.TraceInformation("Record successfully done.");
}
catch (Exception e)
{
Trace.TraceError("TEAAgent.recordSTElement: " + e.ToString());
}
}
...
}
I'm pretty sure all the arguments I send with the call to Record() are accurate. getDescriptionXml() and findObjectId() are used in different cases in the code, and works fine, the method name and argument are correct.
The annoying thing is that the call to Record doesn't even throw exception, and I get "Record successfully done." in the trace log. Needless to say no new object is created in the repository, and no step is added to the test.
As I can't debug QTP, I'm pretty much in the dark with what I'm doing wrong. That's why I'm asking for help with finding QTP's log file, or any other approach that might shed some light on the subject.
For QTP 11 you can turn on the logs by going to QTP's bin directory and running ClientLogs.exe.
Specifically for TEA extensibility do the following.
select the QTP node from the list on the left
find the LogCatPackTEA from the Available Categories list
Click the > button to move it to Selected Categories
Change TEAs level to Debug2 by selecting the category and changing the level
Click OK and run QTP
The logs will show up as QTP.log in the diretory specified in Path:
I'm curious on what the problem you're facing is, please update if you find the cause.

Resources