自动化学生测试运行

2024-05-06 03:19:46 发布

您现在位置: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")
...

随着每个新学生的加入,可以有更多的文件夹。我想用一个命令调用所有测试,但不想为每个新学员添加太多行

如何实现自动化


Tags: runfrompytestimport文件夹asstudent
1条回答
网友
1楼 · 发布于 2024-05-06 03:19:46

您可以使用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)

相关问题 更多 >