gpt4 book ai didi

ruby - 您如何测试是否会调用 Ruby 析构函数?

转载 作者:数据小太阳 更新时间:2023-10-29 07:28:00 30 4
gpt4 key购买 nike

我创建了一个类,我想将其卡在文件描述符上并在实例被 GC 处理时将其关闭。

我创建了一个看起来像这样的类:

class DataWriter
def initialize(file)
# open file
@file = File.open(file, 'wb')
# create destructor
ObjectSpace.define_finalizer(self, self.class.finalize(@file))
end

# write
def write(line)
@file.puts(line)
@file.flush
end

# close file descriptor, note, important that it is a class method
def self.finalize(file)
proc { file.close; p "file closed"; p file.inspect}
end
end

然后我尝试像这样测试析构函数方法:

RSpec.describe DataWriter do
context 'it should call its destructor' do
it 'calls the destructor' do
data_writer = DataWriter.new('/tmp/example.txt')
expect(DataWriter).to receive(:finalize)
data_writer = nil
GC.start
end
end
end

运行此测试时,即使“file closed”与 file.inspect 一起打印,测试也会失败并输出以下内容:

1) DataWriter it should call its destructor calls the destructor
Failure/Error: expect(DataWriter).to receive(:finalize)

(DataWriter (class)).finalize(*(any args))
expected: 1 time with any arguments
received: 0 times with any arguments
# ./spec/utils/data_writer_spec.rb:23:in `block (3 levels) in <top (required)>'

最佳答案

finalizeinitialize 中被调用,返回 proc,并且再也不会被调用,所以你不能期望它在 finalization 时被调用。它是在实例完成时调用的 proc。要检查这一点,让 proc 调用一个方法而不是自己完成工作。这通过了:

class DataWriter
# initialize and write same as above

def self.finalize(file)
proc { actually_finalize file }
end

def self.actually_finalize(file)
file.close
end

end

RSpec.describe DataWriter do
context 'it should call its destructor' do
it 'calls the destructor' do
data_writer = DataWriter.new('/tmp/example.txt')
expect(DataWriter).to receive(:actually_finalize)
data_writer = nil
GC.start
end
end
end

关于ruby - 您如何测试是否会调用 Ruby 析构函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39217681/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com