Python - 使用unittest测试类方法

标签 python python-unittest

我有一个 Scheduler 类和一个使用 unittest__generate_pottial_weeks 编写的测试。

main.py

class Scheduler:
    def __init__(self, num_teams, num_weeks):
        self.potential_weeks = self.__generate_potential_weeks(num_teams)
        # Other stuff

    def __generate_potential_weeks(self, num_teams):
        # Does some things

test_scheduler.py

import unittest
from main import Scheduler

class SchedulerTestCase(unittest.TestCase):
    def test_generate_weeks(self):
        sch = Scheduler(4, 14)
        weeks = sch.__generate_potential_weeks(4)

当我尝试测试 __generate_pottial_weeks 时,出现以下错误

AttributeError: 'Scheduler' object has no attribute '_SchedulerTestCase__generate_potential_weeks'

问题

  • 为什么测试找不到__generate_pottial_weeks
  • 如何测试__generate_pottial_weeks?它有一些复杂的逻辑,我想与 Scheduler
  • 分开测试

最佳答案

双下划线在Python中有特殊的含义。该名称将被破坏以避免子类中的名称冲突。

如果这不是您的意图,我建议您用一个下划线对其进行标记。如果是,您仍然可以使用损坏的名称来访问该函数。我认为这对你有用:sch._Scheduler__generate_pottial_weeks(4)

关于Python - 使用unittest测试类方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54808092/

相关文章:

python - 使用 Python 更新 MongoDB 集合

python - Flask:使用 unittest 进行测试 - 如何从响应中获取 .post json

Python单元测试: How to assert the existence of a file or folder and print the path on failure?

python - len 函数未按预期运行

python - unittest.main() 导致 Spyder 中的 python 解释器崩溃

python - 如何使用 pandas 中的这个 "|"符号转换数据以用于推荐系统

python - 重新编号数组中元素的有效方法

python - 防止系统范围和 virtualenv ipython 使用同一目录进行配置

python - 如何将文本文件作为字典导入python

Python unittest 不识别测试