【问题标题】:How to write unit tests with gem `memory_profiler` usage?如何使用 gem `memory_profiler` 编写单元测试?
【发布时间】:2020-11-15 15:31:12
【问题描述】:

例如,我们有类实现:

class Memory
  def call
   2 * 2
  end
end

我们可以通过 memory_profiler 的使用情况得到报告:

require 'memory_profiler'
MemoryProfiler.report{ Memory.new.call  }.pretty_print

当我们增加内存或内存泄漏并更改为Memory#call时,如何实现单元测试失败?

例如,如果我们要这样更改Memory#call

- 2 * 2
+ loop { 2 * 2 }

【问题讨论】:

  • 老实说,我会从“为什么?”开始。在“如何?”之前。为什么需要这么奇怪的测试?
  • 检查分配的内存是否超过

标签: ruby unit-testing memory memory-leaks


【解决方案1】:

我不认为你应该把它作为单元测试,因为测试是一个有点不同的环境它不应该知道你的代码的时间成本或内存成本,它不应该验证指标,这是其他工具的工作.

对于您的情况,我建议您编写一些模块,您可以在其中断言分配的内存对您来说是可以的,例如您可以做一些事情

module MyMemsizeNotifier
  extend self
  ALLOWED_MEMSIZE = 0..4640

  # Or you can receive block, lambdas, procs
  # I will leave it for you implementation
  def call(klass) 
    report = MemoryProfiler.report
      klass.new.call
    end

    exceeds_limit?(report.total_allocated_memsize)
    report
  end

  def exceeds_limit?(total_usage)
    return if ALLOWED_MEMSIZE.include?(total_usage)

    # notify in rollbar, write a log to stdout or to file or any other way to notify
  end
end

## Usage

class MyController
  def index
    ...
    MyMemsizeNotifier.call(Memory)
    ...
  end
end

【讨论】:

  • 谢谢!这正是我正在寻找的,关于它的另一个问题:你如何得到这个号码4640
  • @AlexeyStrizhak 我只是在我的控制台中运行简单的示例,只是为了自己玩 gem。您可以将其更改为您需要的,例如将您的代码包装在 memory_profiler 块中并通过代码,并检查 report 结果对象,您将得到这个 total_allocated_memsize 对我来说是 4640
猜你喜欢
  • 2012-02-03
  • 2019-01-28
  • 1970-01-01
  • 1970-01-01
  • 2014-07-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多