创建以下Ruby代码的单元测试

时间:2016-01-08 00:45:16

标签: ruby sqlite unit-testing csv minitest

我正在研究创建Ruby程序的单元测试程序的问题。

Ruby代码如下:

require 'sqlite3'
require 'CSV'

class Task8
  def initialize
      @f=File.open('C:/Users/aroraku/Desktop/boc-adap_td-agent.log-2.log','r')
      # @f1=CSV.open('C:/Users/aroraku/Desktop/task8_data.csv','wb')
      @db=SQLite3::Database.open('adaptive.db')
  end


 def check_line(line)
      if(line=~/deregistered adap_tdagt$/)
         return line
      end
 end

 def store_in_file
       CSV.open('C:/Users/aroraku/Desktop/task8_data.csv','wb') do |csv|
        while line=@f.gets do
            if( check_line(line)!=nil)
                line=~ (/(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2} \+\d{4}) \[info\]:\s(\S+) /)
                uuid=@db.execute(
                "Select devices.uuid
                 from devices,bas_tokens
                 where bas_tokens.device_id=devices.id AND
                 bas_tokens.token='#{$2}'")
                 uuid=uuid[0]
                 uuid=uuid[0]
              csv << [$1,uuid]
              end
        end
      end
 end
end

我能够成功编写的单元测试程序如下:

require 'minitest/autorun'
require 'minitest/unit'
require './task8'

class TestTask8 < Minitest::Test
  def system

  end
  def test_check_line
     result=Task8.new.check_line("Nov 13 01:46:57 10.232.47.76 qas-adaptiveip-10-232-47-76 2015-11-13 01:46:57 +0000 [info]: qas-296d1fa95fd0ac5a84ea73234c0c48d64f6ea22d has been deregistered adap_tdagt")
     assert_equal result,"Nov 13 01:46:57 10.232.47.76 qas-adaptiveip-10-232-47-76 2015-11-13 01:46:57 +0000 [info]: qas-296d1fa95fd0ac5a84ea73234c0c48d64f6ea22d has been deregistered adap_tdagt",
     'Wrong Output'
  end
  def test_check_line_wrong
     result=Task8.new.check_line("Nov 13 01:46:57 10.232.47.76 qas-adaptiveip-10-232-47-76 2015-11-13 01:46:57 +0000 [info]: qas-296d1fa95fd0ac5a84ea73234c0c48d64f6ea22d has been deregistered")
     assert_nil result
  end
end

我无法为store_in_file函数创建测试程序。如果有人请帮助我,那么这将是非常好的。另外,如果我能以任何方式改进我的Ruby程序,请告诉我。

1 个答案:

答案 0 :(得分:0)

首先,您必须了解单元测试,不应与DB或文件等外部资源交互,因此请调用此测试集成或功能测试。

要测试store_in_file方法,您有两个选项:

  1. 转到单元测试方法,存根CSV.open返回值并测试块执行可以使用Rspec模拟轻松完成。

  2. 让它与实际文件一起使用,并在测试结束时打开'C:/Users/aroraku/Desktop/task8_data.csv'并验证它的内容如下

      file.each_line do |line|
        line.split(",").each do |item|
          assert...
         end
      end