0

I'm doing a simple script to run and test my code. How can i import dinamically and run my test classes?

4
  • I'm not sure what you're asking here. If you've got a solution, then you can answer it yourself by posting it first as a question. Commented Jul 28, 2015 at 16:42
  • Welcome to SO! I'm sorry, but I don't understand your question. Can you clarify? What are the expected results? What are you seeing? Commented Jul 28, 2015 at 16:43
  • Sorry @AIG. I hope I have clarified the idea. Commented Jul 28, 2015 at 16:52
  • Did you read the documentation? Commented Jul 29, 2015 at 11:59

3 Answers 3

1

This is the solution that I found to import and dynamically run my test classes.

import glob import os import imp import unittest def execute_all_tests(tests_folder): test_file_strings = glob.glob(os.path.join(tests_folder, 'test_*.py')) suites = [] for test in test_file_strings: mod_name, file_ext = os.path.splitext(os.path.split(test)[-1]) py_mod = imp.load_source(mod_name, test) suites.append(unittest.defaultTestLoader.loadTestsFromModule(py_mod)) text_runner = unittest.TextTestRunner().run(unittest.TestSuite(suites)) 
Sign up to request clarification or add additional context in comments.

1 Comment

You don't need to do this as it is reinventing what is already available.
0

Install pytest, and run your tests with a command like:

py.test src 

That's it. Py.test will load all test_*.py files, find all def test_* calls inside them, and run each one for you.

The board is having trouble answering your question because it's in "why is water wet?" territory; all test rigs come with runners that automatically do what your code snip does, so you only need read the tutorial for one to get started.

And major props for writing auto tests at all; they put you above 75% of all programmers.

Comments

0

This solution is too simple and perform what i want.

import unittest def execute_all_tests(tests_folder): suites = unittest.TestLoader().discover(tests_folder) text_runner = unittest.TextTestRunner().run(suites) 

1 Comment

Note to community - the incorrect answer is upvoted, here. Yes, it's the close second, but it's not DRY, bc all these Python auto-test rigs have automated runners. Only use this code if you need to screw with the default runner's highest-level behaviors; I can't think of a reason.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.