[python-nl] testing

Konrad Delong konryd at gmail.com
Fri Apr 23 12:11:40 CEST 2010

On 23 April 2010 11:56, C.T. Matsumoto <c.t.matsumoto at gmail.com> wrote:
> Hello all,
> Does anyone know a good way to test function objects? It's easy enough to
> test class attributes, but for some reason I'm finding it difficult to test
> if a function has the right 'attributes'.
> I'm using unittest and nosetests.
> Sample function:
> def foo():
>    x = 3
>    y = 4
> This example is super simple but lets pretend that x and y were derived from
> some more complicated code that was done inside the function. The best way I
> can come up with is moving the complicated code into another function that
> returns the derived value and then test the return value, but if i want to
> keep the code in the function how can I get to those 'attribute' values to
> test?

x and y in your example are not attributes, but variables. They
disappear right after the function returns. There is no way to access
their values from outside. The only thing you can test for functions
is its return value (for a given set of arguments). If x and y are in
fact generated by a complicated expression you should extract those
expressions into external function.

def foo(arg1, arg2):
  x = <huge complicated expression that depends on values of arg1 and arg2>
  return x + 7

def huge_complicated_expression(arg1, arg2):
  return <huge complicated expression that depends on values of arg1 and arg2>

def foo(arg1, arg2):
  x = huge_complicated_expression(arg1, arg2)
  return x + 7


More information about the Python-nl mailing list