如果类通过名称存在于具有给定路径的文件中,则声明

问题描述 投票:0回答:1

在我正在研究的python项目中,我有一个包含代码和单元测试的文件结构(不能更改),我创建了一个单独的test / data文件夹,以按顺序保留单元测试所需的所有数据文件保持清洁。

为了使事情井井有条,我在测试/数据中复制了src中使用的相同结构,并为每个测试文件,其中的每个类以及其中的每个测试方法添加了一个文件夹级别。

最后,如果src

src
 | module_a
 | module_b
   | sub_module_c
     | some_test_file.py

并且some_test_file.py具有

class SomeTestClass(unittest.TestCase):
  def test_something(self):
    some_json_dict = get_json("some_json_dict.json")

然后test/data将具有

test/data
 | module_a
 | module_b
   | sub_module_c
     | some_test_file
       | some_test_class
         | test_something
           | some_json_dict.json

因为要确保维持这种结构(这是一个共享项目)可能并不容易,所以我正在创建一个单元测试,该单元测试断言test / data中的整个结构是否有效,即断言:

  • 文件src/module_b/sub_module_c/some_test_file.py存在
  • SomeTestClass存在于该文件中
  • 该类中存在方法test_something

我已经设法达到了第一点(在这里获得了很多赞赏的帮助),>

for directory, child_directories, child_files in walk(test_data_base_path):
    if not child_directories and not child_files:
        self.fail("Directory {} is empty".format(directory))
    # if we are in a "leaf" level
    if child_files:
        test_data_file_name = path.abspath(path.join(directory, pardir, pardir))
        test_file = path.join(code_base_path, path.relpath(test_data_file_name, test_data_base_path)) + ".py"
        self.assertTrue(path.exists(test_file))

        # TODO: also check if the class exists
        class_name = "..."
        # TODO: also check if the test exists
        test_name = "..."

但是我在主张其他两个要求时遇到了麻烦。

TL; DR

我需要一种方法,给定一个类名(str)和一个文件路径名(str),断言该类是否存在于该文件中;并给定方法名称(str)断言该方法是否存在于同一类中。

提前感谢!

[我正在研究的python项目中,我有一个包含代码和单元测试的文件结构(不能更改),我创建了一个单独的test / data文件夹来保存...所需的所有数据文件。]

python unit-testing
1个回答
0
投票

经过一番调查,我设法得到了所需的东西。这是实现它的代码:

# assert the class exists
module = importlib.import_module(package)
try:
    the_class = getattr(module, class_name)
except AttributeError:
    self.fail("...")

# assert the test exists
if test_name not in dir(the_class):
    self.fail("...")
© www.soinside.com 2019 - 2024. All rights reserved.