【问题标题】:OS specific tests with ruby使用 ruby​​ 进行操作系统特定测试
【发布时间】:2016-04-27 14:50:04
【问题描述】:

我有以下 Rakefile

require 'bundler/gem_tasks'
require 'rake/testtask'

Rake::TestTask.new do |task|
  task.libs << %w(test lib)
  task.pattern = 'test/**/*_test.rb'
end

task default: :test

而测试是用minitest定义的:

require 'test_helper'
require 'certmanager'

class CertificateTest < Minitest::Test
  context 'settings' do
    should 'retrieve settings' do
      assert_equal 'test123', Certmanager::Settings.key_passphrase
    end
  end
end

现在还有一些特定于操作系统的代码,例如 Linux 上的 FileUtils.ln_s 和 Windows 上的 FileUtils.cp。此代码需要不同的测试。在这种情况下,例如assert_equal filepath, File.readlink(linkpath)(Linux)与assert File.exist?(filepath)(Windows)

区分操作系统类型的最佳做法是什么? 我是否没有以 Linux 可以测试 Windows 特定代码的方式编写测试,反之亦然? 是否可以在测试中区分“内联”? 是否有必要拥有两个不同的测试集并在 Rakefile 中决定需要执行哪个测试集?甚至可能在 Rakefile 中吗?

【问题讨论】:

  • 是的,它可以工作,而File.readlinkFileUtils.ln_s 在 Windows 上不起作用(未实现的异常)。因此,您必须在 Windows 上使用不同的东西。在我的情况下FileUtils.cp。由于FileUtils.cpFileUtils.ln_s 具有不同的返回值,因此您必须使用不同的测试。此外,这只是一个例子。有不同的情况。另一个可能是默认配置路径。在 Linux 上,例如/etc/certmanager 和 Windows C:/User/.../AppData/.../certmanager。我再说一遍,你需要依赖于操作系统的两个不同的测试

标签: ruby unit-testing testing operating-system tdd


【解决方案1】:

为了能够运行每个测试而不管当前的操作系统,我写了一个模块TestHelper。这个模块包含几个方法来

  • 为测试假装一个 windows 或 posix 环境
  • 为在实际操作系统上未实现(或以不同方式工作)的方法设置存根 - 目前我只在 Windows 上找到了这些方法
  • 检查实际操作系统是否为windows(如果有必要知道)

在测试中,只要特定于操作系统,就可以简单地使用TestHelper.setup_windows_envTestHelper.setup_posix_env

require 'rbconfig'
require 'fileutils'
module TestHelper
  extend self

  def setup_windows_env
    is_windows?
    RbConfig::CONFIG.stubs(:[]).with('host_os').returns('windows')
    ENV.stubs(:[]).with('OS').returns('Windows_NT')
  end

  def setup_stubs_for_windows_in_posix_env
    class << FileUtils
      def ln_s(src, dest, options = {})
        File.open(dest, 'w') { |file| file.write src }
        return 0
      end
    end

    class << File
      def readlink(file_name)
        return File.read(file_name)
      end
    end
  end

  def setup_posix_env
    setup_stubs_for_windows_in_posix_env if is_windows?
    RbConfig::CONFIG.stubs(:[]).with('host_os').returns('darwin')
    ENV.stubs(:[]).with('OS').returns('OSX')
  end

  def is_windows?
    @is_windows ||= ApplicationToTest::Util::OS.is_windows?
  end
end

为了完整性ApplicationToTest::Util::OS.is_windows?

require 'rbconfig'
module ApplicationToTest
  module Util
    module OS
      def self.is_windows?
        begin
          env_os = ENV['OS']
        rescue NameError
          return false
        end
        if RbConfig::CONFIG['host_os'] =~ /^mingw2$|^mingw$|^mswin$|^windows$/
            true
        elsif env_os  == 'Windows_NT'
            true
        else
            false
        end
      end
    end
  end
end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-06-25
    • 1970-01-01
    • 2021-11-01
    • 2015-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多