dbgrandi-ruby-aws 1.2.0

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.
Files changed (70) hide show
  1. data/History.txt +38 -0
  2. data/LICENSE.txt +202 -0
  3. data/Manifest.txt +69 -0
  4. data/NOTICE.txt +4 -0
  5. data/README.txt +105 -0
  6. data/Rakefile +20 -0
  7. data/bin/ruby-aws +9 -0
  8. data/lib/amazon/util.rb +10 -0
  9. data/lib/amazon/util/binder.rb +44 -0
  10. data/lib/amazon/util/data_reader.rb +157 -0
  11. data/lib/amazon/util/filter_chain.rb +79 -0
  12. data/lib/amazon/util/hash_nesting.rb +93 -0
  13. data/lib/amazon/util/lazy_results.rb +59 -0
  14. data/lib/amazon/util/logging.rb +23 -0
  15. data/lib/amazon/util/paginated_iterator.rb +70 -0
  16. data/lib/amazon/util/proactive_results.rb +116 -0
  17. data/lib/amazon/util/threadpool.rb +129 -0
  18. data/lib/amazon/util/user_data_store.rb +100 -0
  19. data/lib/amazon/webservices/mechanical_turk.rb +117 -0
  20. data/lib/amazon/webservices/mechanical_turk_requester.rb +261 -0
  21. data/lib/amazon/webservices/mturk/mechanical_turk_error_handler.rb +136 -0
  22. data/lib/amazon/webservices/mturk/question_generator.rb +58 -0
  23. data/lib/amazon/webservices/util/amazon_authentication_relay.rb +64 -0
  24. data/lib/amazon/webservices/util/command_line.rb +156 -0
  25. data/lib/amazon/webservices/util/convenience_wrapper.rb +90 -0
  26. data/lib/amazon/webservices/util/filter_proxy.rb +45 -0
  27. data/lib/amazon/webservices/util/mock_transport.rb +70 -0
  28. data/lib/amazon/webservices/util/request_signer.rb +42 -0
  29. data/lib/amazon/webservices/util/rest_transport.rb +108 -0
  30. data/lib/amazon/webservices/util/soap_simplifier.rb +48 -0
  31. data/lib/amazon/webservices/util/soap_transport.rb +38 -0
  32. data/lib/amazon/webservices/util/soap_transport_header_handler.rb +27 -0
  33. data/lib/amazon/webservices/util/unknown_result_exception.rb +27 -0
  34. data/lib/amazon/webservices/util/validation_exception.rb +55 -0
  35. data/lib/amazon/webservices/util/xml_simplifier.rb +61 -0
  36. data/lib/ruby-aws.rb +21 -0
  37. data/lib/ruby-aws/version.rb +8 -0
  38. data/samples/mturk/best_image/BestImage.rb +61 -0
  39. data/samples/mturk/best_image/best_image.properties +39 -0
  40. data/samples/mturk/best_image/best_image.question +82 -0
  41. data/samples/mturk/blank_slate/BlankSlate.rb +63 -0
  42. data/samples/mturk/blank_slate/BlankSlate_multithreaded.rb +67 -0
  43. data/samples/mturk/helloworld/MTurkHelloWorld.rb +56 -0
  44. data/samples/mturk/helloworld/mturk.yml +8 -0
  45. data/samples/mturk/reviewer/Reviewer.rb +103 -0
  46. data/samples/mturk/reviewer/mturk.yml +8 -0
  47. data/samples/mturk/simple_survey/SimpleSurvey.rb +90 -0
  48. data/samples/mturk/simple_survey/simple_survey.question +30 -0
  49. data/samples/mturk/site_category/SiteCategory.rb +87 -0
  50. data/samples/mturk/site_category/externalpage.htm +71 -0
  51. data/samples/mturk/site_category/site_category.input +6 -0
  52. data/samples/mturk/site_category/site_category.properties +45 -0
  53. data/samples/mturk/site_category/site_category.question +9 -0
  54. data/test/mturk/test_changehittypeofhit.rb +130 -0
  55. data/test/mturk/test_error_handler.rb +135 -0
  56. data/test/mturk/test_mechanical_turk_requester.rb +178 -0
  57. data/test/mturk/test_mock_mechanical_turk_requester.rb +205 -0
  58. data/test/test_ruby-aws.rb +22 -0
  59. data/test/unit/test_binder.rb +89 -0
  60. data/test/unit/test_data_reader.rb +135 -0
  61. data/test/unit/test_exceptions.rb +32 -0
  62. data/test/unit/test_hash_nesting.rb +93 -0
  63. data/test/unit/test_lazy_results.rb +89 -0
  64. data/test/unit/test_mock_transport.rb +132 -0
  65. data/test/unit/test_paginated_iterator.rb +58 -0
  66. data/test/unit/test_proactive_results.rb +108 -0
  67. data/test/unit/test_question_generator.rb +54 -0
  68. data/test/unit/test_threadpool.rb +50 -0
  69. data/test/unit/test_user_data_store.rb +80 -0
  70. metadata +158 -0
@@ -0,0 +1,30 @@
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <QuestionForm xmlns="http://mechanicalturk.amazonaws.com/AWSMechanicalTurkDataSchemas/2005-10-01/QuestionForm.xsd">
3
+ <Question>
4
+ <QuestionIdentifier>1</QuestionIdentifier>
5
+ <QuestionContent>
6
+ <Text>What is your political party affiliation?</Text>
7
+ </QuestionContent>
8
+ <AnswerSpecification>
9
+ <SelectionAnswer>
10
+ <MinSelectionCount>1</MinSelectionCount>
11
+ <MaxSelectionCount>1</MaxSelectionCount>
12
+ <StyleSuggestion>radiobutton</StyleSuggestion>
13
+ <Selections>
14
+ <Selection>
15
+ <SelectionIdentifier>republican</SelectionIdentifier>
16
+ <Text>Republican</Text>
17
+ </Selection>
18
+ <Selection>
19
+ <SelectionIdentifier>democrat</SelectionIdentifier>
20
+ <Text>Democrat</Text>
21
+ </Selection>
22
+ <Selection>
23
+ <SelectionIdentifier>noneoftheabove</SelectionIdentifier>
24
+ <Text>None of the Above</Text>
25
+ </Selection>
26
+ </Selections>
27
+ </SelectionAnswer>
28
+ </AnswerSpecification>
29
+ </Question>
30
+ </QuestionForm>
@@ -0,0 +1,87 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ # Copyright:: Copyright (c) 2007 Amazon Technologies, Inc.
4
+ # License:: Apache License, Version 2.0
5
+
6
+ begin ; require 'rubygems' ; rescue LoadError ; end
7
+
8
+ # The Site Category sample application will create 5 HITs asking workers to categorize websites into predefined categories.
9
+ #
10
+ # The following concepts are covered:
11
+ # - Bulk load HITs using an input file
12
+ # - File based HIT loading
13
+
14
+ require 'ruby-aws'
15
+ @mturk = Amazon::WebServices::MechanicalTurkRequester.new
16
+
17
+ # Check to see if your account has sufficient funds
18
+ def hasEnoughFunds?
19
+ available = @mturk.availableFunds
20
+ puts "Got account balance: %.2f" % available
21
+ return available > (0.055 * 5)
22
+ end
23
+
24
+ def getHITUrl( hitTypeId )
25
+ if @mturk.host =~ /sandbox/
26
+ "http://workersandbox.mturk.com/mturk/preview?groupId=#{hitTypeId}" # Sandbox Url
27
+ else
28
+ "http://mturk.com/mturk/preview?groupId=#{hitTypeId}" # Production Url
29
+ end
30
+ end
31
+
32
+ # Create the website category HITs.
33
+ def createSiteCategoryHITs
34
+
35
+ # Defining the locations of the input files
36
+ rootDir = File.dirname $0
37
+ inputFile = rootDir + "/site_category.input"
38
+ propertiesFile = rootDir + "/site_category.properties"
39
+ questionFile = rootDir + "/site_category.question"
40
+
41
+ # Loading the input file. The input file is a tab delimited file where the first row
42
+ # defines the fields/variables and the remaining rows contain the values for each HIT.
43
+ # Each row represents a unique HIT. ERB is used to merge the values into the Question template.
44
+ input = Amazon::Util::DataReader.load( inputFile, :Tabular )
45
+
46
+ # Loading the question (QuestionForm) file
47
+ question = File.read( questionFile )
48
+
49
+ # Loading the HIT properties file. The properties file defines two system qualifications that will
50
+ # be used for the HIT. The properties file can also be an ERB template. This allows the developer
51
+ # to "tie in" the input value to the results.
52
+ props = Amazon::Util::DataReader.load( propertiesFile, :Properties )
53
+
54
+ hits = [];
55
+
56
+ # Create multiple HITs using the input, properties, and question files
57
+
58
+ puts "--[Loading HITs]----------"
59
+ startTime = Time.now
60
+ puts " Start time: #{startTime}"
61
+
62
+ # The simpliest way to bulk load a large number of HITs where all details are defined in files.
63
+ # This method returns a hash with two arrays:
64
+ # - :Created is an array of successfully created HITs
65
+ # - :Failed is an array of lines we failed to create HITs with
66
+ hits = @mturk.createHITs(props, question, input);
67
+
68
+ puts "--[End Loading HITs]----------"
69
+ endTime = Time.now
70
+ puts " End time: #{endTime}"
71
+ puts "--[Done Loading HITs]----------"
72
+ puts " Total load time: #{ endTime - startTime } seconds."
73
+
74
+ hit_ids = hits[:Created].collect {|h| h[:HITId] }
75
+ hit_type_id = hits[:Created].first[:HITTypeId]
76
+
77
+ puts " Created HITs: #{hit_ids.join(' ')}"
78
+ puts " Url: #{getHITUrl( hit_type_id )}"
79
+
80
+ # We'll save the results to hits.success and hits.failure
81
+ Amazon::Util::DataReader.save( rootDir + "/hits.success", hits[:Created], :Tabular )
82
+ Amazon::Util::DataReader.save( rootDir + "/hits.failure", hits[:Failed], :Tabular )
83
+ # The .success file can be used in subsequent operations to retrieve the results that workers submitted.
84
+
85
+ end
86
+
87
+ createSiteCategoryHITs if hasEnoughFunds?
@@ -0,0 +1,71 @@
1
+ <!-- This file needs to be hosted on an external server. -->
2
+ <html>
3
+ <script language="Javascript">
4
+ //
5
+ // This method Gets URL Parameters (GUP)
6
+ //
7
+ function gup( name )
8
+ {
9
+ var regexS = "[\\?&]"+name+"=([^&#]*)";
10
+ var regex = new RegExp( regexS );
11
+ var tmpURL = window.location.href;
12
+ var results = regex.exec( tmpURL );
13
+ if( results == null )
14
+ return "";
15
+ else
16
+ return results[1];
17
+ }
18
+
19
+ //
20
+ // This method decodes the query parameters that were URL-encoded
21
+ //
22
+ function decode(strToDecode)
23
+ {
24
+ var encoded = strToDecode;
25
+ return unescape(encoded.replace(/\+/g, " "));
26
+ }
27
+
28
+ </script>
29
+ <body>
30
+ <form id="mturk_form" method="POST" action="http://www.mturk.com/mturk/externalSubmit">
31
+ <input type="hidden" id="assignmentId" name="assignmentId" value="">
32
+ <table border="0" height="100%" width="100%">
33
+ <tr><td>
34
+ <h1>What type of webpage is shown below?</h1>
35
+ <p>
36
+ <input type="radio" name="category" value="news">&nbsp;News Site<br>
37
+ <input type="radio" name="category" value="search">&nbsp;Search Engine<br>
38
+ <input type="radio" name="category" value="retail">&nbsp;Online Retailer<br>
39
+ <input type="radio" name="category" value="other" selected>&nbsp;Other<br>
40
+ <p>
41
+ <input id="submitButton" type="submit" name="Submit" value="Submit">
42
+ <p>
43
+ </td></tr>
44
+ <tr><td height="100%">
45
+ <iframe id="pageFrame" width="100%" height="100%"></iframe>
46
+ </td></tr>
47
+ </table>
48
+ </form>
49
+ <script language="Javascript">
50
+ document.getElementById('pageFrame').src = decode(gup('url'));
51
+ document.getElementById('assignmentId').value = gup('assignmentId');
52
+
53
+
54
+ //
55
+ // Check if the worker is PREVIEWING the HIT or if they've ACCEPTED the HIT
56
+ //
57
+ if (gup('assignmentId') == "ASSIGNMENT_ID_NOT_AVAILABLE")
58
+ {
59
+ // If we're previewing, disable the button and give it a helpful message
60
+ document.getElementById('submitButton').disabled = true;
61
+ document.getElementById('submitButton').value = "You must ACCEPT the HIT before you can submit the results.";
62
+ } else {
63
+ var form = document.getElementById('mturk_form');
64
+ if (document.referrer && ( document.referrer.indexOf('workersandbox') != -1) ) {
65
+ form.action = "http://workersandbox.mturk.com/mturk/externalSubmit";
66
+ }
67
+ }
68
+
69
+ </script>
70
+ </body>
71
+ </html>
@@ -0,0 +1,6 @@
1
+ urls
2
+ http://www.reuters.com/
3
+ http://www.google.com/
4
+ http://www.amazon.com/
5
+ http://www.apple.com/
6
+ http://www.yahoo.com/
@@ -0,0 +1,45 @@
1
+ ######################################
2
+ ## External HIT Properties
3
+ ######################################
4
+
5
+ Title:What website is this?
6
+ Description:Please look at this website and tell us, in simple words, what website this is.
7
+ Keywords:category, website, SDK, sample
8
+ Reward.Amount:0.05
9
+ Reward.CurrencyCode:USD
10
+ MaxAssignments:1
11
+
12
+ #Notice the use of ERB template directives here.
13
+ #This allows the input file to define the value of the HIT level annotation field.
14
+ RequesterAnnotation:<%= @urls %>
15
+
16
+ ######################################
17
+ ## HIT Timing Properties
18
+ ######################################
19
+
20
+ # this Assignment Duration value is 60 * 60 = 1 hour
21
+ AssignmentDuration:3600
22
+
23
+ # this HIT Lifetime value is 60 * 60 = 1 hour
24
+ LifetimeInSeconds:3600
25
+
26
+ # this Auto Approval period is 60 * 60 = 1 hour
27
+ AutoApprovalDelayInSeconds:3600
28
+
29
+ ######################################
30
+ ## Qualification Properties
31
+ ######################################
32
+
33
+ # In this example, two system qualifications are specified for the HIT.
34
+
35
+ # this is a built-in qualification -- user must have an approval rate of 25% or greater
36
+ QualificationRequirement.1.QualificationTypeId:000000000000000000L0
37
+ QualificationRequirement.1.Comparator:GreaterThan
38
+ QualificationRequirement.1.IntegerValue:25
39
+ QualificationRequirement.1.RequiredToPreview:false
40
+
41
+ # this is a built-in qualification -- user must have an abandonment rate of 50% or less
42
+ QualificationRequirement.2.QualificationTypeId:00000000000000000070
43
+ QualificationRequirement.2.Comparator:LessThan
44
+ QualificationRequirement.2.IntegerValue:51
45
+ QualificationRequirement.2.RequiredToPreview:true
@@ -0,0 +1,9 @@
1
+ <?xml version="1.0"?>
2
+ <!-- Note the inclusion of the @urls variable which is defined as a field in the input file. ERB is the template engine that is
3
+ used to perform the merging of variables into template files.
4
+ -->
5
+ <% require 'cgi' %>
6
+ <ExternalQuestion xmlns="http://mechanicalturk.amazonaws.com/AWSMechanicalTurkDataSchemas/2006-07-14/ExternalQuestion.xsd">
7
+ <ExternalURL>http://s3.amazonaws.com/mturk/samples/sitecategory/externalpage.htm?url=<%= CGI::escape @urls %></ExternalURL>
8
+ <FrameHeight>400</FrameHeight>
9
+ </ExternalQuestion>
@@ -0,0 +1,130 @@
1
+ # Copyright:: Copyright (c) 2007 Amazon Technologies, Inc.
2
+ # License:: Apache License, Version 2.0
3
+
4
+ require 'test/unit/testcase'
5
+ require 'ruby-aws'
6
+ require 'amazon/webservices/mturk/question_generator'
7
+ require 'amazon/webservices/util/soap_transport'
8
+ require 'amazon/webservices/util/rest_transport'
9
+ require 'amazon/webservices/util/mock_transport'
10
+
11
+
12
+ class TestChangeHITTypeOfHIT < Test::Unit::TestCase
13
+ include Amazon::WebServices
14
+
15
+ def setup
16
+ # Setting up the default requester interface.
17
+ # This will default to running against Sandbox, but we specify the host explicitly for safety.
18
+ # Access Key ID and Secret Access Key will be loaded from user preference file
19
+ # If not found, the user will be interatively queried for their authentication information.
20
+ @@mturk ||= Amazon::WebServices::MechanicalTurkRequester.new :Host => :Sandbox if ENV['DISABLE_MTURK_SANDBOX_TEST'].nil?
21
+
22
+ # set up a mock version of the service
23
+ @@mock ||= Amazon::WebServices::Util::MockTransport.new
24
+ @@mockturk ||= Amazon::WebServices::MechanicalTurkRequester.new( :Transport => @@mock, :AWSAccessKey => 'bogus', :AWSAccessKeyId => 'fake' )
25
+
26
+ # lets just build this question once
27
+ @@question ||= MTurk::QuestionGenerator.build { |q| q.ask 'Have you tried changing the description of a HIT?' }
28
+ end
29
+
30
+ def testUpdateHITMock
31
+ @@mock.listen do |call|
32
+ case call.name
33
+ when :GetHIT
34
+ {:HIT => {:HITId => call.request[:HITId], :Title => "old title", :Description => "foo", :Request => {} } }
35
+ when :RegisterHITType
36
+ {:RegisterHITTypeResult => {:HITTypeId => 'mockHITType', :Request => {} } }
37
+ else
38
+ {}
39
+ end
40
+ end
41
+
42
+ hit = @@mockturk.updateHIT( 'mockHIT', { :Title => 'new title' } )
43
+ assert_equal :GetHIT, @@mock.next.name
44
+
45
+ ht = @@mock.next
46
+ assert_equal :RegisterHITType, ht.name
47
+ assert_equal "new title", ht.request[:Title]
48
+ assert_equal "foo", ht.request[:Description]
49
+
50
+ update = @@mock.next
51
+ assert_equal :ChangeHITTypeOfHIT, update.name
52
+ assert_equal 'mockHIT', update.request[:HITId]
53
+ assert_equal 'mockHITType', update.request[:HITTypeId]
54
+ end
55
+
56
+ # Allow user to skip these tests by setting the DISABLE_MTURK_SANDBOX_TEST environment variable
57
+ if ENV['DISABLE_MTURK_SANDBOX_TEST'].nil?
58
+
59
+ def testHappyCase
60
+ hit_result = @@mturk.createHIT :Title => 'Ruby SDK Test Hit (ChangeHITTypeOfHIT)',
61
+ :Description => 'Autogenerated ruby-aws test case description1',
62
+ :Keywords => 'Ruby, test, SDK, changehittypeofhit, description1',
63
+ :Reward => { :Amount => 0.01, :CurrencyCode => 'USD' },
64
+ :Question => @@question
65
+ new_hit_type = @@mturk.registerHITType :Title => 'Ruby SDK Test Hit (ChangeHITTypeOfHIT) - Updated',
66
+ :Description => 'Autogenerated ruby-aws test case description2',
67
+ :Keywords => 'Ruby, test, SDK, changehittypeofhit, description2',
68
+ :Reward => { :Amount => 0.01, :CurrencyCode => 'USD' }
69
+ @@mturk.changeHITTypeOfHIT :HITId => hit_result[:HITId],
70
+ :HITTypeId => new_hit_type[:HITTypeId]
71
+ updated_hit = @@mturk.getHIT :HITId => hit_result[:HITId]
72
+ assert_equal new_hit_type[:HITTypeId], updated_hit[:HITTypeId], 'HITTypeId of ' + hit_result[:HITId] + ' not updated'
73
+ @@mturk.forceExpireHIT :HITId => hit_result[:HITId]
74
+ @@mturk.disposeHIT :HITId => hit_result[:HITId]
75
+ end
76
+
77
+ def testUpdateHIT
78
+ hit_result = @@mturk.createHIT :Title => 'Ruby SDK Test Hit (ChangeHITTypeOfHIT)',
79
+ :Description => 'Autogenerated ruby-aws test case description1',
80
+ :Keywords => 'Ruby, test, SDK, changehittypeofhit, description1',
81
+ :Reward => { :Amount => 0.01, :CurrencyCode => 'USD' },
82
+ :Question => @@question
83
+ new_template = { :Title => 'Ruby SDK Test Hit (ChangeHITTypeOfHIT) - Updated',
84
+ :Description => 'Autogenerated ruby-aws test case description2',
85
+ :Keywords => 'Ruby, test, SDK, changehittypeofhit, description2',
86
+ :Reward => { :Amount => 0.01, :CurrencyCode => 'USD' } }
87
+ @@mturk.updateHIT(hit_result[:HITId], new_template)
88
+ assert_not_equal hit_result[:HITTypeId], @@mturk.getHIT(:HITId=>hit_result[:HITId])[:HITTypeId], 'HITTypeId not changed'
89
+ @@mturk.forceExpireHIT :HITId => hit_result[:HITId]
90
+ @@mturk.disposeHIT :HITId => hit_result[:HITId]
91
+ end
92
+
93
+ def testUpdateHITs
94
+ hit_result1 = @@mturk.createHIT :Title => 'Ruby SDK Test Hit (ChangeHITTypeOfHIT)',
95
+ :Description => 'Autogenerated ruby-aws test case description1',
96
+ :Keywords => 'Ruby, test, SDK, changehittypeofhit, description1',
97
+ :Reward => { :Amount => 0.01, :CurrencyCode => 'USD' },
98
+ :Question => @@question
99
+ hit_result2 = @@mturk.createHIT :Title => 'Ruby SDK Test Hit (ChangeHITTypeOfHIT)',
100
+ :Description => 'Autogenerated ruby-aws test case description1',
101
+ :Keywords => 'Ruby, test, SDK, changehittypeofhit, description1',
102
+ :Reward => { :Amount => 0.01, :CurrencyCode => 'USD' },
103
+ :Question => @@question
104
+ hit_result3 = @@mturk.createHIT :Title => 'Ruby SDK Test Hit (ChangeHITTypeOfHIT)',
105
+ :Description => 'Autogenerated ruby-aws test case description1',
106
+ :Keywords => 'Ruby, test, SDK, changehittypeofhit, description1',
107
+ :Reward => { :Amount => 0.01, :CurrencyCode => 'USD' },
108
+ :Question => @@question
109
+ new_template = { :Title => 'Ruby SDK Test Hit (ChangeHITTypeOfHIT) - Updated',
110
+ :Description => 'Autogenerated ruby-aws test case description2',
111
+ :Keywords => 'Ruby, test, SDK, changehittypeofhit, description2',
112
+ :Reward => { :Amount => 0.01, :CurrencyCode => 'USD' } }
113
+
114
+ @@mturk.updateHITs(new_template, [hit_result1[:HITId], hit_result2[:HITId], hit_result3[:HITId]])
115
+
116
+ assert_not_equal hit_result1[:HITTypeId], @@mturk.getHIT(:HITId=>hit_result1[:HITId])[:HITTypeId], 'HITTypeId not changed'
117
+ assert_not_equal hit_result2[:HITTypeId], @@mturk.getHIT(:HITId=>hit_result2[:HITId])[:HITTypeId], 'HITTypeId not changed'
118
+ assert_not_equal hit_result3[:HITTypeId], @@mturk.getHIT(:HITId=>hit_result3[:HITId])[:HITTypeId], 'HITTypeId not changed'
119
+ @@mturk.forceExpireHIT :HITId => hit_result1[:HITId]
120
+ @@mturk.disposeHIT :HITId => hit_result1[:HITId]
121
+ @@mturk.forceExpireHIT :HITId => hit_result2[:HITId]
122
+ @@mturk.disposeHIT :HITId => hit_result2[:HITId]
123
+ @@mturk.forceExpireHIT :HITId => hit_result3[:HITId]
124
+ @@mturk.disposeHIT :HITId => hit_result3[:HITId]
125
+ end
126
+
127
+ end # if not DISABLE_MTURK_SANDBOX_TEST
128
+
129
+ end
130
+
@@ -0,0 +1,135 @@
1
+ # Copyright:: Copyright (c) 2007 Amazon Technologies, Inc.
2
+ # License:: Apache License, Version 2.0
3
+
4
+ require 'test/unit/testcase'
5
+ require 'ruby-aws'
6
+ require 'amazon/webservices/util/mock_transport'
7
+ require 'timeout'
8
+
9
+ class TestErrorHandler < Test::Unit::TestCase
10
+
11
+ def setup
12
+ @mock = Amazon::WebServices::Util::MockTransport.new
13
+ @mturk = Amazon::WebServices::MechanicalTurkRequester.new( :Transport => @mock, :AWSAccessKey => 'bogus', :AWSAccessKeyId => 'fake' )
14
+ end
15
+
16
+ def testTimeoutOnce
17
+
18
+ # mock will timeout first time, return success on second call
19
+ toggle = false
20
+ @mock.listen do |call|
21
+ Timeout.timeout(1) do
22
+ if toggle
23
+ toggle = !toggle
24
+ else
25
+ toggle = !toggle
26
+ sleep(5)
27
+ end
28
+ end
29
+ nil
30
+ end
31
+
32
+ assert_equal false, toggle
33
+ # invoke a retryable call once, should auto-retry and return success
34
+ @mturk.getAccountBalance
35
+ assert_equal 2, @mock.call_buffer.size, "Should have retried once"
36
+ @mock.each {|call| assert_equal :GetAccountBalance, call.name, "Should have been a GetAccountBalance call" }
37
+
38
+ @mock.flush
39
+ assert_equal false, toggle
40
+ # but invoking a non-retryable call will throw an exception
41
+ begin
42
+ @mturk.grantBonus
43
+ fail "Should have thrown an exception"
44
+ rescue Timeout::Error => e
45
+ # expect this exception
46
+ end
47
+ assert_equal true, toggle
48
+ assert_equal :GrantBonus, @mock.next.name
49
+ assert_nil @mock.next
50
+ end
51
+
52
+ def testTimeoutAlways
53
+
54
+ #mock will always timeout
55
+ @mock.listen do |call|
56
+ Timeout.timeout(1) { sleep(2) }
57
+ end
58
+
59
+ begin
60
+ @mturk.searchHITs
61
+ fail "Should have thrown an exception"
62
+ rescue Timeout::Error => e
63
+ # expect this exception
64
+ end
65
+
66
+ 7.times do
67
+ assert_equal :SearchHITs, @mock.next.name
68
+ end
69
+ assert_nil @mock.next
70
+ end
71
+
72
+
73
+ def testRuntimeError
74
+ @mock.listen do |call|
75
+ raise "Blah"
76
+ end
77
+
78
+ begin
79
+ @mturk.searchHITs
80
+ fail "Should have thrown an exception"
81
+ rescue RuntimeError => e
82
+ assert_equal "Blah", e.to_s
83
+ end
84
+ end
85
+
86
+ def testRuntimeErrorThrottled
87
+ @mock.listen do |call|
88
+ raise "Throttled"
89
+ end
90
+
91
+ begin
92
+ @mturk.searchHITs
93
+ fail "Should have thrown an exception"
94
+ rescue RuntimeError => e
95
+ assert_equal "Throttled", e.to_s
96
+ end
97
+ end
98
+
99
+ def testSOAPFaultError
100
+ arg = (Struct.new :faultcode, :faultstring, :faultactor, :detail).new
101
+ arg.faultcode = (Struct.new :data).new 'aws:blarg'
102
+ arg.faultstring = (Struct.new :data).new 'blarg blarg blarg'
103
+ s = SOAP::FaultError.new( arg )
104
+
105
+ @mock.listen do |call|
106
+ raise s
107
+ end
108
+
109
+ begin
110
+ @mturk.searchHITs
111
+ fail "Should have thrown an exception"
112
+ rescue SOAP::FaultError => e
113
+ assert_equal s, e
114
+ end
115
+ end
116
+
117
+ def testSOAPFaultErrorThrottled
118
+ arg = (Struct.new :faultcode, :faultstring, :faultactor, :detail).new
119
+ arg.faultcode = (Struct.new :data).new 'aws:Server.ServiceUnavailable'
120
+ arg.faultstring = (Struct.new :data).new 'Hey, give us a break!'
121
+ s = SOAP::FaultError.new( arg )
122
+
123
+ @mock.listen do |call|
124
+ raise s
125
+ end
126
+
127
+ begin
128
+ @mturk.searchHITs
129
+ fail "Should have thrown an exception"
130
+ rescue SOAP::FaultError => e
131
+ assert_equal s, e
132
+ end
133
+ end
134
+
135
+ end