Skip to content

Instantly share code, notes, and snippets.

@coreyward
Created February 23, 2011 01:25
Show Gist options
  • Save coreyward/839814 to your computer and use it in GitHub Desktop.
Save coreyward/839814 to your computer and use it in GitHub Desktop.
Test cloudfiles gem for thread safety through trial and error...
require 'rubygems'
require 'cloudfiles'
class Hash
def reverse_merge(other_hash)
other_hash.merge(self)
end
end
class Cloud
@username = 'username'
@api_key = 'api_key'
def initialize (path, options = {})
@path = path
@options = options.reverse_merge :data => nil, :make_paths => true
end
def save
object = container.create_object @path, @options[:make_paths]
object.write @options[:data] || open(@path, 'rb')
end
def delete
self.class.delete @path
end
def container
self.class.container
end
def url
self.class.url @path
end
class << self
def connect (container = nil)
cf = CloudFiles::Connection.new :username => @username, :api_key => @api_key
@@container = cf.container('test')
end
def container
@@container ||= connect
end
def ls (params = {})
container.objects params
end
alias :objects :ls
alias :list :ls
def url (path)
container.cdn_url + '/' << path
end
def add_file (path, data)
file = Cloud.new path, :data => data
file if file.save
end
def download (path)
container.object(path).data
end
def delete (path)
begin
container.delete_object path
rescue NoSuchObjectException
true
end
end
def delete_all (confirmation)
if confirmation[:i_really_want_to_do_this] === true
ls.each do |path|
delete path
end
end
ls.empty?
end
end
end
def test(basename, n = 5)
threads = []
n.times do |i|
threads << Thread.new do
thread_local_id = (i + 1).to_s
file = Cloud.add_file("#{basename}_#{thread_local_id}.txt", "This is a file.")
puts "ID '#{thread_local_id} = #{file.inspect}"
end
end
threads.map(&:join)
end
def testdelete()
files = Cloud.ls
threads = []
files.each do |file|
threads << Thread.new do
result = Cloud.delete(file)
print "Result: #{result} for file #{file}\n"
end
end
threads.map(&:join)
end
# Another test, just to make sure the others weren't getting by on dumb luck
def hmm
threads = []
5.times do |i|
threads << Thread.new do #(i) do |v|
sleep rand(5)
i = i
print "i = #{i}\n"
end
end
threads.map &:join
end
# Run `test('test')` and verify that the ID and the id in the filename are equal
# Run `testdelete` and make sure everything returns true; then run `Cloud.ls` to ensure that all files really were deleted
# Run `hmm` for another test with random sleeping to make sure that the other tests weren't just lucky
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment