From 019d52fc6ca7e906b4500253a75c93e0d7f47720 Mon Sep 17 00:00:00 2001 From: Patrik Wenger Date: Mon, 17 Oct 2022 18:36:00 +0200 Subject: [PATCH] modernize syntax using Rubocop --- .rubocop.yml | 15 +- spec/cztop/actor_spec.rb | 271 ++++++------ spec/cztop/authenticator_spec.rb | 90 ++-- spec/cztop/beacon_spec.rb | 93 ++-- spec/cztop/cert_store_spec.rb | 50 +-- spec/cztop/certificate_spec.rb | 186 ++++---- spec/cztop/config/comments_spec.rb | 114 ++--- spec/cztop/config/serialization_spec.rb | 170 ++++---- spec/cztop/config/traversing_spec.rb | 186 ++++---- spec/cztop/config_spec.rb | 237 +++++------ spec/cztop/frame_spec.rb | 197 ++++----- spec/cztop/has_ffi_delegate_spec.rb | 72 ++-- spec/cztop/message/frames_spec.rb | 57 +-- spec/cztop/message_spec.rb | 260 ++++++------ spec/cztop/metadata_spec.rb | 146 +++---- spec/cztop/monitor_spec.rb | 84 ++-- spec/cztop/poller_spec.rb | 399 ++++++++--------- spec/cztop/polymorphic_zsock_methods_spec.rb | 20 +- spec/cztop/proxy_spec.rb | 175 ++++---- spec/cztop/send_receive_methods_spec.rb | 25 +- spec/cztop/socket/types_spec.rb | 175 ++++---- spec/cztop/socket_spec.rb | 162 +++---- spec/cztop/spec_helper.rb | 6 +- spec/cztop/z85/padded_spec.rb | 52 +-- spec/cztop/z85/pipe_spec.rb | 136 +++--- spec/cztop/z85_spec.rb | 94 +++-- spec/cztop/zap_spec.rb | 187 ++++---- spec/cztop/zsock_options_spec.rb | 423 +++++++++---------- spec/cztop_spec.rb | 4 +- spec/spec_helper.rb | 6 +- spec/zmq_helper.rb | 5 + 31 files changed, 2086 insertions(+), 2011 deletions(-) diff --git a/.rubocop.yml b/.rubocop.yml index 9e6fbb3..9ba6a8c 100644 --- a/.rubocop.yml +++ b/.rubocop.yml @@ -5,7 +5,6 @@ Layout/EmptyLineAfterMagicComment: Enabled: true Layout/ExtraSpacing: AllowForAlignment: true - ForceEqualSignAlignment: true Layout/EmptyLines: Enabled: false Layout/EmptyLineBetweenDefs: @@ -152,3 +151,17 @@ Style/SwapValues: # new in 1.1 Enabled: true Style/ClassAndModuleChildren: Enabled: false +Style/StringConcatenation: + Enabled: false +Style/RescueModifier: + Enabled: false +Style/YodaCondition: + Enabled: false +Lint/AmbiguousRegexpLiteral: + Enabled: false +Style/WordArray: + Enabled: false +Style/Semicolon: + Enabled: false +Lint/AmbiguousOperatorPrecedence: + Enabled: false diff --git a/spec/cztop/actor_spec.rb b/spec/cztop/actor_spec.rb index 937299f..2541b8c 100644 --- a/spec/cztop/actor_spec.rb +++ b/spec/cztop/actor_spec.rb @@ -1,17 +1,19 @@ +# frozen_string_literal: true + require_relative 'spec_helper' describe CZTop::Actor do - include_examples "has FFI delegate" + include_examples 'has FFI delegate' - it "has Zsock options" do + it 'has Zsock options' do assert_operator described_class, :<, CZTop::ZsockOptions end - it "has send/receive methods" do + it 'has send/receive methods' do assert_operator described_class, :<, CZTop::SendReceiveMethods end - it "has polymorphic Zsock methods" do + it 'has polymorphic Zsock methods' do assert_operator described_class, :<, CZTop::PolymorphicZsockMethods end @@ -25,8 +27,7 @@ let(:received_messages) { [] } let(:yielded) { [] } - describe "#initialize" do - + describe '#initialize' do before do expect(::CZMQ::FFI::Zactor).to receive(:new) .with(kind_of(FFI::Pointer), nil) @@ -38,7 +39,7 @@ let(:callback_shim) { actor.instance_variable_get(:@callback) } - context "with C callback" do # pointer to C function + context 'with C callback' do # pointer to C function let(:c_function) { CZTop::Beacon::ZBEACON_FPTR } let(:actor) { CZTop::Actor.new(c_function) } @@ -47,7 +48,7 @@ end end - context "with Proc callback" do + context 'with Proc callback' do let(:proc_) do lambda do |msg, pipe| received_messages << msg.to_a @@ -61,144 +62,144 @@ expect_any_instance_of(CZTop::Actor).to receive(:shim) .and_call_original end - it "shims it" do + it 'shims it' do refute_nil callback_shim refute_same proc_, callback_shim end - it "works" do - actor << "FOO" + it 'works' do + actor << 'FOO' actor.terminate - assert_equal [["FOO"]], received_messages + assert_equal [['FOO']], received_messages end end - context "with block" do + context 'with block' do # can use default actor - it "works" do - actor << "FOO" + it 'works' do + actor << 'FOO' actor.terminate - assert_equal [["FOO"]], received_messages + assert_equal [['FOO']], received_messages end end end - describe "#shim" do - context "with invalid handler" do - it "raises" do - assert_raises(ArgumentError) { actor.__send__(:shim, "foo") } + describe '#shim' do + context 'with invalid handler' do + it 'raises' do + assert_raises(ArgumentError) { actor.__send__(:shim, 'foo') } end end - context "with faulty handler" do - let(:error) { RuntimeError.new("foobar") } + context 'with faulty handler' do + let(:error) { RuntimeError.new('foobar') } let(:actor) { CZTop::Actor.new { raise error } } before do - actor << "foo" + actor << 'foo' actor.terminate end - it "stores exception" do + it 'stores exception' do assert_same error, actor.exception end end end - describe "#crashed?" do + describe '#crashed?' do before do - actor << "foo" + actor << 'foo' actor.terminate end - context "with crashed actor" do + context 'with crashed actor' do let(:actor) { CZTop::Actor.new { raise } } - it "returns true" do + it 'returns true' do assert_operator actor, :crashed? end end - context "with normally terminated actor" do - it "returns true" do + context 'with normally terminated actor' do + it 'returns true' do refute_operator actor, :crashed? end end end - describe "#exception" do + describe '#exception' do before do - actor << "foo" + actor << 'foo' actor.terminate end - context "with crashed actor" do - let(:error) { RuntimeError.new("foobar") } + context 'with crashed actor' do + let(:error) { RuntimeError.new('foobar') } let(:actor) { CZTop::Actor.new { raise error } } - it "returns stored exception" do + it 'returns stored exception' do assert_same error, actor.exception end end - context "with alive actor" do - it "returns nil" do + context 'with alive actor' do + it 'returns nil' do assert_nil actor.exception end end - context "with normally terminated actor" do - it "returns nil" do + context 'with normally terminated actor' do + it 'returns nil' do assert_nil actor.exception end end end - describe "#send_picture" do + describe '#send_picture' do let(:ffi_delegate) { actor.ffi_delegate } - let(:picture) { "si" } - let(:ffi_args) { [ :string, "foo", :int, 42 ] } - it "sends picture" do + let(:picture) { 'si' } + let(:ffi_args) { [:string, 'foo', :int, 42] } + it 'sends picture' do expect(::CZMQ::FFI::Zsock).to receive(:send) .with(ffi_delegate, picture, *ffi_args) actor.send_picture(picture, *ffi_args) end - context "with dead actor" do + context 'with dead actor' do before { actor.terminate } - it "raises DeadActorError" do + it 'raises DeadActorError' do assert_raises(CZTop::Actor::DeadActorError) do - actor.send_picture("s", :string, "foo") + actor.send_picture('s', :string, 'foo') end end end end - describe "#wait" do + describe '#wait' do let(:actor) do CZTop::Actor.new do |msg, pipe| case msg[0] - when "SIGNAL0" + when 'SIGNAL0' pipe.signal(0) - when "SIGNAL1" + when 'SIGNAL1' pipe.signal(1) end end end - it "waits for signal" do - actor << "SIGNAL0" + it 'waits for signal' do + actor << 'SIGNAL0' assert_equal 0, actor.wait - actor << "SIGNAL1" + actor << 'SIGNAL1' assert_equal 1, actor.wait end end - describe "#process_messages" do - context "when sending $TERM" do + describe '#process_messages' do + context 'when sending $TERM' do before do # can't use #<< actor.instance_eval do @mtx.synchronize do - CZTop::Message.new("$TERM").send_to(self) + CZTop::Message.new('$TERM').send_to(self) end end end - it "breaks" do + it 'breaks' do begin - actor << "foo" + actor << 'foo' rescue CZTop::Actor::DeadActorError # that's okay end @@ -208,23 +209,23 @@ end end - context "when interrupted" do + context 'when interrupted' do before do expect(actor).to receive(:next_message).and_raise(Interrupt).once end - it "terminates actor" do + it 'terminates actor' do begin - actor << "foo" << "INTERRUPTED" << "bar" + actor << 'foo' << 'INTERRUPTED' << 'bar' rescue CZTop::Actor::DeadActorError # that's okay end actor.terminate # idempotent - refute_includes received_messages, ["bar"] + refute_includes received_messages, ['bar'] end end - it "yields message and pipe" do - actor << "foo" + it 'yields message and pipe' do + actor << 'foo' actor.terminate assert_equal 2, yielded[0].size assert_kind_of CZTop::Message, yielded[0][0] @@ -232,33 +233,32 @@ end end - describe "#dead?" do - context "when terminated" do - it "returns true" do + describe '#dead?' do + context 'when terminated' do + it 'returns true' do actor.terminate assert actor.dead? end end - context "when not yet terminated" do - it "returns false" do + context 'when not yet terminated' do + it 'returns false' do refute actor.dead? end end end - describe "#<<" do - - context "threads" do + describe '#<<' do + context 'threads' do let(:mutex) { actor.instance_variable_get(:@mtx) } - it "is thread-safe" do + it 'is thread-safe' do expect(mutex).to receive(:synchronize).at_least(:once) - .and_call_original - actor << "foo" + .and_call_original + actor << 'foo' end end - context "with commands" do - let(:commands) { %w[ PRINT SHOW DO ] } + context 'with commands' do + let(:commands) { %w[PRINT SHOW DO] } let(:received_commands) do received_messages.map(&:first) end @@ -266,54 +266,54 @@ commands.each { |c| actor << c } actor.terminate end - it "sends commands to actor" do + it 'sends commands to actor' do assert_equal commands, received_commands end end - it "returns self" do # so it can be chained - assert_same actor, actor << "foo" + it 'returns self' do # so it can be chained + assert_same actor, actor << 'foo' end - context "with array" do - let(:msg) { %w[ SHOW foo bar ] } + context 'with array' do + let(:msg) { %w[SHOW foo bar] } before do actor << msg actor.terminate end - it "sends one message" do + it 'sends one message' do assert_equal 1, received_messages.size assert_equal msg, received_messages.first end end - context "with dead actor" do + context 'with dead actor' do before { actor.terminate } - it "raises DeadActorError" do + it 'raises DeadActorError' do assert_raises(CZTop::Actor::DeadActorError) do - actor << "FOO" + actor << 'FOO' end end end - context "with $TERM" do - it "calls #terminate" do + context 'with $TERM' do + it 'calls #terminate' do # one more call from the #after filter expect(actor).to receive(:terminate).twice.and_call_original - actor << "$TERM" + actor << '$TERM' end - it "is synchronous" do - actor << "$TERM" + it 'is synchronous' do + actor << '$TERM' assert_operator actor, :dead? end end - context "sndtimeo reached" do - let(:msg) { CZTop::Message.new("foobar") } + context 'sndtimeo reached' do + let(:msg) { CZTop::Message.new('foobar') } after { actor << msg } - it "retries" do + it 'retries' do expect(msg).to receive(:send_to) .with(actor).and_raise(IO::EAGAINWaitWritable).ordered expect(msg).to receive(:send_to) @@ -322,7 +322,7 @@ end end - describe "#receive" do + describe '#receive' do let(:actor) do # echo actor CZTop::Actor.new do |msg, pipe| @@ -330,30 +330,30 @@ end end - context "threads" do + context 'threads' do let(:mutex) { actor.instance_variable_get(:@mtx) } - it "is thread-safe" do + it 'is thread-safe' do expect(mutex).to receive(:synchronize).at_least(:once) - .and_call_original - actor << "foo" + .and_call_original + actor << 'foo' actor.receive end end - context "with messages available" do + context 'with messages available' do before do - actor << "foo" << "bar" + actor << 'foo' << 'bar' end - it "returns messages" do - assert_equal "foo", actor.receive[0] - assert_equal "bar", actor.receive[0] + it 'returns messages' do + assert_equal 'foo', actor.receive[0] + assert_equal 'bar', actor.receive[0] end end - context "with dead actor" do + context 'with dead actor' do before { actor.terminate } - it "raises DeadActorError" do + it 'raises DeadActorError' do assert_raises(CZTop::Actor::DeadActorError) do actor.receive end @@ -361,50 +361,50 @@ end end - describe "#request" do + describe '#request' do let(:actor) do CZTop::Actor.new do |msg, pipe| - pipe << msg.to_a.map{|s| s.downcase } + pipe << msg.to_a.map(&:downcase) end end - let(:word) { "FOO" } + let(:word) { 'FOO' } let(:response) do actor.request(word).to_a[0] end - it "returns response" do + it 'returns response' do assert_equal word.downcase, response end - context "threads" do + context 'threads' do let(:mutex) { actor.instance_variable_get(:@mtx) } - it "is thread-safe" do + it 'is thread-safe' do expect(mutex).to receive(:synchronize).at_least(:once) - .and_call_original + .and_call_original response end end - context "with dead actor" do + context 'with dead actor' do before { actor.terminate } - it "raises DeadActorError" do + it 'raises DeadActorError' do assert_raises(CZTop::Actor::DeadActorError) do response end end end - context "with $TERM message" do - let(:word) { "$TERM" } - it "raises" do + context 'with $TERM message' do + let(:word) { '$TERM' } + it 'raises' do assert_raises(ArgumentError) do response end end end - context "sndtimeo reached" do - let(:msg) { CZTop::Message.new("foobar") } + context 'sndtimeo reached' do + let(:msg) { CZTop::Message.new('foobar') } after { actor.request(msg) } - it "retries" do + it 'retries' do expect(msg).to receive(:send_to) .with(actor).and_raise(IO::EAGAINWaitWritable).ordered expect(msg).to receive(:send_to) @@ -413,36 +413,37 @@ end end - describe "#terminate" do - context "when actor is alive" do - it "tells actor to terminate" do - msg = CZTop::Message.new "$TERM" - expect(CZTop::Message).to receive(:new).with("$TERM").and_return(msg) + describe '#terminate' do + context 'when actor is alive' do + it 'tells actor to terminate' do + msg = CZTop::Message.new '$TERM' + expect(CZTop::Message).to receive(:new).with('$TERM').and_return(msg) expect(msg).to receive(:send_to).with(actor).and_call_original end - it "returns true" do + it 'returns true' do assert_equal true, actor.terminate end - it "waits for handler to terminate" do + it 'waits for handler to terminate' do expect(actor.instance_variable_get(:@handler_dead_signal)).to( - receive(:pop).and_call_original) + receive(:pop).and_call_original + ) end - context "with slow handler death" do + context 'with slow handler death' do let(:handler_thread) { actor.instance_variable_get(:@handler_thread) } - it "waits for heandler thread to terminate" do + it 'waits for heandler thread to terminate' do expect(handler_thread).to receive(:join).and_call_original end end - context "sndtimeo reached" do - let(:term_msg) { CZTop::Message.new("$TERM") } + context 'sndtimeo reached' do + let(:term_msg) { CZTop::Message.new('$TERM') } before do allow(CZTop::Message).to receive(:new).and_return(term_msg) end - it "retries" do + it 'retries' do expect(term_msg).to receive(:send_to) .with(actor).and_raise(IO::EAGAINWaitWritable).ordered expect(term_msg).to receive(:send_to) @@ -451,10 +452,10 @@ end end - context "with dead actor" do + context 'with dead actor' do before { actor.terminate } - it "returns false" do + it 'returns false' do assert_equal false, actor.terminate end end diff --git a/spec/cztop/authenticator_spec.rb b/spec/cztop/authenticator_spec.rb index 7bd61fd..897e7d1 100644 --- a/spec/cztop/authenticator_spec.rb +++ b/spec/cztop/authenticator_spec.rb @@ -1,7 +1,9 @@ +# frozen_string_literal: true + require_relative '../spec_helper' -describe "CZTop::Authenticator::ZAUTH_FPTR" do - it "points to a dynamic library symbol" do +describe 'CZTop::Authenticator::ZAUTH_FPTR' do + it 'points to a dynamic library symbol' do assert_kind_of FFI::DynamicLibrary::Symbol, CZTop::Authenticator::ZAUTH_FPTR end end @@ -11,72 +13,72 @@ let(:actor) { subject.actor } after { subject.terminate } - it "initializes" do + it 'initializes' do subject end - describe "#actor" do + describe '#actor' do Then { actor.is_a? CZTop::Actor } end - describe "#verbose!" do + describe '#verbose!' do after { subject.verbose! } - it "sends correct message to actor" do - expect(actor).to receive(:<<).with("VERBOSE").and_call_original + it 'sends correct message to actor' do + expect(actor).to receive(:<<).with('VERBOSE').and_call_original end - it "waits for signal" do + it 'waits for signal' do expect(actor).to receive(:wait).and_call_original end end - describe "#allow" do - let(:addrs) { %w[ 1.1.1.1 2.2.2.2 ] } - after { subject.allow *addrs } - it "whitelists addresses" do - expect(actor).to receive(:<<).with(["ALLOW", *addrs]).and_call_original + describe '#allow' do + let(:addrs) { %w[1.1.1.1 2.2.2.2] } + after { subject.allow(*addrs) } + it 'whitelists addresses' do + expect(actor).to receive(:<<).with(['ALLOW', *addrs]).and_call_original end end - describe "#deny" do - let(:addrs) { %w[ 3.3.3.3 4.4.4.4 foobar ] } - after { subject.deny *addrs } - it "blacklists addresses" do - expect(actor).to receive(:<<).with(["DENY", *addrs]).and_call_original + describe '#deny' do + let(:addrs) { %w[3.3.3.3 4.4.4.4 foobar] } + after { subject.deny(*addrs) } + it 'blacklists addresses' do + expect(actor).to receive(:<<).with(['DENY', *addrs]).and_call_original end end - describe "#plain" do - let(:filename) { "/path/to/file" } + describe '#plain' do + let(:filename) { '/path/to/file' } after { subject.plain(filename) } - it "enables PLAIN security" do - expect(actor).to receive(:<<).with(["PLAIN", filename]).and_call_original + it 'enables PLAIN security' do + expect(actor).to receive(:<<).with(['PLAIN', filename]).and_call_original end end - describe "#curve" do - context "when allowing keys from directory" do - let(:directory) { "/path/to/directory" } + describe '#curve' do + context 'when allowing keys from directory' do + let(:directory) { '/path/to/directory' } after { subject.curve(directory) } - it "enables CURVE security for keys in directory" do - expect(actor).to receive(:<<).with(["CURVE", directory]).and_call_original + it 'enables CURVE security for keys in directory' do + expect(actor).to receive(:<<).with(['CURVE', directory]).and_call_original end end - context "when allowing any key" do + context 'when allowing any key' do after { subject.curve } - it "enables CURVE security for any key" do - expect(actor).to receive(:<<).with(["CURVE", "*"]).and_call_original + it 'enables CURVE security for any key' do + expect(actor).to receive(:<<).with(['CURVE', '*']).and_call_original end end end - describe "#gssapi" do + describe '#gssapi' do after { subject.gssapi } - it "enables GSSAPI security" do - expect(actor).to receive(:<<).with("GSSAPI").and_call_original + it 'enables GSSAPI security' do + expect(actor).to receive(:<<).with('GSSAPI').and_call_original end end - describe "with certificate store" do + describe 'with certificate store' do subject { CZTop::Authenticator.new(cert_store) } let(:cert_store) { CZTop::CertStore.new } let(:cert) { CZTop::Certificate.new } @@ -95,22 +97,22 @@ subject.terminate end - it "initializes" do + it 'initializes' do subject end - it "uses certificate store passed" do + it 'uses certificate store passed' do assert_kind_of CZTop::Certificate, cert end - context "authentication" do - let(:domain) { "global" } + context 'authentication' do + let(:domain) { 'global' } let(:req) do # REQ socket acting as a CURVE server trying to authenticate a client CZTop::Socket::REQ.new(CZTop::ZAP::ENDPOINT) end rid = 0 - let(:request_id) { "#{rid += 1}" } + let(:request_id) { (rid += 1).to_s } let(:zap_request) do CZTop::ZAP::Request.new(domain, credentials).tap do |r| r.request_id = request_id @@ -124,16 +126,16 @@ req << zap_request.to_msg end - context "with valid credentials" do + context 'with valid credentials' do let(:credentials) { [pubkey_bin] } - it "authenticates" do + it 'authenticates' do assert_operator zap_response, :success? assert_equal request_id, zap_response.request_id end end - context "with invalid credentials" do - let(:credentials) { ["f" * 32] } # unknown public key - it "does not authenticate" do + context 'with invalid credentials' do + let(:credentials) { ['f' * 32] } # unknown public key + it 'does not authenticate' do refute_operator zap_response, :success? assert_equal request_id, zap_response.request_id assert_nil zap_response.user_id diff --git a/spec/cztop/beacon_spec.rb b/spec/cztop/beacon_spec.rb index ad87e27..f9fceae 100644 --- a/spec/cztop/beacon_spec.rb +++ b/spec/cztop/beacon_spec.rb @@ -1,13 +1,14 @@ +# frozen_string_literal: true + require_relative '../spec_helper' -describe "CZTop::Beacon::ZBEACON_FPTR" do - it "points to a dynamic library symbol" do +describe 'CZTop::Beacon::ZBEACON_FPTR' do + it 'points to a dynamic library symbol' do assert_kind_of FFI::DynamicLibrary::Symbol, CZTop::Beacon::ZBEACON_FPTR end end describe CZTop::Beacon do - subject { CZTop::Beacon.new } let(:actor) { subject.actor } @@ -15,126 +16,126 @@ subject.terminate end - it "initializes and terminates" do + it 'initializes and terminates' do subject end - describe "#verbose!" do + describe '#verbose!' do before do - expect(actor).to receive(:<<).with("VERBOSE").and_call_original + expect(actor).to receive(:<<).with('VERBOSE').and_call_original end - it "sends correct message to actor" do + it 'sends correct message to actor' do subject.verbose! end end - describe "#configure" do + describe '#configure' do let(:port) { 9999 } - let(:hostname) { "example.com" } + let(:hostname) { 'example.com' } let(:ptr) { FFI::MemoryPointer.from_string(hostname) } - context "with support for UDP broadcasts" do + context 'with support for UDP broadcasts' do before do expect(actor).to receive(:send_picture) - .with(kind_of(String), :string, "CONFIGURE", :int, port) + .with(kind_of(String), :string, 'CONFIGURE', :int, port) expect(CZMQ::FFI::Zstr).to receive(:recv).with(actor) - .and_return(ptr) + .and_return(ptr) end - it "sends correct message to actor" do + it 'sends correct message to actor' do assert_equal hostname, subject.configure(port) end end - context "no support for UDP broadcasts" do - let(:hostname) { "" } + context 'no support for UDP broadcasts' do + let(:hostname) { '' } let(:ptr) { FFI::MemoryPointer.from_string(hostname) } before do allow(actor).to receive(:send_picture) expect(CZMQ::FFI::Zstr).to receive(:recv).with(actor).and_return(ptr) end - it "raises" do + it 'raises' do assert_raises(NotImplementedError) do subject.configure(port) end end end - context "when interrupted" do + context 'when interrupted' do let(:nullptr) { ::FFI::Pointer::NULL } # represents failure before do expect(CZMQ::FFI::Zstr).to receive(:recv).with(actor) - .and_return(nullptr) + .and_return(nullptr) expect(CZMQ::FFI::Errors).to receive(:errno) .and_return(Errno::EINTR::Errno) end - it "raises" do + it 'raises' do assert_raises(Interrupt) do subject.configure(port) end end end end - describe "#publish" do - let(:data) { "foobar data" } + describe '#publish' do + let(:data) { 'foobar data' } let(:data_size) { data.bytesize } let(:interval) { 1000 } - context "with data" do + context 'with data' do before do - expect(actor).to receive(:send_picture). - with(kind_of(String), :string, "PUBLISH", :string, data, - :int, data_size, :int, interval) + expect(actor).to receive(:send_picture) + .with(kind_of(String), :string, 'PUBLISH', :string, data, + :int, data_size, :int, interval) end - it "sends correct message to actor" do + it 'sends correct message to actor' do subject.publish(data, interval) end end - context "with data too long" do - let(:data) { "x" * 256 } # max = 255 bytes - it "raises" do + context 'with data too long' do + let(:data) { 'x' * 256 } # max = 255 bytes + it 'raises' do assert_raises(ArgumentError) do subject.publish(data, interval) end end end end - describe "#silence" do - it "sends correct message to actor" do - expect(actor).to receive(:<<).with("SILENCE") + describe '#silence' do + it 'sends correct message to actor' do + expect(actor).to receive(:<<).with('SILENCE') subject.silence end end - describe "#subscribe" do - let(:filter) { "foo filter" } + describe '#subscribe' do + let(:filter) { 'foo filter' } let(:filter_size) { filter.bytesize } before do expect(actor).to receive(:send_picture) - .with(kind_of(String), :string, "SUBSCRIBE", :string, filter, :int, - filter_size) + .with(kind_of(String), :string, 'SUBSCRIBE', :string, filter, :int, + filter_size) end - it "sends correct message to actor" do + it 'sends correct message to actor' do subject.subscribe(filter) end end - describe "#listen" do + describe '#listen' do before do expect(actor).to receive(:send_picture) - .with(kind_of(String), :string, "SUBSCRIBE", :string, nil, :int, 0) + .with(kind_of(String), :string, 'SUBSCRIBE', :string, nil, :int, 0) end - it "sends correct message to actor" do + it 'sends correct message to actor' do subject.listen end end - describe "#unsubscribe" do + describe '#unsubscribe' do before do - expect(actor).to receive(:<<).with("UNSUBSCRIBE") + expect(actor).to receive(:<<).with('UNSUBSCRIBE') end - it "sends correct message to actor" do + it 'sends correct message to actor' do subject.unsubscribe end end - describe "#receive" do - let(:msg) { double("message") } + describe '#receive' do + let(:msg) { double('message') } before do expect(actor).to receive(:receive).and_return(msg) end - it "receives a message from actor" do + it 'receives a message from actor' do assert_equal msg, subject.receive end end diff --git a/spec/cztop/cert_store_spec.rb b/spec/cztop/cert_store_spec.rb index bc38f5b..348d334 100644 --- a/spec/cztop/cert_store_spec.rb +++ b/spec/cztop/cert_store_spec.rb @@ -1,44 +1,46 @@ +# frozen_string_literal: true + require_relative 'spec_helper' require 'tmpdir' require 'pathname' describe CZTop::CertStore do - include_examples "has FFI delegate" + include_examples 'has FFI delegate' - context "with disk location" do + context 'with disk location' do subject { CZTop::CertStore.new(location) } let(:location) do - Pathname.new(Dir.mktmpdir("zcertstore_test")) + Pathname.new(Dir.mktmpdir('zcertstore_test')) end let(:cert1) { CZTop::Certificate.new } before do - cert1.save(location + "cert1") + cert1.save(location + 'cert1') end - it "initializes" do + it 'initializes' do subject end - describe "#lookup" do - context "with known public key" do + describe '#lookup' do + context 'with known public key' do let(:key) { cert1.public_key(format: :z85) } - it "finds certificate" do + it 'finds certificate' do assert_kind_of CZTop::Certificate, subject.lookup(key) end end - context "with unknown public key" do + context 'with unknown public key' do let(:key) { CZTop::Certificate.new.public_key(format: :z85) } - it "returns nil" do + it 'returns nil' do assert_nil subject.lookup(key) end end end - describe "#insert" do - context "with certificate" do + describe '#insert' do + context 'with certificate' do let(:cert) { CZTop::Certificate.new } let(:key) { cert.public_key(format: :z85) } @@ -47,7 +49,7 @@ subject.insert(cert) end - it "inserts certificate" do + it 'inserts certificate' do looked_up_cert = subject.lookup(key) assert_kind_of CZTop::Certificate, looked_up_cert assert_equal key, looked_up_cert.public_key @@ -61,25 +63,25 @@ end end end - context "with invalid argument" do - it "raises" do + context 'with invalid argument' do + it 'raises' do assert_raises(ArgumentError) do - subject.insert(CZTop::Message.new("foo")) + subject.insert(CZTop::Message.new('foo')) end end end end end - context "without disk location" do + context 'without disk location' do subject { CZTop::CertStore.new } - it "initializes" do + it 'initializes' do subject end - describe "#insert" do - context "with certificate" do + describe '#insert' do + context 'with certificate' do let(:cert) { CZTop::Certificate.new } let(:key) { cert.public_key(format: :z85) } @@ -88,16 +90,16 @@ subject.insert(cert) end - it "inserts certificate" do + it 'inserts certificate' do looked_up_cert = subject.lookup(key) assert_kind_of CZTop::Certificate, looked_up_cert assert_equal key, looked_up_cert.public_key end end - context "with invalid argument" do - it "raises" do + context 'with invalid argument' do + it 'raises' do assert_raises(ArgumentError) do - subject.insert(CZTop::Message.new("foo")) + subject.insert(CZTop::Message.new('foo')) end end end diff --git a/spec/cztop/certificate_spec.rb b/spec/cztop/certificate_spec.rb index 5679c1e..73d2b89 100644 --- a/spec/cztop/certificate_spec.rb +++ b/spec/cztop/certificate_spec.rb @@ -1,62 +1,64 @@ +# frozen_string_literal: true + require_relative 'spec_helper' require 'tmpdir' require 'pathname' describe CZTop::Certificate do - include_examples "has FFI delegate" + include_examples 'has FFI delegate' - context "with certificate" do + context 'with certificate' do let(:cert) { CZTop::Certificate.new } let(:ffi_delegate) { cert.ffi_delegate } - describe "#initialize" do + describe '#initialize' do Then { cert } end - describe "#public_key" do - context "with :z85 format" do + describe '#public_key' do + context 'with :z85 format' do Given(:key) { cert.public_key(format: :z85) } Then { Encoding::ASCII == key.encoding } And { 40 == key.size } And { CZTop::Z85.new.encode(cert.public_key(format: :binary)) == key } end - context "with no format" do + context 'with no format' do let(:key) { cert.public_key } Then { cert.public_key(format: :z85) == key } # same as with no format end - context "with :binary format" do + context 'with :binary format' do Given(:key) { cert.public_key(format: :binary) } Then { Encoding::BINARY == key.encoding } And { 32 == key.bytesize } end - context "with invalid format" do + context 'with invalid format' do When(:result) { cert.public_key(format: :foo) } Then { result == Failure(ArgumentError) } end end - describe "#secret_key" do - context "with :z85 format" do + describe '#secret_key' do + context 'with :z85 format' do Given(:key) { cert.secret_key(format: :z85) } Then { Encoding::ASCII == key.encoding } And { 40 == key.size } And { CZTop::Z85.new.encode(cert.secret_key(format: :binary)) == key } end - context "with no format" do + context 'with no format' do let(:key) { cert.secret_key } Then { cert.secret_key(format: :z85) == key } # same as with no format end - context "with :binary format" do + context 'with :binary format' do Given(:key) { cert.secret_key(format: :binary) } Then { Encoding::BINARY == key.encoding } And { 32 == key.bytesize } end - context "with undefined secret key" do + context 'with undefined secret key' do # NOTE: this happens when cert was loaded from file created with # #save_public - let(:undefined_z85) { "0" * 40 } + let(:undefined_z85) { '0' * 40 } let(:undefined_bin) { "\0" * 32 } # the zcert API defines zcert_secret_key()'s return value as buffer, @@ -67,247 +69,249 @@ expect(ffi_delegate).to(receive(:secret_txt).and_return(undefined_z85)) expect(ffi_delegate).to(receive(:secret_key).and_return(pointer_bin)) end - it "returns nil" do + it 'returns nil' do assert_nil cert.secret_key(format: :z85) assert_nil cert.secret_key(format: :binary) end end - context "with invalid format" do + context 'with invalid format' do When(:result) { cert.secret_key(format: :foo) } Then { result == Failure(ArgumentError) } end end - describe "meta information" do - Given(:key) { "foo" } - Given(:value) { "bar" } - describe "#meta" do - context "with existing meta key" do + describe 'meta information' do + Given(:key) { 'foo' } + Given(:value) { 'bar' } + describe '#meta' do + context 'with existing meta key' do Given { cert[key] = value } Then { cert[key] == value } end - context "with non-existing meta key" do + context 'with non-existing meta key' do Then { cert[key].nil? } end end - describe "#meta=" do - context "when setting" do - it "sets" do + describe '#meta=' do + context 'when setting' do + it 'sets' do expect(ffi_delegate).to( - receive(:set_meta).with(key, String, :string, value)) + receive(:set_meta).with(key, String, :string, value) + ) cert[key] = value end end - context "when unsetting", if: has_czmq_drafts? do + context 'when unsetting', if: has_czmq_drafts? do Given { cert[key] = value } When { cert[key] = nil } Then { cert[key].nil? } end - it "does safe format handling" do - expect(ffi_delegate).to receive(:set_meta).with(String, "%s", any_args) + it 'does safe format handling' do + expect(ffi_delegate).to receive(:set_meta).with(String, '%s', any_args) cert[key] = value end end - describe "#meta_keys" do - context "with meta keys set" do - let(:values) { { "key1" => "value1", "key2" => "value2" } } + describe '#meta_keys' do + context 'with meta keys set' do + let(:values) { { 'key1' => 'value1', 'key2' => 'value2' } } before do - values.each {|k,v| cert[k] = v } + values.each { |k, v| cert[k] = v } end - it "returns keys" do + it 'returns keys' do assert_equal values.keys.sort, cert.meta_keys.sort end end - context "with no meta keys set" do - it "returns empty array" do + context 'with no meta keys set' do + it 'returns empty array' do assert_equal [], cert.meta_keys end end end - describe "#dup" do + describe '#dup' do When(:duplicate_cert) { cert.dup } Then { cert == duplicate_cert } - context "with failure" do - it "raises" do + context 'with failure' do + it 'raises' do expect(cert.ffi_delegate).to( - receive(:dup).and_return(::FFI::Pointer::NULL)) + receive(:dup).and_return(::FFI::Pointer::NULL) + ) assert_raises(SystemCallError) { cert.dup } end end end - describe ".check_curve_availability" do - context "with CURVE available" do + describe '.check_curve_availability' do + context 'with CURVE available' do before do expect(::CZMQ::FFI::Zsys).to receive(:has_curve).and_return(true) end it "doesn't warn" do - assert_output("", "") do + assert_output('', '') do described_class.check_curve_availability end end end - context "with CURVE not available" do + context 'with CURVE not available' do before do expect(::CZMQ::FFI::Zsys).to receive(:has_curve).and_return(false) end - it "warns" do - assert_output("", /curve.*libsodium/i) do + it 'warns' do + assert_output('', /curve.*libsodium/i) do described_class.check_curve_availability end end end end - describe ".new_from" do + describe '.new_from' do Given(:public_key) { cert.public_key(format: :binary) } Given(:secret_key) { cert.secret_key(format: :binary) } When(:new_cert) do CZTop::Certificate.new_from(public_key, secret_key) end - context "with valid binary key pair" do + context 'with valid binary key pair' do Then { cert == new_cert && new_cert == cert } end - context "with valid Z85 (text) key pair" do + context 'with valid Z85 (text) key pair' do Given(:public_key) { cert.public_key(format: :z85) } Given(:secret_key) { cert.secret_key(format: :z85) } Then { cert == new_cert && new_cert == cert } end - context "with invalid public key size" do - Given(:public_key) { "too short" } + context 'with invalid public key size' do + Given(:public_key) { 'too short' } Then { new_cert == Failure(ArgumentError) } end - context "with invalid secret key size" do - Given(:secret_key) { "too short" } + context 'with invalid secret key size' do + Given(:secret_key) { 'too short' } Then { new_cert == Failure(ArgumentError) } end - context "with missing public key" do + context 'with missing public key' do Given(:public_key) { nil } Then { new_cert == Failure(ArgumentError) } end - context "with missing secret key" do + context 'with missing secret key' do # public key only certificate, should work Given(:secret_key) { nil } Then { cert.public_key == new_cert.public_key } end end - describe "#==" do - context "with equal certificate" do + describe '#==' do + context 'with equal certificate' do Given(:other) { cert.dup } Then { cert == other } And { other == cert } end - context "with different certificate" do + context 'with different certificate' do Given(:other) { CZTop::Certificate.new } Then { cert != other } And { other != cert } end end - describe "#apply" do - let(:zocket) { double("zocket") } + describe '#apply' do + let(:zocket) { double('zocket') } - it "applies to socket" do + it 'applies to socket' do expect(ffi_delegate).to(receive(:apply).with(zocket)) cert.apply(zocket) end - context "with undefined secret key" do + context 'with undefined secret key' do before do expect(cert).to(receive(:secret_key).and_return(nil)) end - it "raises" do + it 'raises' do assert_raises(SystemCallError) do cert.apply(zocket) end end end - context "with invalid socket" do + context 'with invalid socket' do let(:zocket) { nil } - it "raises" do + it 'raises' do assert_raises(ArgumentError) { cert.apply(zocket) } end end - context "with real socket" do + context 'with real socket' do let(:zocket) { CZTop::Socket::REQ.new } - it "works" do + it 'works' do cert.apply(zocket) end end end end - describe "serialization" do + describe 'serialization' do let(:tmpdir) do - Pathname.new(Dir.mktmpdir("zcert_test")) + Pathname.new(Dir.mktmpdir('zcert_test')) end - let(:path) { tmpdir + "zcert.txt" } + let(:path) { tmpdir + 'zcert.txt' } - describe "#save" do + describe '#save' do When(:result) { cert.save(path) } - context "with valid path" do + context 'with valid path' do Given { !path.exist? } Then { path.exist? } end - context "with invalid path" do - Given(:path) { "/" } + context 'with invalid path' do + Given(:path) { '/' } Then { result == Failure(SystemCallError) } end - context "with empty path" do - Given(:path) { "" } + context 'with empty path' do + Given(:path) { '' } Then { result == Failure(ArgumentError) } end end - describe "#save_public" do + describe '#save_public' do When(:result) { cert.save_public(path) } - context "with valid path" do + context 'with valid path' do Given { !path.exist? } Then { path.exist? } end - context "with invalid path" do - Given(:path) { "/" } + context 'with invalid path' do + Given(:path) { '/' } Then { result == Failure(SystemCallError) } end - context "reading such a file" do + context 'reading such a file' do Given { cert.save_public(path) } Given(:loaded_cert) { CZTop::Certificate.load(path) } Then { loaded_cert.secret_key.nil? } And { loaded_cert.public_key } end end - describe "#save_secret" do + describe '#save_secret' do When(:result) { cert.save_secret(path) } - context "with valid path" do + context 'with valid path' do Given { !path.exist? } Then { path.exist? } end - context "with invalid path" do - Given(:path) { "/" } + context 'with invalid path' do + Given(:path) { '/' } Then { result == Failure(SystemCallError) } end end - describe ".load" do - context "with existing file" do + describe '.load' do + context 'with existing file' do before { cert.save(path) } let(:loaded_cert) { CZTop::Certificate.load(path) } - it "loads the certificate" do + it 'loads the certificate' do assert_kind_of CZTop::Certificate, loaded_cert assert_equal cert, loaded_cert end end - context "with non-existing file" do - it "raises" do + context 'with non-existing file' do + it 'raises' do assert_raises(Errno::ENOENT) do - CZTop::Certificate.load("/does/not/exist") + CZTop::Certificate.load('/does/not/exist') end end end diff --git a/spec/cztop/config/comments_spec.rb b/spec/cztop/config/comments_spec.rb index ba4c18f..5e74f9c 100644 --- a/spec/cztop/config/comments_spec.rb +++ b/spec/cztop/config/comments_spec.rb @@ -1,134 +1,136 @@ +# frozen_string_literal: true + require_relative '../../spec_helper' describe CZTop::Config do - describe "comments" do + describe 'comments' do let(:config_contents) do - <<-EOF -test - has_no_comments - has_one_comment - has_two_comments + <<~EOF + test + has_no_comments + has_one_comment + has_two_comments EOF end let(:config) do c = CZTop::Config.from_string(config_contents) - c.locate("test/has_one_comment").comments << "foo" - c.locate("test/has_two_comments").comments << "foo" << "bar" + c.locate('test/has_one_comment').comments << 'foo' + c.locate('test/has_two_comments').comments << 'foo' << 'bar' c end let(:comments) { item.comments } - describe "#comments" do - let(:item) { config.locate("test") } - it "returns CommentsAccessor" do + describe '#comments' do + let(:item) { config.locate('test') } + it 'returns CommentsAccessor' do assert_kind_of CZTop::Config::CommentsAccessor, comments end end describe CZTop::Config::CommentsAccessor do - let(:item) { config.locate("test/has_no_comments") } + let(:item) { config.locate('test/has_no_comments') } - describe "#<<" do - let(:new_comment) { "foo bar" } + describe '#<<' do + let(:new_comment) { 'foo bar' } before { comments << new_comment } - it "adds a new comment" do + it 'adds a new comment' do assert_equal 1, comments.size end - context "with malicious comment" do - let(:new_comment) { "%s foo" } - it "is safe" do # uses %s in comment + context 'with malicious comment' do + let(:new_comment) { '%s foo' } + it 'is safe' do # uses %s in comment assert_equal new_comment, comments.to_a.last end end end - describe "#delete_all" do - let(:item) { config.locate("test/has_two_comments") } - it "removes all comments" do + describe '#delete_all' do + let(:item) { config.locate('test/has_two_comments') } + it 'removes all comments' do assert_equal 2, comments.size comments.delete_all assert_equal 0, comments.size end end - describe "#size" do - context "with no comment" do - let(:item) { config.locate("test/has_no_comments") } - it "returns zero" do + describe '#size' do + context 'with no comment' do + let(:item) { config.locate('test/has_no_comments') } + it 'returns zero' do assert_equal 0, comments.size end end - context "with one comment" do - let(:item) { config.locate("test/has_one_comment") } - it "returns one" do + context 'with one comment' do + let(:item) { config.locate('test/has_one_comment') } + it 'returns one' do assert_equal 1, comments.size end end - context "with two comments" do - let(:item) { config.locate("test/has_two_comments") } - it "returns two" do + context 'with two comments' do + let(:item) { config.locate('test/has_two_comments') } + it 'returns two' do assert_equal 2, comments.size end end end - describe "#each" do - let(:block) { ->(_){@called += 1} } + describe '#each' do + let(:block) { ->(_) { @called += 1 } } before { @called = 0; comments.each(&block) } - context "with no comment" do - let(:item) { config.locate("test/has_no_comments") } - it "does not call block" do + context 'with no comment' do + let(:item) { config.locate('test/has_no_comments') } + it 'does not call block' do assert_equal 0, @called end - it "#to_a works correctly" do + it '#to_a works correctly' do assert_empty comments.to_a end end - context "with one comment" do - let(:item) { config.locate("test/has_one_comment") } - it "returns one" do + context 'with one comment' do + let(:item) { config.locate('test/has_one_comment') } + it 'returns one' do assert_equal 1, @called end - it "#to_a works correctly" do + it '#to_a works correctly' do assert_equal %w[foo], comments.to_a end end - context "with two comments" do - let(:item) { config.locate("test/has_two_comments") } - it "returns two" do + context 'with two comments' do + let(:item) { config.locate('test/has_two_comments') } + it 'returns two' do assert_equal 2, @called end - it "#to_a works correctly" do + it '#to_a works correctly' do assert_equal %w[foo bar], comments.to_a end end end end - describe "serialization" do + describe 'serialization' do let(:config) do root = described_class.new - root.children.new("foo") do |c| - c.value = "bar" - c.comments << "baz" - c.comments << "bii" + root.children.new('foo') do |c| + c.value = 'bar' + c.comments << 'baz' + c.comments << 'bii' end root end - context "when serializing" do + context 'when serializing' do let(:serialized) { config.to_s } - it "serializes first comment" do + it 'serializes first comment' do assert_match /#baz/, serialized end - it "serializes second comment" do + it 'serializes second comment' do assert_match /#bii/, serialized end end - context "when loading" do + context 'when loading' do let(:loaded_config) { described_class.from_string(config.to_s) } - let(:comments) { loaded_config.locate("foo").comments } - it "ignores comments" do + let(:comments) { loaded_config.locate('foo').comments } + it 'ignores comments' do assert_operator comments, :none? end end diff --git a/spec/cztop/config/serialization_spec.rb b/spec/cztop/config/serialization_spec.rb index 326167f..d1d1791 100644 --- a/spec/cztop/config/serialization_spec.rb +++ b/spec/cztop/config/serialization_spec.rb @@ -1,101 +1,103 @@ +# frozen_string_literal: true + require_relative '../../spec_helper' require 'tempfile' describe CZTop::Config do let(:config_contents) do - <<-EOF -context - iothreads = 1 - verbose = 1 # Ask for a trace -main - type = zqueue # ZMQ_DEVICE type - frontend - option - hwm = 1000 - swap = 25000000 # 25MB - bind = 'inproc:@@//@@addr1' - bind = 'ipc:@@//@@addr2' - backend - bind = inproc:@@//@@addr3 - EOF + <<~EOF + context + iothreads = 1 + verbose = 1 # Ask for a trace + main + type = zqueue # ZMQ_DEVICE type + frontend + option + hwm = 1000 + swap = 25000000 # 25MB + bind = 'inproc:@@//@@addr1' + bind = 'ipc:@@//@@addr2' + backend + bind = inproc:@@//@@addr3 + EOF end let(:config) { described_class.from_string(config_contents) } - describe ".from_string" do + describe '.from_string' do let(:loaded_config) { described_class.from_string(config_contents) } - context "given a string containing config tree" do - it "returns a config" do + context 'given a string containing config tree' do + it 'returns a config' do assert_kind_of described_class, loaded_config end end end - describe "#to_s" do - it "serializes the config tree to a string" do + describe '#to_s' do + it 'serializes the config tree to a string' do assert_kind_of String, config.to_s end - it "serializes correctly" do + it 'serializes correctly' do assert_equal config, described_class.from_string(config.to_s) end - context "with only root element" do - context "with no name" do + context 'with only root element' do + context 'with no name' do let(:config) { described_class.new } - it "serializes to empty string" do - assert_equal "", config.to_s + it 'serializes to empty string' do + assert_equal '', config.to_s end end - context "with name and value set" do + context 'with name and value set' do let(:config) do - c = described_class.new("foo") - c.value = "bar" + c = described_class.new('foo') + c.value = 'bar' c end # NOTE: doesn't make a lot of sense to me - it "serializes to empty string" do - assert_equal "", config.to_s + it 'serializes to empty string' do + assert_equal '', config.to_s end end end - context "with root as parent" do + context 'with root as parent' do let(:root) { described_class.new } - context "with no name" do + context 'with no name' do let(:config) { described_class.new nil, root } - it "serializes to the empty string" do - assert_equal "", config.to_s + it 'serializes to the empty string' do + assert_equal '', config.to_s end - it "even root serializes to the empty string" do - assert_equal "", root.to_s + it 'even root serializes to the empty string' do + assert_equal '', root.to_s end end - context "with just a name" do - let(:name) { "foo" } + context 'with just a name' do + let(:name) { 'foo' } let(:config) { described_class.new(name, parent: root) } - it "serializes to just the name" do - assert_equal "", config.to_s + it 'serializes to just the name' do + assert_equal '', config.to_s assert_equal "#{name}\n", root.to_s end end - context "with a name and a vaue" do - let(:name) { "foo" } - let(:value) { "bar" } + context 'with a name and a vaue' do + let(:name) { 'foo' } + let(:value) { 'bar' } let(:config) do c = described_class.new(name, parent: root) c.value = value c end - it "serializes to the full config item" do - assert_equal "", config.to_s + it 'serializes to the full config item' do + assert_equal '', config.to_s assert_equal "#{name} = \"#{value}\"\n", root.to_s end end end end - describe ".load" do - context "given config file" do + describe '.load' do + context 'given config file' do let(:file) do - file = Tempfile.new("zconfig_test") + file = Tempfile.new('zconfig_test') file.write(config_contents) file.rewind return file @@ -103,67 +105,67 @@ let(:filename) { file.path } let(:loaded_config) { described_class.load(filename) } - it "loads the file" do + it 'loads the file' do assert_kind_of described_class, loaded_config assert_equal filename, loaded_config.filename end - describe "#reload" do - context "loaded from file" do + describe '#reload' do + context 'loaded from file' do let(:fix_config) { described_class.from_string(config_contents) } - context "when unchanged" do + context 'when unchanged' do before { loaded_config.reload } - it "is still the same" do + it 'is still the same' do assert_equal fix_config, loaded_config assert_operator fix_config, :tree_equal?, loaded_config end end - context "when changed" do + context 'when changed' do before do changing_config = described_class.from_string(config_contents) - changing_config["context/verbose"] = 0 # normally 1 + changing_config['context/verbose'] = 0 # normally 1 changing_config.save(filename) # overwrite existing file loaded_config.reload end - it "item is different" do - refute_equal fix_config["context/verbose"], loaded_config["context/verbose"] + it 'item is different' do + refute_equal fix_config['context/verbose'], loaded_config['context/verbose'] end - it "tree is different" do + it 'tree is different' do refute_operator fix_config, :tree_equal?, loaded_config end end - context "when file has been deleted" do - it "raises" do + context 'when file has been deleted' do + it 'raises' do loaded_config Pathname.new(filename).delete assert_raises(Errno::ENOENT) { loaded_config.reload } end end end - context "created in-memory" do # or any other problem - it "raises" do + context 'created in-memory' do # or any other problem + it 'raises' do assert_raises(TypeError) { config.reload } end end end - describe "#filename" do - context "root config item" do - it "returns filename" do + describe '#filename' do + context 'root config item' do + it 'returns filename' do assert_equal filename, loaded_config.filename end end - context "child item" do - let(:item) { loaded_config.locate("context/verbose") } - it "returns nil" do + context 'child item' do + let(:item) { loaded_config.locate('context/verbose') } + it 'returns nil' do assert_nil item.filename end end end end - context "given no config file" do - let(:nonexistent_filename) { "/foo/bar.zpl" } - it "raises" do + context 'given no config file' do + let(:nonexistent_filename) { '/foo/bar.zpl' } + it 'raises' do assert_raises(Errno::ENOENT) do described_class.load(nonexistent_filename) end @@ -171,8 +173,8 @@ end end - describe "#save" do - let(:file) { Tempfile.new("zconfig_test") } + describe '#save' do + let(:file) { Tempfile.new('zconfig_test') } let(:saved_file) do config.save(file.path) Pathname.new(file.path) @@ -191,29 +193,29 @@ end end - it "saves to that file" do + it 'saves to that file' do assert_operator saved_file, :size? end - it "saves correctly" do + it 'saves correctly' do assert_equal config, described_class.load(saved_file.to_s) end - context "with empty path" do - it "raises" do - assert_raises(Errno::ENOENT) { config.save("") } + context 'with empty path' do + it 'raises' do + assert_raises(Errno::ENOENT) { config.save('') } end end - context "with invalid path" do - it "raises" do - assert_raises(Errno::EISDIR) { config.save("/") } + context 'with invalid path' do + it 'raises' do + assert_raises(Errno::EISDIR) { config.save('/') } end end end - context "Marshalling" do + context 'Marshalling' do let(:marshaled) { Marshal.dump(config) } let(:unmarshaled) { Marshal.load(marshaled) } - describe "#_dump and ._load" do - it "roundtrips" do + describe '#_dump and ._load' do + it 'roundtrips' do assert_equal config, unmarshaled end end diff --git a/spec/cztop/config/traversing_spec.rb b/spec/cztop/config/traversing_spec.rb index 0243f8f..10ad798 100644 --- a/spec/cztop/config/traversing_spec.rb +++ b/spec/cztop/config/traversing_spec.rb @@ -1,37 +1,39 @@ +# frozen_string_literal: true + require_relative '../../spec_helper' describe CZTop::Config do let(:config_contents) do - <<-EOF -context - iothreads = 1 - verbose = 1 # Ask for a trace -main - type = zqueue # ZMQ_DEVICE type - frontend - option - hwm = 1000 - swap = 25000000 # 25MB - bind = 'inproc:@@//@@addr1' - bind = 'ipc:@@//@@addr2' - backend - bind = inproc:@@//@@addr3 - EOF + <<~EOF + context + iothreads = 1 + verbose = 1 # Ask for a trace + main + type = zqueue # ZMQ_DEVICE type + frontend + option + hwm = 1000 + swap = 25000000 # 25MB + bind = 'inproc:@@//@@addr1' + bind = 'ipc:@@//@@addr2' + backend + bind = inproc:@@//@@addr3 + EOF end let(:config) { described_class.from_string(config_contents) } - describe "#execute" do - context "with a block" do - it "yields config and level" do - config.execute do |c,l| + describe '#execute' do + context 'with a block' do + it 'yields config and level' do + config.execute do |c, l| assert_kind_of described_class, c assert_kind_of Integer, l end end - it "level starts at 0" do + it 'level starts at 0' do first_level = nil - config.execute do |_,level| + config.execute do |_, level| first_level ||= level break # NOTE: doesn't work on JRuby (yet) # see https://github.com/jruby/jruby/issues/3559 @@ -39,11 +41,11 @@ assert_equal 0, first_level end - context "starting from non-root element" do + context 'starting from non-root element' do let(:child) { config.children.first } - it "level still starts at 0" do + it 'level still starts at 0' do first_level = nil - child.execute do |_,level| + child.execute do |_, level| first_level ||= level break # NOTE: doesn't work on JRuby (yet) # see https://github.com/jruby/jruby/issues/3559 @@ -61,8 +63,8 @@ end end - context "with a block that breaks" do - it "calls block no more" do + context 'with a block that breaks' do + it 'calls block no more' do called = 0 config.execute { |_| called += 1; break } assert_equal 1, called @@ -74,99 +76,99 @@ end end - it "returns nil" do + it 'returns nil' do assert_nil config.execute { |_| break } end - context "with break value" do + context 'with break value' do # NOTE: broken on JRuby # see https://github.com/jruby/jruby/issues/3559 (JRuby only because # it keeps calling the block, even though it break'd) - it "returns break value", skip: (%w[jruby].include?(RUBY_ENGINE)\ - && "broken on JRuby") do + it 'returns break value', skip: (%w[jruby].include?(RUBY_ENGINE) \ + && 'broken on JRuby') do assert_equal :foo, config.execute { |_| break :foo } end end end - context "with a block that raises" do - it "calls block no more" do + context 'with a block that raises' do + it 'calls block no more' do called = 0 begin config.execute { |_| called += 1; raise } - rescue + rescue StandardError assert_equal 1, called end end let(:exception) { Class.new(RuntimeError) } - it "raises" do + it 'raises' do assert_raises(exception) do config.execute { raise exception } end end end - context "with no block" do - it "raises" do + context 'with no block' do + it 'raises' do assert_raises(ArgumentError) { config.execute } end end end - describe "#children" do + describe '#children' do let(:parent) { config } let(:children) { parent.children } - it "returns SiblingsAccessor" do + it 'returns SiblingsAccessor' do assert_kind_of CZTop::Config::ChildrenAccessor, children end - context "with children" do - let(:parent) { config.locate("/main/frontend/option") } - it "returns first child" do + context 'with children' do + let(:parent) { config.locate('/main/frontend/option') } + it 'returns first child' do refute_nil children.first - assert_equal "hwm", children.first.name + assert_equal 'hwm', children.first.name end - it "returns all children" do + it 'returns all children' do assert_equal %w[hwm swap], children.to_a.map(&:name) end end - context "with no children" do - let(:parent) { config.locate("/main/frontend/option/swap") } - it "has no children" do + context 'with no children' do + let(:parent) { config.locate('/main/frontend/option/swap') } + it 'has no children' do assert_nil parent.children.first assert_empty parent.children.to_a end end - context "adding a new child" do + context 'adding a new child' do let(:new_child) { children.new } - it "returns new child" do + it 'returns new child' do assert_kind_of CZTop::Config, new_child end - it "adds new child" do + it 'adds new child' do new_child - assert_equal 2+1, children.count + assert_equal 2 + 1, children.count assert_equal new_child, parent.last_at_depth(1) end - context "with name" do - let(:name) { "foo" } - it "sets name" do + context 'with name' do + let(:name) { 'foo' } + it 'sets name' do assert_equal name, children.new(name).name end end - context "with name and value" do - let(:name) { "foo" } - let(:value) { "bar" } + context 'with name and value' do + let(:name) { 'foo' } + let(:value) { 'bar' } let(:new_child) { children.new(name, value) } - it "sets name and value" do + it 'sets name and value' do assert_equal name, new_child.name assert_equal value, new_child.value end end - context "with block given" do - it "yields new child" do + context 'with block given' do + it 'yields new child' do yielded = nil new_child = children.new { |c| yielded = c } assert_same new_child, yielded @@ -175,88 +177,88 @@ end end - describe "#siblings" do + describe '#siblings' do let(:item) { config } let(:siblings) { item.siblings } - it "returns SiblingsAccessor" do + it 'returns SiblingsAccessor' do assert_kind_of CZTop::Config::SiblingsAccessor, siblings end - context "with no siblings" do - it "has no siblings" do + context 'with no siblings' do + it 'has no siblings' do refute_operator siblings, :any? assert_equal 0, siblings.count assert_nil siblings.first end end - context "with siblings" do - let(:item) { config.locate("main/frontend/option") } - it "has siblings" do + context 'with siblings' do + let(:item) { config.locate('main/frontend/option') } + it 'has siblings' do assert_operator siblings, :any? end - it "returns correct first sibling" do - assert_equal config.locate("main/frontend/bind"), siblings.first + it 'returns correct first sibling' do + assert_equal config.locate('main/frontend/bind'), siblings.first end - it "returns all siblings" do + it 'returns all siblings' do assert_equal 2, siblings.count end - it "returns siblings as Config objects" do + it 'returns siblings as Config objects' do siblings.each { |s| assert_kind_of CZTop::Config, s } end end - context "with no younger siblings" do + context 'with no younger siblings' do # has only an "older" sibling - let(:item) { config.locate("main/backend") } - it "acts like it has no siblings" do + let(:item) { config.locate('main/backend') } + it 'acts like it has no siblings' do assert_empty siblings.to_a assert_nil siblings.first end end end - describe "#locate" do - context "given existing path" do - let(:located_item) { config.locate("/main/frontend/option/swap") } - it "returns config item" do + describe '#locate' do + context 'given existing path' do + let(:located_item) { config.locate('/main/frontend/option/swap') } + it 'returns config item' do assert_kind_of described_class, located_item - assert_equal "swap", located_item.name + assert_equal 'swap', located_item.name end end - context "given non-existent path" do - let(:nonexistent_path) { "/foo/bar" } + context 'given non-existent path' do + let(:nonexistent_path) { '/foo/bar' } let(:located_item) { config.locate nonexistent_path } - it "returns nil" do + it 'returns nil' do assert_nil located_item end end end - describe "#last_at_depth" do + describe '#last_at_depth' do let(:found) { config.last_at_depth(level) } - context "with level 0" do + context 'with level 0' do let(:level) { 0 } let(:expected) { config } - it "finds correct item" do + it 'finds correct item' do assert_equal expected, found end end - context "with level 1" do + context 'with level 1' do let(:level) { 1 } - let(:expected) { config.locate("main") } - it "finds correct item" do + let(:expected) { config.locate('main') } + it 'finds correct item' do assert_equal expected, found end end - context "with level 2" do + context 'with level 2' do let(:level) { 2 } - let(:expected) { config.locate("main/backend") } - it "finds correct item" do + let(:expected) { config.locate('main/backend') } + it 'finds correct item' do assert_equal expected, found end end - context "with level 99" do + context 'with level 99' do let(:level) { 99 } - it "returns nil" do + it 'returns nil' do assert_nil nil, found end end diff --git a/spec/cztop/config_spec.rb b/spec/cztop/config_spec.rb index 05af2a7..39fe091 100644 --- a/spec/cztop/config_spec.rb +++ b/spec/cztop/config_spec.rb @@ -1,56 +1,57 @@ +# frozen_string_literal: true + require_relative 'spec_helper' describe CZTop::Config do - - describe "#initialize" do - context "with a name" do - let(:name) { "foo" } + describe '#initialize' do + context 'with a name' do + let(:name) { 'foo' } let(:config) { described_class.new name } - it "sets that name" do + it 'sets that name' do assert_equal name, config.name end end - context "with no name" do + context 'with no name' do let(:config) { described_class.new } - it "creates a config item anyway" do + it 'creates a config item anyway' do assert_kind_of described_class, config end - it "has nil name" do + it 'has nil name' do assert_nil config.name end end - context "with name and value" do - let(:name) { "foo" } - let(:value) { "bar" } + context 'with name and value' do + let(:name) { 'foo' } + let(:value) { 'bar' } let(:config) { described_class.new name, value } - it "sets name and value" do + it 'sets name and value' do assert_equal name, config.name assert_equal value, config.value end end - context "given a parent" do - let(:parent_name) { "foo" } + context 'given a parent' do + let(:parent_name) { 'foo' } let(:parent_config) { described_class.new parent_name } - let(:name) { "bar" } + let(:name) { 'bar' } let(:config) { described_class.new name, parent: parent_config } - it "appends it to that parent" do + it 'appends it to that parent' do assert_nil parent_config.children.first config assert_equal config.to_ptr, parent_config.children.first.to_ptr end - it "removes finalizer from delegate" do # parent will free it + it 'removes finalizer from delegate' do # parent will free it assert_nil config.ffi_delegate.instance_variable_get(:@finalizer) end end - context "with no parent" do + context 'with no parent' do let(:config) { described_class.new } it "doesn't remove finalizer from delegate" do refute_nil config.ffi_delegate.instance_variable_get(:@finalizer) end end - context "with a block" do - it "yields self" do + context 'with a block' do + it 'yields self' do yielded = nil config = described_class.new { |c| yielded = c } assert_same config, yielded @@ -58,54 +59,54 @@ end end - context "given a config" do + context 'given a config' do let(:config_contents) do - <<-EOF -context - iothreads = 1 - verbose = 1 # Ask for a trace -main - type = zqueue # ZMQ_DEVICE type - frontend - option - hwm = 1000 - swap = 25000000 # 25MB - bind = 'inproc:@@//@@addr1' - bind = 'ipc:@@//@@addr2' - backend - bind = inproc:@@//@@addr3 + <<~EOF + context + iothreads = 1 + verbose = 1 # Ask for a trace + main + type = zqueue # ZMQ_DEVICE type + frontend + option + hwm = 1000 + swap = 25000000 # 25MB + bind = 'inproc:@@//@@addr1' + bind = 'ipc:@@//@@addr2' + backend + bind = inproc:@@//@@addr3 EOF end let(:config) { described_class.from_string(config_contents) } - context "#inspect" do - it "has a nice output" do + context '#inspect' do + it 'has a nice output' do assert_match /Config.+name=.+value=/, config.inspect end end - describe "#==" do - Given(:this_name) { "foo" } - Given(:this_value) { "bar" } + describe '#==' do + Given(:this_name) { 'foo' } + Given(:this_value) { 'bar' } Given(:this) { described_class.new(this_name, this_value) } - context "with equal config" do + context 'with equal config' do Given(:that) { described_class.new(this_name, this_value) } Then { this == that } And { that == this } end - context "with different config" do - Given(:that_name) { "quu" } - Given(:that_value) { "quux" } + context 'with different config' do + Given(:that_name) { 'quu' } + Given(:that_value) { 'quux' } - context "with different name" do + context 'with different name' do Given(:that) { described_class.new(that_name, this_value) } Then { this != that } And { that != this } end - context "with different value" do + context 'with different value' do Given(:that) { described_class.new(this_name, that_value) } Then { this != that } And { that != this } @@ -113,32 +114,32 @@ end end - describe "#tree_equal?" do - context "given equal config tree" do - Given(:this) { config.locate("main/frontend") } + describe '#tree_equal?' do + context 'given equal config tree' do + Given(:this) { config.locate('main/frontend') } Given(:other) { described_class.from_string(config_contents) } - Given(:that) { other.locate("main/frontend") } + Given(:that) { other.locate('main/frontend') } When do # mangle an independent side-tree a bit - backend = config.locate("main/backend") - backend.name = "foobar" - backend.children.new("foo", "bar") + backend = config.locate('main/backend') + backend.name = 'foobar' + backend.children.new('foo', 'bar') end Then { this.tree_equal? that } And { that.tree_equal? this } end - context "given different config tree" do - let(:other_config) { described_class.new("foo") } + context 'given different config tree' do + let(:other_config) { described_class.new('foo') } Then { !config.tree_equal?(other_config) } And { !other_config.tree_equal?(config) } end end - describe "#name" do + describe '#name' do context 'with named elements' do - it "returns name" do - assert_equal "root", config.name - assert_equal "context", config.children.first.name + it 'returns name' do + assert_equal 'root', config.name + assert_equal 'context', config.children.first.name end end @@ -149,131 +150,131 @@ end end - describe "#name=" do - let(:new_name) { "foo" } - it "sets name" do + describe '#name=' do + let(:new_name) { 'foo' } + it 'sets name' do config.name = new_name assert_equal new_name, config.name end end - describe "#value" do + describe '#value' do let(:config_contents) do - <<-EOF -a = 1 -b = "" -c - d = "foo" - f = bar - g - h # no value either + <<~EOF + a = 1 + b = "" + c + d = "foo" + f = bar + g + h # no value either EOF end - context "with no value" do - let(:item) { config.locate("/c/g") } - it "returns the empty string" do + context 'with no value' do + let(:item) { config.locate('/c/g') } + it 'returns the empty string' do assert_empty item.value end end - context "with value" do + context 'with value' do let(:paths_values) do - { "a" => "1", - "b" => "", - "c" => "", - "c/d" => "foo", - "c/f" => "bar", - "c/g" => "", - "c/h" => "" } + { 'a' => '1', + 'b' => '', + 'c' => '', + 'c/d' => 'foo', + 'c/f' => 'bar', + 'c/g' => '', + 'c/h' => '' } end - it "reads value" do - paths_values.each do |path,expected| + it 'reads value' do + paths_values.each do |path, expected| assert_equal expected, config.locate(path).value end end end end - describe "#value=" do - let(:item) { config.locate("main/frontend/option/hwm") } + describe '#value=' do + let(:item) { config.locate('main/frontend/option/hwm') } before { item.value = new_value } - context "given safe string" do - let(:new_value) { "foo bar" } + context 'given safe string' do + let(:new_value) { 'foo bar' } - it "sets value" do + it 'sets value' do assert_equal new_value, item.value end end - context "given integer" do + context 'given integer' do let(:new_value) { 555 } - it "sets value" do + it 'sets value' do assert_equal new_value.to_s, item.value end end - context "given unsafe, user-supplied value" do - let(:new_value) { "%s" } + context 'given unsafe, user-supplied value' do + let(:new_value) { '%s' } - it "sets value" do + it 'sets value' do assert_equal new_value, item.value end end end - describe "#[]=" do - context "given a path and value" do - let(:path) { "main/type" } - let(:new_value) { "foobar" } + describe '#[]=' do + context 'given a path and value' do + let(:path) { 'main/type' } + let(:new_value) { 'foobar' } it "changes the item's value" do refute_equal new_value, config[path] config[path] = new_value assert_equal new_value, config[path] end - it "has alias #put" do + it 'has alias #put' do config.put(path, new_value) assert_equal new_value, config[path] end end end - describe "#[]" do - context "given existing path" do - context "with value set" do - let(:path) { "main/type" } - it "returns correct value" do - assert_equal "zqueue", config.get(path) + describe '#[]' do + context 'given existing path' do + context 'with value set' do + let(:path) { 'main/type' } + it 'returns correct value' do + assert_equal 'zqueue', config.get(path) end - it "has alias #get" do + it 'has alias #get' do assert_equal config[path], config.get(path) end end - context "with no value set" do - let(:path) { "main/frontend" } - it "returns the empty string" do + context 'with no value set' do + let(:path) { 'main/frontend' } + it 'returns the empty string' do assert_empty config[path] end - context "given default value" do - let(:default) { "my default value" } - it "returns empty string" do + context 'given default value' do + let(:default) { 'my default value' } + it 'returns empty string' do assert_empty config[path, default] end end end end - context "given non-existent path" do - let(:path) { "main/foobar" } - it "returns the empty string" do + context 'given non-existent path' do + let(:path) { 'main/foobar' } + it 'returns the empty string' do assert_empty config[path] end - context "given default value" do - let(:default) { "my default value" } - it "returns default value" do + context 'given default value' do + let(:default) { 'my default value' } + it 'returns default value' do assert_equal default, config[path, default] end end diff --git a/spec/cztop/frame_spec.rb b/spec/cztop/frame_spec.rb index c9c33e9..73c9fcd 100644 --- a/spec/cztop/frame_spec.rb +++ b/spec/cztop/frame_spec.rb @@ -1,29 +1,31 @@ +# frozen_string_literal: true + require_relative 'spec_helper' describe CZTop::Frame do - include_examples "has FFI delegate" + include_examples 'has FFI delegate' - describe ".send_to" do + describe '.send_to' do Given(:frame) { CZTop::Frame.new } - Given(:socket) { double() } # doesn't matter - it "delegates it to CZMQ::FFI" do + Given(:socket) { double } # doesn't matter + it 'delegates it to CZMQ::FFI' do expect(CZMQ::FFI::Zframe).to receive(:send) frame.send_to(socket) end - describe "with MORE option set" do - it "provides correct flags" do + describe 'with MORE option set' do + it 'provides correct flags' do provided_flags = nil - expect(CZMQ::FFI::Zframe).to receive(:send) do |_,_,flags| + expect(CZMQ::FFI::Zframe).to receive(:send) do |_, _, flags| provided_flags = flags end.and_return(0) frame.send_to(socket, more: true) assert_operator CZTop::Frame::FLAG_MORE & provided_flags, :>, 0 end end - describe "with DONTWAIT set" do - it "provides correct flags" do + describe 'with DONTWAIT set' do + it 'provides correct flags' do provided_flags = nil - expect(CZMQ::FFI::Zframe).to receive(:send) do |_,_,flags| + expect(CZMQ::FFI::Zframe).to receive(:send) do |_, _, flags| provided_flags = flags end.and_return(0) frame.send_to(socket, dontwait: true) @@ -36,7 +38,7 @@ Then { result == Failure(IO::EAGAINWaitWritable) } end end - describe "with a surviving zframe_t" do + describe 'with a surviving zframe_t' do # this is the case if: # * there's an error, or # * the REUSE flag was set @@ -44,18 +46,18 @@ let(:current_delegate) { frame.ffi_delegate } let!(:old_delegate) { frame.ffi_delegate } - describe "with REUSE option set" do - it "provides correct flags" do + describe 'with REUSE option set' do + it 'provides correct flags' do provided_flags = nil - expect(CZMQ::FFI::Zframe).to receive(:send) do |zframe,_,flags| + expect(CZMQ::FFI::Zframe).to receive(:send) do |zframe, _, flags| provided_flags = flags zframe.__ptr_give_ref # detach, so it won't try to free() end.and_return(0) frame.send_to(socket, reuse: true) assert_operator CZTop::Frame::FLAG_REUSE & provided_flags, :>, 0 end - it "wraps native counterpart in new Zframe" do - expect(CZMQ::FFI::Zframe).to receive(:send) do |zframe,_,_| + it 'wraps native counterpart in new Zframe' do + expect(CZMQ::FFI::Zframe).to receive(:send) do |zframe, _, _| zframe.__ptr_give_ref # detach, so it won't try to free() end.and_return(0) frame.send_to(socket, reuse: true) @@ -65,18 +67,18 @@ describe "when there's an error" do # avoid memory leak before do - expect(CZMQ::FFI::Zframe).to receive(:send) do |zframe,_,_| + expect(CZMQ::FFI::Zframe).to receive(:send) do |zframe, _, _| zframe.__ptr_give_ref # detach, so it won't try to free() end.and_return(-1) end let(:expected_return_code) { -1 } # fake an error - it "wraps native counterpart in new Zframe" do + it 'wraps native counterpart in new Zframe' do # NOTE: This is to avoid a memory leak. frame.send_to(socket) rescue nil refute_same old_delegate, current_delegate end - it "raises" do + it 'raises' do assert_raises(SystemCallError) do frame.send_to(socket) end @@ -85,202 +87,203 @@ end end - describe ".receive_from" do - let(:source) { double("source") } + describe '.receive_from' do + let(:source) { double('source') } let(:frame_delegate) { CZTop::Frame.new.ffi_delegate } before do expect(CZMQ::FFI::Zframe).to( - receive(:recv).with(source).and_return(frame_delegate)) + receive(:recv).with(source).and_return(frame_delegate) + ) end - it "receives frame from source" do + it 'receives frame from source' do assert_equal frame_delegate, - CZTop::Frame.receive_from(source).ffi_delegate + CZTop::Frame.receive_from(source).ffi_delegate end end - describe "#initialize" do - context "given content" do - let(:content) { "foobar" } + describe '#initialize' do + context 'given content' do + let(:content) { 'foobar' } let(:frame) { described_class.new content } - it "initializes frame with content" do + it 'initializes frame with content' do assert_equal content, frame.content end end - context "given no content" do + context 'given no content' do let(:frame) { described_class.new } - it "initializes empty frame" do + it 'initializes empty frame' do assert_empty frame end - it "has empty string as content" do - assert_equal "", frame.content + it 'has empty string as content' do + assert_equal '', frame.content end end end - describe "#size" do - Given(:content) { "foobar" } + describe '#size' do + Given(:content) { 'foobar' } Given(:frame) { described_class.new(content) } Then { content.bytesize == frame.size } end - describe "#empty" do - context "given empty frame" do + describe '#empty' do + context 'given empty frame' do let(:frame) { described_class.new } - it "returns true" do + it 'returns true' do assert_operator frame, :empty? end end - context "given non-empty frame" do - let(:frame) { described_class.new("foo") } - it "returns false" do + context 'given non-empty frame' do + let(:frame) { described_class.new('foo') } + it 'returns false' do refute_operator frame, :empty? end end end - describe "#content" do - let(:content) { "foobar" } + describe '#content' do + let(:content) { 'foobar' } let(:frame) { described_class.new(content) } - it "returns its content as a String" do + it 'returns its content as a String' do assert_equal content, frame.content end - it "has alias #to_s" do + it 'has alias #to_s' do assert_equal content, frame.to_s end - it "returns content as binary string" do + it 'returns content as binary string' do assert_equal Encoding::BINARY, frame.to_s.encoding end end - describe "#content=" do + describe '#content=' do Given(:frame) { described_class.new } When { frame.content = content } - context "with text content" do - Given(:content) { "foobar" } + context 'with text content' do + Given(:content) { 'foobar' } # doesn't include trailing null byte Then { content == frame.content } And { content.bytesize == frame.size } end - context "with binary content" do - Given(:content) { "foobar".encode!(Encoding::BINARY) } + context 'with binary content' do + Given(:content) { (+'foobar').encode!(Encoding::BINARY) } Then { content == frame.content } Then { content.bytesize == frame.size } end end - describe "#dup" do - context "given frame and its duplicate" do - Given(:frame) { described_class.new("foo") } + describe '#dup' do + context 'given frame and its duplicate' do + Given(:frame) { described_class.new('foo') } When(:duplicate_frame) { frame.dup } Then { frame == duplicate_frame } # equal frame And { frame.content == duplicate_frame.content } # same content - And { not frame.equal?(duplicate_frame) } # not same object + And { !frame.equal?(duplicate_frame) } # not same object end end - describe "#more?" do + describe '#more?' do Given(:frame) { described_class.new } - context "given Frame with MORE indicator set" do + context 'given Frame with MORE indicator set' do When { frame.more = true } Then { frame.more? } end - context "given Frame with MORE indicator NOT set" do + context 'given Frame with MORE indicator NOT set' do When { frame.more = false } - Then { not frame.more? } + Then { !frame.more? } end end - describe "#more=" do + describe '#more=' do Given(:frame) { described_class.new } - Then { not frame.more? } + Then { !frame.more? } - context "when setting to true" do + context 'when setting to true' do When { frame.more = true } Then { frame.more? } end - context "when setting to false" do + context 'when setting to false' do When { frame.more = false } - Then { not frame.more? } + Then { !frame.more? } end end - describe "#==" do - let(:frame) { described_class.new("foo") } - context "given identical other frame" do - let(:other_frame) { described_class.new("foo") } - it "is equal" do + describe '#==' do + let(:frame) { described_class.new('foo') } + context 'given identical other frame' do + let(:other_frame) { described_class.new('foo') } + it 'is equal' do assert_operator frame, :==, other_frame assert_operator other_frame, :==, frame end - context "given other frame has MORE flag set" do - let(:other_frame) { f=described_class.new("foo"); f.more=true; f } - it "is still equal" do + context 'given other frame has MORE flag set' do + let(:other_frame) { f = described_class.new('foo'); f.more = true; f } + it 'is still equal' do assert_operator frame, :==, other_frame end end end - context "given different other frame" do - let(:other_frame) { described_class.new("bar") } - it "is not equal" do + context 'given different other frame' do + let(:other_frame) { described_class.new('bar') } + it 'is not equal' do refute_operator frame, :==, other_frame refute_operator other_frame, :==, frame end end end - describe "#routing_id", if: has_czmq_drafts? do + describe '#routing_id', if: has_czmq_drafts? do Given(:frame) { described_class.new } - context "with no routing ID set" do + context 'with no routing ID set' do Then { frame.routing_id == 0 } end - context "with routing ID set" do - Given(:new_routing_id) { 123456 } + context 'with routing ID set' do + Given(:new_routing_id) { 123_456 } When { frame.routing_id = new_routing_id } Then { frame.routing_id == new_routing_id } end end - describe "#routing_id=", if: has_czmq_drafts? do + describe '#routing_id=', if: has_czmq_drafts? do Given(:frame) { described_class.new } - context "with valid routing ID" do + context 'with valid routing ID' do # code duplication for completeness' sake - Given(:new_routing_id) { 123456 } + Given(:new_routing_id) { 123_456 } When { frame.routing_id = new_routing_id } Then { frame.routing_id == new_routing_id } end - context "with negative routing ID" do - Given(:new_routing_id) { -123456 } + context 'with negative routing ID' do + Given(:new_routing_id) { -123_456 } When(:result) { frame.routing_id = new_routing_id } Then { result == Failure(RangeError) } end - context "with too big routing ID" do - Given(:new_routing_id) { 123456345676543456765 } + context 'with too big routing ID' do + Given(:new_routing_id) { 123_456_345_676_543_456_765 } When(:result) { frame.routing_id = new_routing_id } Then { result == Failure(RangeError) } end end - describe "#group", if: has_czmq_drafts? do + describe '#group', if: has_czmq_drafts? do Given(:frame) { described_class.new } - context "with no group set" do - Then { frame.group == nil } + context 'with no group set' do + Then { frame.group.nil? } end - context "with empty group set" do + context 'with empty group set' do before do - allow(subject.ffi_delegate).to receive(:group) { "" } + allow(subject.ffi_delegate).to receive(:group) { '' } end it 'returns nil' do @@ -288,25 +291,25 @@ end end - context "with group set" do - Given(:new_group) { "group1" } + context 'with group set' do + Given(:new_group) { 'group1' } When { frame.group = new_group } Then { frame.group == new_group } end end - describe "#group=", if: has_czmq_drafts? do + describe '#group=', if: has_czmq_drafts? do Given(:frame) { described_class.new } - context "with valid group" do + context 'with valid group' do # code duplication for completeness' sake - Given(:new_group) { "group1" } + Given(:new_group) { 'group1' } When { frame.group = new_group } Then { frame.group == new_group } end - context "with too long group" do - Given(:new_group) { "x" * 256 } + context 'with too long group' do + Given(:new_group) { 'x' * 256 } When(:result) { frame.group = new_group } Then { result == Failure(ArgumentError) } end diff --git a/spec/cztop/has_ffi_delegate_spec.rb b/spec/cztop/has_ffi_delegate_spec.rb index 8554b8c..21995ce 100644 --- a/spec/cztop/has_ffi_delegate_spec.rb +++ b/spec/cztop/has_ffi_delegate_spec.rb @@ -1,16 +1,32 @@ +# frozen_string_literal: true + require_relative '../spec_helper' describe CZTop::HasFFIDelegate do let(:delegate_class) do Class.new do - def initialize(ptr) @ptr = ptr end - def to_ptr() @ptr end - def null?() @ptr.nil? end - def foo() :foo end + def initialize(ptr) + @ptr = ptr + end + + + def to_ptr + @ptr + end + + + def null? + @ptr.nil? + end + + + def foo + :foo + end end end - let(:ptr) { "some pointer" } + let(:ptr) { 'some pointer' } let(:delegate) { delegate_class.new(ptr) } let(:delegator_class) do Class.new do @@ -20,11 +36,11 @@ def foo() :foo end end let(:delegator) { delegator_class.new } - describe ".ffi_delegate" do + describe '.ffi_delegate' do let(:method) { :m1 } - it "defines delegator method" do - expect(delegator_class).to receive(:def_delegator). - with(:@ffi_delegate, method) + it 'defines delegator method' do + expect(delegator_class).to receive(:def_delegator) + .with(:@ffi_delegate, method) delegator_class.ffi_delegate(method) end @@ -35,45 +51,45 @@ def foo() :foo end end end - describe "#ffi_delegate" do - context "with no delegate attached" do - it "returns nil" do + describe '#ffi_delegate' do + context 'with no delegate attached' do + it 'returns nil' do assert_nil delegator.ffi_delegate end end - context "with delegate attached" do + context 'with delegate attached' do before { delegator.attach_ffi_delegate(delegate) } - it "returns delegate" do + it 'returns delegate' do assert_same delegator.ffi_delegate, delegate end end end - describe "#to_ptr" do + describe '#to_ptr' do before { delegator.attach_ffi_delegate(delegate) } - it "returns pointer" do + it 'returns pointer' do assert_same ptr, delegator.to_ptr end - it "delegates" do + it 'delegates' do expect(delegate).to receive(:to_ptr) delegator.to_ptr end end - describe "#attach_ffi_delegate" do - context "with valid delegate" do - it "attaches delegate" do + describe '#attach_ffi_delegate' do + context 'with valid delegate' do + it 'attaches delegate' do delegator.attach_ffi_delegate(delegate) assert_same delegate, delegator.ffi_delegate end end - context "with nullified delegate" do + context 'with nullified delegate' do let(:ptr) { nil } # represents nullpointer before do expect(CZMQ::FFI::Errors).to receive(:errno) .and_return(Errno::EINVAL::Errno) end - it "raises" do + it 'raises' do assert_raises(ArgumentError) do delegator.attach_ffi_delegate(delegate) end @@ -81,22 +97,22 @@ def foo() :foo end end end - describe "#from_ffi_delegate" do - let(:arg) { "foo" } - it "delegates to class method equivalent" do + describe '#from_ffi_delegate' do + let(:arg) { 'foo' } + it 'delegates to class method equivalent' do expect(delegator_class).to \ receive(:from_ffi_delegate).with(arg) delegator.from_ffi_delegate(arg) end end - describe ".from_ffi_delegate" do + describe '.from_ffi_delegate' do let(:obj) { delegator_class.from_ffi_delegate(delegate) } - it "creates a fresh object" do + it 'creates a fresh object' do assert_instance_of delegator_class, obj end - it "attaches delegate" do + it 'attaches delegate' do assert_same delegate, obj.ffi_delegate end diff --git a/spec/cztop/message/frames_spec.rb b/spec/cztop/message/frames_spec.rb index e451446..ae71594 100644 --- a/spec/cztop/message/frames_spec.rb +++ b/spec/cztop/message/frames_spec.rb @@ -1,47 +1,48 @@ +# frozen_string_literal: true + require_relative '../../spec_helper' describe CZTop::Message do subject { CZTop::Message.new } - context "empty message" do - describe "#size" do - it "return zero" do + context 'empty message' do + describe '#size' do + it 'return zero' do assert_equal 0, subject.size end end end - describe "#frames" do + describe '#frames' do let(:frames) { subject.frames } - it "returns FramesAccessor" do + it 'returns FramesAccessor' do assert_kind_of CZTop::Message::FramesAccessor, frames end end end describe CZTop::Message::FramesAccessor do - - it "is enumerable" do + it 'is enumerable' do assert_operator described_class, :<, Enumerable end let(:frames) { msg.frames } let(:msg) { CZTop::Message.new(frame_contents) } - context "message with content" do - let(:frame_contents) { %w[ foo bar baz ] } + context 'message with content' do + let(:frame_contents) { %w[foo bar baz] } - describe "#first" do - it "returns first frame" do - assert_equal "foo", frames.first.to_s + describe '#first' do + it 'returns first frame' do + assert_equal 'foo', frames.first.to_s end end - describe "#last" do - it "returns last frame" do - assert_equal "baz", frames.last.to_s + describe '#last' do + it 'returns last frame' do + assert_equal 'baz', frames.last.to_s end end - describe "#[]" do - it "returns correct frame" do + describe '#[]' do + it 'returns correct frame' do assert_equal frames.to_a[0], frames[0] assert_equal frames.to_a[1], frames[1] assert_equal frames.to_a[2], frames[2] @@ -49,31 +50,31 @@ assert_nil frames[99] end end - describe "#each" do - it "yields frames" do + describe '#each' do + it 'yields frames' do frames.each { |frame| assert_kind_of CZTop::Frame, frame } end - it "yields all frames" do + it 'yields all frames' do assert_equal frame_contents, frames.to_a.map(&:to_s) end end end - context "message with no content" do + context 'message with no content' do let(:frame_contents) { [] } - describe "#first" do - it "returns nil" do + describe '#first' do + it 'returns nil' do assert_nil frames.first end end - describe "#last" do - it "returns nil" do + describe '#last' do + it 'returns nil' do assert_nil frames.last end end - describe "#[]" do - it "returns nil" do + describe '#[]' do + it 'returns nil' do assert_nil frames[0] assert_nil frames[1] assert_nil frames[2] @@ -81,7 +82,7 @@ assert_nil frames[99] end end - describe "#each" do + describe '#each' do it "doesn't yield" do frames.each { flunk } end diff --git a/spec/cztop/message_spec.rb b/spec/cztop/message_spec.rb index ffe2f2c..6957a69 100644 --- a/spec/cztop/message_spec.rb +++ b/spec/cztop/message_spec.rb @@ -1,392 +1,394 @@ +# frozen_string_literal: true + require_relative 'spec_helper' describe CZTop::Message do - include_examples "has FFI delegate" + include_examples 'has FFI delegate' let(:msg) { CZTop::Message.new } let(:ffi_delegate) { msg.ffi_delegate } - describe "#initialize" do + describe '#initialize' do subject { CZTop::Message.new } - context "with initial string" do - let(:content) { "foo" } + context 'with initial string' do + let(:content) { 'foo' } subject { described_class.new(content) } - it "sets content" do + it 'sets content' do assert_equal content, subject.frames.first.to_s end - it "has one frame" do + it 'has one frame' do assert_equal 1, subject.frames.count end end - context "with array of strings" do - let(:parts) { [ "foo", "", "bar"] } + context 'with array of strings' do + let(:parts) { ['foo', '', 'bar'] } let(:msg) { described_class.new(parts) } - it "takes them as frames" do + it 'takes them as frames' do assert_equal parts.size, msg.size assert_equal parts, msg.frames.map(&:to_s) end end end - describe ".coerce" do - context "with a Message" do - it "takes the Message as is" do + describe '.coerce' do + context 'with a Message' do + it 'takes the Message as is' do assert_same msg, described_class.coerce(msg) end end - context "with a String" do - let(:content) { "foobar" } + context 'with a String' do + let(:content) { 'foobar' } let(:coerced_msg) { described_class.coerce(content) } - it "creates a new Message from the String" do + it 'creates a new Message from the String' do assert_kind_of described_class, coerced_msg assert_equal 1, coerced_msg.size assert_equal content, coerced_msg.frames.first.to_s end end - context "with a Frame" do - Given(:frame_content) { "foobar special content" } + context 'with a Frame' do + Given(:frame_content) { 'foobar special content' } Given(:frame) { CZTop::Frame.new(frame_content) } When(:coerced_msg) { described_class.coerce(frame) } - Then { coerced_msg.kind_of? described_class } + Then { coerced_msg.is_a? described_class } And { coerced_msg.size == 1 } And { coerced_msg.frames.first.to_s == frame_content } end - context "with array of strings" do - let(:parts) { [ "foo", "", "bar"] } + context 'with array of strings' do + let(:parts) { ['foo', '', 'bar'] } let(:coerced_msg) { described_class.coerce(parts) } - it "takes them as frames" do + it 'takes them as frames' do assert_equal parts.size, coerced_msg.size assert_equal parts, coerced_msg.frames.map(&:to_s) end end - context "given something else" do + context 'given something else' do Given(:something) { Object.new } When(:result) { described_class.coerce(something) } Then { result == Failure(ArgumentError) } end end - describe "#<<" do - Given(:msg) { CZTop::Message.new "foo" } + describe '#<<' do + Given(:msg) { CZTop::Message.new 'foo' } Then { msg.size == 1 } - context "with a string" do - Given(:frame) { "bar" } + context 'with a string' do + Given(:frame) { 'bar' } When { msg << frame } Then { msg.size == 2 } And { msg.to_a == %w[foo bar] } - context "when this fails" do + context 'when this fails' do before do expect(ffi_delegate).to receive(:addmem).and_return(-1) expect(CZMQ::FFI::Errors).to receive(:errno) .and_return(Errno::EPERM::Errno) end - it "raises" do + it 'raises' do assert_raises(Errno::EPERM) { msg << frame } end end end - context "with binary data" do + context 'with binary data' do Given(:frame) { "foo\x08\0\0bar\0\0\0\x11" } # contains NULL bytes When { msg << frame } Then { msg.size == 2 } And { msg[-1] == frame } end - context "with a frame" do - Given(:frame) { CZTop::Frame.new("bar") } + context 'with a frame' do + Given(:frame) { CZTop::Frame.new('bar') } When { msg << frame } Then { msg.size == 2 } And { msg.to_a == %w[foo bar] } - context "when this fails" do + context 'when this fails' do before do expect(ffi_delegate).to receive(:append).and_return(-1) expect(CZMQ::FFI::Errors).to receive(:errno) .and_return(Errno::EPERM::Errno) end - it "raises" do + it 'raises' do assert_raises(Errno::EPERM) { msg << frame } end end end - context "with something else" do + context 'with something else' do Given(:frame) { Object.new } When(:result) { msg << frame } Then { result == Failure(ArgumentError) } end - context "method chaining" do - When { msg << "FOO" << "BAR" } - Then { msg.to_a == %w[ foo FOO BAR ] } + context 'method chaining' do + When { msg << 'FOO' << 'BAR' } + Then { msg.to_a == %w[foo FOO BAR] } end end - describe "#prepend" do - Given(:msg) { CZTop::Message.new "foo" } + describe '#prepend' do + Given(:msg) { CZTop::Message.new 'foo' } Then { msg.size == 1 } - context "with a string" do - Given(:frame) { "bar" } + context 'with a string' do + Given(:frame) { 'bar' } When { msg.prepend frame } Then { msg.size == 2 } And { msg.to_a == %w[bar foo] } end - context "with binary data" do + context 'with binary data' do Given(:frame) { "foo\0\0\0bar" } # contains NULL byte When { msg.prepend frame } Then { msg.size == 2 } And { msg[0] == frame } - context "when this fails" do + context 'when this fails' do before do expect(ffi_delegate).to receive(:pushmem).and_return(-1) expect(CZMQ::FFI::Errors).to receive(:errno) .and_return(Errno::EPERM::Errno) end - it "raises" do + it 'raises' do assert_raises(Errno::EPERM) { msg.prepend frame } end end end - context "with a frame" do - Given(:frame) { CZTop::Frame.new("bar") } + context 'with a frame' do + Given(:frame) { CZTop::Frame.new('bar') } When { msg.prepend frame } Then { msg.size == 2 } And { msg.to_a == %w[bar foo] } - context "when this fails" do + context 'when this fails' do before do expect(ffi_delegate).to receive(:prepend).and_return(-1) expect(CZMQ::FFI::Errors).to receive(:errno) .and_return(Errno::EPERM::Errno) end - it "raises" do + it 'raises' do assert_raises(Errno::EPERM) { msg.prepend frame } end end end - context "with something else" do + context 'with something else' do Given(:frame) { Object.new } When(:result) { msg.prepend frame } Then { result == Failure(ArgumentError) } end end - describe "#pop" do - before { subject << "FOO" << "BAR" } - it "returns first part" do - assert_equal "FOO", subject.pop + describe '#pop' do + before { subject << 'FOO' << 'BAR' } + it 'returns first part' do + assert_equal 'FOO', subject.pop end - it "removes it from message" do + it 'removes it from message' do subject.pop assert_equal %w[BAR], subject.to_a end end - describe "#send_to" do - let(:destination) { double "destination socket" } - context "when successful" do + describe '#send_to' do + let(:destination) { double 'destination socket' } + context 'when successful' do after { msg.send_to(destination) } - it "sends its delegate to the destination" do + it 'sends its delegate to the destination' do expect(CZMQ::FFI::Zmsg).to receive(:send).with(ffi_delegate, destination) - .and_return(0) + .and_return(0) end end - context "when NOT successful" do + context 'when NOT successful' do before do expect(CZMQ::FFI::Zmsg).to receive(:send).with(ffi_delegate, destination) - .and_return(-1) + .and_return(-1) expect(CZMQ::FFI::Errors).to receive(:errno) .and_return(errno) end - context "with sndtimeo reached" do + context 'with sndtimeo reached' do let(:errno) { Errno::EAGAIN::Errno } - it "raises IO::EAGAINWaitWritable" do + it 'raises IO::EAGAINWaitWritable' do assert_raises(IO::EAGAINWaitWritable) { msg.send_to(destination) } end end - context "with host unreachable" do + context 'with host unreachable' do # NOTE: unroutable message given to ROUTER with ROUTER_MANDATORY # option set. let(:errno) { Errno::EHOSTUNREACH::Errno } - it "raises" do + it 'raises' do assert_raises(SocketError) { msg.send_to(destination) } end end - context "with other error" do + context 'with other error' do let(:errno) { Errno::EPERM::Errno } - it "raises" do + it 'raises' do assert_raises(Errno::EPERM) { msg.send_to(destination) } end end end end - describe ".receive_from" do + describe '.receive_from' do let(:received_message) { CZTop::Message.receive_from(src) } - let(:src) { double "source" } - context "when successful" do - it "receives message from source" do + let(:src) { double 'source' } + context 'when successful' do + it 'receives message from source' do expect(CZMQ::FFI::Zmsg).to receive(:recv).with(src) - .and_return(ffi_delegate) + .and_return(ffi_delegate) assert_kind_of CZTop::Message, received_message assert_same msg.ffi_delegate, received_message.ffi_delegate end end - context "when NOT successful" do + context 'when NOT successful' do let(:nullptr) { ::FFI::Pointer::NULL } before do expect(CZMQ::FFI).to receive(:zmsg_recv).and_return(nullptr) expect(CZMQ::FFI::Errors).to receive(:errno) .and_return(errno) end - context "when interrupted" do + context 'when interrupted' do let(:errno) { Errno::EINTR::Errno } - it "raises Interrupt" do + it 'raises Interrupt' do assert_raises(Interrupt) { received_message } end end - context "with rcvtimeo reached" do + context 'with rcvtimeo reached' do let(:errno) { Errno::EAGAIN::Errno } - it "raises IO::EAGAINWaitReadable" do + it 'raises IO::EAGAINWaitReadable' do assert_raises(IO::EAGAINWaitReadable) { received_message } end end - context "with other error" do + context 'with other error' do let(:errno) { Errno::EPERM::Errno } - it "raises RuntimeError" do + it 'raises RuntimeError' do assert_raises(Errno::EPERM) { received_message } end end end end - describe "#empty?" do - context "with no content" do + describe '#empty?' do + context 'with no content' do Then { subject.empty? } end - context "with content" do - subject { CZTop::Message.new "foo" } - Then { ! subject.empty? } + context 'with content' do + subject { CZTop::Message.new 'foo' } + Then { !subject.empty? } end end - describe "#content_size" do - context "with no content" do - it "has content size zero" do + describe '#content_size' do + context 'with no content' do + it 'has content size zero' do assert_equal 0, subject.content_size end end - context "with content" do - subject { CZTop::Message.new "foo" } - it "returns correct content size" do + context 'with content' do + subject { CZTop::Message.new 'foo' } + it 'returns correct content size' do assert_equal 3, subject.content_size end end end - describe "#to_a" do - context "with no frames" do + describe '#to_a' do + context 'with no frames' do Then { [] == subject.to_a } end - context "with frames" do - Given(:parts) { %w[ foo bar ] } + context 'with frames' do + Given(:parts) { %w[foo bar] } subject { CZTop::Message.new parts } Then { parts == subject.to_a } end end - describe "#inspect" do - let(:s) { msg.inspect} - context "with empty message" do - it "contains class name" do + describe '#inspect' do + let(:s) { msg.inspect } + context 'with empty message' do + it 'contains class name' do assert_match /\A#\z/, s end - it "contains native address" do + it 'contains native address' do assert_match /:0x[[:xdigit:]]+\b/, s end - it "contains number of frames" do + it 'contains number of frames' do assert_match /\bframes=0\b/, s end - it "contains content size" do + it 'contains content size' do assert_match /\bcontent_size=0\b/, s end - it "contains empty content description" do + it 'contains empty content description' do assert_match /\bcontent=\[\]/, s end end - context "with content" do - before { msg << "FOO" << "BAR" } - it "contains number of frames" do + context 'with content' do + before { msg << 'FOO' << 'BAR' } + it 'contains number of frames' do assert_match /\bframes=2\b/, s end - it "contains content size" do + it 'contains content size' do assert_match /\bcontent_size=6\b/, s end - it "contains content description" do + it 'contains content description' do assert_match /\bcontent=\[.+\]/, s end end - context "with huge message" do - before { msg << "FOO" * 1000 } # 3000 byte message - it "contains content placeholder" do + context 'with huge message' do + before { msg << 'FOO' * 1000 } # 3000 byte message + it 'contains content placeholder' do assert_match /\bcontent=\[\.\.\.\]/, s end end end - describe "#[]" do - context "with existing frame" do - subject { CZTop::Message.new %w[ foo ] } - Then { "foo" == subject[0] } + describe '#[]' do + context 'with existing frame' do + subject { CZTop::Message.new %w[foo] } + Then { 'foo' == subject[0] } end - context "with non-existing frame" do - subject { CZTop::Message.new %w[ foo ] } + context 'with non-existing frame' do + subject { CZTop::Message.new %w[foo] } Then { subject[1].nil? } end end - describe "#routing_id", if: has_czmq_drafts? do - context "with no routing ID set" do + describe '#routing_id', if: has_czmq_drafts? do + context 'with no routing ID set' do Then { msg.routing_id == 0 } end - context "with routing ID set" do - Given(:routing_id) { 12345 } + context 'with routing ID set' do + Given(:routing_id) { 12_345 } When { msg.routing_id = routing_id } Then { msg.routing_id == routing_id } end end - describe "#routing_id=", if: has_czmq_drafts? do - context "with valid routing ID" do + describe '#routing_id=', if: has_czmq_drafts? do + context 'with valid routing ID' do # code duplication for completeness' sake - Given(:new_routing_id) { 123456 } + Given(:new_routing_id) { 123_456 } When { msg.routing_id = new_routing_id } Then { msg.routing_id == new_routing_id } end - context "with negative routing ID" do - Given(:new_routing_id) { -123456 } + context 'with negative routing ID' do + Given(:new_routing_id) { -123_456 } When(:result) { msg.routing_id = new_routing_id } Then { result == Failure(RangeError) } end - context "with too big routing ID" do - Given(:new_routing_id) { 123456345676543456765 } + context 'with too big routing ID' do + Given(:new_routing_id) { 123_456_345_676_543_456_765 } When(:result) { msg.routing_id = new_routing_id } Then { result == Failure(RangeError) } end - context "with non-integer" do - Given(:new_routing_id) { "foo" } + context 'with non-integer' do + Given(:new_routing_id) { 'foo' } When(:result) { msg.routing_id = new_routing_id } Then { result == Failure(ArgumentError) } end diff --git a/spec/cztop/metadata_spec.rb b/spec/cztop/metadata_spec.rb index 68e0e65..0185755 100644 --- a/spec/cztop/metadata_spec.rb +++ b/spec/cztop/metadata_spec.rb @@ -1,193 +1,195 @@ +# frozen_string_literal: true + require_relative 'spec_helper' describe CZTop::Metadata do subject { described_class } let(:properties) do - { foo: "A", bar: "B", baz: "C" } + { foo: 'A', bar: 'B', baz: 'C' } end let(:serialized) do - "\x03foo\x00\x00\x00\x01A" + - "\x03bar\x00\x00\x00\x01B" + - "\x03baz\x00\x00\x00\x01C" + "\x03foo\x00\x00\x00\x01A" \ + "\x03bar\x00\x00\x00\x01B" \ + "\x03baz\x00\x00\x00\x01C" end - describe ".dump" do - context "with a single property" do + describe '.dump' do + context 'with a single property' do let(:name) { :foo } - let(:value) { "barbaz" } - let(:property) { { name => value} } + let(:value) { 'barbaz' } + let(:property) { { name => value } } - let(:encoded_name_length) { [name.to_s.size].pack("C") } - let(:encoded_value_length) { [value.to_s.size].pack("N") } + let(:encoded_name_length) { [name.to_s.size].pack('C') } + let(:encoded_value_length) { [value.to_s.size].pack('N') } let(:serialized) do "#{encoded_name_length}#{name}#{encoded_value_length}#{value}" end - it "encodes correctly" do + it 'encodes correctly' do assert_equal serialized, subject.dump(property) end - context "with too long property name" do - let(:name) { ("f" * 256).to_sym } - it "raises" do + context 'with too long property name' do + let(:name) { ('f' * 256).to_sym } + it 'raises' do assert_raises(ArgumentError) do subject.dump(property) end end end - context "with too long data" do + context 'with too long data' do let(:value) { double(to_s: value_string) } let(:value_string) { double(bytesize: 2**31) } - it "raises" do + it 'raises' do assert_raises(ArgumentError) { subject.dump(property) } end end end - context "with multiple properties" do - it "encodes correctly" do + context 'with multiple properties' do + it 'encodes correctly' do assert_equal serialized, subject.dump(properties) end end - context "with case-insensitively duplicate names" do - let(:properties) { { foo: "A", FOO: "B" } } - it "raises" do + context 'with case-insensitively duplicate names' do + let(:properties) { { foo: 'A', FOO: 'B' } } + it 'raises' do assert_raises(ArgumentError) { subject.dump(properties) } end end - context "with zero-length property names" do - let(:properties) { { :"" => "A", foo: "B" } } - it "raises" do + context 'with zero-length property names' do + let(:properties) { { "": 'A', foo: 'B' } } + it 'raises' do assert_raises(ArgumentError) do subject.dump(properties) end end end - context "with zero-length values" do - let(:properties) { { a: "" } } + context 'with zero-length values' do + let(:properties) { { a: '' } } let(:serialized) { "\x01a\x00\x00\x00\x00" } - it "is encodes correctly" do + it 'is encodes correctly' do assert_equal serialized, subject.dump(properties) end end - context "with invalid property names" do + context 'with invalid property names' do let(:bad_names) do [ - :"abc/foo", - "@abc", - "%", - "#", - "!", - ":name", - "~", - "(", - ")", - "}", - "=", - :"foo;bar", + :'abc/foo', + '@abc', + '%', + '#', + '!', + ':name', + '~', + '(', + ')', + '}', + '=', + :'foo;bar' ] end - it "raises" do + it 'raises' do bad_names.each do |name| assert_raises(ArgumentError) do - subject.dump(name => "") + subject.dump(name => '') end end end end end - describe ".load" do - it "decodes correctly" do + describe '.load' do + it 'decodes correctly' do deserialized = subject.load(serialized) - properties.each do |name,value| + properties.each do |name, value| assert_equal value, deserialized[name] end end - context "with zero-length values" do + context 'with zero-length values' do let(:serialized) { "\x01x\x00\x00\x00\x00" } - it "is decodes correctly" do - assert_equal "", subject.load(serialized)[:x] + it 'is decodes correctly' do + assert_equal '', subject.load(serialized)[:x] end end InvalidData = CZTop::Metadata::InvalidData - context "with zero-length property names" do + context 'with zero-length property names' do let(:serialized) do "\x00\x00\x00\x00\x01A" # "" => "A" end - it "raises" do + it 'raises' do ex = assert_raises(InvalidData) { subject.load(serialized) } assert_match /zero-length property name/, ex.message end end - context "with case-insensitively duplicate names" do + context 'with case-insensitively duplicate names' do let(:serialized) { "\x01x\x00\x00\x00\x00\x01X\x00\x00\x00\x00" } - it "raises" do + it 'raises' do ex = assert_raises(InvalidData) { subject.load(serialized) } assert_match /duplicate name/, ex.message end end - context "with cut-off value length" do + context 'with cut-off value length' do let(:serialized) { "\x01x\x00\x00\x00" } - it "raises" do + it 'raises' do ex = assert_raises(InvalidData) { subject.load(serialized) } assert_match /incomplete length/, ex.message end end - context "with cut-off value" do + context 'with cut-off value' do let(:serialized) { "\x01x\x00\x00\x00\x06fooba" } - it "raises" do + it 'raises' do ex = assert_raises(InvalidData) { subject.load(serialized) } assert_match /incomplete value/, ex.message end end end - describe "#initialize" do - context "with properties" do + describe '#initialize' do + context 'with properties' do subject { CZTop::Metadata.new(properties) } let(:properties_before) { properties.dup } before { properties_before } - it "remembers properties as-is" do + it 'remembers properties as-is' do assert_same properties, subject.to_h assert_equal properties_before, subject.to_h end end end - describe "#[]" do + describe '#[]' do subject { CZTop::Metadata.new(properties) } - context "with String property name" do - it "returns correct value" do - assert_equal properties[:foo], subject["fOo"] + context 'with String property name' do + it 'returns correct value' do + assert_equal properties[:foo], subject['fOo'] end end - context "with exact-case Symbol property name" do - it "returns correct value" do + context 'with exact-case Symbol property name' do + it 'returns correct value' do assert_equal properties[:foo], subject[:foo] end end - context "with fuzzy-case Symbol property name" do - it "returns correct value" do + context 'with fuzzy-case Symbol property name' do + it 'returns correct value' do assert_equal properties[:foo], subject[:fOo] end end - context "with inexistent property name" do - it "returns correct value" do - assert_nil subject["doesnt-exist"] + context 'with inexistent property name' do + it 'returns correct value' do + assert_nil subject['doesnt-exist'] end end end - describe "#to_h" do + describe '#to_h' do subject { CZTop::Metadata.new(properties) } let(:properties_before) { properties.dup } before { properties_before } - it "returns properties" do + it 'returns properties' do assert_equal properties_before, subject.to_h end end diff --git a/spec/cztop/monitor_spec.rb b/spec/cztop/monitor_spec.rb index fde8e94..070dd4a 100644 --- a/spec/cztop/monitor_spec.rb +++ b/spec/cztop/monitor_spec.rb @@ -1,7 +1,9 @@ +# frozen_string_literal: true + require_relative '../spec_helper' -describe "CZTop::Monitor::ZMONITOR_FPTR" do - it "points to a dynamic library symbol" do +describe 'CZTop::Monitor::ZMONITOR_FPTR' do + it 'points to a dynamic library symbol' do assert_kind_of FFI::DynamicLibrary::Symbol, CZTop::Monitor::ZMONITOR_FPTR end end @@ -9,8 +11,8 @@ describe CZTop::Monitor do subject { CZTop::Monitor.new(rep_socket) } let(:actor) { subject.actor } - i = 55578 - let(:endpoint) { "tcp://127.0.0.1:#{i+=1}" } + i = 55_578 + let(:endpoint) { "tcp://127.0.0.1:#{i += 1}" } let(:req_socket) { CZTop::Socket::REQ.new(endpoint) } let(:rep_socket) { CZTop::Socket::REP.new(endpoint) } @@ -18,13 +20,13 @@ subject.terminate end - it "initializes and terminates" do + it 'initializes and terminates' do subject end - describe "#initialize" do - context "with socket" do - it "passes socket" do + describe '#initialize' do + context 'with socket' do + it 'passes socket' do expect(CZTop::Actor).to receive(:new) .with(CZTop::Monitor::ZMONITOR_FPTR, rep_socket).and_call_original subject @@ -32,31 +34,31 @@ end end - describe "#verbose" do - it "sends correct message to actor" do - expect(actor).to receive(:<<).with("VERBOSE").and_call_original + describe '#verbose' do + it 'sends correct message to actor' do + expect(actor).to receive(:<<).with('VERBOSE').and_call_original subject.verbose! end end - describe "#listen" do - context "with one valid event" do - let(:event) { "CONNECTED" } + describe '#listen' do + context 'with one valid event' do + let(:event) { 'CONNECTED' } after { subject.listen(event) } - it "tells zmonitor actor" do - expect(actor).to receive(:<<).with(["LISTEN", event]) + it 'tells zmonitor actor' do + expect(actor).to receive(:<<).with(['LISTEN', event]) end end - context "with multiple valid events" do - let(:events) { %w[ CONNECTED DISCONNECTED ] } + context 'with multiple valid events' do + let(:events) { %w[CONNECTED DISCONNECTED] } after { subject.listen(*events) } - it "tells zmonitor actor" do - expect(actor).to receive(:<<).with(["LISTEN", *events]) + it 'tells zmonitor actor' do + expect(actor).to receive(:<<).with(['LISTEN', *events]) end end - context "with invalid event" do + context 'with invalid event' do let(:event) { :FOO } - it "raises" do + it 'raises' do assert_raises(ArgumentError) do subject.listen(event) end @@ -64,31 +66,31 @@ end end - describe "#start" do + describe '#start' do after { subject.start } - it "tells zmonitor to start" do - expect(actor).to receive(:<<).with("START").and_call_original + it 'tells zmonitor to start' do + expect(actor).to receive(:<<).with('START').and_call_original end - it "waits" do + it 'waits' do expect(actor).to receive(:wait).and_call_original end end - describe "#fd" do - it "returns FD" do + describe '#fd' do + it 'returns FD' do assert_equal subject.actor.options.fd, subject.fd end end - describe "#readable?" do - it "returns false if no event is available" do - subject.listen(*%w(ACCEPTED CLOSED MONITOR_STOPPED)) + describe '#readable?' do + it 'returns false if no event is available' do + subject.listen(*%w[ACCEPTED CLOSED MONITOR_STOPPED]) subject.start refute_operator subject, :readable? end - it "returns true if an event is available" do - subject.listen(*%w(ACCEPTED CLOSED MONITOR_STOPPED)) + it 'returns true if an event is available' do + subject.listen(*%w[ACCEPTED CLOSED MONITOR_STOPPED]) subject.start req_socket sleep 0.1 @@ -96,24 +98,24 @@ end end - describe "#next" do - it "returns Message" do - subject.listen(*%w(ACCEPTED CLOSED MONITOR_STOPPED)) + describe '#next' do + it 'returns Message' do + subject.listen(*%w[ACCEPTED CLOSED MONITOR_STOPPED]) subject.actor.options.rcvtimeo = 100 subject.start req_socket # connects assert_kind_of CZTop::Message, subject.next end - it "gets the next event" do - subject.listen(*%w(ACCEPTED CLOSED MONITOR_STOPPED)) + it 'gets the next event' do + subject.listen(*%w[ACCEPTED CLOSED MONITOR_STOPPED]) subject.start req_socket # connects req_socket.disconnect(endpoint) subject.actor.options.rcvtimeo = 100 - assert_equal "ACCEPTED", subject.next[0] + assert_equal 'ACCEPTED', subject.next[0] rep_socket.ffi_delegate.destroy - assert_equal "CLOSED", subject.next[0] - assert_equal "MONITOR_STOPPED", subject.next[0] + assert_equal 'CLOSED', subject.next[0] + assert_equal 'MONITOR_STOPPED', subject.next[0] end end end diff --git a/spec/cztop/poller_spec.rb b/spec/cztop/poller_spec.rb index e5b8d4d..48d131d 100644 --- a/spec/cztop/poller_spec.rb +++ b/spec/cztop/poller_spec.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require_relative 'spec_helper' require 'benchmark' @@ -24,22 +26,22 @@ POLLIN = CZTop::Poller::ZMQ::POLLIN POLLOUT = CZTop::Poller::ZMQ::POLLOUT - describe "#initialize" do - context "with no readers" do - it "initializes empty" do + describe '#initialize' do + context 'with no readers' do + it 'initializes empty' do expect_any_instance_of(CZTop::Poller).not_to receive(:add) end end - context "with one reader" do + context 'with one reader' do let(:socket) { reader1 } after { CZTop::Poller.new(socket) } - it "adds reader" do + it 'adds reader' do expect_any_instance_of(CZTop::Poller).to receive(:add_reader).with(socket) end end - context "with multiple readers" do + context 'with multiple readers' do let(:poller) { CZTop::Poller.new(reader1, reader2) } - it "adds readers" do + it 'adds readers' do # NOTE: # This doesn't work anymore on at least Rubinius 3.28: # expect_any_instance_of(CZTop::Poller).to receive(:add_reader).with(r1) @@ -54,156 +56,156 @@ end end end - describe "#add" do - context "with reader" do + describe '#add' do + context 'with reader' do let(:socket) { reader1 } after do poller.add(socket, POLLIN) assert_includes poller.sockets, reader1 # keeps ref end - it "adds reader socket" do - expect(CZTop::Poller::ZMQ).to receive(:poller_add). - with(poller_ptr, socket_ptr, nil, POLLIN). - and_call_original + it 'adds reader socket' do + expect(CZTop::Poller::ZMQ).to receive(:poller_add) + .with(poller_ptr, socket_ptr, nil, POLLIN) + .and_call_original end end - context "with writer" do + context 'with writer' do let(:socket) { writer1 } after do poller.add(socket, POLLOUT) assert_includes poller.sockets, writer1 # keeps ref end - it "adds writer socket" do - expect(CZTop::Poller::ZMQ).to receive(:poller_add). - with(poller_ptr, socket_ptr, nil, POLLOUT). - and_call_original + it 'adds writer socket' do + expect(CZTop::Poller::ZMQ).to receive(:poller_add) + .with(poller_ptr, socket_ptr, nil, POLLOUT) + .and_call_original end end - context "with non-socket" do - it "raises" do - assert_raises(ArgumentError) { poller.add("foo", POLLOUT) } + context 'with non-socket' do + it 'raises' do + assert_raises(ArgumentError) { poller.add('foo', POLLOUT) } end end end - describe "#add_reader" do + describe '#add_reader' do after { poller.add_reader(reader1) } - it "adds reader" do + it 'adds reader' do expect(poller).to receive(:add).with(reader1, POLLIN) end end - describe "#add_writer" do + describe '#add_writer' do after { poller.add_writer(writer1) } - it "adds writer" do + it 'adds writer' do expect(poller).to receive(:add).with(writer1, POLLOUT) end end - describe "#modify" do - context "with registered socket" do + describe '#modify' do + context 'with registered socket' do let(:socket) { reader1 } let(:events) { POLLIN | POLLOUT } before { poller.add_reader(reader1) } after { poller.modify(reader1, events) } - it "modifies events" do - expect(CZTop::Poller::ZMQ).to receive(:poller_modify). - with(poller_ptr, socket_ptr, events).and_call_original + it 'modifies events' do + expect(CZTop::Poller::ZMQ).to receive(:poller_modify) + .with(poller_ptr, socket_ptr, events).and_call_original end end - context "with unregistered socket" do - it "raises" do + context 'with unregistered socket' do + it 'raises' do assert_raises(ArgumentError) { poller.modify(reader1, POLLIN) } end end end - describe "#remove" do - context "with registered socket" do + describe '#remove' do + context 'with registered socket' do let(:socket) { reader1 } before { poller.add_reader(socket) } after do poller.remove(socket) refute_includes poller.sockets, reader1 # forgets ref end - it "removes reader" do - expect(CZTop::Poller::ZMQ).to receive(:poller_remove). - with(poller_ptr, socket_ptr).and_call_original + it 'removes reader' do + expect(CZTop::Poller::ZMQ).to receive(:poller_remove) + .with(poller_ptr, socket_ptr).and_call_original end end - context "with unregistered reader" do - it "raises" do + context 'with unregistered reader' do + it 'raises' do assert_raises(ArgumentError) { poller.remove(reader1) } end end - context "with non-socket" do - it "raises" do - assert_raises(ArgumentError) { poller.remove("foo") } + context 'with non-socket' do + it 'raises' do + assert_raises(ArgumentError) { poller.remove('foo') } end end end - describe "#remove_reader" do - context "with socket registered for readability only" do + describe '#remove_reader' do + context 'with socket registered for readability only' do let(:socket) { reader1 } before { poller.add_reader(socket) } after do poller.remove_reader(socket) end - it "removes reader" do - expect(poller).to receive(:remove). - with(socket) + it 'removes reader' do + expect(poller).to receive(:remove) + .with(socket) end end - context "with unregistered reader" do - it "raises" do + context 'with unregistered reader' do + it 'raises' do assert_raises(ArgumentError) { poller.remove_reader(reader1) } end end - context "with socket registered for writability" do + context 'with socket registered for writability' do let(:socket) { writer1 } before { poller.add_writer(socket) } - it "raises" do + it 'raises' do assert_raises(ArgumentError) { poller.remove_reader(socket) } end end - context "with socket registered for readability and writability" do + context 'with socket registered for readability and writability' do let(:socket) { CZTop::Socket::DEALER.new(endpoint1) } before { poller.add(socket, POLLIN | POLLOUT) } - it "raises" do + it 'raises' do assert_raises(ArgumentError) { poller.remove_reader(socket) } end end end - describe "#remove_writer" do - context "with socket registered for writability only" do + describe '#remove_writer' do + context 'with socket registered for writability only' do let(:socket) { writer1 } before { poller.add_writer(socket) } after do poller.remove_writer(socket) end - it "removes writer" do - expect(poller).to receive(:remove). - with(socket) + it 'removes writer' do + expect(poller).to receive(:remove) + .with(socket) end end - context "with unregistered writer" do - it "raises" do + context 'with unregistered writer' do + it 'raises' do assert_raises(ArgumentError) { poller.remove_writer(writer1) } end end - context "with socket registered for readability" do + context 'with socket registered for readability' do let(:socket) { reader1 } before { poller.add_reader(socket) } - it "raises" do + it 'raises' do assert_raises(ArgumentError) { poller.remove_writer(socket) } end end - context "with socket registered for readability and writability" do + context 'with socket registered for readability and writability' do let(:socket) { CZTop::Socket::DEALER.new(endpoint1) } before { poller.add(socket, POLLIN | POLLOUT) } - it "raises" do + it 'raises' do assert_raises(ArgumentError) { poller.remove_writer(socket) } end end end - describe "#wait" do - context "in general" do + describe '#wait' do + context 'in general' do let(:poller_ptr) { poller.instance_variable_get(:@poller_ptr) } let(:event_ptr) { poller.instance_variable_get(:@event_ptr) } @@ -217,7 +219,7 @@ end after { poller.wait(15) } - it "passes arguments to zmq_poller_wait()" do + it 'passes arguments to zmq_poller_wait()' do expect(CZTop::Poller::ZMQ).to receive(:poller_wait) .with(poller_ptr, event_ptr, 15).and_return(-1) allow(CZMQ::FFI::Errors).to receive(:errno) @@ -225,43 +227,43 @@ end end - context "with no registered sockets" do + context 'with no registered sockets' do it "doesn't raise" do poller.wait(0) end end - context "with readable socket" do + context 'with readable socket' do before do - writer1 << "foobar" + writer1 << 'foobar' poller.add(reader1, POLLIN) end - it "returns first readable socket" do + it 'returns first readable socket' do assert_same reader1, event.socket assert_operator event, :readable? end end - context "with no readable socket" do + context 'with no readable socket' do before do poller.add(reader1, POLLIN) end - it "returns nil" do + it 'returns nil' do assert_nil poller.wait(20) end end - context "with thread-safe sockets", if: has_czmq_drafts? do + context 'with thread-safe sockets', if: has_czmq_drafts? do i = 0 let(:endpoint) { "inproc://poller_spec_srv_client_#{i += 1}" } let(:server) { CZTop::Socket::SERVER.new(endpoint) } let(:client) { CZTop::Socket::CLIENT.new(endpoint) } let(:poller) { CZTop::Poller.new(server) } - context "with message from client" do + context 'with message from client' do before do - client << "foobar" + client << 'foobar' end - it "makes server socket readable" do + it 'makes server socket readable' do assert_same server, event.socket assert_operator event, :readable? end @@ -269,27 +271,27 @@ end end - describe "#simple_wait" do - context "with event" do + describe '#simple_wait' do + context 'with event' do before do - writer1 << "foobar" + writer1 << 'foobar' poller.add_reader(reader1) end - it "returns socket" do + it 'returns socket' do assert_same reader1, poller.simple_wait(20) end end - context "with timeout expired" do + context 'with timeout expired' do before do poller.add_reader(reader1) end - it "returns nil" do + it 'returns nil' do assert_nil poller.simple_wait(20) end end end - describe "with actor" do + describe 'with actor' do let(:actor) do # echo actor CZTop::Actor.new { |msg, pipe| pipe << msg } end @@ -301,29 +303,29 @@ actor.terminate end - context "with unreadable actor" do - it "returns nil" do + context 'with unreadable actor' do + it 'returns nil' do assert_nil poller.wait(20) end end - context "with readable actor" do - before { actor << "foo" } - it "returns actor" do + context 'with readable actor' do + before { actor << 'foo' } + it 'returns actor' do assert_same actor, event.socket end end end - describe "#socket_for_ptr" do + describe '#socket_for_ptr' do let(:socket) { reader1 } - context "with known pointer" do + context 'with known pointer' do before { poller.add_reader(socket) } - it "returns socket" do + it 'returns socket' do assert_same socket, poller.socket_for_ptr(socket_ptr) end end - context "with unknown pointer" do - it "raises" do + context 'with unknown pointer' do + it 'raises' do assert_raises(ArgumentError) do poller.socket_for_ptr(socket_ptr) end @@ -331,48 +333,48 @@ end end - describe "#sockets" do - context "with no registered sockets" do - it "returns empty array" do + describe '#sockets' do + context 'with no registered sockets' do + it 'returns empty array' do assert_equal [], poller.sockets end end - context "with registered sockets" do + context 'with registered sockets' do before do poller.add_reader(reader1) poller.add_writer(writer2) end - it "returns registered sockets" do + it 'returns registered sockets' do assert_equal [reader1, writer2], poller.sockets end end end - describe "#event_mask_for_socket" do - context "for registered reader socket" do + describe '#event_mask_for_socket' do + context 'for registered reader socket' do before { poller.add_reader(reader1) } - it "returns event mask" do + it 'returns event mask' do assert_equal POLLIN, poller.event_mask_for_socket(reader1) end end - context "for registered writer socket" do + context 'for registered writer socket' do before { poller.add_writer(writer1) } - it "returns event mask" do + it 'returns event mask' do assert_equal POLLOUT, poller.event_mask_for_socket(writer1) end end - context "for registered reader/writer socket (in 1 step)" do + context 'for registered reader/writer socket (in 1 step)' do let(:socket) { CZTop::Socket::DEALER.new(endpoint1) } before do poller.add(socket, POLLIN | POLLOUT) end - it "returns event mask" do - assert_equal POLLIN|POLLOUT, poller.event_mask_for_socket(socket) + it 'returns event mask' do + assert_equal POLLIN | POLLOUT, poller.event_mask_for_socket(socket) end end - context "for unregistered socket" do - it "raises" do + context 'for unregistered socket' do + it 'raises' do assert_raises(ArgumentError) do poller.event_mask_for_socket(reader1) end @@ -384,14 +386,14 @@ let(:poller) { CZTop::Poller.new } let(:aggpoller) { CZTop::Poller::Aggregated.new(poller) } - describe "#poller" do - it "returns associated CZTop::Poller" do + describe '#poller' do + it 'returns associated CZTop::Poller' do assert_same poller, aggpoller.poller end end - describe "#wait" do - context "when building lists" do + describe '#wait' do + context 'when building lists' do let(:readables_before) { aggpoller.readables } let(:writables_before) { aggpoller.writables } before do @@ -399,36 +401,36 @@ writables_before aggpoller.wait(0) end - it "builds completely new lists" do # forgetting the previous ones + it 'builds completely new lists' do # forgetting the previous ones refute_same readables_before, aggpoller.readables refute_same writables_before, aggpoller.writables end end - context "when calling CZTop::Poller#wait" do + context 'when calling CZTop::Poller#wait' do let(:timeout) { 11 } after { aggpoller.wait(timeout) } - it "passes timeout" do + it 'passes timeout' do expect(poller).to receive(:wait).with(timeout).and_call_original end end - context "with new event" do + context 'with new event' do before do - writer1 << "foobar" + writer1 << 'foobar' poller.add_reader(reader1) end - it "returns true" do + it 'returns true' do assert aggpoller.wait(20) end end - context "with no event" do - it "returns false" do + context 'with no event' do + it 'returns false' do refute aggpoller.wait(0) end end - context "having been called previously" do + context 'having been called previously' do before do writer1 << "i'll teach you how to read" poller.add_reader(reader1) @@ -436,45 +438,44 @@ aggpoller.wait(20) assert_includes aggpoller.readables, reader1 end - it "is level-triggered" do # recognizes the socket as readable again + it 'is level-triggered' do # recognizes the socket as readable again aggpoller.wait(0) assert_includes aggpoller.readables, reader1 end end end - describe "#readables" do - it "returns array" do + describe '#readables' do + it 'returns array' do assert_kind_of Array, aggpoller.readables end - context "with no previous call to #wait" do - it "returns empty array" do + context 'with no previous call to #wait' do + it 'returns empty array' do assert_equal [], aggpoller.readables end end - context "with readable and unreadable socket" do + context 'with readable and unreadable socket' do before do - writer1 << "foobar" + writer1 << 'foobar' poller.add_reader(reader1) # readable poller.add_reader(reader2) # unreadable poller.add_writer(writer1) # a writer aggpoller.wait(20) end - it "returns readable socket" do + it 'returns readable socket' do assert_equal [reader1], aggpoller.readables end end end - describe "#writables" do - it "returns array" do + describe '#writables' do + it 'returns array' do assert_kind_of Array, aggpoller.writables end - context "with no previous call to #wait" do - it "returns empty array" do + context 'with no previous call to #wait' do + it 'returns empty array' do assert_equal [], aggpoller.writables end end - context "with writable and unwritable sockets" do - + context 'with writable and unwritable sockets' do let(:writable) { CZTop::Socket::DEALER.new(endpoint1) } let(:unwritable) do s = CZTop::Socket::DEALER.new # an unconnected socket is not writable @@ -487,58 +488,58 @@ poller.add_reader(reader3) # a reader aggpoller.wait(20) end - it "returns writable socket" do + it 'returns writable socket' do assert_equal [writable], aggpoller.writables end end end - describe "forwarded methods" do + describe 'forwarded methods' do let(:obj) { Object.new } - describe "#add" do + describe '#add' do after { assert_equal :foo, aggpoller.add(obj) } - it "forwards to Poller" do + it 'forwards to Poller' do expect(poller).to receive(:add).with(obj).and_return(:foo) end end - describe "#add_reader" do + describe '#add_reader' do after { assert_equal :foo, aggpoller.add_reader(obj) } - it "forwards to Poller" do + it 'forwards to Poller' do expect(poller).to receive(:add_reader).with(obj).and_return(:foo) end end - describe "#add_writer" do + describe '#add_writer' do after { assert_equal :foo, aggpoller.add_writer(obj) } - it "forwards to Poller" do + it 'forwards to Poller' do expect(poller).to receive(:add_writer).with(obj).and_return(:foo) end end - describe "#modify" do + describe '#modify' do after { assert_equal :foo, aggpoller.modify(obj) } - it "forwards to Poller" do + it 'forwards to Poller' do expect(poller).to receive(:modify).with(obj).and_return(:foo) end end - describe "#remove" do + describe '#remove' do after { assert_equal :foo, aggpoller.remove(obj) } - it "forwards to Poller" do + it 'forwards to Poller' do expect(poller).to receive(:remove).with(obj).and_return(:foo) end end - describe "#remove_reader" do + describe '#remove_reader' do after { assert_equal :foo, aggpoller.remove_reader(obj) } - it "forwards to Poller" do + it 'forwards to Poller' do expect(poller).to receive(:remove_reader).with(obj).and_return(:foo) end end - describe "#remove_writer" do + describe '#remove_writer' do after { assert_equal :foo, aggpoller.remove_writer(obj) } - it "forwards to Poller" do + it 'forwards to Poller' do expect(poller).to receive(:remove_writer).with(obj).and_return(:foo) end end - describe "#sockets" do + describe '#sockets' do after { assert_equal :foo, aggpoller.sockets(obj) } - it "forwards to Poller" do + it 'forwards to Poller' do expect(poller).to receive(:sockets).with(obj).and_return(:foo) end end @@ -547,7 +548,7 @@ end describe CZTop::Poller::ZPoller do - include_examples "has FFI delegate" + include_examples 'has FFI delegate' let(:poller) { CZTop::Poller::ZPoller.new(reader1) } let(:ffi_delegate) { poller.ffi_delegate } @@ -556,28 +557,28 @@ let(:reader2) { CZTop::Socket::PULL.new("inproc://zpoller_spec_r2_#{i += 1}") } let(:reader3) { CZTop::Socket::PULL.new("inproc://zpoller_spec_r3_#{i += 1}") } - describe "#initialize" do + describe '#initialize' do after { poller } - context "with one reader" do - it "passes reader" do + context 'with one reader' do + it 'passes reader' do expect(CZMQ::FFI::Zpoller).to receive(:new) .with(reader1, :pointer, nil).and_call_original end - it "remembers the reader" do + it 'remembers the reader' do expect_any_instance_of(CZTop::Poller::ZPoller).to receive(:remember_socket) .with(reader1) poller end end - context "with additional readers" do + context 'with additional readers' do let(:poller) { CZTop::Poller::ZPoller.new(reader1, reader2, reader3) } - it "passes all readers" do + it 'passes all readers' do expect(CZMQ::FFI::Zpoller).to receive(:new) .with(reader1, :pointer, reader2, :pointer, reader3, :pointer, nil) .and_call_original end - it "remembers all readers" do + it 'remembers all readers' do expect_any_instance_of(CZTop::Poller::ZPoller).to receive(:remember_socket) .with(reader1) expect_any_instance_of(CZTop::Poller::ZPoller).to receive(:remember_socket) @@ -588,121 +589,121 @@ end end - describe "#add" do - it "adds reader" do + describe '#add' do + it 'adds reader' do expect(ffi_delegate).to receive(:add).with(reader2).and_call_original poller.add(reader2) end - it "remembers the reader" do + it 'remembers the reader' do expect(poller).to receive(:remember_socket).with(reader2) - .and_call_original + .and_call_original poller.add(reader2) end - context "with failure" do + context 'with failure' do before do allow(ffi_delegate).to receive(:add).and_return(-1) allow(CZMQ::FFI::Errors).to receive(:errno) .and_return(Errno::EPERM::Errno) end - it "raises" do + it 'raises' do assert_raises(SystemCallError) { poller.add(reader2) } end end end - describe "#remove" do - it "removes reader" do + describe '#remove' do + it 'removes reader' do expect(ffi_delegate).to receive(:remove).with(reader1) - .and_call_original + .and_call_original poller.remove(reader1) end - it "forgets the reader" do + it 'forgets the reader' do expect(poller).to receive(:forget_socket).with(reader1) - .and_call_original + .and_call_original poller.remove(reader1) end - context "with failure" do + context 'with failure' do before do allow(ffi_delegate).to receive(:remove).and_return(-1) allow(CZMQ::FFI::Errors).to receive(:errno) .and_return(Errno::EPERM::Errno) end - it "raises" do + it 'raises' do assert_raises(SystemCallError) { poller.remove(reader2) } end end - context "with unregistered socket" do - it "fails" do + context 'with unregistered socket' do + it 'fails' do assert_raises(ArgumentError) { poller.remove(reader2) } end end end - describe "#wait" do - context "with readable socket" do + describe '#wait' do + context 'with readable socket' do before do - CZTop::Socket::PUSH.new(reader1.last_endpoint) << "foo" + CZTop::Socket::PUSH.new(reader1.last_endpoint) << 'foo' end - it "returns socket" do + it 'returns socket' do assert_same reader1, poller.wait end end - context "with expired timeout" do - it "returns nil" do + context 'with expired timeout' do + it 'returns nil' do assert_nil poller.wait(0) end end - context "with interrupt" do + context 'with interrupt' do before do allow(ffi_delegate).to receive(:terminated).and_return(true) end - it "raises Interrupt" do + it 'raises Interrupt' do assert_raises(Interrupt) do poller.wait(0) end end end - it "the timeout is in ms" do + it 'the timeout is in ms' do duration = Benchmark.realtime { poller.wait(30) } assert_in_delta 0.03, duration, 0.02 # +- 20ms is OK end - context "with no timeout" do + context 'with no timeout' do after { poller.wait } - it "waits indefinitely" do + it 'waits indefinitely' do expect(ffi_delegate).to receive(:wait).with(-1) - .and_return(FFI::Pointer::NULL) + .and_return(FFI::Pointer::NULL) end end - context "with wrong pointer from zpoller_wait" do - let(:wrong_ptr) { double("pointer", to_i: 0, null?: false) } + context 'with wrong pointer from zpoller_wait' do + let(:wrong_ptr) { double('pointer', to_i: 0, null?: false) } before do allow(ffi_delegate).to receive(:wait).and_return(wrong_ptr) allow(CZMQ::FFI::Errors).to receive(:errno) .and_return(Errno::EPERM::Errno) end - it "raises" do # instead of returning nil + it 'raises' do # instead of returning nil assert_raises(SystemCallError) { poller.wait(0) } end end end - describe "#ignore_interrupts" do + describe '#ignore_interrupts' do after { poller.ignore_interrupts } - it "tells zpoller to ignore interrupts" do + it 'tells zpoller to ignore interrupts' do expect(ffi_delegate).to receive(:ignore_interrupts) end end - describe "#nonstop=" do + describe '#nonstop=' do after { poller.nonstop = new_flag } - context "with true" do + context 'with true' do let(:new_flag) { true } - it "tells zpoller to set nonstop flag" do + it 'tells zpoller to set nonstop flag' do expect(ffi_delegate).to receive(:set_nonstop).with(new_flag) end end - context "with true" do + context 'with true' do let(:new_flag) { false } - it "tells zpoller to set nonstop flag" do + it 'tells zpoller to set nonstop flag' do expect(ffi_delegate).to receive(:set_nonstop).with(new_flag) end end diff --git a/spec/cztop/polymorphic_zsock_methods_spec.rb b/spec/cztop/polymorphic_zsock_methods_spec.rb index b16fee0..7faa4f2 100644 --- a/spec/cztop/polymorphic_zsock_methods_spec.rb +++ b/spec/cztop/polymorphic_zsock_methods_spec.rb @@ -1,37 +1,39 @@ +# frozen_string_literal: true + require_relative 'spec_helper' describe CZTop::PolymorphicZsockMethods do i = 0 - let(:endpoint) { "inproc://send_receive_method_spec_#{i+=1}" } + let(:endpoint) { "inproc://send_receive_method_spec_#{i += 1}" } let(:socket_a) { CZTop::Socket::PAIR.new("@#{endpoint}") } let(:socket_b) { CZTop::Socket::PAIR.new(">#{endpoint}") } - describe "signals" do + describe 'signals' do let(:delegate_b) { socket_b.ffi_delegate } let(:status) { 5 } - describe "#signal" do - context "with signal" do - it "sends a signal" do + describe '#signal' do + context 'with signal' do + it 'sends a signal' do expect(CZMQ::FFI::Zsock).to receive(:signal).with(delegate_b, status) socket_b.signal(status) end end - context "with no signal given" do - it "sends signal 0" do + context 'with no signal given' do + it 'sends signal 0' do expect(CZMQ::FFI::Zsock).to receive(:signal).with(delegate_b, 0) socket_b.signal end end end - describe "#wait" do + describe '#wait' do When { socket_b.signal(status) } Then { status == socket_a.wait } end end - describe "#set_unbounded" do + describe '#set_unbounded' do Given(:options) { socket_a.options } When { socket_a.set_unbounded } Then { options.sndhwm == 0 } diff --git a/spec/cztop/proxy_spec.rb b/spec/cztop/proxy_spec.rb index f806685..3f0e192 100644 --- a/spec/cztop/proxy_spec.rb +++ b/spec/cztop/proxy_spec.rb @@ -1,7 +1,9 @@ +# frozen_string_literal: true + require_relative '../spec_helper' -describe "CZTop::Proxy::ZPROXY_FPTR" do - it "points to a dynamic library symbol" do +describe 'CZTop::Proxy::ZPROXY_FPTR' do + it 'points to a dynamic library symbol' do assert_kind_of FFI::DynamicLibrary::Symbol, CZTop::Proxy::ZPROXY_FPTR end end @@ -14,67 +16,66 @@ proxy.terminate end - it "initializes and terminates" do + it 'initializes and terminates' do proxy end - describe "#verbose" do + describe '#verbose' do after { proxy.verbose! } - it "sends correct message to actor" do - expect(actor).to receive(:<<).with("VERBOSE").and_call_original + it 'sends correct message to actor' do + expect(actor).to receive(:<<).with('VERBOSE').and_call_original end - it "waits for signal" do + it 'waits for signal' do expect(actor).to receive(:wait).and_call_original end end - describe "#frontend" do - it "returns configurator" do + describe '#frontend' do + it 'returns configurator' do assert_kind_of CZTop::Proxy::Configurator, proxy.frontend end - it "memoizes it" do + it 'memoizes it' do assert_same proxy.frontend, proxy.frontend end end - describe "#backend" do - it "returns configurator" do + describe '#backend' do + it 'returns configurator' do assert_kind_of CZTop::Proxy::Configurator, proxy.backend end - it "memoize it" do + it 'memoize it' do assert_same proxy.backend, proxy.backend end end - describe "#capture" do + describe '#capture' do i = 0 - let(:endpoint) { "inproc://proxy_capture_spec_#{i+=1}" } - context "with endpoint" do + let(:endpoint) { "inproc://proxy_capture_spec_#{i += 1}" } + context 'with endpoint' do after { proxy.capture(endpoint) } - it "tells zproxy to capture" do - expect(actor).to receive(:<<).with(["CAPTURE", endpoint]).and_call_original + it 'tells zproxy to capture' do + expect(actor).to receive(:<<).with(['CAPTURE', endpoint]).and_call_original end - it "waits for signal" do + it 'waits for signal' do expect(actor).to receive(:wait).and_call_original end end - end - describe "#pause" do + describe '#pause' do after { proxy.pause } - it "tells zproxy to pause" do - expect(actor).to receive(:<<).with("PAUSE").and_call_original + it 'tells zproxy to pause' do + expect(actor).to receive(:<<).with('PAUSE').and_call_original end - it "waits for signal" do + it 'waits for signal' do expect(actor).to receive(:wait).and_call_original end end - describe "#resume" do + describe '#resume' do after { proxy.resume } - it "tells zproxy to resume" do - expect(actor).to receive(:<<).with("RESUME").and_call_original + it 'tells zproxy to resume' do + expect(actor).to receive(:<<).with('RESUME').and_call_original end - it "waits for signal" do + it 'waits for signal' do expect(actor).to receive(:wait).and_call_original end end @@ -83,169 +84,165 @@ let(:configurator) { CZTop::Proxy::Configurator.new(proxy, side) } let(:side) { :frontend } # default for specs - describe "#initialize" do - - context "with proxy" do - it "assigns proxy" do + describe '#initialize' do + context 'with proxy' do + it 'assigns proxy' do assert_equal proxy, configurator.proxy end end - context "with frontend side argument" do + context 'with frontend side argument' do let(:side) { :frontend } - it "assigns side" do - assert_equal "FRONTEND", configurator.side + it 'assigns side' do + assert_equal 'FRONTEND', configurator.side end end - context "with backend side argument" do + context 'with backend side argument' do let(:side) { :backend } - it "assigns side" do - assert_equal "BACKEND", configurator.side + it 'assigns side' do + assert_equal 'BACKEND', configurator.side end end - context "with wrong side argument" do + context 'with wrong side argument' do let(:side) { :foo } - it "raises" do + it 'raises' do assert_raises(ArgumentError) { configurator } end end end - describe "#proxy" do - it "returns proxy" do + describe '#proxy' do + it 'returns proxy' do assert_same proxy, configurator.proxy end end - describe "#side" do - it "returns string" do + describe '#side' do + it 'returns string' do # NOTE: functionality already tested in #initialize assert_kind_of String, configurator.side end end - describe "#bind" do + describe '#bind' do i = 0 - let(:endpoint) { "inproc://proxy_bind_spec_#{i+=1}" } + let(:endpoint) { "inproc://proxy_bind_spec_#{i += 1}" } - context "with valid arguments" do + context 'with valid arguments' do before do expect(actor).to receive(:wait).and_call_original end after do configurator.bind(socket_type, endpoint) end - context "for frontend" do + context 'for frontend' do let(:side) { :frontend } let(:socket_type) { :ROUTER } - it "configures frontend socket" do + it 'configures frontend socket' do expect(actor).to receive(:<<) - .with(["FRONTEND", "ROUTER", endpoint]).and_call_original + .with(['FRONTEND', 'ROUTER', endpoint]).and_call_original end end - context "for backend" do + context 'for backend' do let(:side) { :backend } let(:socket_type) { :DEALER } - it "configures backend socket" do + it 'configures backend socket' do expect(actor).to receive(:<<) - .with(["BACKEND", "DEALER", endpoint]).and_call_original + .with(['BACKEND', 'DEALER', endpoint]).and_call_original end end end - context "with invalid socket type" do + context 'with invalid socket type' do let(:type) { :foo } - it "raises" do + it 'raises' do assert_raises(ArgumentError) { configurator.bind(type, endpoint) } end end end - describe "#domain=" do - - let(:domain) { "foobar" } + describe '#domain=' do + let(:domain) { 'foobar' } after { configurator.domain = domain } - context "for frontend" do + context 'for frontend' do let(:side) { :frontend } - it "tells actor the ZAP domain" do + it 'tells actor the ZAP domain' do expect(actor).to receive(:<<) - .with(["DOMAIN", "FRONTEND", domain]).and_call_original + .with(['DOMAIN', 'FRONTEND', domain]).and_call_original end - it "waits for signal" do + it 'waits for signal' do expect(actor).to receive(:wait).and_call_original end end - context "for backend" do + context 'for backend' do let(:side) { :backend } - it "tells actor the ZAP domain" do + it 'tells actor the ZAP domain' do expect(actor).to receive(:<<) - .with(["DOMAIN", "BACKEND", domain]).and_call_original + .with(['DOMAIN', 'BACKEND', domain]).and_call_original end - it "waits for signal" do + it 'waits for signal' do expect(actor).to receive(:wait).and_call_original end end end - describe "#PLAIN!" do - + describe '#PLAIN!' do after { configurator.PLAIN_server! } - context "for frontend" do + context 'for frontend' do let(:side) { :frontend } - it "tells actor to configure PLAIN" do + it 'tells actor to configure PLAIN' do expect(actor).to receive(:<<) - .with(["PLAIN", "FRONTEND"]).and_call_original + .with(['PLAIN', 'FRONTEND']).and_call_original end - it "waits for signal" do + it 'waits for signal' do expect(actor).to receive(:wait).and_call_original end end - context "for backend" do + context 'for backend' do let(:side) { :backend } - it "tells actor to configure PLAIN" do + it 'tells actor to configure PLAIN' do expect(actor).to receive(:<<) - .with(["PLAIN", "BACKEND"]).and_call_original + .with(['PLAIN', 'BACKEND']).and_call_original end - it "waits for signal" do + it 'waits for signal' do expect(actor).to receive(:wait).and_call_original end end end - describe "#CURVE!" do - + describe '#CURVE!' do let(:cert) { CZTop::Certificate.new } let(:public_key) { cert.public_key } let(:secret_key) { cert.secret_key } - context "with correct arguments" do + context 'with correct arguments' do after { configurator.CURVE_server!(cert) } - context "for frontend" do + context 'for frontend' do let(:side) { :frontend } - it "tells actor to configure CURVE" do + it 'tells actor to configure CURVE' do expect(actor).to receive(:<<) - .with(["CURVE", "FRONTEND", public_key, secret_key]).and_call_original + .with(['CURVE', 'FRONTEND', public_key, secret_key]).and_call_original end - it "waits for signal" do + it 'waits for signal' do expect(actor).to receive(:wait).and_call_original end end - context "for backend" do + context 'for backend' do let(:side) { :backend } - it "tells actor to configure CURVE" do + it 'tells actor to configure CURVE' do expect(actor).to receive(:<<) - .with(["CURVE", "BACKEND", public_key, secret_key]).and_call_original + .with(['CURVE', 'BACKEND', public_key, secret_key]).and_call_original end - it "waits for signal" do + it 'waits for signal' do expect(actor).to receive(:wait).and_call_original end end end - context "with secret key missing" do + context 'with secret key missing' do before do expect(cert).to receive(:secret_key).and_return(nil) end - it "raises" do + it 'raises' do assert_raises(ArgumentError) { configurator.CURVE_server!(cert) } end end diff --git a/spec/cztop/send_receive_methods_spec.rb b/spec/cztop/send_receive_methods_spec.rb index 0a083e2..55f9ada 100644 --- a/spec/cztop/send_receive_methods_spec.rb +++ b/spec/cztop/send_receive_methods_spec.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require_relative 'spec_helper' describe CZTop::SendReceiveMethods do @@ -6,32 +8,33 @@ o.extend CZTop::SendReceiveMethods o end - describe "#<<" do - context "when sending message" do - let(:content) { "foobar" } - let(:msg) { double("Message") } + describe '#<<' do + context 'when sending message' do + let(:content) { 'foobar' } + let(:msg) { double('Message') } before do expect(CZTop::Message).to receive(:coerce).with(content).and_return(msg) expect(msg).to receive(:send_to).with(zocket) end - it "sends content" do + it 'sends content' do zocket << content end - it "returns self" do # so it can be chained + it 'returns self' do # so it can be chained assert_same zocket, zocket << content end end end - describe "#receive" do - context "given a sent content" do - let(:content) { "foobar" } - it "receives the content" do + describe '#receive' do + context 'given a sent content' do + let(:content) { 'foobar' } + it 'receives the content' do msg = double expect(CZTop::Message).to( - receive(:receive_from).with(zocket).and_return(msg)) + receive(:receive_from).with(zocket).and_return(msg) + ) assert_same msg, zocket.receive end end diff --git a/spec/cztop/socket/types_spec.rb b/spec/cztop/socket/types_spec.rb index c71e1a1..da51dcf 100644 --- a/spec/cztop/socket/types_spec.rb +++ b/spec/cztop/socket/types_spec.rb @@ -1,16 +1,18 @@ +# frozen_string_literal: true + require_relative '../../spec_helper' describe CZTop::Socket::Types do - it "has constants" do + it 'has constants' do assert_equal 14, described_class.constants.size end - it "has names for each type" do + it 'has names for each type' do assert_equal CZTop::Socket::Types.constants.sort, - CZTop::Socket::TypeNames.values.sort + CZTop::Socket::TypeNames.values.sort end - it "has an entry for each socket type" do + it 'has an entry for each socket type' do CZTop::Socket::Types.constants.each do |const_name| type_code = CZTop::Socket::Types.const_get(const_name) assert_operator CZTop::Socket::TypeNames, :has_key?, type_code @@ -20,49 +22,49 @@ end describe CZTop::Socket do - describe ".new_by_type" do + describe '.new_by_type' do let(:socket) { described_class.new_by_type(type) } - context "given valid type" do + context 'given valid type' do let(:expected_class) { CZTop::Socket::PUSH } - context "by integer" do + context 'by integer' do let(:type) { CZTop::Socket::Types::PUSH } - it "returns socket" do + it 'returns socket' do assert_kind_of Integer, type assert_kind_of expected_class, socket end end - context "by symbol" do + context 'by symbol' do let(:type) { :PUSH } - it "returns socket" do + it 'returns socket' do assert_kind_of expected_class, socket end end end - context "given invalid type name" do - context "by integer" do + context 'given invalid type name' do + context 'by integer' do let(:type) { 99 } # non-existent type - it "raises" do + it 'raises' do assert_raises(ArgumentError) { socket } end end - context "by symbol" do + context 'by symbol' do let(:type) { :FOOBAR } # non-existent type - it "raises" do + it 'raises' do assert_raises(NameError) { socket } end end - context "by string" do + context 'by string' do # NOTE: No support for Strings as socket types for now. - let(:type) { "PUB" } - it "raises" do + let(:type) { 'PUB' } + it 'raises' do assert_raises(ArgumentError) { socket } end end - context "by Socket::* class" do + context 'by Socket::* class' do # NOTE: No support for socket Socket::* classes as types for now. let(:type) { CZTop::Socket::PUB } - it "raises" do + it 'raises' do assert_raises(ArgumentError) { socket } end end @@ -72,28 +74,27 @@ describe CZTop::Socket::CLIENT, if: has_czmq_drafts? do Given(:socket) { described_class.new } - it "instanciates" do + it 'instanciates' do socket end - context "when sending multi-part message" do - it "raises" do + context 'when sending multi-part message' do + it 'raises' do assert_raises(ArgumentError) do - socket << %w[ foo bar ] + socket << %w[foo bar] end end end end describe CZTop::Socket::SERVER, if: has_czmq_drafts? do - Given(:server) { CZTop::Socket::SERVER.new } - it "instanciates" do + it 'instanciates' do server end - describe "when communicating" do - i = 58578 + describe 'when communicating' do + i = 58_578 Given(:endpoint) { "inproc://server_spec_#{i += 1}" } Given(:server_sndtimeo) { 50 } Given(:server) do @@ -109,59 +110,59 @@ s.connect(endpoint) end end - Given(:msg_content) { "FOO" } - Given(:routing_id) { 23456 } + Given(:msg_content) { 'FOO' } + Given(:routing_id) { 23_456 } Given(:msg) { CZTop::Message.new(msg_content) } Given(:received_msg) { server.receive } - context "when receiving message from CLIENT" do + context 'when receiving message from CLIENT' do When { client << msg_content } Then { received_msg[0].to_s == msg_content } And { received_msg.routing_id > 0 } end - context "when responding to a message from CLIENT" do + context 'when responding to a message from CLIENT' do Given { client << msg_content } Given { received_msg } - Given(:response) { CZTop::Message.new("BAR") } - context "with routing_id set" do + Given(:response) { CZTop::Message.new('BAR') } + context 'with routing_id set' do Given { response.routing_id = received_msg.routing_id } When { server << response } - Then { client.receive[0] == "BAR" } + Then { client.receive[0] == 'BAR' } end - context "with two responses with routing_id set" do - Given(:second_response) { CZTop::Message.new("BAZ") } + context 'with two responses with routing_id set' do + Given(:second_response) { CZTop::Message.new('BAZ') } Given { response.routing_id = received_msg.routing_id } Given { second_response.routing_id = received_msg.routing_id } When { server << response << second_response } - Then { client.receive[0] == "BAR" && client.receive[0] == "BAZ" } + Then { client.receive[0] == 'BAR' && client.receive[0] == 'BAZ' } end - context "with wrong routing_id set" do - context "with SERVER SNDTIMEO set" do + context 'with wrong routing_id set' do + context 'with SERVER SNDTIMEO set' do Given(:server_timeo) { 50 } Given { response.routing_id = 1234 } # wrong routing_id When(:result) { server << response } Then { result == Failure(SocketError) } end - context "with no SERVER SNDTIMEO set" do + context 'with no SERVER SNDTIMEO set' do Given(:server_timeo) { 0 } Given { response.routing_id = 1234 } # wrong routing_id When(:result) { server << response } Then { result == Failure(SocketError) } end end - context "without routing_id set" do + context 'without routing_id set' do When(:result) { server << response } Then { result == Failure(SocketError) } end - context "with disconnected CLIENT" do + context 'with disconnected CLIENT' do Given { client.disconnect(endpoint) } Given { response.routing_id = received_msg.routing_id } When(:result) { server << response } Then { result == Failure(IO::EAGAINWaitWritable) } end - describe "with multi-part response" do + describe 'with multi-part response' do Given(:response) { CZTop::Message.new(%w[BAR BAZ]) } Given { response.routing_id = received_msg.routing_id } When(:result) { server << response } @@ -169,7 +170,7 @@ end end - describe "when SERVER tries to initiate a conversation" do + describe 'when SERVER tries to initiate a conversation' do Given { client } Given { server } Given { msg.routing_id = 1234 } # fake routing_id @@ -200,48 +201,48 @@ s.connect(endpoint) end end - Given(:group) { "group1" } + Given(:group) { 'group1' } - describe "#join" do - context "given a message sent to a joined group" do + describe '#join' do + context 'given a message sent to a joined group' do Given { dish.join group } - Given(:msg) { CZTop::Frame.new("foo").tap{ |f| f.group = group } } + Given(:msg) { CZTop::Frame.new('foo').tap { |f| f.group = group } } When { radio << msg } When(:received) { dish.receive } Then { group == received.frames[0].group } - And { "foo" == received[0] } + And { 'foo' == received[0] } end - context "given a message sent to an unjoined group" do + context 'given a message sent to an unjoined group' do Given { dish.join group } - Given(:msg) { CZTop::Frame.new("foo").tap{ |f| f.group = "group2" } } + Given(:msg) { CZTop::Frame.new('foo').tap { |f| f.group = 'group2' } } When { radio << msg } When(:result) { dish.receive } Then { result == Failure(Errno::EAGAIN) } end - context "given an invalid group name" do - Given(:group) { "x" * 256 } + context 'given an invalid group name' do + Given(:group) { 'x' * 256 } When(:result) { dish.join group } Then { result == Failure(ArgumentError) } end - context "given an already joined group" do - Given(:group) { "group1" } + context 'given an already joined group' do + Given(:group) { 'group1' } When { dish.join group } When(:result) { dish.join group } Then { result == Failure(ArgumentError) } end end - describe "#leave" do - context "leaving a previously joined group" do - Given(:group) { "group1" } + describe '#leave' do + context 'leaving a previously joined group' do + Given(:group) { 'group1' } When { dish.join group } When(:result) { dish.leave group } Then { true } end - context "leaving an unjoined group" do - Given(:unjoined_group) { "group1" } + context 'leaving an unjoined group' do + Given(:unjoined_group) { 'group1' } When(:result) { dish.leave unjoined_group } Then { result == Failure(ArgumentError) } end @@ -270,14 +271,14 @@ end end - context "given message from SCATTER" do + context 'given message from SCATTER' do Given { gather } - Given { scatter << "foo" } + Given { scatter << 'foo' } When(:msg) { gather.receive } - Then { "foo" == msg.to_a[0] } + Then { 'foo' == msg.to_a[0] } end - context "given message from SCATTER and multiple GATHER sockets" do + context 'given message from SCATTER and multiple GATHER sockets' do Given { gather } Given(:gather2) do described_class.new.tap do |s| @@ -285,7 +286,7 @@ s.connect(endpoint) end end - Given { scatter << "foo" } + Given { scatter << 'foo' } When(:result1) { gather.receive } When(:result2) { gather2.receive } Then { result1 == Failure(Errno::EAGAIN) || result2 == Failure(Errno::EAGAIN) } @@ -312,12 +313,12 @@ Given(:socket) { described_class.new } Then { socket } - describe "#send_to" do - let(:receiver) { "mike" } - let(:content) { "foobar" } - it "sends message to receiver" do + describe '#send_to' do + let(:receiver) { 'mike' } + let(:content) { 'foobar' } + it 'sends message to receiver' do expect(socket).to receive(:<<) do |msg| - assert_equal [receiver, "", content], msg.to_a + assert_equal [receiver, '', content], msg.to_a end socket.send_to(receiver, content) end @@ -333,38 +334,38 @@ Given(:socket) { described_class.new } Then { socket } - let(:subscription) { "test_prefix" } + let(:subscription) { 'test_prefix' } - context "with subscription" do - it "subscribes" do - expect(::CZMQ::FFI::Zsock).to receive(:new_sub).with(nil, subscription). - and_call_original + context 'with subscription' do + it 'subscribes' do + expect(::CZMQ::FFI::Zsock).to receive(:new_sub).with(nil, subscription) + .and_call_original described_class.new(nil, subscription) end end - describe "#subscribe" do - context "with subscription prefix" do + describe '#subscribe' do + context 'with subscription prefix' do before do expect(socket.ffi_delegate).to receive(:set_subscribe) .with(subscription) end - it "subscribes" do + it 'subscribes' do socket.subscribe(subscription) end end - context "without subscription prefix" do + context 'without subscription prefix' do before do - expect(socket.ffi_delegate).to receive(:set_subscribe).with("") + expect(socket.ffi_delegate).to receive(:set_subscribe).with('') end - it "subscribes to everything" do + it 'subscribes to everything' do socket.subscribe end end end - describe "#unsubscribe" do - it "unsubscribes" do + describe '#unsubscribe' do + it 'unsubscribes' do expect(socket.ffi_delegate).to receive(:set_unsubscribe).with(subscription) socket.unsubscribe(subscription) end @@ -393,16 +394,16 @@ describe CZTop::Socket::PAIR do i = 0 - let(:endpoint) { "inproc://socket_types_spec_#{i+=1}" } + let(:endpoint) { "inproc://socket_types_spec_#{i += 1}" } let(:binding_socket) { described_class.new("@#{endpoint}") } let(:connecting_socket) { described_class.new(">#{endpoint}") } - it "creates PAIR sockets" do + it 'creates PAIR sockets' do binding_socket connecting_socket end - it "raises when more than 2 PAIR sockets are connected" do + it 'raises when more than 2 PAIR sockets are connected' do binding_socket connecting_socket assert_raises(SystemCallError) do diff --git a/spec/cztop/socket_spec.rb b/spec/cztop/socket_spec.rb index 663b7b1..c3f8104 100644 --- a/spec/cztop/socket_spec.rb +++ b/spec/cztop/socket_spec.rb @@ -1,44 +1,46 @@ +# frozen_string_literal: true + require_relative 'spec_helper' require 'tmpdir' require 'pathname' describe CZTop::Socket do - include_examples "has FFI delegate" + include_examples 'has FFI delegate' i = 0 - let(:endpoint) { "inproc://endpoint_socket_spec_#{i+=1}" } + let(:endpoint) { "inproc://endpoint_socket_spec_#{i += 1}" } let(:req_socket) { CZTop::Socket::REQ.new(endpoint) } let(:rep_socket) { CZTop::Socket::REP.new(endpoint) } let(:binding_pair_socket) { CZTop::Socket::PAIR.new("@#{endpoint}") } let(:connecting_pair_socket) { CZTop::Socket::PAIR.new(">#{endpoint}") } - it "has Zsock options" do + it 'has Zsock options' do assert_operator described_class, :<, CZTop::ZsockOptions end - it "has send/receive methods" do + it 'has send/receive methods' do assert_operator described_class, :<, CZTop::SendReceiveMethods end - it "has polymorphic Zsock methods" do + it 'has polymorphic Zsock methods' do assert_operator described_class, :<, CZTop::PolymorphicZsockMethods end - describe "#initialize" do - context "given invalid endpoint" do - let(:endpoint) { "foo://bar" } - it "raises" do + describe '#initialize' do + context 'given invalid endpoint' do + let(:endpoint) { 'foo://bar' } + it 'raises' do assert_raises(SystemCallError) do CZTop::Socket::REP.new(endpoint) end end end - context "given same binding endpoint to multiple REP sockets" do - let(:endpoint) { "inproc://the_one_and_only" } + context 'given same binding endpoint to multiple REP sockets' do + let(:endpoint) { 'inproc://the_one_and_only' } let(:sock1) { CZTop::Socket::REP.new(endpoint) } before { sock1 } - it "raises" do + it 'raises' do # there can only be one REP socket bound to one endpoint assert_raises(SystemCallError) do CZTop::Socket::REP.new(endpoint) @@ -47,10 +49,10 @@ end end - describe "#<< and #receive" do - context "given a sent content" do - let(:content) { "foobar" } - it "receives the content" do + describe '#<< and #receive' do + context 'given a sent content' do + let(:content) { 'foobar' } + it 'receives the content' do connecting_pair_socket << content # REQ => REP msg = binding_pair_socket.receive # REQ <= REP assert_equal content, msg.frames.first.to_s @@ -58,11 +60,11 @@ end end - describe "#CURVE_server!" do + describe '#CURVE_server!' do let(:certificate) { CZTop::Certificate.new } let(:options) { rep_socket.options } - context "with valid certificate" do + context 'with valid certificate' do When do rep_socket.CURVE_server!(certificate) end @@ -71,10 +73,10 @@ Then { options.CURVE_publickey == certificate.public_key } end - context "with no secret key in certificate" do + context 'with no secret key in certificate' do let(:certificate) do - tmpdir = Pathname.new(Dir.mktmpdir("zsock_test")) - path = tmpdir + "server_cert.txt" + tmpdir = Pathname.new(Dir.mktmpdir('zsock_test')) + path = tmpdir + 'server_cert.txt' # NOTE: ensure only public key is set CZTop::Certificate.new.save_public(path) CZTop::Certificate.load(path) @@ -87,11 +89,11 @@ end end - describe "#CURVE_client!" do + describe '#CURVE_client!' do let(:tmpdir) do - Pathname.new(Dir.mktmpdir("zsock_test")) + Pathname.new(Dir.mktmpdir('zsock_test')) end - let(:path) { tmpdir + "server_cert.txt" } + let(:path) { tmpdir + 'server_cert.txt' } let(:server_cert) do # NOTE: ensure only public key is set CZTop::Certificate.new.save_public(path) @@ -100,15 +102,15 @@ let(:client_cert) { CZTop::Certificate.new } let(:options) { req_socket.options } - context "with client certificate" do + context 'with client certificate' do before do req_socket.CURVE_client!(client_cert, server_cert) end - it "sets client secret key" do + it 'sets client secret key' do assert_equal client_cert.secret_key, options.CURVE_secretkey end - it "sets client public key" do + it 'sets client public key' do assert_equal client_cert.public_key, options.CURVE_publickey end it "sets server's public key" do @@ -117,26 +119,26 @@ it "doesn't set CURVE server" do refute options.CURVE_server? end - it "changes mechanism to :CURVE" do + it 'changes mechanism to :CURVE' do assert_equal :CURVE, options.mechanism end end - context "with secret key in server certificate" do + context 'with secret key in server certificate' do let(:server_cert) { CZTop::Certificate.new } - it "raises" do # server's secret key compromised + it 'raises' do # server's secret key compromised assert_raises(SecurityError) do req_socket.CURVE_client!(client_cert, server_cert) end end end - context "with no secret key in certificate" do + context 'with no secret key in certificate' do let(:client_cert) do # NOTE: ensure only public key is set - path = tmpdir + "client_cert.txt" + path = tmpdir + 'client_cert.txt' CZTop::Certificate.new.save_public(path) CZTop::Certificate.load(path) end - it "raises" do + it 'raises' do assert_raises(SystemCallError) do req_socket.CURVE_client!(client_cert, server_cert) end @@ -144,128 +146,128 @@ end end - describe "#last_endpoint" do - context "unbound socket" do + describe '#last_endpoint' do + context 'unbound socket' do let(:socket) { CZTop::Socket.new_by_type(:REP) } - it "returns nil" do + it 'returns nil' do assert_nil socket.last_endpoint end end - context "bound socket" do - it "returns endpoint" do + context 'bound socket' do + it 'returns endpoint' do assert_equal endpoint, rep_socket.last_endpoint end end end - describe "#connect" do + describe '#connect' do Given(:socket) { rep_socket } - context "with valid endpoint" do - let(:another_endpoint) { "inproc://foo" } - it "connects" do + context 'with valid endpoint' do + let(:another_endpoint) { 'inproc://foo' } + it 'connects' do req_socket.connect(another_endpoint) end end - context "with invalid endpoint" do - Given(:another_endpoint) { "foo://bar" } + context 'with invalid endpoint' do + Given(:another_endpoint) { 'foo://bar' } When(:result) { socket.connect(another_endpoint) } Then { result == Failure(ArgumentError) } end - it "does safe format handling" do - expect(socket.ffi_delegate).to receive(:connect).with("%s", any_args).and_return(0) - socket.connect(double("endpoint")) + it 'does safe format handling' do + expect(socket.ffi_delegate).to receive(:connect).with('%s', any_args).and_return(0) + socket.connect(double('endpoint')) end end - describe "#disconnect" do + describe '#disconnect' do Given(:socket) { rep_socket } - context "with valid endpoint" do - it "disconnects" do + context 'with valid endpoint' do + it 'disconnects' do expect(socket.ffi_delegate).to receive(:disconnect) socket.disconnect(endpoint) end end - context "with invalid endpoint" do - Given(:another_endpoint) { "foo://bar" } + context 'with invalid endpoint' do + Given(:another_endpoint) { 'foo://bar' } When(:result) { socket.disconnect(another_endpoint) } Then { result == Failure(ArgumentError) } end - it "does safe format handling" do - expect(socket.ffi_delegate).to receive(:disconnect).with("%s", any_args).and_return(0) - socket.disconnect(double("endpoint")) + it 'does safe format handling' do + expect(socket.ffi_delegate).to receive(:disconnect).with('%s', any_args).and_return(0) + socket.disconnect(double('endpoint')) end end - describe "#close" do + describe '#close' do Given(:socket) { rep_socket } When { rep_socket.close } Then { rep_socket.ffi_delegate.null? } end - describe "#bind" do + describe '#bind' do Given(:socket) { rep_socket } - context "with valid endpoint" do + context 'with valid endpoint' do Then { assert_nil socket.last_tcp_port } - context "with automatic TCP port selection endpoint" do - Given(:another_endpoint) { "tcp://127.0.0.1:*" } + context 'with automatic TCP port selection endpoint' do + Given(:another_endpoint) { 'tcp://127.0.0.1:*' } When { socket.bind(another_endpoint) } Then { assert_kind_of Integer, socket.last_tcp_port } And { socket.last_tcp_port > 0 } end - context "with explicit TCP port endpoint" do + context 'with explicit TCP port endpoint' do Given(:port) { rand(55_755..58_665) } Given(:another_endpoint) { "tcp://127.0.0.1:#{port}" } When { socket.bind(another_endpoint) } Then { socket.last_tcp_port == port } end - context "with non-TCP endpoint" do - Given(:another_endpoint) { "inproc://non_tcp_endpoint" } + context 'with non-TCP endpoint' do + Given(:another_endpoint) { 'inproc://non_tcp_endpoint' } When { socket.bind(another_endpoint) } Then { assert_nil socket.last_tcp_port } end end - context "with invalid endpoint" do - Given(:another_endpoint) { "foo://bar" } + context 'with invalid endpoint' do + Given(:another_endpoint) { 'foo://bar' } When(:result) { socket.bind(another_endpoint) } Then { result == Failure(SystemCallError) } end - it "does safe format handling" do - expect(socket.ffi_delegate).to receive(:bind).with("%s", any_args).and_return(0) - socket.bind(double("endpoint")) + it 'does safe format handling' do + expect(socket.ffi_delegate).to receive(:bind).with('%s', any_args).and_return(0) + socket.bind(double('endpoint')) end end - describe "#unbind" do + describe '#unbind' do Given(:socket) { rep_socket } - context "with valid endpoint" do - it "unbinds" do + context 'with valid endpoint' do + it 'unbinds' do expect(socket.ffi_delegate).to receive(:unbind) socket.unbind(endpoint) end end - context "with invalid endpoint" do - Given(:another_endpoint) { "bar://foo" } + context 'with invalid endpoint' do + Given(:another_endpoint) { 'bar://foo' } When(:result) { socket.unbind(another_endpoint) } Then { result == Failure(ArgumentError) } end - it "does safe format handling" do - expect(socket.ffi_delegate).to receive(:unbind).with("%s", any_args).and_return(0) - socket.unbind(double("endpoint")) + it 'does safe format handling' do + expect(socket.ffi_delegate).to receive(:unbind).with('%s', any_args).and_return(0) + socket.unbind(double('endpoint')) end end - describe "#inspect" do + describe '#inspect' do context 'with native object alive' do - it "contains class name" do + it 'contains class name' do assert_match /\A#\z/, req_socket.inspect end - it "contains native address" do + it 'contains native address' do assert_match /:0x[[:xdigit:]]+\b/, req_socket.inspect end - it "contains last endpoint" do + it 'contains last endpoint' do assert_match /\blast_endpoint=.+\b/, req_socket.inspect end end diff --git a/spec/cztop/spec_helper.rb b/spec/cztop/spec_helper.rb index ced49ff..91c3840 100644 --- a/spec/cztop/spec_helper.rb +++ b/spec/cztop/spec_helper.rb @@ -1,7 +1,9 @@ +# frozen_string_literal: true + require_relative '../spec_helper' -RSpec.shared_examples "has FFI delegate" do - it "has an FFI delegate" do +RSpec.shared_examples 'has FFI delegate' do + it 'has an FFI delegate' do assert_operator described_class, :<, CZTop::HasFFIDelegate assert_kind_of CZTop::HasFFIDelegate::ClassMethods, described_class end diff --git a/spec/cztop/z85/padded_spec.rb b/spec/cztop/z85/padded_spec.rb index 09bea91..c442eaa 100644 --- a/spec/cztop/z85/padded_spec.rb +++ b/spec/cztop/z85/padded_spec.rb @@ -1,62 +1,64 @@ +# frozen_string_literal: true + require_relative '../../spec_helper' describe CZTop::Z85::Padded do subject { CZTop::Z85::Padded.new } - describe "#encode" do + describe '#encode' do let(:encoded) { subject.encode(input) } let(:output_size) { encoded.bytesize } - context "with empty data" do - let(:input) { "" } - it "returns empty string" do - assert_equal "", encoded + context 'with empty data' do + let(:input) { '' } + it 'returns empty string' do + assert_equal '', encoded end end - context "with even data" do - let(:input) { "abcd" } + context 'with even data' do + let(:input) { 'abcd' } - it "encodes to correct size" do + it 'encodes to correct size' do assert_equal 10, output_size end end - context "with uneven data" do - let(:input) { "abc" } + context 'with uneven data' do + let(:input) { 'abc' } - it "encodes to correct size" do + it 'encodes to correct size' do assert_equal 5, output_size end end end - describe "#decode" do - context "with empty data" do - it "decodes without trying chop off padding" do - assert_equal "", subject.decode("") + describe '#decode' do + context 'with empty data' do + it 'decodes without trying chop off padding' do + assert_equal '', subject.decode('') end end end - it "round trips" do - input = "foo bar baz" + it 'round trips' do + input = 'foo bar baz' z85 = subject.encode(input) assert_equal input, subject.decode(z85) end - describe ".encode" do - let(:input) { "abcde" * 1_000 } - it "does the same as #encode" do + describe '.encode' do + let(:input) { 'abcde' * 1_000 } + it 'does the same as #encode' do assert_equal CZTop::Z85::Padded.new.encode(input), - CZTop::Z85::Padded.encode(input) + CZTop::Z85::Padded.encode(input) end end - describe ".decode" do - let(:input) { CZTop::Z85::Padded.new.encode("abcde" * 1_000) } - it "does the same as #decode" do + describe '.decode' do + let(:input) { CZTop::Z85::Padded.new.encode('abcde' * 1_000) } + it 'does the same as #decode' do assert_equal CZTop::Z85::Padded.new.decode(input), - CZTop::Z85::Padded.decode(input) + CZTop::Z85::Padded.decode(input) end end end diff --git a/spec/cztop/z85/pipe_spec.rb b/spec/cztop/z85/pipe_spec.rb index 4ddb591..299c48c 100644 --- a/spec/cztop/z85/pipe_spec.rb +++ b/spec/cztop/z85/pipe_spec.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require_relative '../spec_helper' describe CZTop::Z85::Pipe do @@ -6,40 +8,40 @@ let(:pipe) { Z85::Pipe.new(source, sink) } let(:source) { StringIO.new(input) } - let(:sink) { StringIO.new("") } + let(:sink) { StringIO.new(+'') } let(:output_len) { output.bytesize } let(:input_len) { input.bytesize } - context "when encoding" do + context 'when encoding' do let(:output) { pipe.encode; sink.string } - context "with zero-length input" do - let(:input) { "" } - it "produces zero-length output" do + context 'with zero-length input' do + let(:input) { '' } + it 'produces zero-length output' do assert_equal input, output end end - context "with chunk-sized input" do - let(:input) { "." * ENC_SZ } - it "works correctly" do - correct = Z85.encode("." * ENC_SZ + ("\x04" * 4)) + context 'with chunk-sized input' do + let(:input) { '.' * ENC_SZ } + it 'works correctly' do + correct = Z85.encode('.' * ENC_SZ + ("\x04" * 4)) assert_equal correct, output end - it "produces output of correct length" do - assert_equal (ENC_SZ + 4)/4*5, output_len + it 'produces output of correct length' do + assert_equal (ENC_SZ + 4) / 4 * 5, output_len end - context "times two" do - let(:input) { "." * 2 * ENC_SZ } - it "works correctly" do - correct = Z85.encode("." * ENC_SZ * 2 + ("\x04" * 4)) + context 'times two' do + let(:input) { '.' * 2 * ENC_SZ } + it 'works correctly' do + correct = Z85.encode('.' * ENC_SZ * 2 + ("\x04" * 4)) assert_equal correct, output end end end - context "with long input" do - let(:input) { "." * (ENC_SZ * 1.1).to_i } # >chunk + context 'with long input' do + let(:input) { '.' * (ENC_SZ * 1.1).to_i } # >chunk let(:nfull_chunks) { input_len / ENC_SZ } # number of full chunks let(:full_chunks_len) do # total length of all full (non-padded) chunks - Z85.encode("." * ENC_SZ).bytesize * nfull_chunks + Z85.encode('.' * ENC_SZ).bytesize * nfull_chunks end let(:last_chunk_len) do # encoded length len = (input_len % ENC_SZ) @@ -49,21 +51,21 @@ let(:correct_length) do # encoded length full_chunks_len + last_chunk_len end - it "produces output of correct length" do + it 'produces output of correct length' do assert_equal correct_length, output_len end - it "produces correct output" do + it 'produces correct output' do beginning = input.byteslice(0, ENC_SZ) - rest = input.byteslice(ENC_SZ .. -1) + rest = input.byteslice(ENC_SZ..-1) padding_bytes = 4 - rest.bytesize % 4 padding_bytes = 4 if padding_bytes.zero? - rest << ([padding_bytes].pack("C") * padding_bytes) + rest << ([padding_bytes].pack('C') * padding_bytes) correct = Z85.encode(beginning + rest) assert_equal correct, output end end end - context "when decoding" do + context 'when decoding' do let(:output) { pipe.decode; sink.string } let(:input) do source = StringIO.new(unencoded_input) @@ -71,29 +73,29 @@ Z85::Pipe.new(source, sink).encode sink.string end - context "with zero-length input" do - let(:input) { "" } - it "output is also zero-length" do + context 'with zero-length input' do + let(:input) { '' } + it 'output is also zero-length' do assert_equal input, output end end - context "with chunks-sized input" do - let(:unencoded_input) { "." * ENC_SZ } - it "works correctly" do + context 'with chunks-sized input' do + let(:unencoded_input) { '.' * ENC_SZ } + it 'works correctly' do assert_equal unencoded_input, output end - context "times two" do - let(:unencoded_input) { "." * 2 * ENC_SZ } - it "works correctly" do + context 'times two' do + let(:unencoded_input) { '.' * 2 * ENC_SZ } + it 'works correctly' do assert_equal unencoded_input, output end end end - context "with long input" do + context 'with long input' do # a bit more than a full chunk size - let(:unencoded_input) { "." * (ENC_SZ * 1.1).to_i } # >chunk + let(:unencoded_input) { '.' * (ENC_SZ * 1.1).to_i } # >chunk - it "decodes to original input" do + it 'decodes to original input' do assert_equal unencoded_input.bytesize, output_len assert_equal unencoded_input, output end @@ -105,7 +107,7 @@ Sequential = CZTop::Z85::Pipe::Strategy::Sequential Parallel = CZTop::Z85::Pipe::Strategy::Parallel - let(:input) { "foobar " * 100 } + let(:input) { 'foobar ' * 100 } let(:source) { StringIO.new(input) } let(:sink) { StringIO.new } let(:roundtrip_output) do @@ -118,7 +120,7 @@ let(:strategy) do strategy_class.new(source, sink, read_sz) do |chunk, prev_chunk| - calls << [ prev_chunk, chunk ] + calls << [prev_chunk, chunk] end end let(:read_sz) { 4 } @@ -126,32 +128,32 @@ context Sequential do let(:strategy_class) { Sequential } - context "when used" do - it "roundtrips" do + context 'when used' do + it 'roundtrips' do assert_equal input, roundtrip_output end end - describe "#execute" do - context "with even input" do - let(:input) { "abcdefgh" } # multiple of chunk + describe '#execute' do + context 'with even input' do + let(:input) { 'abcdefgh' } # multiple of chunk before { strategy.execute } - it "passes chunks one by one, and trailing nil" do + it 'passes chunks one by one, and trailing nil' do assert_equal [ - [ nil, "abcd" ], - [ "abcd", "efgh" ], - [ "efgh", nil ] + [nil, 'abcd'], + ['abcd', 'efgh'], + ['efgh', nil] ], calls end end - context "with uneven input" do - let(:input) { "abcdef" } + context 'with uneven input' do + let(:input) { 'abcdef' } before { strategy.execute } - it "passes chunks one by one, and trailing nil" do + it 'passes chunks one by one, and trailing nil' do assert_equal [ - [ nil, "abcd" ], - [ "abcd", "ef" ], - [ "ef", nil ] + [nil, 'abcd'], + ['abcd', 'ef'], + ['ef', nil] ], calls end end @@ -159,31 +161,31 @@ end context Parallel do let(:strategy_class) { Parallel } - context "when used" do - it "roundtrips" do + context 'when used' do + it 'roundtrips' do assert_equal input, roundtrip_output end end - describe "#execute" do - context "with even input" do - let(:input) { "abcdefgh" } # multiple of chunk + describe '#execute' do + context 'with even input' do + let(:input) { 'abcdefgh' } # multiple of chunk before { strategy.execute } - it "passes chunks one by one, and trailing nil" do + it 'passes chunks one by one, and trailing nil' do assert_equal [ - [ nil, "abcd" ], - [ "abcd", "efgh" ], - [ "efgh", nil ] + [nil, 'abcd'], + ['abcd', 'efgh'], + ['efgh', nil] ], calls end end - context "with uneven input" do - let(:input) { "abcdef" } + context 'with uneven input' do + let(:input) { 'abcdef' } before { strategy.execute } - it "passes chunks one by one, and trailing nil" do + it 'passes chunks one by one, and trailing nil' do assert_equal [ - [ nil, "abcd" ], - [ "abcd", "ef" ], - [ "ef", nil ] + [nil, 'abcd'], + ['abcd', 'ef'], + ['ef', nil] ], calls end end diff --git a/spec/cztop/z85_spec.rb b/spec/cztop/z85_spec.rb index d10aead..c84be4e 100644 --- a/spec/cztop/z85_spec.rb +++ b/spec/cztop/z85_spec.rb @@ -1,126 +1,128 @@ +# frozen_string_literal: true + require_relative 'spec_helper' describe CZTop::Z85 do - include_examples "has FFI delegate" + include_examples 'has FFI delegate' subject { CZTop::Z85.new } let(:ffi_delegate) { subject.ffi_delegate } - it "instantiates" do + it 'instantiates' do assert_kind_of CZTop::Z85, subject end - describe "#encode" do - context "with empty data" do - it "encodes" do - assert_equal "", subject.encode("") + describe '#encode' do + context 'with empty data' do + it 'encodes' do + assert_equal '', subject.encode('') end - it "returns ASCII encoded string" do - assert_equal Encoding::ASCII, subject.encode("").encoding + it 'returns ASCII encoded string' do + assert_equal Encoding::ASCII, subject.encode('').encoding end end - context "with even data" do + context 'with even data' do # "even" means its length is divisible by 4 with no remainder # test data from https://github.com/zeromq/rfc/blob/master/src/spec_32.c let(:input) do [ - 0x8E, 0x0B, 0xDD, 0x69, 0x76, 0x28, 0xB9, 0x1D, - 0x8F, 0x24, 0x55, 0x87, 0xEE, 0x95, 0xC5, 0xB0, - 0x4D, 0x48, 0x96, 0x3F, 0x79, 0x25, 0x98, 0x77, - 0xB4, 0x9C, 0xD9, 0x06, 0x3A, 0xEA, 0xD3, 0xB7 - ].map { |i| i.chr }.join + 0x8E, 0x0B, 0xDD, 0x69, 0x76, 0x28, 0xB9, 0x1D, + 0x8F, 0x24, 0x55, 0x87, 0xEE, 0x95, 0xC5, 0xB0, + 0x4D, 0x48, 0x96, 0x3F, 0x79, 0x25, 0x98, 0x77, + 0xB4, 0x9C, 0xD9, 0x06, 0x3A, 0xEA, 0xD3, 0xB7 + ].map(&:chr).join end - let(:expected_output) { "JTKVSB%%)wK0E.X)V>+}o?pNmC{O&4W4b!Ni{Lh6" } + let(:expected_output) { 'JTKVSB%%)wK0E.X)V>+}o?pNmC{O&4W4b!Ni{Lh6' } - it "encodes test data" do + it 'encodes test data' do assert_equal expected_output, subject.encode(input) end - it "round trips" do + it 'round trips' do z85 = subject.encode(input) assert_equal input, subject.decode(z85) end end - context "with odd data" do + context 'with odd data' do # input length is not divisible by 4 with no remainder - let(:input) { "foo bar" } # 7 bytes + let(:input) { 'foo bar' } # 7 bytes - it "raises" do + it 'raises' do err = assert_raises(ArgumentError) { subject.encode(input) } assert_match /wrong input length/, err.message end end - context "with failure" do + context 'with failure' do let(:nullptr) { ::FFI::Pointer::NULL } # represents failure before do allow(ffi_delegate).to receive(:encode).and_return(nullptr) end - it "raises" do - assert_raises(SystemCallError) { subject.encode("abcd") } + it 'raises' do + assert_raises(SystemCallError) { subject.encode('abcd') } end end end - describe "#decode" do - context "with empty data" do - it "decodes" do - assert_equal "", subject.decode("") + describe '#decode' do + context 'with empty data' do + it 'decodes' do + assert_equal '', subject.decode('') end end - context "with even data" do - let(:input) { "HelloWorld" } + context 'with even data' do + let(:input) { 'HelloWorld' } let(:expected_output) do - "\x86\x4F\xD2\x6F\xB5\x59\xF7\x5B".force_encoding Encoding::BINARY + (+"\x86\x4F\xD2\x6F\xB5\x59\xF7\x5B").force_encoding Encoding::BINARY end - it "decodes" do + it 'decodes' do assert_equal expected_output, subject.decode(input) end - it "returns binary encoded string" do + it 'returns binary encoded string' do assert_equal Encoding::BINARY, subject.decode(input).encoding end end - context "with odd data" do - let(:input) { "w]zPgvQTp1vQTO" } # 14 instead of 15 chars - it "raises" do + context 'with odd data' do + let(:input) { 'w]zPgvQTp1vQTO' } # 14 instead of 15 chars + it 'raises' do err = assert_raises(ArgumentError) { subject.decode(input) } assert_match /wrong input length/, err.message end end - context "with failure" do + context 'with failure' do let(:nullptr) { ::FFI::Pointer::NULL } # represents failure before do allow(ffi_delegate).to receive(:decode).and_return(nullptr) end - it "raises" do - assert_raises(SystemCallError) { subject.decode("abcde") } + it 'raises' do + assert_raises(SystemCallError) { subject.decode('abcde') } end end end - describe ".encode" do - let(:input) { "abcd" * 1_000 } - it "does the same as #encode" do + describe '.encode' do + let(:input) { 'abcd' * 1_000 } + it 'does the same as #encode' do assert_equal CZTop::Z85.new.encode(input), CZTop::Z85.encode(input) end - it "is thread-safe" do + it 'is thread-safe' do # NOTE: kind of of course, since the data manipulated isn't shared should = CZTop::Z85.new.encode(input) - (0 .. 1_000).map { Thread.new { CZTop::Z85.encode(input) } }.each do |t| + (0..1_000).map { Thread.new { CZTop::Z85.encode(input) } }.each do |t| assert_equal should, t.value end end end - describe ".decode" do - let(:input) { "abcde" } - it "does the same as #decode" do + describe '.decode' do + let(:input) { 'abcde' } + it 'does the same as #decode' do assert_equal CZTop::Z85.new.decode(input), CZTop::Z85.decode(input) end end diff --git a/spec/cztop/zap_spec.rb b/spec/cztop/zap_spec.rb index ccce25a..27a8e73 100644 --- a/spec/cztop/zap_spec.rb +++ b/spec/cztop/zap_spec.rb @@ -1,53 +1,55 @@ +# frozen_string_literal: true + require_relative 'spec_helper' describe CZTop::ZAP do i = 0 - let(:endpoint) { "inproc://endpoint_zap_spec_#{i+=1}" } + let(:endpoint) { "inproc://endpoint_zap_spec_#{i += 1}" } let(:req_socket) { CZTop::Socket::REQ.new(endpoint) } let(:rep_socket) { CZTop::Socket::REP.new(endpoint) } - it "is a has a version" do + it 'is a has a version' do assert_kind_of String, CZTop::ZAP::VERSION end - it "knows ZAP endpoint" do + it 'knows ZAP endpoint' do assert_kind_of String, CZTop::ZAP::ENDPOINT end describe CZTop::ZAP::Error do - it "is a StandardError" do + it 'is a StandardError' do assert_equal StandardError, CZTop::ZAP::Error.superclass end end describe CZTop::ZAP::VersionMismatch do - it "is an Error" do + it 'is an Error' do assert_equal CZTop::ZAP::Error, CZTop::ZAP::VersionMismatch.superclass end end describe CZTop::ZAP::Mechanisms do - it "it knows NULL" do - assert_equal "NULL", CZTop::ZAP::Mechanisms::NULL + it 'it knows NULL' do + assert_equal 'NULL', CZTop::ZAP::Mechanisms::NULL end - it "it knows PLAIN" do - assert_equal "PLAIN", CZTop::ZAP::Mechanisms::PLAIN + it 'it knows PLAIN' do + assert_equal 'PLAIN', CZTop::ZAP::Mechanisms::PLAIN end - it "it knows CURVE" do - assert_equal "CURVE", CZTop::ZAP::Mechanisms::CURVE + it 'it knows CURVE' do + assert_equal 'CURVE', CZTop::ZAP::Mechanisms::CURVE end end describe CZTop::ZAP::Request do - let(:version) { "1.0" } - let(:request_id) { "request 42" } - let(:domain) { "global" } - let(:address) { "1.2.3.4" } - let(:identity) { "john_doe" } - let(:mechanism) { "PLAIN" } - let(:credentials) { %w[ john66 pass1234 ] } + let(:version) { '1.0' } + let(:request_id) { 'request 42' } + let(:domain) { 'global' } + let(:address) { '1.2.3.4' } + let(:identity) { 'john_doe' } + let(:mechanism) { 'PLAIN' } + let(:credentials) { %w[john66 pass1234] } - describe ".from_message" do + describe '.from_message' do let(:msg) do fields = [version, request_id, domain, address, identity, mechanism, *credentials] @@ -56,11 +58,11 @@ let(:request) { CZTop::ZAP::Request.from_message(msg) } - context "with valid request message" do - it "builds a request" do + context 'with valid request message' do + it 'builds a request' do assert_kind_of CZTop::ZAP::Request, request end - it "builds request correctly" do + it 'builds request correctly' do assert_equal version, request.version assert_equal request_id, request.request_id assert_equal domain, request.domain @@ -70,9 +72,9 @@ assert_equal credentials, request.credentials end end - context "with invalid version" do - let(:version) { "0.9" } - it "raises" do + context 'with invalid version' do + let(:version) { '0.9' } + it 'raises' do assert_raises(CZTop::ZAP::VersionMismatch) do request end @@ -80,65 +82,64 @@ end end - describe "#initialize" do - context "with only domain and credentials" do - let(:domain) { "example.com" } - let(:credentials) { %w[ user pass ] } + describe '#initialize' do + context 'with only domain and credentials' do + let(:domain) { 'example.com' } + let(:credentials) { %w[user pass] } subject { CZTop::ZAP::Request.new(domain, credentials) } - it "sets domain" do + it 'sets domain' do assert_equal domain, subject.domain end - it "sets credentials" do + it 'sets credentials' do assert_equal credentials, subject.credentials end - it "sets CURVE mechanism" do - assert_equal "CURVE", subject.mechanism + it 'sets CURVE mechanism' do + assert_equal 'CURVE', subject.mechanism end - it "sets default version" do - assert_equal "1.0", subject.version + it 'sets default version' do + assert_equal '1.0', subject.version end end - context "with only a domain" do - let(:domain) { "example.com" } + context 'with only a domain' do + let(:domain) { 'example.com' } subject { CZTop::ZAP::Request.new(domain) } - it "sets credentials to empty array" do + it 'sets credentials to empty array' do assert_equal [], subject.credentials end - it "sets default version" do - assert_equal "1.0", subject.version + it 'sets default version' do + assert_equal '1.0', subject.version end end end - describe "#to_msg" do + describe '#to_msg' do let(:msg) { request.to_msg } - context "with no credentials" do + context 'with no credentials' do let(:request) { CZTop::ZAP::Request.new(domain) } it "doesn't include credential frames" do assert_equal 6, msg.size end end - context "with credentials" do + context 'with credentials' do let(:request) { CZTop::ZAP::Request.new(domain, %w[one two three]) } - it "includes credential frames" do + it 'includes credential frames' do assert_equal 9, msg.size end end end - end describe CZTop::ZAP::Response do - let(:version) { "1.0" } - let(:request_id) { "request 42" } - let(:status_code) { "200" } - let(:status_text) { "Welcome!" } - let(:user_id) { "jane77" } - let(:meta_data) { "properties in ZMTP 3.0 format" } + let(:version) { '1.0' } + let(:request_id) { 'request 42' } + let(:status_code) { '200' } + let(:status_text) { 'Welcome!' } + let(:user_id) { 'jane77' } + let(:meta_data) { 'properties in ZMTP 3.0 format' } subject do CZTop::ZAP::Response.new(status_code).tap do |r| @@ -151,7 +152,7 @@ end end - describe ".from_message" do + describe '.from_message' do let(:msg) do fields = [version, request_id, status_code, status_text, user_id, meta_data].map(&:to_s) @@ -159,11 +160,11 @@ end subject { CZTop::ZAP::Response.from_message(msg) } - context "given a valid response message" do - it "builds a response" do + context 'given a valid response message' do + it 'builds a response' do assert_kind_of CZTop::ZAP::Response, subject end - it "builds response correctly" do + it 'builds response correctly' do assert_equal version, subject.version assert_equal request_id, subject.request_id assert_equal status_code, subject.status_code @@ -173,33 +174,33 @@ end end - context "given invalid version" do - let(:version) { "0.9" } - it "raises" do + context 'given invalid version' do + let(:version) { '0.9' } + it 'raises' do assert_raises(CZTop::ZAP::VersionMismatch) do subject end end end - context "given status code for temporary failure" do + context 'given status code for temporary failure' do let(:status_code) { 300 } - it "raises" do + it 'raises' do assert_raises(CZTop::ZAP::Response::TemporaryError) do subject end end end - context "given status code for internal error" do + context 'given status code for internal error' do let(:status_code) { 500 } - it "raises" do + it 'raises' do assert_raises(CZTop::ZAP::Response::InternalError) do subject end end end - context "given invalid status code" do + context 'given invalid status code' do let(:status_code) { 666 } - it "raises" do + it 'raises' do assert_raises(CZTop::ZAP::Response::InternalError) do subject end @@ -207,70 +208,70 @@ end end - describe "#initialize" do + describe '#initialize' do subject { described_class.new(status_code) } - it "sets default version" do - assert_equal "1.0", subject.version + it 'sets default version' do + assert_equal '1.0', subject.version end - context "with valid status code" do + context 'with valid status code' do let(:status_code) { 500 } - it "initializes" do + it 'initializes' do subject end end - context "with invalid status code" do + context 'with invalid status code' do let(:status_code) { 333 } - it "raises" do + it 'raises' do assert_raises(ArgumentError) do subject end end end end - describe "#success?" do - let(:status_code) { "200" } - context "with successful authentication" do - it "returns true" do + describe '#success?' do + let(:status_code) { '200' } + context 'with successful authentication' do + it 'returns true' do assert_operator subject, :success? end end - context "with failed authentication" do - let(:status_code) { "400" } - it "returns false" do + context 'with failed authentication' do + let(:status_code) { '400' } + it 'returns false' do refute_operator subject, :success? end end end - describe "#to_msg" do + describe '#to_msg' do let(:fields) do - [ version, request_id, status_code, status_text, user_id, meta_data ] + [version, request_id, status_code, status_text, user_id, meta_data] end - it "packs response into a message" do + it 'packs response into a message' do assert_equal fields, subject.to_msg.to_a end end - describe "#user_id" do - context "when authenticated" do - it "returns user ID" do + describe '#user_id' do + context 'when authenticated' do + it 'returns user ID' do assert_equal user_id, subject.user_id end end - context "when not authenticated" do - let(:status_code) { "300" } - it "returns nil" do + context 'when not authenticated' do + let(:status_code) { '300' } + it 'returns nil' do assert_nil subject.user_id end end end - describe "#meta_data" do - context "when authenticated" do - it "returns meta data" do + describe '#meta_data' do + context 'when authenticated' do + it 'returns meta data' do assert_equal meta_data, subject.meta_data end end - context "when not authenticated" do - let(:status_code) { "300" } - it "returns meta data" do + context 'when not authenticated' do + let(:status_code) { '300' } + it 'returns meta data' do assert_nil subject.meta_data end end diff --git a/spec/cztop/zsock_options_spec.rb b/spec/cztop/zsock_options_spec.rb index fc3be78..2ae5eee 100644 --- a/spec/cztop/zsock_options_spec.rb +++ b/spec/cztop/zsock_options_spec.rb @@ -1,17 +1,19 @@ +# frozen_string_literal: true + require_relative 'spec_helper' describe CZTop::ZsockOptions do i = 0 - let(:endpoint) { "inproc://zsock_options_#{i+=1}" } + let(:endpoint) { "inproc://zsock_options_#{i += 1}" } let(:socket) { CZTop::Socket::REQ.new(endpoint) } let(:options) { socket.options } - describe "#options" do - it "returns options accessor" do + describe '#options' do + it 'returns options accessor' do assert_kind_of CZTop::ZsockOptions::OptionsAccessor, options end - it "memoizes the options accessor" do + it 'memoizes the options accessor' do assert_same socket.options, socket.options end @@ -20,78 +22,78 @@ end end - describe "event-based methods" do + describe 'event-based methods' do before do expect(options).to receive(:events).and_return(events) end - describe "#readable?" do - context "with read event set" do + describe '#readable?' do + context 'with read event set' do let(:events) { CZTop::Poller::ZMQ::POLLIN } - it "returns true" do + it 'returns true' do assert_operator socket, :readable? end end - context "with read event unset" do + context 'with read event unset' do let(:events) { 0 } - it "returns false" do + it 'returns false' do refute_operator socket, :readable? end end end - describe "#writable?" do - context "with write event set" do + describe '#writable?' do + context 'with write event set' do let(:events) { CZTop::Poller::ZMQ::POLLOUT } - it "returns true" do + it 'returns true' do assert_operator socket, :writable? end end - context "with write event unset" do + context 'with write event unset' do let(:events) { 0 } - it "returns false" do + it 'returns false' do refute_operator socket, :writable? end end end end - describe "#fd" do - it "returns socket FD" do + describe '#fd' do + it 'returns socket FD' do assert_equal socket.options.fd, socket.fd end end describe CZTop::ZsockOptions::OptionsAccessor do - describe "#sndhwm" do - context "when getting current value" do - it "returns value" do + describe '#sndhwm' do + context 'when getting current value' do + it 'returns value' do assert_kind_of Integer, options.sndhwm end end - context "when setting new value" do + context 'when setting new value' do let(:new_value) { 99 } before { options.sndhwm = new_value } - it "sets new value" do + it 'sets new value' do assert_equal new_value, options.sndhwm end end end - describe "#rcvhwm" do - context "when getting current value" do - it "returns value" do + describe '#rcvhwm' do + context 'when getting current value' do + it 'returns value' do assert_kind_of Integer, options.rcvhwm end end - context "when setting new value" do + context 'when setting new value' do let(:new_value) { 99 } before { options.rcvhwm = new_value } - it "sets new value" do + it 'sets new value' do assert_equal new_value, options.rcvhwm end end end - describe "#CURVE_server" do - it "sets and gets CURVE server flag" do + describe '#CURVE_server' do + it 'sets and gets CURVE server flag' do refute options.CURVE_server? options.CURVE_server = true assert options.CURVE_server? @@ -99,104 +101,104 @@ refute options.CURVE_server? end - it "is mutually exclusive with PLAIN" do + it 'is mutually exclusive with PLAIN' do options.CURVE_server = true options.PLAIN_server = true refute_operator options, :CURVE_server? end end - describe "#CURVE_serverkey" do - context "with key not set" do - it "returns nil" do + describe '#CURVE_serverkey' do + context 'with key not set' do + it 'returns nil' do assert_nil options.CURVE_serverkey end end - context "with valid key" do + context 'with valid key' do let(:cert) { CZTop::Certificate.new } let(:key_bin) { cert.public_key(format: :binary) } let(:key_z85) { cert.public_key(format: :z85) } - context "as binary" do + context 'as binary' do When { options.CURVE_serverkey = key_bin } Then { key_z85 == options.CURVE_serverkey } end - context "as Z85" do + context 'as Z85' do When { options.CURVE_serverkey = key_z85 } Then { key_z85 == options.CURVE_serverkey } end end - context "with invalid key" do - it "raises" do - assert_raises(ArgumentError) { options.CURVE_serverkey = "foo" } + context 'with invalid key' do + it 'raises' do + assert_raises(ArgumentError) { options.CURVE_serverkey = 'foo' } assert_raises { options.CURVE_serverkey = nil } end end end - describe "#CURVE_secretkey" do - context "with key not set" do + describe '#CURVE_secretkey' do + context 'with key not set' do Then { options.CURVE_secretkey.nil? } end - context "with valid key" do + context 'with valid key' do let(:cert) { CZTop::Certificate.new } let(:key_bin) { cert.secret_key(format: :binary) } let(:key_z85) { cert.secret_key(format: :z85) } When { cert.apply(socket) } Then { key_z85 == options.CURVE_secretkey } end - context "with only CURVE mechanism enabled but no key set" do + context 'with only CURVE mechanism enabled but no key set' do When { options.CURVE_server = true } # just enable CURVE Then { options.CURVE_secretkey.is_a? String } - And { not options.CURVE_secretkey.empty? } + And { !options.CURVE_secretkey.empty? } end end - describe "#mechanism" do - context "with no security" do - it "returns :NULL" do + describe '#mechanism' do + context 'with no security' do + it 'returns :NULL' do assert_equal :NULL, options.mechanism end end - context "with PLAIN security" do + context 'with PLAIN security' do When { options.PLAIN_server = true } Then { :PLAIN == options.mechanism } end - context "with CURVE security" do + context 'with CURVE security' do When { options.CURVE_server = true } Then { :CURVE == options.mechanism } end -# context "with GSSAPI security" do -# it "returns :GSSAPI" # FIXME: see "GSSAPI" branch -# end - context "with unknown security mechanism" do + # context "with GSSAPI security" do + # it "returns :GSSAPI" # FIXME: see "GSSAPI" branch + # end + context 'with unknown security mechanism' do before do expect(CZMQ::FFI::Zsock).to receive(:mechanism) .with(socket).and_return(99) end - it "raises" do + it 'raises' do assert_raises { options.mechanism } end end end - describe "#zap_domain" do - context "with no ZAP domain set" do - Then { "" == options.zap_domain } + describe '#zap_domain' do + context 'with no ZAP domain set' do + Then { '' == options.zap_domain } end - context "with valid ZAP domain" do - Given(:domain) { "foobar" } + context 'with valid ZAP domain' do + Given(:domain) { 'foobar' } When { options.zap_domain = domain } Then { domain == options.zap_domain } end - context "with too long ZAP domain" do - Given(:domain) { "o" * 255 } + context 'with too long ZAP domain' do + Given(:domain) { 'o' * 255 } When(:result) { options.zap_domain = domain } Then { result == Failure(ArgumentError) } end end - describe "#PLAIN_server" do - it "sets and gets PLAIN server flag" do + describe '#PLAIN_server' do + it 'sets and gets PLAIN server flag' do refute options.PLAIN_server? options.PLAIN_server = true assert options.PLAIN_server? @@ -204,211 +206,208 @@ refute options.PLAIN_server? end - it "is mutually exclusive with CURVE" do + it 'is mutually exclusive with CURVE' do options.PLAIN_server = true options.CURVE_server = true refute_operator options, :PLAIN_server? end end - describe "#PLAIN_username" do - context "with no username set" do + describe '#PLAIN_username' do + context 'with no username set' do Then { options.PLAIN_username.nil? } end - context "setting and getting" do - Given(:username) { "foo" } + context 'setting and getting' do + Given(:username) { 'foo' } When { options.PLAIN_username = username } Then { username == options.PLAIN_username } end end - describe "#PLAIN_password" do - context "with not PLAIN mechanism" do + describe '#PLAIN_password' do + context 'with not PLAIN mechanism' do Then { options.PLAIN_password.nil? } end - context "with password set" do - Given(:password) { "secret" } + context 'with password set' do + Given(:password) { 'secret' } When { options.PLAIN_password = password } Then { options.PLAIN_password == password } end - context "with only username set" do - When { options.PLAIN_username = "foo" } - Then { "" == options.PLAIN_password } + context 'with only username set' do + When { options.PLAIN_username = 'foo' } + Then { '' == options.PLAIN_password } end - context "setting and getting" do - Given(:password) { "foo" } + context 'setting and getting' do + Given(:password) { 'foo' } When { options.PLAIN_password = password } When { password == options.PLAIN_password } end end - describe "#sndtimeo" do - it "sets and gets send timeout" do - assert_equal -1, options.sndtimeo + describe '#sndtimeo' do + it 'sets and gets send timeout' do + assert_equal(-1, options.sndtimeo) options.sndtimeo = 7 assert_equal 7, options.sndtimeo end end - describe "#rcvtimeo" do - it "sets and gets receive timeout" do - assert_equal -1, options.rcvtimeo + describe '#rcvtimeo' do + it 'sets and gets receive timeout' do + assert_equal(-1, options.rcvtimeo) options.rcvtimeo = 7 assert_equal 7, options.rcvtimeo end end - describe "#router_mandatory=" do + describe '#router_mandatory=' do let(:socket) { CZTop::Socket::ROUTER.new } - it "can set the flag" do + it 'can set the flag' do expect(CZMQ::FFI::Zsock).to receive(:set_router_mandatory) .with(socket, 1) options.router_mandatory = true end - it "can unset the flag" do + it 'can unset the flag' do expect(CZMQ::FFI::Zsock).to receive(:set_router_mandatory) .with(socket, 0) options.router_mandatory = false end - context "with flag set and message unroutable" do + context 'with flag set and message unroutable' do before { options.router_mandatory = true } - let(:identity) { "receiver identity" } - let(:content) { "foobar" } - let(:msg) { [ identity, "", content ] } - it "raises" do + let(:identity) { 'receiver identity' } + let(:content) { 'foobar' } + let(:msg) { [identity, '', content] } + it 'raises' do assert_raises(SocketError) { socket << msg } end end end - describe "#identity" do - context "with no identity set" do - it "returns empty string" do - assert_equal "", options.identity + describe '#identity' do + context 'with no identity set' do + it 'returns empty string' do + assert_equal '', options.identity end end - context "with identity set" do - let(:identity) { "foobar" } + context 'with identity set' do + let(:identity) { 'foobar' } before { options.identity = identity } - it "returns identity" do + it 'returns identity' do assert_equal identity, options.identity end end end - describe "#identity=" do - context "with zero-length identity" do - let(:identity) { "" } - it "raises" do + describe '#identity=' do + context 'with zero-length identity' do + let(:identity) { '' } + it 'raises' do assert_raises(ArgumentError) { options.identity = identity } end end - context "with invalid identity" do + context 'with invalid identity' do # NOTE: leading null byte is reserved for ZMQ let(:identity) { "\x00foobar" } - it "raises" do + it 'raises' do assert_raises(ArgumentError) { options.identity = identity } end end - context "with too long identity" do + context 'with too long identity' do # NOTE: identities are 255 bytes maximum - let(:identity) { "x" * 256 } - it "raises" do + let(:identity) { 'x' * 256 } + it 'raises' do assert_raises(ArgumentError) { options.identity = identity } end end end - describe "#tos" do - context "with no TOS" do - it "returns zero" do + describe '#tos' do + context 'with no TOS' do + it 'returns zero' do assert_equal 0, options.tos end end - context "with TOS set" do + context 'with TOS set' do let(:tos) { 5 } before { options.tos = tos } - it "returns TOS" do + it 'returns TOS' do assert_equal tos, options.tos end end - context "with invalid TOS" do - it "raises" do + context 'with invalid TOS' do + it 'raises' do assert_raises(ArgumentError) { options.tos = -5 } end end - context "when resetting to zero" do + context 'when resetting to zero' do before { options.tos = 10 } it "doesn't raise" do options.tos = 0 end end end - describe "#heartbeat_ivl", if: (has_zmq_version?("4.2") && has_czmq_drafts?) do - - context "with no IVL" do - it "returns zero" do + describe '#heartbeat_ivl', if: (has_zmq_version?('4.2') && has_czmq_drafts?) do + context 'with no IVL' do + it 'returns zero' do assert_equal 0, options.heartbeat_ivl end end - context "with IVL set" do + context 'with IVL set' do let(:ivl) { 5 } before { options.heartbeat_ivl = ivl } - it "returns IVL" do + it 'returns IVL' do assert_equal ivl, options.heartbeat_ivl end end end - describe "#heartbeat_ttl", if: (has_zmq_version?("4.2") && has_czmq_drafts?) do - - context "with no TTL" do - it "returns zero" do + describe '#heartbeat_ttl', if: (has_zmq_version?('4.2') && has_czmq_drafts?) do + context 'with no TTL' do + it 'returns zero' do assert_equal 0, options.heartbeat_ttl end end - context "with TTL set" do + context 'with TTL set' do let(:ttl) { 500 } before { options.heartbeat_ttl = ttl } - it "returns TTL" do + it 'returns TTL' do assert_equal ttl, options.heartbeat_ttl end end - context "with invalid TTL" do + context 'with invalid TTL' do let(:ttl) { 500.3 } - it "raises" do + it 'raises' do assert_raises(ArgumentError) { options.heartbeat_ttl = ttl } end end - context "with out-of-range TTL" do + context 'with out-of-range TTL' do let(:ttl) { 100_000 } - it "raises" do + it 'raises' do assert_raises(ArgumentError) { options.heartbeat_ttl = ttl } end end - context "with insignificant TTL" do + context 'with insignificant TTL' do let(:ttl) { 80 } # less than 100 before { options.heartbeat_ttl = ttl } - it "has no effect" do + it 'has no effect' do assert_equal 0, options.heartbeat_ttl end end end - describe "#heartbeat_timeout", if: (has_zmq_version?("4.2") && has_czmq_drafts?) do - - context "with no timeout" do - it "returns -1" do - assert_equal -1, options.heartbeat_timeout + describe '#heartbeat_timeout', if: (has_zmq_version?('4.2') && has_czmq_drafts?) do + context 'with no timeout' do + it 'returns -1' do + assert_equal(-1, options.heartbeat_timeout) end end - context "with timeout set" do + context 'with timeout set' do let(:timeout) { 5 } before { options.heartbeat_timeout = timeout } - it "returns timeout" do + it 'returns timeout' do assert_equal timeout, options.heartbeat_timeout end end - context "integration test" do + context 'integration test' do let(:timeout) { 50 } - i = 55556 + i = 55_556 let(:endpoint) { "tcp://127.0.0.1:#{i += 1}" } let(:server_socket) do socket = CZTop::Socket::SERVER.new @@ -425,30 +424,30 @@ end let(:server_mon) do mon = CZTop::Monitor.new(server_socket) - mon.listen(*%w[ CONNECTED DISCONNECTED ACCEPTED ]) + mon.listen(*%w[CONNECTED DISCONNECTED ACCEPTED]) mon.start mon.actor.options.rcvtimeo = 50 mon end let(:accepted_event) do - assert_equal "ACCEPTED", server_mon.next[0] + assert_equal 'ACCEPTED', server_mon.next[0] end let(:disconnected_event) do - assert_equal "DISCONNECTED", server_mon.next[0] + assert_equal 'DISCONNECTED', server_mon.next[0] end - context "with client connected" do + context 'with client connected' do before do server_socket server_mon client_socket end - it "accepts connection" do + it 'accepts connection' do accepted_event end end - context "with client socket dead" do + context 'with client socket dead' do before do server_socket server_mon @@ -459,15 +458,13 @@ client_socket.ffi_delegate.destroy end - it "closes connection" do - begin - disconnected_event - rescue IO::EAGAINWaitReadable - flunk "client wasn't disconnected" - end + it 'closes connection' do + disconnected_event + rescue IO::EAGAINWaitReadable + flunk "client wasn't disconnected" end end - context "with talking and then dead client socket" do + context 'with talking and then dead client socket' do let(:received_msg) { server_socket.receive } # to know the routing ID before do server_socket @@ -475,8 +472,8 @@ server_mon client_socket accepted_event - client_socket << "foo" - assert_equal %w"foo", received_msg.to_a + client_socket << 'foo' + assert_equal %w[foo], received_msg.to_a # NOTE: Disconnecting alone won't do it. It has to be destroyed. client_socket.ffi_delegate.destroy @@ -485,13 +482,13 @@ end let(:test_msg) do - msg = CZTop::Message.new "bar" + msg = CZTop::Message.new 'bar' msg.routing_id = received_msg.routing_id msg end - context "when server sends message" do - it "raises" do + context 'when server sends message' do + it 'raises' do assert_raises(IO::EAGAINWaitWritable) do server_socket << test_msg end @@ -501,151 +498,151 @@ end end - describe "#linger" do - context "with no LINGER" do - it "returns default" do + describe '#linger' do + context 'with no LINGER' do + it 'returns default' do assert_equal 0, options.linger # ZMQ docs say 30_000, but they're wrong end end - context "with LINGER set" do + context 'with LINGER set' do let(:linger) { 500 } before { options.linger = linger } - it "returns LINGER" do + it 'returns LINGER' do assert_equal linger, options.linger end end end - describe "#ipv6=" do - it "can enable IPv6" do + describe '#ipv6=' do + it 'can enable IPv6' do expect(CZMQ::FFI::Zsock).to receive(:set_ipv6) .with(socket, 1) options.ipv6 = true end - it "can disable IPv6" do + it 'can disable IPv6' do expect(CZMQ::FFI::Zsock).to receive(:set_ipv6) .with(socket, 0) options.ipv6 = false end end - describe "#ipv6?" do - context "with default setting" do - it "returns false" do + describe '#ipv6?' do + context 'with default setting' do + it 'returns false' do refute_operator options, :ipv6? end end - context "with ipv6 enabled" do - before {options.ipv6 = true} - it "returns true" do + context 'with ipv6 enabled' do + before { options.ipv6 = true } + it 'returns true' do assert_operator options, :ipv6? end end - context "with ipv6 disabled" do - before {options.ipv6 = false} - it "returns false" do + context 'with ipv6 disabled' do + before { options.ipv6 = false } + it 'returns false' do refute_operator options, :ipv6? end end end - describe "#[]" do - context "with vague option name" do - let(:identity) { "foobar" } + describe '#[]' do + context 'with vague option name' do + let(:identity) { 'foobar' } before do options.identity = identity end - it "gets option" do + it 'gets option' do assert_equal options.CURVE_server?, options[:curve_server] assert_equal identity, options[:IDENTITY] - assert_equal identity, options["IDENTITY"] + assert_equal identity, options['IDENTITY'] assert_equal options.tos, options[:ToS] end end - context "with plain wrong option name" do - it "raises" do + context 'with plain wrong option name' do + it 'raises' do assert_raises(NoMethodError) { options[:foo] } assert_raises(NoMethodError) { options[5] } assert_raises(NoMethodError) { options['!!'] } end end end - describe "#[]=" do - let(:identity) { "foobar" } + describe '#[]=' do + let(:identity) { 'foobar' } let(:tos) { 5 } before do options[:curve_server] = true options[:IDENTITY] = identity options[:ToS] = tos end - context "with vague option name" do - it "sets option" do + context 'with vague option name' do + it 'sets option' do assert_operator options, :CURVE_server? assert_equal identity, options.identity assert_equal tos, options.tos end end - context "with plain wrong option name" do - it "raises" do + context 'with plain wrong option name' do + it 'raises' do assert_raises(NoMethodError) { options[:foo] = 5 } - assert_raises(NoMethodError) { options[5] = "foo" } + assert_raises(NoMethodError) { options[5] = 'foo' } assert_raises(NoMethodError) { options['!!'] = :bar } end end end - describe "#fd" do - it "FD is of correct type" do + describe '#fd' do + it 'FD is of correct type' do fd_type = FFI::Platform.unix? ? Integer : FFI::Pointer assert_kind_of(fd_type, socket.options.fd) end end - fdescribe "#reconnect_ivl" do - context "with no RECONNECT_IVL" do - it "returns default" do + fdescribe '#reconnect_ivl' do + context 'with no RECONNECT_IVL' do + it 'returns default' do assert_equal 100, options.reconnect_ivl end end - context "with RECONNECT_IVL set" do + context 'with RECONNECT_IVL set' do let(:reconnect_ivl) { 500 } before { options.reconnect_ivl = reconnect_ivl } - it "returns RECONNECT_IVL" do + it 'returns RECONNECT_IVL' do assert_equal reconnect_ivl, options.reconnect_ivl end end end - describe "#events" do + describe '#events' do let(:writer) { CZTop::Socket::PUSH.new(endpoint) } let(:reader) { CZTop::Socket::PULL.new(endpoint) } - context "with readable socket" do - before { writer << "foo" } - it "is readable" do + context 'with readable socket' do + before { writer << 'foo' } + it 'is readable' do assert (reader.options.events & CZTop::Poller::ZMQ::POLLIN) > 0, - "should be readable" + 'should be readable' end end - context "with non-readable socket" do - it "is not readable" do + context 'with non-readable socket' do + it 'is not readable' do assert (reader.options.events & CZTop::Poller::ZMQ::POLLIN) == 0, - "should not be readable" + 'should not be readable' end end - context "with writable socket" do - it "is writable" do + context 'with writable socket' do + it 'is writable' do assert (writer.options.events & CZTop::Poller::ZMQ::POLLOUT) > 0, - "should be writable" + 'should be writable' end end - context "with non-writable socket" do + context 'with non-writable socket' do let(:full_writer) do sock = CZTop::Socket::PUSH.new sock.options.sndhwm = 1 # set SNDHWM option before connecting sock.connect(endpoint) - sock << "is now full" + sock << 'is now full' sock end - it "is not writable" do + it 'is not writable' do assert (full_writer.options.events & CZTop::Poller::ZMQ::POLLOUT) == 0, - "should not be writable" + 'should not be writable' end end end diff --git a/spec/cztop_spec.rb b/spec/cztop_spec.rb index 8b58ebf..bc39d10 100644 --- a/spec/cztop_spec.rb +++ b/spec/cztop_spec.rb @@ -1,7 +1,9 @@ +# frozen_string_literal: true + require_relative 'spec_helper' describe CZTop do - it "has a version" do + it 'has a version' do refute_nil CZTop::VERSION end diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index e2879f3..b44f9d0 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'bundler/setup' require 'simplecov' require 'rspec' @@ -30,9 +32,7 @@ # raise it to a more sane 1024, like on Linux. begin soft_limit, hard_limit = Process.getrlimit(:NOFILE) - if soft_limit < 1024 - Process.setrlimit(:NOFILE, 1024, hard_limit) - end + Process.setrlimit(:NOFILE, 1024, hard_limit) if soft_limit < 1024 rescue NotImplementedError # JRuby end diff --git a/spec/zmq_helper.rb b/spec/zmq_helper.rb index 0e9c347..4526083 100644 --- a/spec/zmq_helper.rb +++ b/spec/zmq_helper.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + # Helper to deal with certain version or build differences of the ZMQ and CZMQ # libraries. # @@ -12,6 +14,7 @@ def has_zmq_version?(version) ::CZMQ::FFI::ZMQ_VERSION >= version end + # This can be used to run certain test examples only if the required minimal # CZMQ version is available. # @@ -22,6 +25,7 @@ def has_czmq_version?(version) ::CZMQ::FFI::CZMQ_VERSION >= version end + # This can be used to run certain test examples only if ZMQ draft API is # available. # @@ -31,6 +35,7 @@ def has_zmq_drafts? CZMQ::FFI::LibZMQ.has_draft? end + # This can be used to run certain test examples only if CZMQ draft API is # available. #