require 'fileutils'
module IMWTest
module Random
STRING_CHARS = ("a".."z").to_a + ("A".."Z").to_a + ("0".."9").to_a + [' ',' ',' ',' ',' '] unless defined?(STRING_CHARS)
TEXT_CHARS = ("a".."z").to_a + ("A".."Z").to_a + ("0".."9").to_a + [' ',' ',' ',' ',' ',"\n"] unless defined?(TEXT_CHARS)
FILENAME_CHARS = ("a".."z").to_a + ("A".."Z").to_a + ("0".."9").to_a + ["-","_",' '] unless defined?(FILENAME_CHARS)
FILENAME_MAX_LENGTH = 9 unless defined?(FILENAME_MAX_LENGTH)
TEXT_MAX_LENGTH = 1024 unless defined?(TEXT_MAX_LENGTH)
EXTENSIONS = [
[/\.csv$/ , :csv_file],
[/\.xml$/ , :xml_file],
[/\.html$/ , :html_file],
[/\.tar\.gz$/ , :targz_file],
[/\.tar\.bz2$/ , :tarbz2_file],
[/\.bz2$/ , :bz2_file],
[/\.gz$/ , :gz_file],
[/\.tar$/ , :tar_file],
[/\.rar$/ , :rar_file],
[/\.zip$/ , :zip_file]
] unless defined?(EXTENSIONS)
# Return a random filename. Optional +length+ to set the maximum
# length of the filename returned.
def self.basename options = {}
length = (options[:length] or FILENAME_MAX_LENGTH)
filename = (1..length).map { |i| FILENAME_CHARS.random }.join
# filenames beginning with hyphens suck
while (filename[0,1] == '-') do
filename[0] = FILENAME_CHARS.random
end
filename
end
# Return a random string of text up. Control the length with
# optional +length+ and also the presence of +newlines+.
def self.text options = {}
length = (options[:length] or TEXT_MAX_LENGTH)
char_pool = options[:newlines] ? TEXT_CHARS : STRING_CHARS
(1..length).map { |i| char_pool.random }.join
end
# Create a random file by matching the extension of the given
# +filename+ or a text file if no match is found.
def self.file filename
match = EXTENSIONS.find { |regex,func| regex.match filename }
match ? self.send(match.last,filename) : self.text_file(filename)
end
# Create a random text file at +filename+ containing a maximum of
# +length+ characters.
def self.text_file filename, options = {}
File.open(filename,'w') { |f| f.write text(:newlines => true) }
end
# Create a comma-separated value file containing random text at
# +filename+ with the maximum +num_rows+, the given +num_columns+,
# and the maximum +entry_length+.
def self.csv_file(filename,num_rows = 500, num_columns = 9, entry_length = 9)
f = File.open(filename,'w')
rand(num_rows).times do # rows
num_columns.times do # columns
f.write(text(:length => entry_length)) # entry
f.write ','
end
f.write(text(:length => entry_length)) # last entry
f.write("\n")
end
f.close
end
# Create an XML file at +filename+ of the maximum +length+.
#
# At the present moment, this file contains random text in a very
# boring single-element XML tree. Randomizing the tree has not
# been implemented.
def self.xml_file filename, options = {}
options = options.reverse_merge({:max_depth => 5, :starting_depth => 1, :depth => nil, :pretty_print => true})
File.open(filename,'w') do |file|
file.write "\n"
file.write "