代码之家  ›  专栏  ›  技术社区  ›  Lori

Minitest有时会提前终止,并显示netither完成或错误消息

  •  0
  • Lori  · 技术社区  · 6 年前

    我有一个测试文件, 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
    

    ( Git repo of entire tree )

    josie@josie-Inspiron-580:/var/www/html/ruby/ipca$ruby-Itest test/ipca_test.rb运行选项:--seed 44059

    #运行:

    ..josie@josie-Inspiron-580:/var/www/html/ruby/ipca$ruby-Itest test/ipca_test.rb运行选项:--seed 57681

    #运行:

    test/ipca_test.rb运行选项:--seed 57222

    test/ipca_test.rb运行选项:--seed 7474

    #运行:

    ..josie@josie-Inspiron-580:/var/www/html/ruby/ipca$ruby-Itest test/ipca_test.rb运行选项:--seed 1938

    ..josie@josie-Inspiron-580:/var/www/html/ruby/ipca$ruby-Itest test/ipca_test.rb运行选项:--seed 61325

    #运行:

    ..特征值:2027.68758011128,r:向量[0.0328854230122999, -0.09533529249551115, 0.3033273986606458, 0.07951734565050736, 0.3575555246291426, 0.41614419068773545, 0.4928822662304588, 0.28785088479078025, 0.5144766379975693] .

    以0.037173s、80.7047次运行/秒、107.6063次断言/秒的速度完成。

    3次运行,4次断言,0次失败,0次错误,0次跳过 josie@josie-Inspiron-580:/var/www/html/ruby/ipca$

    1 回复  |  直到 6 年前
        1
  •  1
  •   Raj    6 年前

    使用 break 而不是 exit

    break if error < tolerance
    

    打破 只退出do循环。

    出口 退出程序本身,不允许minitest通过测试