自动化学生测试运行

时间:2016-10-15 16:08:14

标签: python

我有一些文件夹结构用于某些任务,它们是这样的:

- student_id1/answers.py
- student_id2/answers.py
- student_id3/answers.py
- student_id4/answers.py
- ...

我有一个主文件:run_tests.py

from student_id1.answers import run_test as test1
from student_id2.answers import run_test as test2
...


try:
    test1()
    print("student_id1: OK")
except Exception as ee:
    print("Error for student_id1")

try:
    test2()
    print("student_id2: OK")
except Exception as ee:
    print("Error for student_id2")
...

每个新学生都可以添加更多文件夹。我想用一个命令调用所有测试,但不想为每个新学生添加这么多行。

如何自动执行此操作?

1 个答案:

答案 0 :(得分:2)

您可以使用importlib模块:https://docs.python.org/3/library/importlib.html

import os
import importlib

for student_dir in os.listdir():
    if os.path.isdir(student_dir):
        # here you may add an additional check for not desired folders like 'lib', 'settings', etc
        if not os.path.exists(os.path.join(student_dir, 'answers.py')):
            print("Error: file answers.py is not found in %s" % (student_dir))
            continue
        student_module = importlib.import_module("%s.answers" % student_dir)
        try:
            student_module.run_test()
            print("%s: OK" % student_dir)
        except Exception as ee:
            print("Error for %s" % student_dir)