简体   繁体   English

Python-使用unittest测试类方法

[英]Python - Testing class methods with unittest

I have a Scheduler class and a test written for __generate_potential_weeks using unittest 我有一个Scheduler类和一个使用unittest__generate_potential_weeks编写的测试

main.py 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 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)

When I try to test __generate_potential_weeks , I get the following error 当我尝试测试__generate_potential_weeks ,出现以下错误

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

Questions 问题

  • Why can't the test find __generate_potential_weeks 为什么测试找不到__generate_potential_weeks
  • How can I test __generate_potential_weeks ? 如何测试__generate_potential_weeks It has some complex logic I would like to test separately from Scheduler 它具有一些复杂的逻辑,我想与Scheduler分开进行测试

Double underscore has a special meaning within python. 双下划线在python中具有特殊含义。 The name will be mangled to avoid a conflicting name in a subclass. 该名称将被修改以避免子类中的名称冲突。

If that wasn't your intent, I'd encourage you to mark it with a single underscore. 如果这不是您的意图,我鼓励您在单个下划线处进行标记。 If it was, you can still access the function by using the mangled name. 如果是这样,您仍然可以使用变形的名称来访问该函数。 I think this will work for you: sch._Scheduler__generate_potential_weeks(4) 我认为这对您sch._Scheduler__generate_potential_weeks(4)sch._Scheduler__generate_potential_weeks(4)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM