0

I'm currently using nose to perform some tests, and when using generators with nose+xunit output you need to set the current function's __name__ attribute to properly control the name of the test in the xunit output (see here for example).

Since I don't want to hard-code the name of the function each time like this:

def my_function():
  for foo in bar:
    fn = lambda: some_generated_test(foo)
    fn.description = foo.get('name')
    my_function.__name__ = foo.get('name')
    yield fn

How can I programatically reference the function and set __name__?

I had tried with sys._getframe() which yields various properties about the current function (name etc), which I tried to use with setattr(*something*, "__name__", some_test_name), but that didn't work as I couldn't seem to work out which part of sys._getframe() references the function.

Community
  • 1
  • 1
AndyC
  • 2,513
  • 3
  • 17
  • 17
  • Why not just `def some_test_name():`? – user2357112 Feb 02 '17 at 00:47
  • do that outside of function, or write decorator that does that. – YOU Feb 02 '17 at 00:48
  • also I think inspect module could help you get name of the function. – YOU Feb 02 '17 at 00:58
  • @user2357112 the function contains generators, but nose+xunit use the function name as the test name which isn't accurate when you want the generated test name to be used. – AndyC Feb 02 '17 at 01:11
  • What's wrong with setting `function.__name__`? How do you want to reference the function? It's not really clear what you want to do here. – a_guest Feb 02 '17 at 01:46

1 Answers1

0

Finally found a solution via SO: https://stackoverflow.com/a/4506081/1808861

A lot more complicated than I expected, but I can now:

def my_function():
  for foo in bar:
    fn = lambda: some_generated_test(foo)
    fn.description = foo.get('name')
    setattr(get_func(), "__name__", foo.get('name'))
    yield fn

The xunit output then contains the generator's data name entry.

Community
  • 1
  • 1
AndyC
  • 2,513
  • 3
  • 17
  • 17