使用Enumerable模块实现简单的测试框架并进行数据统计
Ruby核心库中的Enumerable模块可能听起来很陌生,但实际上大家是应该经常接触到的。这里简单总结一下Enumerable模块的常用方法。
require 'pp'Object.method_undefined(:assert_true) if Object.method_defined?(:assert_true)Object.method_undefined(:assert_false) if Object.method_defined?(:assert_false)Object.module_eval do def assert_true self == true end def assert_false self == false endendclass TestCase attr_accessor :priority attr_reader :execute_time, :name, :test_result def initialize(name, priority, &case_step) @name = name @priority = priority @case_step = case_step end def <=>(other) @priority <=> other.priority end def execute @test_result = @case_step.call @execute_time = @priority endendclass TestCaseGroup include Enumerable attr_reader :test_cases, :test_result def initialize @test_cases = [] @test_result = {} end def add_case *test_case test_case.each do |c| @test_cases << c end end def delete_case test_cases @test_cases.delete test_cases end def each(&block) @test_cases.each &block end def execute @test_cases.each do |c| @test_result[c.name.to_sym] = c.execute end endend#定义具体用例case1 = TestCase.new('case1', 1) do (1 > 1).assert_falseendcase2 = TestCase.new('case2', 2) do (1 > 1).assert_trueendcase3 = TestCase.new('case3', 3) do (1 == 1).assert_trueend#创建用例组并添加用例test_group = TestCaseGroup.newtest_group.add_case case1, case2, case3#执行用例并输出结果test_group.executep test_group.test_result#是否有case的执行时间大于2?#from Enumerablepp test_group.any? {|c| c.execute_time > 2}#是否有case失败#from Enumerablepp test_group.any? {|c| c.test_result.eql? false}#统计总共执行时间#from Enumerableputs test_group.inject(0){|total, c|total + c.execute_time}#按执行时间长短分组#小于等于2的一组,其他的一组pp test_group.partition{|c| c.execute_time < 2}
Enumerable模块中提供了大量的实用迭代方法。这里用到到any? all? inject partition方法只是冰山一角而已。
其他的如each_with_index,collect等方法应用也非常广泛。总而言之Enumerable模块是需要下功夫掌握的1个模块。