python nose from a script, gathers test classes fr

2019-07-23 17:10发布

问题:

How would I use nose from a python script to

  1. gather python files from a directory
  2. foreach file
    1. run all test classes found using passed parameters

Here's an example, given files

/run.py
/tests/TestClassA.py

and within TestClassA.py is the code

  class A():
     __init__(self, b):
          self._b = b
     test_run():
          print("%s",self._b)



To restate the need:
I want to call nose from run.py. I want nose (or some part of nose) to

  1. find class A in file TestClassA.py
  2. create an instance of A, named a, passing the string "foo" to A.__ init __ function
  3. call a.test_run()

What is the python nose code within run.py for this request?
If not python nose , would python unittests do any better?

回答1:

In run.py:

import nose
result = nose.run()

You select which tests to run by passing the run() call the appropriate arguments, see the usage options for nose. Nose will find TestClassA.py just fine as the filename starts with test. You just have to pass the root path of your project, generally.

You should probably read the nose docs about instantiating objects to use in your tests. If you really want to do it like you've written, you could write a unit test that creates an A object and runs the test, but that kind of defeats the purpose of using nose - Normally you test something that's not solely defined in the code defining the test.