【问题标题】:Is this unit test correct for what I am trying to achieve?这个单元测试是否适合我想要实现的目标?
【发布时间】:2022-01-11 20:21:48
【问题描述】:

我的函数中定义了一个列表 CountryList[],我想检查它 不是空的。我将其初始化为空,但稍后在函数中将数据放入其中。 这是我输入的单元测试。

 def assertEmpty(self, CountryList):
      self.assertFalse(CountryList)

 def assertNotEmpty(self, CountryList):
      self.assertTrue(CountryList)

这是我程序中的方法。

def onCountry(self, doc_id):
        if(doc_id==None):
            return

        output_list = self.findBySubjectDocId(doc_id)

        country_list=[]
        for x in output_list:
            country_id=x["visitor_country"]
            if(SHOW_FULL_NAMES):
                country_id=pc.country_alpha2_to_country_name(country_id)
            country_list.append(country_id)

        ts=pd.Series(country_list).value_counts().plot(kind='bar',color='purple')
        plt.xticks(rotation='horizontal')
        plt.xlabel('Country')
        plt.ylabel('Number of Viewers')
        plt.title("Viewers based on Country")
        ts.plot()
        plt.show()

        print("Countries of Visitors:")
        x = []
        y = []
        for k,v in Counter(country_list).items():
            x.append(k)
            y.append(v)
            print(k,"-",v)

您是否建议我以其他方式测试此代码?或者上述测试是否可以接受?

【问题讨论】:

  • 你在哪里创建这个CountryList?它是在测试中以某种方式创建的还是在您的代码中创建的?你的 assertEmptyassertNotEmpty 函数真的是全局的还是属于一个类?
  • @Code-Apprentice CountryList 位于名为 program 的 .py 文件中,assertEmpty 和 asertNotEmpty 位于另一个 Test_Browser.py 文件中
  • edit你的代码解释文件结构。有关创建示例代码 sn-p 的更多提示,请阅读minimal reproducible example

标签: python unit-testing testing pycharm histogram


【解决方案1】:

这里有几个建议:

  1. 要正确使用 Python 的 unittest 包,您需要创建一个扩展 unittest.TestCase 的类。

  2. 将您的测试方法命名为test_* 而不是assert*

  3. 测试只能接受一个参数self

  4. 您可以定义一个setUp() 方法,该方法在每个test_* 方法之前运行。使用它来创建所有测试通用的数据。

  5. 测试是代码,就像任何其他代码一样,遵循所有相同的规则。

  6. 首先用文字描述您要测试的场景。通常这是“当我用参数 P 调用函数 F 时,结果将是 R”的形式。然后编写测试来复制这个特定场景。

【讨论】:

  • 感谢您的回复,但我对在这里实际需要测试的内容感到困惑,因为此方法用于绘制直方图。我想调用函数 onCountry(self, doc_id) 通过传递一个文档 id 代替 doc_ id 但我不知道如何检查它是否根据数据绘制直方图。
  • @abc 这是家庭作业吗?我的意思是测试的要求从何而来?正如我在第 6 步中解释的那样,单元测试应该测试函数的行为。通过行为,我的意思是测试应该清楚地表明对于某些输入,该函数会给出正确的输出。也许您需要将 onCountry() 函数拆分为更小的辅助函数。然后你可以单独测试每一个。
【解决方案2】:

由于country_list 是一个不返回的局部变量,因此您的单元测试无法直接检查它;您的测试助手看起来不错,但您似乎没有任何使用它们的实际测试,因为代码的编写方式难以测试。

使测试更容易的一种方法是将函数重构为如下两部分:

def build_country_list(self, doc_id):
    output_list = self.findBySubjectDocId(doc_id)

    country_list=[]
    for x in output_list:
        country_id=x["visitor_country"]
        if(SHOW_FULL_NAMES):
            country_id=pc.country_alpha2_to_country_name(country_id)
        country_list.append(country_id)
    return country_list

def onCountry(self, doc_id):
    if doc_id is None:
        return
    country_list = self.build_country_list(doc_id)
        
    ts=pd.Series(country_list).value_counts().plot(kind='bar',color='purple')
    plt.xticks(rotation='horizontal')
    plt.xlabel('Country')
    plt.ylabel('Number of Viewers')
    plt.title("Viewers based on Country")
    ts.plot()
    plt.show()

    print("Countries of Visitors:")
    x = []
    y = []
    for k,v in Counter(country_list).items():
        x.append(k)
        y.append(v)
        print(k,"-",v)

现在您可以为build_country_list 编写一个单元测试,以验证您构建列表的逻辑是否正确,与同样绘制和打印数据的onCountry 逻辑分开,例如:

def test_build_country_list(self):
    # probably need to have done some setUp that sets up a test_doc_id?
    self.assertNotEmpty(self.test_instance.build_country_list(self.test_doc_id))

如果你想测试输出逻辑,你需要模拟输出函数并编写一个测试来验证当onCountry被调用时它们被正确的参数调用.

【讨论】:

  • 您好,感谢您的回复。你说的可能需要做一些设置 test_doc_id 的设置是什么意思?
  • 您需要设置您的类的一个实例用于测试目的,这样findBySubjectDocId(test_doc_id) 将产生一些有用的东西。执行此操作的标准位置是在单元测试的 setUp() 方法中。我看不到您正在测试的其他课程,因此我无法提供有关您如何使用有用的测试数据进行设置的任何具体指示。
  • 另一种方法是 patch out findBySubjectDocId -- 但我认为该函数也是您想要测试覆盖率的东西。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多