0

I know how to set attribute for a class, but can't find how to set for a file..

flow = ['1','4','5','2']

def test_generator(test):
    def test_parser(self):
        print test
    return test_parser

class API_tests(unittest.TestCase):
        pass


for test in flow:
    test_name = 'test_%s' % test
    test = test_generator(test)
    setattr(API_tests, test_name, test)

this, will work.

I want to replace the API_tests on setattr() to be the file as object instead of the class, so that this file will be appended with the functions (test_generator X 4) I set them dynamically

my expected result as I run 'nosetests -v' on command line is it will show '4 tests passed'

this question can be in other works: how to get the current file as an object

Thanks

eligro
  • 785
  • 3
  • 13
  • 23
  • The name of the current file is in `__file__`. That is a string however. – aychedee Oct 21 '12 at 10:08
  • 2
    Is your intention to create X (4 in this case) tests that nosetest can run? If so, look into nosetest support for test generators. In a nutshell, write a generator that yields a callable and the args the callable requires. nose will run them all for you. – Rob Cowie Oct 21 '12 at 10:14
  • Here you can find how to set attributes in the current module (which I think is what you're actually asking): [How do I call setattr() on the current module?](http://stackoverflow.com/questions/2933470/how-do-i-call-setattr-on-the-current-module). – Pedro Romano Oct 21 '12 at 10:16

1 Answers1

0

Rather than dynamically creating test functions in the module namespace (as is your intention I think), use the nosetest support for test generators.

If nose detects a generator and that generator yields a callable and any args that callable requires, it will iterate it and run each test for you.

Your example could be rewritten as

def check_flow_value(val):
    # assert something about val
    assert True

def test_flows():
    flow = ['1','4','5','2']
    for val in flow:
        yield check_flow_value, val

Given this, nose will run 4 tests

Rob Cowie
  • 22,259
  • 6
  • 62
  • 56
  • response will be like: API_tests.test_generator.test_flows('1',) ... ok API_tests.test_generator.test_flows('4',) ... ok API_tests.test_generator.test_flows('5',) ... ok API_tests.test_generator.test_flows('2',) ... ok my problem with this way is that the 1,2,4,5 actually will be replaced with hugh dict of parameters. I just want to provide to output the test name I will generate, and it will show the name only, not the parameters.. possible? – eligro Oct 21 '12 at 10:32
  • If its the output you are worried about you can dynamically wrap your test functions so the **test** as seen by unittest or nosetest will be a very simple function with no args. E.g. with partial: `new_test_method = partial(create_generic_test, arg_name=arg)` – Hardbyte Oct 21 '12 at 11:12