assertEquals throws a NullPointerException, but equals method does not - junit

I have two list objects and want to check that the first items of each are equal. However, I get a NullPointerException at this line:
assertEquals(instance.getPlane(0), planes.get(0));
This is the entire stack trace:
Testcase: testGetPlane(mypackage.PlaneTest): Caused an ERROR
null
java.lang.NullPointerException
at mypackage.PlaneTest.testGetPlane(PlaneTest.java:60)
(Line 60 is the assertion.)
Neither of those objects are null. I'm having a separate issue getting the debugger to work, so instead I added these printouts to my test case:
System.err.println("equals? " + instance.getPlane(0).equals(planes.get(0)));
System.err.println("equals? " + planes.get(0).equals(instance.getPlane(0)));
However, those lines executed without throwing any errors!
I've cleaned and built the project and restarted Netbeans, but still have this issue.
JUnit just calls expected.equals(actual), which should be exactly the same thing as my printouts that aren't throwing the error, right? Why would assertEquals throw a NullPointerException, but equals on the same objects would not?

(I was about to post the question alone when I discovered the fix, but since it was a pain I'm posting it anyways in hopes this may help someone else. I did not find any other questions which had this solution.)
The error is in fact caused by JUnit, when it tries to compose an error message.
In the format function, there are the lines:
String expectedString = String.valueOf(expected);
String actualString = String.valueOf(actual);
if (expectedString.equals(actualString)) { ... }
String.valueOf(Object obj) returns obj.toString() if obj is not null.
My object's toString method simply returned a "name" field, which was never set inside the test. So, the object was not null, but the function returned null. This caused the NullPointerException when JUnit tried to call expectedString.equals. Ensuring that toString never returns null fixed the error.

Related

catching classes that do not inherit from BaseException is not allowed

I'm making a custom plugin to query a database for user info to aide customer support. My backend is slack.
Everytime I start the bot command I'm greeted with:
Computer says nooo. See logs for details:
catching classes that do not inherit from BaseException is not allowed
I'm not sure if this is warning me that I'm attempting to catch an exception that isn't a BaseClass in my code or if an unknown exception was raised and caught elsewhere outside of my plugin.
To debug I tried:
try:
do_the_thing()
except (TypeError, ValueError) as e:
return('Something went wrong.')
I also tried:
try:
do_the_thing()
except Exception as e:
return('Something went wrong.')
And I still get the errbot admonition. Note that the command still runs and does the right thing where there is no exception raised by do_the_thing().
It means that:
Somewhere in your code you have an except ... statement where the exception ... (or one of the exceptions in the sequence ...) is not a subclass of BaseException, and
An exception is being thrown that is caught by that except ... statement.
The TypeError can be raised only when an exception is actually thrown because the names you give to except ... must be evaluated for their current values at that time; just because TypeError referenced a particular class at one point in the program's execution doesn't mean it won't be changed later to reference another object (though that would be admittedly perverse).
The Python interpreter should be giving you a full traceback of the exception; the first thing you need to do is find this. It could be occurring in one of two situations. (This is for single-threaded programs; I'm assuming your program is not multithreaded.)
During the execution of your program, in which case the program will be terminated by the exception, or
During finalization of objects (in their __del__(self) functions) in which case the error will be printed to stderr.
In both cases there should be a stack trace, not just the error message; I've confirmed that at least on Python ≥3.4 a stack trace is printed out for case 2.
You then need to follow this stack trace to see where the problem lies. Remember that the names you give to except ... are variables (even things like TypeError) that can be reassigned, so that you could conceivably be dealing with a (perverse) situation like:
TypeError = False
try:
...
except TypeError:
...
But more likely it will be something obvious such as:
class MyException: # Doesn't inherit from Exception
...
try:
...
except MyException:
...
There is one special case you need to be aware of: if you are seeing messages to stderr (case "2. During finalization," above) printed out as your program exits that means that the exception was thrown during cleanup as the interpreter shuts down, where random variables throughout the program may have already been set to None as part of the cleanup process. But in this case your program should still exit successfully.

2to3 bug: tuple index out of range, fix_raise

I have found what looks like a not tested case to me. When trying to convert following code with 2to3:
def test(arg):
raise()
The execution stops ungracefully with no indication why, nor what file caused the problem, this is very annoying if you are trying to convert a whole folder of python 2 scripts. The following is thrown:
...
exc= exc.children[1].children[0].clone()
IndexError: tuple out of range
I am expecting to obtain a BadInput exception. Clearly, given the source code just above, it is expecting raise("something") and since there is no check that "children" inside the tuple of raise () is even present, this causes error.
Please correct me if I am wrong, of course raise() is incorrect, but this should not crash the execution, likewise the following:
def test(arg):
print 1.method()
Throws BadInput exception with a clear indication what happened.

Throwing a NPE at the start of method for error checking

So im preparing for interviews and in one of Gayle Laakmans career Cup videos a guy is writing a simple method that takes in an array and does something with it. She mentions his lack of error checking so he adds in this line like so:
public int max(int[] array) {
if (array == null)
throw new NullPointerException();
//method body
}
Is it correct to manually throw a NPE exception like this, this exception will get thrown anyway in the method body as it will use the array reference at some point.
A possible advantage to this i can see is that it separates input invalidation from the method logic being invalid and somehow creating a null reference. Otherwise it is a little confusing and maybe IllegalArgumentException would work better?
There's nothing wrong with throwing NullPointerException as soon as you enter the method instead of waiting to detect it after some processing has already been done. If the method is going to fail, it might as well fail fast.
Joshua Bloch's Effective Java recommends throwing NullPointerException over IllegalArgumentException in this situation (Item 60: Favor the use of standard exceptions).
If a caller passes null in some parameter for which null values are prohibited, convention dictates that NullPointerException be thrown rather than IllegalArgumentException.
IllegalArgumentException should be thrown when an illegal non-null value is passed in.
Also have a look at java's own utility class java.util.Objects:
public static <T> T requireNonNull(T obj,
String message)
Checks that the specified object reference is not null and throws a customized NullPointerException if it is. This method is designed primarily for doing parameter validation in methods and constructors with multiple parameters, as demonstrated below:
public Foo(Bar bar, Baz baz) {
this.bar = Objects.requireNonNull(bar, "bar must not be null");
this.baz = Objects.requireNonNull(baz, "baz must not be null");
}
Type Parameters:
T - the type of the reference
Parameters:
obj - the object reference to check for nullity
message - detail message to be used in the event that a NullPointerException is thrown
Returns:
obj if not null
Throws:
NullPointerException - if obj is null
from https://docs.oracle.com/javase/7/docs/api/java/util/Objects.html
Conclusion
Whether or not you use this utility class is another question, but it definitely shows, that the team behind the Java language intended to use NullPointerException for these purposes.

BeepBeep and ErlyDB integration issue

Further to my adventures with Erlang and ErlyDB. I am attempting to get ErlyDB working with BeepBeep
My ErlyDB setup works correctly when run outside of the BeepBeep environment (see Debugging ErlyDB and MySQL). I have basically take the working code and attempted to get it running inside BeepBeep.
I have the following code in my controller:
handle_request("index",[]) ->
erlydb:start(mysql,Database),
erlydb:code_gen(["thing.erl"],mysql),
NewThing = thing:new_with([{name, "name"},{value, "value"}]),
thing:save(NewThing),
{render,"home/index.html",[{data,"Hello World!"}]};
When I call the URL, the response outputs "Server Error".
There is no other error or exception information reported.
I have tried wrapping the call in try/catch to see if there is an underlying error - there is definitely an exception at the call to thing:new_with(), but no further information is available.
The stacktrace reports:
{thing,new,[["name","value"]]}
{home_controller,create,1}
{home_controller,handle_request,3}
{beepbeep,process_request,4}
{test_web,loop,1}
{mochiweb_http,headers,4}
{proc_lib,init_p_do_apply,3}
Use pattern matching to assert that things work up to the call to thing:new/1:
ok = erlydb:start(mysql,Database),
ok = erlydb:code_gen(["thing.erl"],mysql),
You include only the stack trace, look at the exception message as well. I suspect that the error is that you get an 'undef' exception. But check that it is so. The first line in the stack trace indicates that it is a problem with calling thing:new/1 with ["name", "value"] as argument.
It is slightly odd that you show one clause of handle_request that is not calling home_controller:create/1 as per {home_controller,create,1} in the stack-trace. What do the other clauses in your handle_request/2 function look like?

flex3 type casting

Does anyone know the real difference between the two ways of type casting in Flex 3?
var myObject1:MyObject = variable as MyObject;
var myObject2:MyObject = MyObject(variable);
I prefer to use the second method because it will throw an Error when type cast fails, whereas the first method will just return null. But are there any other differences? Perhaps any advantages to using the first method?
The second type of casting has different behaviour for top level(http://livedocs.adobe.com/flex/2/langref/) types, e.g. Array(obj) does not cast in the straightforward way you describe; it creates a new Array if possible from obj, even if obj is an Array.
I'm sure the times this would cause unexpected behaviour would be rare but I always use "as" for this reason. It means if I do
int(str)
I know it's a cast in the "attempt to convert" sense of the word not in the "I promise it is" sense.
ref: got some confirmation on this from http://raghuonflex.wordpress.com/2007/07/27/casting-vs-the-as-operator/
The as method returns null if cast fails.
The () method throws and error if the cast fails.
If the value of variable is not compatible with MyObject, myObject1 will contain null and you will be surprised by a null pointer error (1009 : cannot access a property or method of a null object reference.) somewhere later in the program when you try to access it. Where as if you are casting using the MyObject(variable) syntax, you will get a type coercion error (1034 : Type Coercion failed: cannot convert _ to _) at the same line itself - which is more helpful than getting a 1009 somewhere later and wondering what went wrong.
I think I read somewhere on this site that as is slighty faster than (), but I can't find the question again.
Beside that this question have been asked many times, you will find an more in-depth answer here.
I recently discovered the very useful [] tag when searching on StackOverflow, it allows to only search in questions tagged with the specified tag(s). So you could do a search like [actionscript-3] as vs cast. There are more search tips here: https://stackoverflow.com/search.
And no; the irony in that I can not find the question about performance and write about how to search is not lost on me ;)
I think as returns back the base class and not null when the casting fails and () throws an error.