如何使用gem`memory_profiler`编写单元测试



例如,我们有类实现:

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 }

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

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

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

最新更新