views:

129

answers:

3

I was going through a few tests written in Java using JUnit and I could'nt help noticing the emphasis which is laid on checking the "type" of objects. This is something I have never seen in Python test-suites.

Java being statically-typed and Python being dynamically-typed, should'nt the reverse be the case?

+15  A: 

In dynamically-typed languages, developers often follow the duck typing principle -- "if it looks like a duck and walks like a duck, it is a duck". As long as the object does what all the tests require, does it really matter what kind of object it is? Duck typing says no.

Kaleb Brasee
Exactly what I was going to say. +1!
Santiago Lezica
+5  A: 

Python unit tests do check types. All the time. In fact, that's the only thing they are doing.

Python is duck-typed. Duck typing means that the type of an object is defined by its behavior. Unit tests test behavior. Ergo, they test types.

Jörg W Mittag
*"In fact, that's the* only *thing they are doing."* That's simply not true; they very often also test values. For example, if I were to test my `isqrt` function by `assertEqual(isqrt(9), 3)`, I'm not testing only that the return value is a number (or positive number, or whatever we want to call the return type), but rather a value.
Mike Graham
@Mike Graham: Yes, you are testing that the behavior of your `isqrt` function is that it computes the square root. Which, in a duck-typed language, *is* its type.
Jörg W Mittag
That's not a useful definition of "type".
Mike Graham
A: 

in addition to seconding what everyone is saying about duck typing here, I'd also like to point you in the direction of the types module:

http://docs.python.org/library/types.html

... whose collection of types correspond to many builtins and other commonly used types, so that you may easily explicitly assert for whatever type you want, in your unit tests.

fish2000