【问题标题】:Unit test failing after moving functions into a class将函数移入类后单元测试失败
【发布时间】:2016-08-06 09:16:23
【问题描述】:

我正在尝试为类中的函数编写单元测试,但遇到了一些麻烦。在将导入器函数移入类之前,此测试有效。但是,现在我得到TypeError: grab_column_locations missing 1 required positional argument: 'sheet'。导入器函数本身可以正确解析sheet,并且在程序运行时可以正常工作,但在测试时不能正常工作。

TypeError 在 importer 函数中所指的行是:

columns = self.grab_column_locations(sheet)

失败的测试是:

from unittest import TestCase

from gtt import GTT


class TestGTT(TestCase):

    def test_importer(self):
        """
        Test import of valid xlsx file
        :return:
        """

        file_list = ['testData_1.xls']

        # Run Test 1
        importer_results = GTT.importer(GTT, file_list)
        assert importer_results[0] == True

因此,基本上,当从测试中运行时,importer 不会将sheet 传递到grab_column_locations。当我将这两个函数都移到一个类中时,这才开始发生。我知道我弄坏了一些东西,但是什么?

【问题讨论】:

  • 你的目录结构是什么样的?另外,grab_column_locations 函数是什么样的?

标签: python unit-testing


【解决方案1】:

错误信息是这样说的:

TypeError: grab_column_locations missing 1 required positional argument: 'sheet'

这听起来像函数签名是:

def grab_column_locations(self, sheet):

您不是从拥有此函数的类的实例调用它吗?

即如果函数属于Foo类:

class Foo:
    def grab_column_locations(self, sheet):
        ...

错误信息让我觉得你是这样调用函数的:

Foo.grab_column_locations(sheet)

当你真的应该调用它时:

foo = Foo()
foo.grab_column_locations(sheet)

或者,如果您不想将其绑定到 instance,则该函数可以定义为 class 方法:

class Foo:
    @classmethod
    def grab_column_locations(self, sheet):
        ...

那么你可以这样称呼它:

Foo.grab_column_locations(sheet)

但无论如何,这只是猜测,因为您没有提供太多细节。

【讨论】:

    猜你喜欢
    • 2015-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-12
    相关资源
    最近更新 更多