forked from petergoldstein/dalli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmemcached_mock.rb
111 lines (95 loc) · 2.55 KB
/
memcached_mock.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
require "socket"
$started = {}
module MemcachedMock
def self.start(port=19123, &block)
server = TCPServer.new("localhost", port)
session = server.accept
block.call session
end
def self.delayed_start(port=19123, wait=1, &block)
server = TCPServer.new("localhost", port)
sleep wait
block.call server
end
module Helper
# Forks the current process and starts a new mock Memcached server on
# port 22122.
#
# memcached_mock(lambda {|sock| socket.write('123') }) do
# assert_equal "PONG", Dalli::Client.new('localhost:22122').get('abc')
# end
#
def memcached_mock(proc, meth = :start)
return unless supports_fork?
begin
pid = fork do
trap("TERM") { exit }
MemcachedMock.send(meth) do |*args|
proc.call(*args)
end
end
sleep 0.3 # Give time for the socket to start listening.
yield
ensure
if pid
Process.kill("TERM", pid)
Process.wait(pid)
end
end
end
PATHS = %w(
/usr/local/bin/
/opt/local/bin/
/usr/bin/
)
def find_memcached
output = `memcached -h | head -1`.strip
if output && output =~ /^memcached (\d.\d.\d+)/ && $1 > '1.4'
return (puts "Found #{output} in PATH"; '')
end
PATHS.each do |path|
output = `memcached -h | head -1`.strip
if output && output =~ /^memcached (\d\.\d\.\d+)/ && $1 > '1.4'
return (puts "Found #{output} in #{path}"; path)
end
end
raise Errno::ENOENT, "Unable to find memcached 1.4+ locally"
end
def memcached(port=19122, args='', options={})
Memcached.path ||= find_memcached
cmd = "#{Memcached.path}memcached #{args} -p #{port}"
$started[port] ||= begin
#puts "Starting: #{cmd}..."
pid = IO.popen(cmd).pid
at_exit do
begin
Process.kill("TERM", pid)
Process.wait(pid)
rescue Errno::ECHILD, Errno::ESRCH
end
end
sleep 0.1
pid
end
yield Dalli::Client.new(["localhost:#{port}", "127.0.0.1:#{port}"], options)
end
def supports_fork?
!defined?(RUBY_ENGINE) || RUBY_ENGINE != 'jruby'
end
def memcached_kill(port)
pid = $started.delete(port)
if pid
begin
Process.kill("TERM", pid)
Process.wait(pid)
rescue Errno::ECHILD, Errno::ESRCH
end
end
end
end
end
module Memcached
class << self
attr_accessor :path
end
end