• 【Python基础】lpthw


      一、自动化测试的目的

      利用自动化的测试代码取代手动测试,使得程序中的一些初级bug可以被自动检出,而无需人工进行重复繁琐的测试工作。

      二、编写测试用例

      利用上一节编写的skeleton,这次在projects中创建一个ex47文件夹,将骨架文件复制到ex47下,然后执行以下操作:

      1. 将所有带NAME的东西全部重命名为ex47

      2. 将所用文件中的NAME全部改为ex47

      3. 删除所有的.pyc文件,确保清理干净(该类文件为编译结果?)

      注意,书中提示可以通过执行nosetests命令来运行测试,但此步需要cd到tests的上级目录,然后直接在命令行键入nosetests运行。

      下面在bin同级的ex47文件夹下创建一个game.py,并写一些类作为测试对象,如

     1 class Room(object):
     2 
     3     def __init__(self, name, description):
     4         self.name = name
     5         self.description = description
     6         self.paths = {}
     7 
     8     def go(self, direction):
     9         return self.paths.get(direction, None)      #dict.get(key, default=None) 查找键,指定键不存在时,返回default值
    10 
    11     def add_paths(self, paths):
    12         self.paths.update(paths)        #dict.update(dict2) 将dict2里的键值对更新到dict里

      下面将单元测试骨架修改成下面的样子:

     1 from nose.tools import *
     2 from ex47.game import Room
     3 
     4 def test_room():
     5     gold = Room('GoldRoom',
     6                 """This room has gold in it you can grab. There's a
     7                 door to it in the north.""")
     8     assert_equal(gold.name, "GoldRoom")
     9     assert_equal(gold.paths, {})
    10 
    11 def test_room_paths():
    12     center = Room('Center', "Test room in the center.")
    13     north = Room('North', "Test room in the north.")
    14     south = Room('South', "Test room in the south.")
    15 
    16     center.add_paths({'north':north, 'south':south})
    17     assert_equal(center.go('north'), north)
    18     assert_equal(center.go('south'), south)

      还可以根据模块的功能增加更多的测试用例(上面以test开头的函数,称为test case),用assert_equal断言来判断实际输出值和理想输出值是否一致。

      三、测试指南

      1. 测试文件要放在tests/目录下,并且命名为name_tests.py,否则nosetests就无法识别。这样也可以防止测试代码和别的代码相互混淆。

      2. 为创建的每一个模块写一个测试文件。

      3. 测试用例保持简短。

      4. 保持测试用例的整洁,用辅助函数代替重复代码。

      四、其他建议

      了解doc tests,这是一种另外的测试方式。(nose项目似乎已经不再更新?)

  • 相关阅读:
    Neo4j学习案例【转】
    Genymotion安装总结
    软件工程实践总结
    Markdown中的缩进
    Beta Daily Scrum 第七天
    随堂软工团队小测
    PMD(Put Me Down)用例测试
    第三次作业——个人作业——软件产品案例分析
    用例图
    毕设导师智能匹配
  • 原文地址:https://www.cnblogs.com/cry-star/p/10902735.html
Copyright © 2020-2023  润新知