Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add unit tests for ObjectCache. #1

Merged
merged 1 commit into from
Jul 7, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions ruby/ext/google/protobuf_c/protobuf.c
Original file line number Diff line number Diff line change
Expand Up @@ -272,6 +272,8 @@ static void ObjectCache_Init(VALUE protobuf) {

weak_obj_cache = rb_class_new_instance(0, NULL, cache_class);
rb_const_set(protobuf, rb_intern("OBJECT_CACHE"), weak_obj_cache);
rb_const_set(protobuf, rb_intern("SIZEOF_LONG"), INT2NUM(SIZEOF_LONG));
rb_const_set(protobuf, rb_intern("SIZEOF_VALUE"), INT2NUM(SIZEOF_VALUE));
}

VALUE ObjectCache_TryAdd(const void *key, VALUE val) {
Expand Down
10 changes: 10 additions & 0 deletions ruby/tests/BUILD.bazel
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,16 @@ ruby_test(
],
)

ruby_test(
name = "object_cache_test",
srcs = ["object_cache_test.rb"],
deps = [
"//ruby:protobuf",
"//ruby:test_ruby_protos",
"@protobuf_bundle//:test-unit",
],
)

ruby_test(
name = "repeated_field_test",
srcs = ["repeated_field_test.rb"],
Expand Down
41 changes: 41 additions & 0 deletions ruby/tests/object_cache_test.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
require 'google/protobuf'
require 'test/unit'

class ObjectCacheTest < Test::Unit::TestCase
def test_correct_implementation_for_platform
if Gem::Version.new(RUBY_VERSION) >= Gem::Version.new('2.7.0') and Google::Protobuf::SIZEOF_LONG >= Google::Protobuf::SIZEOF_VALUE
assert_instance_of Google::Protobuf::ObjectCache, Google::Protobuf::OBJECT_CACHE
else
assert_instance_of Google::Protobuf::LegacyObjectCache, Google::Protobuf::OBJECT_CACHE
end
end

def test_try_add_returns_existing_value
cache = Google::Protobuf::OBJECT_CACHE.class.new
key = 0xdeadbeefdeadbeef
first_value = 42
second_value = 43
assert_same first_value, cache.try_add(key, first_value)
assert_same first_value, cache.get(key)
assert_same first_value, cache.try_add(key, second_value)
assert_same first_value, cache.get(key)
end

def test_multithreaded_access
cache = Google::Protobuf::OBJECT_CACHE.class.new
key = 0xdeadbeefdeadbeef
threads = []

100.times do |i|
threads[i] = Thread.new {
Thread.current["result"] = cache.try_add(key, i)
}
end

results = {}

threads.each_with_index {|t, i | t.join; results[i] = t["result"] }
assert_equal 100, results.size
assert_equal 1, results.values.uniq.size
end
end