require 'spec_helper' describe Lifen::Token do describe ':needs_to_be_refreshed?' do context 'default configuration' do it 'knows when a token needs to be refreshed' do token = Lifen::Token.new(value: "valid_token", expires_at: Time.now.to_i + 120) expect(token.needs_to_be_refreshed?).to be_falsy end it 'knows when a token needs to be refreshed' do token = Lifen::Token.new(value: "valid_token", expires_at: Time.now.to_i + 40) expect(token.needs_to_be_refreshed?).to be_falsy end end context 'custom configuration' do before do Lifen.configure do |config| config.expiration_margin = 60 end end it 'knows when a token needs to be refreshed' do token = Lifen::Token.new(value: "valid_token", expires_at: Time.now.to_i + 120) expect(token.needs_to_be_refreshed?).to be_falsy end it 'knows when a token needs to be refreshed' do token = Lifen::Token.new(value: "valid_token", expires_at: Time.now.to_i + 40) expect(token.needs_to_be_refreshed?).to be_truthy end it 'refreshs the token' do token = Lifen::Token.new(value: "valid_token", expires_at: Time.now.to_i + 40) expect(token).to receive(:refresh) do token.expires_at = Time.now.to_i + 120 end token.refresh_once_if_needed end end end describe 'expired token' do let(:expired_token) { Lifen::Token.new(value: "valid_token", expires_at: Time.now.to_i - 60) } context ':refresh_once_if_needed' do it 'refreshs the token' do expect(expired_token).to receive(:refresh) do expired_token.expires_at = Time.now.to_i + 60 end expired_token.refresh_once_if_needed end end end describe 'invalid token' do let(:invalid_token) { Lifen::Token.new(value: "", expires_at: Time.now.to_i + 60) } it 'detects invalid tokens' do expect(invalid_token).to_not be_valid end end describe 'thread safe' do let(:user) { Lifen::User.new } let(:expired_token) { Lifen::Token.new(user: user, value: "valid_token", expires_at: Time.now.to_i - 60) } let(:other_expired_token) { Lifen::Token.new(user: user, value: "valid_token", expires_at: Time.now.to_i - 60) } before do allow(expired_token).to receive(:refresh) do sleep 1 expired_token.expires_at = Time.now.to_i + 60 end allow(other_expired_token).to receive(:refresh) do sleep 1 end end it 'queues refresh calls' do expect(expired_token).to receive(:refresh).once expect(other_expired_token).to_not receive(:refresh) threads = [] threads << Thread.new do expired_token.refresh_once_if_needed do |token| token.value = "expired_token" token.expires_at = Time.now.to_i - 60 end end threads << Thread.new do other_expired_token.refresh_once_if_needed do |token| token.value = "valid_token" token.expires_at = Time.now.to_i + 60 end end threads.map { |t| t.join } # waiting for all threads to finish end end end