faultinjection 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
File without changes
data/History.txt ADDED
@@ -0,0 +1,4 @@
1
+ == 0.0.1 2008-01-10
2
+
3
+ * 1 major enhancement:
4
+ * Initial release
data/License.txt ADDED
@@ -0,0 +1,20 @@
1
+ Copyright (c) 2008 Keisuke Fukuda
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining
4
+ a copy of this software and associated documentation files (the
5
+ "Software"), to deal in the Software without restriction, including
6
+ without limitation the rights to use, copy, modify, merge, publish,
7
+ distribute, sublicense, and/or sell copies of the Software, and to
8
+ permit persons to whom the Software is furnished to do so, subject to
9
+ the following conditions:
10
+
11
+ The above copyright notice and this permission notice shall be
12
+ included in all copies or substantial portions of the Software.
13
+
14
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
data/Manifest.txt ADDED
@@ -0,0 +1,36 @@
1
+ #*scratch*#18552Tu2#
2
+ History.txt
3
+ License.txt
4
+ Manifest.txt
5
+ README.txt
6
+ Rakefile
7
+ config/hoe.rb
8
+ config/requirements.rb
9
+ lib/fault_injection.rb
10
+ lib/fault_injection/fault_condition.rb
11
+ lib/fault_injection/parser.rb
12
+ lib/fault_injection/version.rb
13
+ log/debug.log
14
+ script/destroy
15
+ script/generate
16
+ script/makemanifest.rb
17
+ script/txt2html
18
+ setup.rb
19
+ spec/compile_spec.rb
20
+ spec/fault_condition_call_spec.rb
21
+ spec/fault_injection_spec.rb
22
+ spec/line_condition_spec.rb
23
+ spec/spec.opts
24
+ spec/spec_helper.rb
25
+ spec/target_00.rb
26
+ spec/target_01.rb
27
+ spec/target_02.rb
28
+ tasks/deployment.rake
29
+ tasks/environment.rake
30
+ tasks/rspec.rake
31
+ tasks/website.rake
32
+ website/index.html
33
+ website/index.txt
34
+ website/javascripts/rounded_corners_lite.inc.js
35
+ website/stylesheets/screen.css
36
+ website/template.rhtml
data/README.txt ADDED
@@ -0,0 +1,72 @@
1
+ fault_injection.rb
2
+
3
+ ** FAQ
4
+
5
+ * What is it?
6
+
7
+ - A 'fault injection' tool for ruby.
8
+
9
+ * What is a 'fault injection'? What is it used for?
10
+
11
+ - Fault injection is one of testing techniques.
12
+ It makes easier to test your application's error handling behavior or
13
+ to improve the coverage of your tests.
14
+ See http://en.wikipedia.org/wiki/Fault_injection for more details.
15
+
16
+ * Can I use it in my application code?
17
+
18
+ - No. It is for your testing code.
19
+
20
+ * Can I use it everywhere in my test code?
21
+
22
+ - You should not. It is for some limited situation that rarely
23
+ happen or difficult to set up (ex. IOError).
24
+ If you can make 'evil situation' easily, that's better ;)
25
+
26
+ ** Installing
27
+
28
+ $ sudo gem install faultinjection
29
+
30
+ ** Sample codes
31
+
32
+ # sample.rb
33
+ class Foo
34
+ def foo
35
+ puts "I love injection"
36
+ end
37
+
38
+ def bar
39
+ 10 / 2 # this is line 7
40
+ end
41
+ end
42
+ __END__
43
+
44
+ # test.rb
45
+ require 'fault_injection'
46
+ include FaultInjection
47
+
48
+ inject "Foo#foo > Kernel#puts", IOError, "IO error"
49
+
50
+ f = Foo.new
51
+ f.foo #=> IOError
52
+
53
+ inject "sample.rb:7",ZeroDivisionError
54
+
55
+ f.bar #=> ZeroDivisionError
56
+ __END__
57
+
58
+
59
+ ** License
60
+
61
+ This code is free to use under the terms of the MIT license.
62
+
63
+ ** Contact
64
+
65
+ The SVN repository is available at http://faultinjection.rubyforge.org/svn/
66
+
67
+ Comments are welcome. Feel free to Send an email to keisukefukuda@gmail.com
68
+ (Please include 'ruby' or 'fault_injection' in the title).
69
+
70
+
71
+ Thank you for using fault_injection.rb
72
+
data/Rakefile ADDED
@@ -0,0 +1,6 @@
1
+ require 'config/requirements'
2
+ require 'config/hoe' # setup Hoe + all gem configuration
3
+
4
+ Dir['tasks/**/*.rake'].each { |rake| load rake }
5
+
6
+ task :test => :spec
data/config/hoe.rb ADDED
@@ -0,0 +1,71 @@
1
+ require 'fault_injection/version'
2
+
3
+ AUTHOR = 'FIXME full name' # can also be an array of Authors
4
+ EMAIL = "FIXME email"
5
+ DESCRIPTION = "description of gem"
6
+ GEM_NAME = 'faultinjection' # what ppl will type to install your gem
7
+ RUBYFORGE_PROJECT = 'faultinjection' # The unix name for your project
8
+ HOMEPATH = "http://#{RUBYFORGE_PROJECT}.rubyforge.org"
9
+ DOWNLOAD_PATH = "http://rubyforge.org/projects/#{RUBYFORGE_PROJECT}"
10
+
11
+ @config_file = "~/.rubyforge/user-config.yml"
12
+ @config = nil
13
+ RUBYFORGE_USERNAME = "unknown"
14
+ def rubyforge_username
15
+ unless @config
16
+ begin
17
+ @config = YAML.load(File.read(File.expand_path(@config_file)))
18
+ rescue
19
+ puts <<-EOS
20
+ ERROR: No rubyforge config file found: #{@config_file}
21
+ Run 'rubyforge setup' to prepare your env for access to Rubyforge
22
+ - See http://newgem.rubyforge.org/rubyforge.html for more details
23
+ EOS
24
+ exit
25
+ end
26
+ end
27
+ RUBYFORGE_USERNAME.replace @config["username"]
28
+ end
29
+
30
+
31
+ REV = nil
32
+ # UNCOMMENT IF REQUIRED:
33
+ # REV = `svn info`.each {|line| if line =~ /^Revision:/ then k,v = line.split(': '); break v.chomp; else next; end} rescue nil
34
+ VERS = FaultInjection::VERSION::STRING + (REV ? ".#{REV}" : "")
35
+ RDOC_OPTS = ['--quiet', '--title', 'fault_injection documentation',
36
+ "--opname", "index.html",
37
+ "--line-numbers",
38
+ "--main", "README",
39
+ "--inline-source"]
40
+
41
+ class Hoe
42
+ def extra_deps
43
+ @extra_deps.reject! { |x| Array(x).first == 'hoe' }
44
+ @extra_deps
45
+ end
46
+ end
47
+
48
+ # Generate all the Rake tasks
49
+ # Run 'rake -T' to see list of generated tasks (from gem root directory)
50
+ hoe = Hoe.new(GEM_NAME, VERS) do |p|
51
+ p.author = AUTHOR
52
+ p.description = DESCRIPTION
53
+ p.email = EMAIL
54
+ p.summary = DESCRIPTION
55
+ p.url = HOMEPATH
56
+ p.rubyforge_name = RUBYFORGE_PROJECT if RUBYFORGE_PROJECT
57
+ p.test_globs = ["test/**/test_*.rb"]
58
+ p.clean_globs |= ['**/.*.sw?', '*.gem', '.config', '**/.DS_Store'] #An array of file patterns to delete on clean.
59
+
60
+ # == Optional
61
+ p.changes = p.paragraphs_of("History.txt", 0..1).join("\n\n")
62
+ #p.extra_deps = [] # An array of rubygem dependencies [name, version], e.g. [ ['active_support', '>= 1.3.1'] ]
63
+
64
+ #p.spec_extras = {} # A hash of extra values to set in the gemspec.
65
+
66
+ end
67
+
68
+ CHANGES = hoe.paragraphs_of('History.txt', 0..1).join("\\n\\n")
69
+ PATH = (RUBYFORGE_PROJECT == GEM_NAME) ? RUBYFORGE_PROJECT : "#{RUBYFORGE_PROJECT}/#{GEM_NAME}"
70
+ hoe.remote_rdoc_dir = File.join(PATH.gsub(/^#{RUBYFORGE_PROJECT}\/?/,''), 'rdoc')
71
+ hoe.rsync_args = '-av --delete --ignore-errors'
@@ -0,0 +1,17 @@
1
+ require 'fileutils'
2
+ include FileUtils
3
+
4
+ require 'rubygems'
5
+ %w[rake hoe newgem rubigen].each do |req_gem|
6
+ begin
7
+ require req_gem
8
+ rescue LoadError
9
+ puts "This Rakefile requires the '#{req_gem}' RubyGem."
10
+ puts "Installation: gem install #{req_gem} -y"
11
+ exit
12
+ end
13
+ end
14
+
15
+ $:.unshift(File.join(File.dirname(__FILE__), %w[.. lib]))
16
+
17
+ require 'fault_injection'
@@ -0,0 +1,108 @@
1
+ module FaultInjection
2
+
3
+ class FaultConditionBase
4
+ attr_accessor :error_class
5
+ attr_accessor :message
6
+ attr_accessor :probability
7
+ attr_accessor :limit_times
8
+
9
+ def initialize
10
+ @probability ||= 1
11
+ @limit_times ||= -1
12
+ end
13
+
14
+ def should_raise_on(*args)
15
+ return false if @limit_times == 0
16
+
17
+ b = _should_raise_on(*args)
18
+
19
+ if @probability < 1
20
+ b = b && rand(0) < @probability
21
+ end
22
+
23
+ @limit_times -= 1 if b
24
+
25
+ b
26
+ end
27
+
28
+ private
29
+
30
+ def _should_raise_on(*args)
31
+ false
32
+ end
33
+ end
34
+
35
+ class FaultConditionLine < FaultConditionBase
36
+ attr_accessor :file
37
+ attr_accessor :line
38
+
39
+ def initialize(file,line,prob=1)
40
+ @file = file
41
+ @line = line
42
+ self.probability = prob
43
+
44
+ if @line <= 0
45
+ raise ArgumentError,"line number must be greater than 0."
46
+ end
47
+
48
+ if prob < 0 or prob > 1
49
+ raise ArgumentError, "Probability must be between 0 and 1."
50
+ end
51
+
52
+ super()
53
+ end
54
+
55
+ private
56
+ def _should_raise_on *args
57
+ if args.size == 2
58
+ file,line = *args
59
+ reg = Regexp.new(Regexp.escape(@file) + '$')
60
+ return reg.match(file) && line == @line
61
+
62
+ else
63
+ false
64
+ end
65
+ end
66
+ end
67
+
68
+ class FaultConditionCall < FaultConditionBase
69
+ # representing method chain(callee first)
70
+ # [ [class,'method_name'],
71
+ # [class,'method_name'],
72
+ # ...
73
+ # [class,'method_name'] ]
74
+ attr_accessor :stack_pattern
75
+
76
+ def initialize
77
+ @stack_pattern = []
78
+
79
+ super()
80
+ end
81
+
82
+ def add_callee(klass,method)
83
+ @stack_pattern.unshift [klass,method]
84
+ end
85
+
86
+ private
87
+ def _should_raise_on *args
88
+ return false if @stack_pattern.nil? or @stack_pattern.size == 0
89
+
90
+ if args[0].instance_of? Array
91
+ stack = args[0]
92
+ #STDERR.puts @stack_pattern.map{|e| "#{e[0]}##{e[1]}"}.join("\n")
93
+
94
+ return false if stack.size < @stack_pattern.size
95
+
96
+ @stack_pattern.each_index do |i|
97
+ e = @stack_pattern[i]
98
+ b = stack[-i-1]
99
+ return false if e[0] != b[0].to_s.to_sym or e[1] != b[1].to_sym
100
+ end
101
+
102
+ true
103
+ else
104
+ false
105
+ end
106
+ end
107
+ end
108
+ end
@@ -0,0 +1,31 @@
1
+ # Command examples
2
+ #
3
+ # parser.rb:30 => line 30 in parser.rb
4
+ #
5
+ module FaultInjection
6
+ class Parser
7
+ def self.compile src
8
+ method_pat = '([A-Z][A-Za-z0-9_]*)(?:#|::)([a-z_][a-zA-Z0-9_]*)'
9
+ src.gsub!(/\s/,'')
10
+
11
+ if src =~ /([A-Za-z0-9_.~-]+):(\d+)/
12
+ return FaultConditionLine.new($1,$2.to_i)
13
+
14
+ else
15
+ methods = src.split(">")
16
+ methods.map! do |e|
17
+ unless e =~ Regexp.new(method_pat)
18
+ raise ArgumentError,"Invalid method name:'#{e}'"
19
+ end
20
+
21
+ [$1.to_sym,$2.to_sym]
22
+ end
23
+
24
+ c = FaultConditionCall.new
25
+ c.stack_pattern = methods.reverse # callee first
26
+
27
+ return c
28
+ end
29
+ end
30
+ end
31
+ end
@@ -0,0 +1,9 @@
1
+ module FaultInjection #:nodoc:
2
+ module VERSION #:nodoc:
3
+ MAJOR = 0
4
+ MINOR = 0
5
+ TINY = 1
6
+
7
+ STRING = [MAJOR, MINOR, TINY].join('.')
8
+ end
9
+ end
@@ -0,0 +1,121 @@
1
+ $:.unshift File.dirname(__FILE__)
2
+
3
+ require 'fault_injection/fault_condition.rb'
4
+ require 'fault_injection/parser.rb'
5
+
6
+ module FaultInjection
7
+ @@injected_faults = nil
8
+ @@method_stack = Array.new
9
+
10
+ def inject_fault(*args)
11
+ FaultInjection.inject_fault *args
12
+ end
13
+
14
+ def self.inject_fault(command,error_class=RuntimeError,msg="injected fault")
15
+ unless error_class <= Exception
16
+ raise ArgumentError, "Error class must be a subclass of Exception"
17
+ end
18
+
19
+ cond = nil
20
+
21
+ if String === command
22
+ cond = Parser.compile(command)
23
+ cond.error_class = error_class
24
+ cond.message = msg
25
+
26
+ elsif Hash === command and command.key?(:line) and command.key?(:file)
27
+ cond = inject_fault_on_line(command[:file],
28
+ command[:line],
29
+ error_class,msg)
30
+ elsif Array === command
31
+ cond = inject_fault_on_trace(command,error_class,msg)
32
+ else
33
+ raise "Unknown Command"
34
+ end
35
+
36
+ if @@injected_faults.nil?
37
+ @@injected_faults = Array.new
38
+ set_trace_func method(:fault).to_proc
39
+ end
40
+
41
+ raise "[BUG] Internal Error. Please report this to the author :)" if cond.nil?
42
+
43
+ @@injected_faults << cond
44
+ end
45
+
46
+ # delete all injected faults.
47
+ def self.clear
48
+ @@injected_faults = nil
49
+ set_trace_func Proc.new{}
50
+ end
51
+
52
+ # Same as FaultInjection::clear
53
+ def clear
54
+ FaultInjection.clear
55
+ end
56
+
57
+ private
58
+
59
+ # Create fault condition on file:line.
60
+ def self.inject_fault_on_line(file,line,error_class,msg)
61
+ if line <= 0
62
+ raise ArgumentError,"line number must not be less than 0"
63
+ end
64
+
65
+ cond = FaultConditionLine.new(file,line)
66
+ cond.error_class = error_class
67
+ cond.message = msg
68
+
69
+ cond
70
+ end
71
+
72
+ # Create fault condition on method call trace
73
+ def self.inject_fault_on_trace(trace,error_class,msg)
74
+ trace = trace.flatten
75
+
76
+ if trace.size == 0 or trace.size % 2 != 0
77
+ raise ArgumentError, "command must be array of class/method pair."
78
+ end
79
+
80
+ cond = FaultConditionCall.new
81
+
82
+ while trace.size > 0
83
+ klass = trace.shift.to_sym
84
+ method = trace.shift.to_sym
85
+
86
+ cond.add_callee klass,method
87
+ end
88
+
89
+ cond.error_class = error_class
90
+ cond.message = msg
91
+
92
+ cond
93
+ end
94
+
95
+ # Callback function called by ruby interpreter.
96
+ def self.fault(event,file,line,id,binidng,klass)
97
+ return if @@injected_faults.nil?
98
+
99
+ if event == "line"
100
+ #puts "event = '#{event}', file = #{file}, line = #{line}"
101
+
102
+ @@injected_faults.each do |f|
103
+ if f.should_raise_on(file,line)
104
+ raise f.error_class, f.message, caller(4)
105
+ end
106
+ end
107
+
108
+ elsif event == "call" or event == "c-call"
109
+
110
+ @@injected_faults.each do |f|
111
+ if f.should_raise_on(@@method_stack)
112
+ raise f.error_class, f.message, caller(4)
113
+ end
114
+ end
115
+ @@method_stack.push([klass,id])
116
+
117
+ elsif event == "return" or event == "c-return"
118
+ @@method_stack.pop
119
+ end
120
+ end
121
+ end
data/log/debug.log ADDED
File without changes
data/script/destroy ADDED
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+ APP_ROOT = File.join(File.dirname(__FILE__), '..')
3
+
4
+ begin
5
+ require 'rubigen'
6
+ rescue LoadError
7
+ require 'rubygems'
8
+ require 'rubigen'
9
+ end
10
+ require 'rubigen/scripts/destroy'
11
+
12
+ ARGV.shift if ['--help', '-h'].include?(ARGV[0])
13
+ RubiGen::Base.use_component_sources! [:rubygems, :newgem, :newgem_theme, :test_unit]
14
+ RubiGen::Scripts::Destroy.new.run(ARGV)
data/script/generate ADDED
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+ APP_ROOT = File.join(File.dirname(__FILE__), '..')
3
+
4
+ begin
5
+ require 'rubigen'
6
+ rescue LoadError
7
+ require 'rubygems'
8
+ require 'rubigen'
9
+ end
10
+ require 'rubigen/scripts/generate'
11
+
12
+ ARGV.shift if ['--help', '-h'].include?(ARGV[0])
13
+ RubiGen::Base.use_component_sources! [:rubygems, :newgem, :newgem_theme, :test_unit]
14
+ RubiGen::Scripts::Generate.new.run(ARGV)
@@ -0,0 +1,20 @@
1
+ #!/usr/bin/ruby
2
+
3
+ base_dir = File.join(File.dirname(__FILE__), "..")
4
+ glob_pattern = File.join("**", "*")
5
+ exclude_patterns = [
6
+ /^pkg/,/^doc/,
7
+ ]
8
+
9
+ Dir.chdir(base_dir)
10
+ files = Dir.glob(glob_pattern).delete_if do |fname|
11
+ File.directory?(fname) or
12
+ exclude_patterns.find do |pattern|
13
+ pattern =~ fname
14
+ end
15
+ end
16
+ manifest = File.new("Manifest.txt", "w")
17
+ manifest.puts files.sort.join("\n")
18
+ manifest.close
19
+
20
+ puts "Manifest.txt updated"
data/script/txt2html ADDED
@@ -0,0 +1,74 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require 'rubygems'
4
+ begin
5
+ require 'newgem'
6
+ rescue LoadError
7
+ puts "\n\nGenerating the website requires the newgem RubyGem"
8
+ puts "Install: gem install newgem\n\n"
9
+ exit(1)
10
+ end
11
+ require 'redcloth'
12
+ require 'syntax/convertors/html'
13
+ require 'erb'
14
+ require File.dirname(__FILE__) + '/../lib/fault_injection/version.rb'
15
+
16
+ version = FaultInjection::VERSION::STRING
17
+ download = 'http://rubyforge.org/projects/fault_injection'
18
+
19
+ class Fixnum
20
+ def ordinal
21
+ # teens
22
+ return 'th' if (10..19).include?(self % 100)
23
+ # others
24
+ case self % 10
25
+ when 1: return 'st'
26
+ when 2: return 'nd'
27
+ when 3: return 'rd'
28
+ else return 'th'
29
+ end
30
+ end
31
+ end
32
+
33
+ class Time
34
+ def pretty
35
+ return "#{mday}#{mday.ordinal} #{strftime('%B')} #{year}"
36
+ end
37
+ end
38
+
39
+ def convert_syntax(syntax, source)
40
+ return Syntax::Convertors::HTML.for_syntax(syntax).convert(source).gsub(%r!^<pre>|</pre>$!,'')
41
+ end
42
+
43
+ if ARGV.length >= 1
44
+ src, template = ARGV
45
+ template ||= File.join(File.dirname(__FILE__), '/../website/template.rhtml')
46
+
47
+ else
48
+ puts("Usage: #{File.split($0).last} source.txt [template.rhtml] > output.html")
49
+ exit!
50
+ end
51
+
52
+ template = ERB.new(File.open(template).read)
53
+
54
+ title = nil
55
+ body = nil
56
+ File.open(src) do |fsrc|
57
+ title_text = fsrc.readline
58
+ body_text = fsrc.read
59
+ syntax_items = []
60
+ body_text.gsub!(%r!<(pre|code)[^>]*?syntax=['"]([^'"]+)[^>]*>(.*?)</\1>!m){
61
+ ident = syntax_items.length
62
+ element, syntax, source = $1, $2, $3
63
+ syntax_items << "<#{element} class='syntax'>#{convert_syntax(syntax, source)}</#{element}>"
64
+ "syntax-temp-#{ident}"
65
+ }
66
+ title = RedCloth.new(title_text).to_html.gsub(%r!<.*?>!,'').strip
67
+ body = RedCloth.new(body_text).to_html
68
+ body.gsub!(%r!(?:<pre><code>)?syntax-temp-(\d+)(?:</code></pre>)?!){ syntax_items[$1.to_i] }
69
+ end
70
+ stat = File.stat(src)
71
+ created = stat.ctime
72
+ modified = stat.mtime
73
+
74
+ $stdout << template.result(binding)