Skip to content

Commit 5f07aee

Browse files
More test de-duplication + acquire_token timeout => nil.
1 parent 005b57e commit 5f07aee

File tree

4 files changed

+28
-27
lines changed

4 files changed

+28
-27
lines changed

fixtures/async/limiter/a_limiter.rb

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,20 @@ module Limiter
5959
result = limiter.acquire(timeout: 0.01)
6060
expect(result).to be_truthy
6161
end
62+
63+
with "#acquire_token" do
64+
it "supports acquire_token with resources" do
65+
token = limiter.acquire_token
66+
67+
expect(token.released?).to be == false
68+
69+
token.release
70+
expect(token.released?).to be == true
71+
72+
# Resource returned to queue:
73+
expect(limiter).not.to be(:limited?)
74+
end
75+
end
6276

6377
with "concurrency" do
6478
include Sus::Fixtures::Async::SchedulerContext

fixtures/async/limiter/a_semaphore.rb

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,18 @@ module Limiter
3030
limiter.release
3131
expect(limiter).not.to be(:limited?)
3232
end
33+
34+
with "#acquire_token" do
35+
it "returns nil when timeout is reached" do
36+
# Fill the semaphore to capacity:
37+
limiter.acquire
38+
39+
token = limiter.acquire_token(timeout: 0)
40+
41+
# Should get nil token due to timeout (no resources available)
42+
expect(token).to be == nil
43+
end
44+
end
3345
end
3446
end
3547
end

lib/async/limiter/generic.rb

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -126,6 +126,8 @@ def acquire(timeout: nil, cost: 1, **options)
126126
# @asynchronous
127127
def acquire_token(**options)
128128
resource = acquire(**options)
129+
return nil unless resource
130+
129131
token = Token.new(self, resource, **options)
130132

131133
return token unless block_given?

test/async/limiter/queued.rb

Lines changed: 0 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -101,32 +101,5 @@
101101
# Should be empty again
102102
expect(semaphore).to be(:limited?)
103103
end
104-
105-
with "#acquire_token" do
106-
it "supports acquire_token with resources" do
107-
semaphore.release("token_resource")
108-
109-
token = semaphore.acquire_token
110-
111-
expect(token).to be_a(Async::Limiter::Token)
112-
expect(token.resource).to be == "token_resource" # Actual resource from queue
113-
expect(token.released?).to be == false
114-
115-
token.release
116-
expect(token.released?).to be == true
117-
118-
# Resource returned to queue:
119-
expect(semaphore).not.to be(:limited?)
120-
end
121-
122-
it "supports token with timeout" do
123-
# Empty queue:
124-
token = semaphore.acquire_token(timeout: 0)
125-
126-
# Should get nil resource due to timeout
127-
expect(token.resource).to be == nil
128-
expect(token.released?).to be == true
129-
end
130-
end
131104
end
132105
end

0 commit comments

Comments
 (0)