我有一个测试文件,ipca_test.rb
require "test_helper"
require "matrix" # Does needing to include this here mean I'm doing something wrong?
class IpcaTest < Minitest::Test
def test_that_it_has_a_version_number
refute_nil ::Ipca::VERSION
end
def test_it_does_something_useful
refute false
end
def test_on_a_random_matrix
p = rand(3..10)
n = rand(20..50)
m = Matrix.build(n, p) {|_, _| rand(-10.0..10.0)}
pca = Ipca::Pca.new(m)
eigenvalue, r = pca.first_principal_component
puts "eigenvalue: #{eigenvalue}, r: #{r}"
assert eigenvalue.kind_of? Numeric
assert_equal Vector, r.class
end
end我要测试的程序是ipca.rb
require "ipca/version"
module Ipca
class Error < StandardError; end
class Pca
def initialize data
@data = data.class == Matrix ? data : Matrix.rows(data)
end
# see https://en.wikipedia.org/wiki/Principal_component_analysis#Iterative_computation
def first_principal_component(c = 100, tolerance = 0.001) # not sure whether defaults are apropos
p = @data.column_vectors.count
r = Vector.elements(Array.new(p) {|_| rand}).normalize
eigenvalue = nil
c.times do
s = Vector.zero(p)
@data.row_vectors.each do |x|
s += x.dot(r)*x
end
eigenvalue = r.dot(s) # ?
error = (eigenvalue*r-s).norm
r = s.normalize
exit if error < tolerance
end
return [eigenvalue, r]
end
end
end有时测试是成功的,但更多的情况是,测试永远无法“完成”。在这些情况下,有零个或多个点代表(我想)成功的断言。我猜想测试运行正被包中某个地方的某种超时所停止,这是间歇性的,因为测试的输入数据大小是不同的。但是,如果这是一个超时问题,为什么没有这样的信息呢?下面是一系列测试运行:
josie@josie-Inspiron-580:/var/www/html/ruby/ipca$ ruby ..josie@josie-Inspiron-580:/var/www/html/ruby/ipca$ _test.rb运行选项:..josie@josie-Inspiron-580:/var/www/html/ruby/ipca$ ruby ..josie@josie-Inspiron-580:/var/www/html/ruby/ipca$ _test.rb运行选项:r: Vector0.03288542301229099,-0.09533529249551115,0.3033273986606458,0.07951734565050736,0.3575555246291426,0.41614419068773545,0.4928822662304588,0.28785088479078025,0.5144766379975693。 在0.037173 s中完成,80.7047次运行/秒,107.6063次断言。 3次运行,4次断言,0次失败,0次错误,0次跳过josie@josie-Inspiron-580:/var/www/html/ruby/ipca$
发布于 2018-12-23 06:38:26
使用break而不是exit
break if error < tolerancebreak只退出do循环。
exit退出程序本身,而不给极小的测试失败的机会。
https://stackoverflow.com/questions/53901360
复制相似问题