本文介绍了对打开文件的脚本进行单元测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了一个脚本,用于打开文件、读取内容并执行一些操作和计算并将它们存储在集合和字典中.

I've written a script that opens up a file, reads the content and does some operations and calculations and stores them in sets and dictionaries.

我将如何为这样的事情编写单元测试?我的问题具体是:

How would I write a unit test for such a thing? My questions specifically are:

  1. 我要测试文件是否打开了吗?
  2. 该文件很大(它是 unix 字典文件).我将如何对计算进行单元测试?我真的必须手动计算所有内容并测试结果是否正确吗?我有一种感觉,这违背了单元测试的全部目的.我没有通过标准输入接受任何输入.

推荐答案

这不是单元测试的意义!

That's not what unit-testing is about!

  1. 您的文件不代表 UNIT,因此您不测试文件或 WITH 文件!
  2. 您的单元测试应该测试处理 a) 文件处理 b) 计算的函数/方法的每一种方法
  3. 您的单元测试超过被测单元的代码行的情况并不少见.

单元测试意味着(不完整,也不是书上的定义):

Unit-test means (not complete and not the by-the-book definition):

  • minimalistic/atomic - 您可以将您的单位拆分为最基本/最简单的单位;一个单元通常是一个可调用的(方法、函数、可调用对象)
  • 关注点分离——你在每一个测试中只测试一个东西;如果要测试单个单元的不同条件,则编写不同的测试
  • 确定性 - 你给单元一些处理的东西,事先知道它的结果应该是什么
  • 如果您的被测单元需要特定环境,您可以创建一个装置/测试设置/模型
  • 单元测试(根据经验)非常快!如果它很慢,请检查您是否违反了上面的另一点
  • 如果您需要测试违反上述内容的内容,您可能已经朝着集成测试迈出了下一步
  • 您可以将单元测试框架用于非单元测试,但不要仅仅因为使用了单元测试框架而将其称为单元测试

这个人 (Gary Bernhardt) 有一些有趣的实际示例,说明了什么测试和单元- 测试手段.

This guy (Gary Bernhardt) has some interesting practical examples of what testing and unit-testing means.

更新的一些说明:

1. 我会测试文件是否打开?"

"1. Would I test that the file opened?"

好吧,你可以这样做,但是那个单位"是什么?请记住,测试只有两种解决方案:通过和失败.如果您的测试失败,它应该(理想情况下必须)只有一个原因:您的单元(=函数)很烂!但在这种情况下,您的测试可能会失败,因为:* 文件不存在* 锁住了* 已损坏* 没有文件句柄了* 内存不足(大文件)* 月相等等.

Well you could do that, but what would be the "UNIT" for that? Keep in mind, that a test has just two solutions: pass and fail. If your test fails, it should (ideally must) have only one reason for that: Your unit(=function) sucks! But in this case your test can fail, because:* the file doesn't exist* is locked* is corrupted* no file-handles left* out of memeory (big file)* moon- phaseand so on.

那么失败(或通过)的单元"测试对您的单元有什么影响?您不会单独测试您的设备,而是使用它测试整个周围环境.这更像是一个系统测试!尽管如此,如果您想测试文件是否成功打开,您至少应该模拟一个文件.

so what would a failing (or passing) "unit" test say about your unit? You don't test your unit alone, but the whole surrounding enviroment with it. That's more a system-test!If you would like to test nontheless for successful file-opening you should at least mock a file.

2 ...我将如何对计算进行单元测试?我真的必须手动计算所有内容并测试结果是否正确吗?"

"2 ... How would I unit test the calculations? Do I literally have to manually calculate everything and test that the result is right?"

没有.您将为极端情况和常规情况编写测试,并根据处理后的结果检查预期结果.所需的测试数量取决于计算的复杂性和规则的例外情况.

No. You would write test for the corner- and regular-cases and check the expected outcome against the processed one. The amount of tests needed depends on the complexity of your calculations and the exceptions to the rule.

例如:

def test_negative_factor(self):
   assert result 

def test_discontinuity(self):
   assert raise exception if x == undefined_value

我希望我说得更清楚了!

I hope i made myself clearer!

这篇关于对打开文件的脚本进行单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 06:45