sea_shanty 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 49c70b677534f10db5b3f98e4e49cc7a5259ac816db7f63cdf65d4768bbe207e
4
+ data.tar.gz: fdbe5b1e9588650f4772648973043e35144fdaf5f0c90b035b687901b4dfd05d
5
+ SHA512:
6
+ metadata.gz: 9b7a690390d6a80adb76b8c91a2ac789a07238c460661f77079751993b72321172ddf7175d7b40880815b834d1b59781ec57801f92c91c996b4c6c0a900ef765
7
+ data.tar.gz: 856de8a10bf572640facea7ada229122f2b751f71230152cd4f9a4c44e9b2c1483bb78f1a34a4236c6d1d6cace2e5a7eddb1f91fe33690443599725034d3759e
data/.standard.yml ADDED
@@ -0,0 +1,2 @@
1
+ # For available configuration options, see:
2
+ # https://github.com/testdouble/standard
data/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ ## [Unreleased]
2
+
3
+ ## [0.1.0] - 2023-01-04
4
+
5
+ - Initial release
@@ -0,0 +1,84 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
6
+
7
+ We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
8
+
9
+ ## Our Standards
10
+
11
+ Examples of behavior that contributes to a positive environment for our community include:
12
+
13
+ * Demonstrating empathy and kindness toward other people
14
+ * Being respectful of differing opinions, viewpoints, and experiences
15
+ * Giving and gracefully accepting constructive feedback
16
+ * Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
17
+ * Focusing on what is best not just for us as individuals, but for the overall community
18
+
19
+ Examples of unacceptable behavior include:
20
+
21
+ * The use of sexualized language or imagery, and sexual attention or
22
+ advances of any kind
23
+ * Trolling, insulting or derogatory comments, and personal or political attacks
24
+ * Public or private harassment
25
+ * Publishing others' private information, such as a physical or email
26
+ address, without their explicit permission
27
+ * Other conduct which could reasonably be considered inappropriate in a
28
+ professional setting
29
+
30
+ ## Enforcement Responsibilities
31
+
32
+ Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
33
+
34
+ Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.
35
+
36
+ ## Scope
37
+
38
+ This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
39
+
40
+ ## Enforcement
41
+
42
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at rasmus@nerdd.dk. All complaints will be reviewed and investigated promptly and fairly.
43
+
44
+ All community leaders are obligated to respect the privacy and security of the reporter of any incident.
45
+
46
+ ## Enforcement Guidelines
47
+
48
+ Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
49
+
50
+ ### 1. Correction
51
+
52
+ **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
53
+
54
+ **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
55
+
56
+ ### 2. Warning
57
+
58
+ **Community Impact**: A violation through a single incident or series of actions.
59
+
60
+ **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
61
+
62
+ ### 3. Temporary Ban
63
+
64
+ **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
65
+
66
+ **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
67
+
68
+ ### 4. Permanent Ban
69
+
70
+ **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
71
+
72
+ **Consequence**: A permanent ban from any sort of public interaction within the community.
73
+
74
+ ## Attribution
75
+
76
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0,
77
+ available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
78
+
79
+ Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity).
80
+
81
+ [homepage]: https://www.contributor-covenant.org
82
+
83
+ For answers to common questions about this code of conduct, see the FAQ at
84
+ https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations.
data/Gemfile ADDED
@@ -0,0 +1,14 @@
1
+ # frozen_string_literal: true
2
+
3
+ source "https://rubygems.org"
4
+
5
+ # Specify your gem's dependencies in sea_shanty.gemspec
6
+ gemspec
7
+
8
+ gem "rake"
9
+
10
+ gem "minitest"
11
+
12
+ gem "standard"
13
+
14
+ gem "faraday"
data/Gemfile.lock ADDED
@@ -0,0 +1,59 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ sea_shanty (0.1.0)
5
+
6
+ GEM
7
+ remote: https://rubygems.org/
8
+ specs:
9
+ ast (2.4.2)
10
+ faraday (2.7.2)
11
+ faraday-net_http (>= 2.0, < 3.1)
12
+ ruby2_keywords (>= 0.0.4)
13
+ faraday-net_http (3.0.2)
14
+ json (2.6.3)
15
+ language_server-protocol (3.17.0.2)
16
+ minitest (5.16.3)
17
+ parallel (1.22.1)
18
+ parser (3.1.3.0)
19
+ ast (~> 2.4.1)
20
+ rainbow (3.1.1)
21
+ rake (13.0.6)
22
+ regexp_parser (2.6.1)
23
+ rexml (3.2.5)
24
+ rubocop (1.40.0)
25
+ json (~> 2.3)
26
+ parallel (~> 1.10)
27
+ parser (>= 3.1.2.1)
28
+ rainbow (>= 2.2.2, < 4.0)
29
+ regexp_parser (>= 1.8, < 3.0)
30
+ rexml (>= 3.2.5, < 4.0)
31
+ rubocop-ast (>= 1.23.0, < 2.0)
32
+ ruby-progressbar (~> 1.7)
33
+ unicode-display_width (>= 1.4.0, < 3.0)
34
+ rubocop-ast (1.24.0)
35
+ parser (>= 3.1.1.0)
36
+ rubocop-performance (1.15.1)
37
+ rubocop (>= 1.7.0, < 2.0)
38
+ rubocop-ast (>= 0.4.0)
39
+ ruby-progressbar (1.11.0)
40
+ ruby2_keywords (0.0.5)
41
+ standard (1.20.0)
42
+ language_server-protocol (~> 3.17.0.2)
43
+ rubocop (= 1.40.0)
44
+ rubocop-performance (= 1.15.1)
45
+ unicode-display_width (2.3.0)
46
+
47
+ PLATFORMS
48
+ x86_64-darwin-21
49
+ x86_64-linux
50
+
51
+ DEPENDENCIES
52
+ faraday
53
+ minitest
54
+ rake
55
+ sea_shanty!
56
+ standard
57
+
58
+ BUNDLED WITH
59
+ 2.3.3
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2022 Rasmus Bang Grouleff
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,178 @@
1
+ # SeaShanty
2
+
3
+ SeaShanty is a tiny library that records HTTP interactions and replays responses for requests it has seen before.
4
+
5
+ The primary purpose is to speed up your test suite regardless of which test framework used by not relying on the network.
6
+
7
+ ## Installation
8
+
9
+ Add this line to your application's Gemfile:
10
+
11
+ ```ruby
12
+ gem 'sea_shanty'
13
+ ```
14
+
15
+ And then execute:
16
+
17
+ $ bundle install
18
+
19
+ Or install it yourself as:
20
+
21
+ $ gem install sea_shanty
22
+
23
+ ## Usage
24
+
25
+ The following is a minimal example of how to use SeaShanty.
26
+
27
+ ```ruby
28
+ require "rubygems"
29
+ require "minitest"
30
+ require "faraday"
31
+ require "sea_shanty"
32
+ require "sea_shanty/faraday"
33
+
34
+ SeaShanty.configure do |config|
35
+ config.storage_dir = "fixtures/sea_shanty"
36
+ end
37
+ SeaShanty.intercept(:faraday)
38
+
39
+ class TestSeaShanty < Minitest::Test
40
+ def test_fetch
41
+ response = Faraday.get("https://example.com")
42
+ assert_equal(200, response.status)
43
+ end
44
+ end
45
+ ```
46
+
47
+ The first time the test above is run, the request is sent as normal, because SeaShanty hasn't seen it before, and the request and response is stored, before the response is returned. On subsequent runs of the test, no requests will be sent over the network. Instead the response is loaded from the storage directory and returned.
48
+
49
+ **CAUTION!**
50
+
51
+ To prevent storing sensitive information like `Authorization` headers or credentials in the request body, use the `Configuration#request_body_filter` and `Configuration#request_headers_filter` described in the [Configuration](#configuration) section.
52
+
53
+ ### Interccept requests in an HTTP library
54
+
55
+ The following call intercepts requests made with Faraday.
56
+
57
+ ```ruby
58
+ SeaShanty.intercept :faraday
59
+ ```
60
+
61
+ Any HTTP requests made before the call to `SeaShanty.intercept` will not be handled by SeaShanty.
62
+
63
+ ### Configuration
64
+
65
+ * `storage_dir`
66
+ * The storage directory for the requests and responses.
67
+ * A string that can either be an absolute path or a path relative to `Dir.pwd`
68
+ * `bypass`
69
+ * Tells if SeaShanty should be bypassed
70
+ * A boolean. If it is true, SeaShanty will not look up or store responses, but just pass the request to the HTTP library
71
+ * This can be overwritten by setting the environment variable `SEA_SHANTY_BYPASS`
72
+ * `readonly`
73
+ * Tells if SeaShanty should allow the HTTP library to send the request over the network
74
+ * A boolean. If it is true, no requests are sent over the network. Instead SeaShanty will raise a `SeaShanty::UnknownRequest` error, if the request has not been seen before
75
+ * This can be overwritten by setting the environment variable `SEA_SHANTY_READONLY`
76
+ * `generic_responses`
77
+ * Tells SeaShanty to return generic responses whenever the request url matches one of the keys
78
+ * A hash where the keys are `Regexp`s and the values are strings with the path to a file with a stored response relative to the `storage_dir`
79
+ * The request url is matched against the `Regexp`s, and the first match will make SeaShanty return the response stored in the file with the path in the hash value
80
+ * `request_body_filter`
81
+ * Is applied to the request body before figuring out if the request has been seen before, and before the request and response is saved
82
+ * A callable object with an arity of 1.
83
+ * Is called with the raw request body
84
+ * Must return the filtered body
85
+ * `request_headers_filter`
86
+ * Is applied to the request headers before the request and response is saved
87
+ * A callable object with an arity of 2
88
+ * Is called once with each header name and value
89
+ * Must return the filtered value
90
+
91
+ ### Creating your own interceptor
92
+
93
+ Any object responding to `intercept!` and `remove` can be registered as interceptors in SeaShanty by calling `SeaShanty.register_interceptor(:identifier, interceptor)`.
94
+
95
+ The `intercept!` method must be able to take an instance of a `SeaShanty::RequestStore` as its sole argument.
96
+
97
+ #### Using the RequestStore
98
+
99
+ When intercepting a request from the HTTP library, a `SeaShanty::Request` should be instantiated like so:
100
+
101
+ ```ruby
102
+ request = SeaShanty::Request.new(method: "GET", url: "https://example.com", headers: {}, body: "")
103
+ ```
104
+
105
+ The `method` should be a String or symbol, `url` should be a String or an `URI`, `headers` should be a hash, and `body` a String or `nil`.
106
+
107
+ This `Request` objejct is then passed to `RequestStore#fetch` together with a block that takes no parameters and returns a `SeaShanty::Response`.
108
+
109
+ If the response is not loaded from the request store, the block is instead called.
110
+
111
+ To build a `Response` object use the initializer:
112
+
113
+ ```ruby
114
+ SeaShanty::Response.new(status: 200, message: "OK", headers: {}, body: "", original_response: response_from_library)
115
+ ```
116
+
117
+ The `status` should be an Integer, `message` a String or `nil`, `headers` should be a hash, `body` a String or `nil`. `original_response` is optional provided as a convenience.
118
+
119
+ When `RequestStore#fetch` returns the response, it is the interceptor's responsibility to convert the `Response` object into a format the library understands. If the block to `fetch` was called, and `original_response` is set, `Response#was_stored?` is `true`, and the response from the HTTP library is available in `Response#original_response`. Otherwise the interceptor can retrieve the data from the `Response` object using attributes similarly named as the named parameters in the initializer.
120
+
121
+ #### Registering an interceptor
122
+
123
+ The Faraday interceptor is registered like so in `lib/sea_shanty/faraday.rb`:
124
+
125
+ ```ruby
126
+ require "sea_shanty/faraday/interceptor"
127
+
128
+ SeaShanty.register_interceptor :faraday, SeaShanty::Faraday::Interceptor.new
129
+ ```
130
+
131
+ ### Supported HTTP libraries
132
+
133
+ In the current version [Faraday](https://lostisland.github.io/faraday/) is the only library SeaShanty supports.
134
+
135
+ ## Alternatives
136
+
137
+ * [VCR](https://github.com/vcr/vcr)
138
+ * [Ephemeral Response](https://github.com/sandro/ephemeral_response)
139
+ * [Net::HTTP Spy](https://github.com/martinbtt/net-http-spy)
140
+ * [NetRecorder](https://github.com/chrisyoung/netrecorder)
141
+ * [Puffing Billy](https://github.com/oesmith/puffing-billy)
142
+ * [REST-assured](https://github.com/artemave/REST-assured)
143
+ * [Stale Fish](https://github.com/jsmestad/stale_fish)
144
+ * [WebFixtures](https://github.com/trydionel/web_fixtures)
145
+
146
+ ## Future development
147
+
148
+ - [ ] Add interceptors for more HTTP libraries
149
+ - [ ] Add optional response body compression to reduce storage requirements
150
+ - [ ] Make it possible to overwrite stored requests and responses
151
+ - [ ] Document `Request`, `Response` and `RequestStore`
152
+ - [ ] More? Create an issue or send a pull request, if you think something is missing 🎉
153
+
154
+ ## Development
155
+
156
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake test` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
157
+
158
+ To install this gem onto your local machine, run `bundle exec rake install`.
159
+
160
+ Before creating a pull request, please make sure `rake test` passes, and `rake standard` has no suggestions.
161
+
162
+ ## Releasing a new version
163
+
164
+ To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and the created tag, and push the `.gem` file to [rubygems.org](https://rubygems.org).
165
+
166
+ The SeaShanty versioning scheme follows [SemVer 2.0.0](https://semver.org/spec/v2.0.0.html).
167
+
168
+ ## Contributing
169
+
170
+ Bug reports and pull requests are welcome on GitHub at https://github.com/rbgrouleff/sea_shanty. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [code of conduct](https://github.com/rbgrouleff/sea_shanty/blob/main/CODE_OF_CONDUCT.md).
171
+
172
+ ## License
173
+
174
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
175
+
176
+ ## Code of Conduct
177
+
178
+ Everyone interacting in the SeaShanty project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/rbgrouleff/sea_shanty/blob/main/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -0,0 +1,14 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ require "rake/testtask"
5
+
6
+ Rake::TestTask.new(:test) do |t|
7
+ t.libs << "test"
8
+ t.libs << "lib"
9
+ t.test_files = FileList["test/**/test_*.rb"]
10
+ end
11
+
12
+ require "standard/rake"
13
+
14
+ task default: %i[test standard]
data/bin/console ADDED
@@ -0,0 +1,15 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ require "bundler/setup"
5
+ require "sea_shanty"
6
+
7
+ # You can add fixtures and/or initialization code here to make experimenting
8
+ # with your gem easier. You can also use a different console, if you like.
9
+
10
+ # (If you use this, don't forget to add pry to your Gemfile!)
11
+ # require "pry"
12
+ # Pry.start
13
+
14
+ require "irb"
15
+ IRB.start(__FILE__)
data/bin/setup ADDED
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install
7
+
8
+ # Do any other automated setup that you need to do here
@@ -0,0 +1,48 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "sea_shanty/errors"
4
+
5
+ module SeaShanty
6
+ class Configuration
7
+ attr_accessor :bypass, :readonly, :storage_dir
8
+ alias_method :bypass?, :bypass
9
+ alias_method :readonly?, :readonly
10
+
11
+ def generic_responses=(responses)
12
+ unless Hash === responses
13
+ raise(
14
+ ConfigurationError,
15
+ "Generic responses must be a hash that maps a Regexp or something else that responds to `match?` to a relative path to a file with a recorded response."
16
+ )
17
+ end
18
+
19
+ raise ConfigurationError, "keys in the generic responses hash must respond to `match?`." unless responses.keys.all? { |key| key.respond_to?(:match?) }
20
+
21
+ @generic_responses = responses
22
+ end
23
+
24
+ def generic_responses
25
+ @generic_responses ||= {}
26
+ end
27
+
28
+ def request_body_filter=(filter)
29
+ raise ConfigurationError, "Filter must have a call method" unless filter.respond_to?(:call)
30
+ raise ConfigurationError, "Filter must have an arity of exactly 1" unless filter.arity == 1
31
+ @request_body_filter = filter
32
+ end
33
+
34
+ def request_body_filter
35
+ @request_body_filter ||= lambda { |body| body }
36
+ end
37
+
38
+ def request_headers_filter
39
+ @request_headers_filter ||= lambda { |key, value| value }
40
+ end
41
+
42
+ def request_headers_filter=(filter)
43
+ raise ConfigurationError, "Filter must have a call method" unless filter.respond_to?(:call)
44
+ raise ConfigurationError, "Filter must have an arity of exactly 2" unless filter.arity == 2
45
+ @request_headers_filter = filter
46
+ end
47
+ end
48
+ end
@@ -0,0 +1,15 @@
1
+ # frozen_string_literal: true
2
+
3
+ module SeaShanty
4
+ class Error < StandardError
5
+ end
6
+
7
+ class ConfigurationError < Error
8
+ end
9
+
10
+ class UnknownRequest < Error
11
+ end
12
+
13
+ class UnknownInterceptor < Error
14
+ end
15
+ end
@@ -0,0 +1,21 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "sea_shanty/faraday/middleware"
4
+ require "sea_shanty/faraday/rack_builder"
5
+
6
+ module SeaShanty
7
+ module Faraday
8
+ class Interceptor
9
+ BUILDER_CLASS_ATTR_NAME = :builder_class
10
+
11
+ def intercept!(request_store)
12
+ Middleware.request_store = request_store
13
+ ::Faraday::ConnectionOptions.memoized(BUILDER_CLASS_ATTR_NAME) { RackBuilder }
14
+ end
15
+
16
+ def remove
17
+ ::Faraday::ConnectionOptions.memoized(BUILDER_CLASS_ATTR_NAME) { ::Faraday::RackBuilder }
18
+ end
19
+ end
20
+ end
21
+ end
@@ -0,0 +1,68 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "faraday"
4
+
5
+ require "sea_shanty/request"
6
+ require "sea_shanty/response"
7
+
8
+ module SeaShanty
9
+ module Faraday
10
+ class Middleware
11
+ class << self
12
+ attr_accessor :request_store
13
+ end
14
+
15
+ attr_reader :request_store
16
+
17
+ def initialize(app, request_store: self.class.request_store)
18
+ @app = app
19
+ @request_store = request_store
20
+ end
21
+
22
+ def call(env)
23
+ response = request_store.fetch(build_request(env)) do
24
+ faraday_response = @app.call(env).on_complete do |response_env|
25
+ response_env
26
+ end
27
+
28
+ build_response(faraday_response.env)
29
+ end
30
+
31
+ build_faraday_response(response, env)
32
+ end
33
+
34
+ def close
35
+ @app.close if @app.respond_to?(:close)
36
+ end
37
+
38
+ private
39
+
40
+ def build_request(env)
41
+ Request.new(method: env.method, url: env.url, headers: env.request_headers.to_h, body: env.request_body)
42
+ end
43
+
44
+ def build_response(response_env)
45
+ Response.new(
46
+ status: response_env.status,
47
+ message: response_env.reason_phrase,
48
+ headers: response_env.response_headers.to_h,
49
+ body: response_env.response_body,
50
+ original_response: response_env.response
51
+ )
52
+ end
53
+
54
+ def build_faraday_response(response, env)
55
+ if response.was_stored?
56
+ response.original_response
57
+ else
58
+ env.response = ::Faraday::Response.new
59
+ env.status = response.status
60
+ env.reason_phrase = response.message
61
+ env.response_headers = ::Faraday::Utils::Headers.from(response.headers)
62
+ env.response_body = response.body
63
+ env.response.finish(env)
64
+ end
65
+ end
66
+ end
67
+ end
68
+ end
@@ -0,0 +1,22 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "faraday"
4
+ require "sea_shanty/faraday/middleware"
5
+
6
+ module SeaShanty
7
+ module Faraday
8
+ class RackBuilder < ::Faraday::RackBuilder
9
+ def lock!
10
+ insert_middleware
11
+ super
12
+ end
13
+
14
+ private
15
+
16
+ def insert_middleware
17
+ return if handlers.any? { |h| ::SeaShanty::Faraday::Middleware == h.klass }
18
+ insert_before(handlers.size, ::SeaShanty::Faraday::Middleware)
19
+ end
20
+ end
21
+ end
22
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "sea_shanty/faraday/interceptor"
4
+
5
+ SeaShanty.register_interceptor(:faraday, SeaShanty::Faraday::Interceptor.new)
@@ -0,0 +1,35 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "uri"
4
+
5
+ module SeaShanty
6
+ class Request
7
+ attr_reader :method, :url, :headers, :body
8
+
9
+ def initialize(method:, url:, headers:, body:)
10
+ @method = method
11
+ @url = case url
12
+ when String
13
+ URI.parse(url)
14
+ when URI
15
+ url
16
+ else
17
+ raise ArgumentError, "url should be a String or an URI"
18
+ end
19
+ @headers = headers
20
+ @body = body
21
+ end
22
+
23
+ def to_h
24
+ {
25
+ method: method.to_s,
26
+ url: url.to_s,
27
+ headers: headers,
28
+ body: {
29
+ string: body.to_s,
30
+ encoding: body.nil? ? "" : body.encoding.name
31
+ }
32
+ }
33
+ end
34
+ end
35
+ end
@@ -0,0 +1,38 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "digest/sha1"
4
+ require "pathname"
5
+
6
+ module SeaShanty
7
+ class RequestSerializer
8
+ def initialize(headers_filter: lambda { |_name, value| value }, body_filter: lambda { |body| body })
9
+ @headers_filter = headers_filter
10
+ @body_filter = body_filter
11
+ end
12
+
13
+ def digest(request)
14
+ Digest::SHA1.hexdigest(request.method.to_s + request.url.to_s + body_filter.call(request.body.to_s))
15
+ end
16
+
17
+ def filename(request)
18
+ "#{digest(request)}.yml"
19
+ end
20
+
21
+ def file_path(request)
22
+ # Don't assume system directory separator is /
23
+ url_path = request.url.path.delete_prefix("/").split("/").join(File::SEPARATOR)
24
+ Pathname.new(request.url.hostname).join(url_path, request.method.to_s, filename(request))
25
+ end
26
+
27
+ def serialize(request)
28
+ hash = request.to_h
29
+ hash[:headers] = hash.fetch(:headers).map { |name, value| [name, headers_filter.call(name, value)] }.to_h
30
+ hash[:body] = body_filter.call(hash.fetch(:body))
31
+ hash
32
+ end
33
+
34
+ private
35
+
36
+ attr_reader :headers_filter, :body_filter
37
+ end
38
+ end
@@ -0,0 +1,73 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "date"
4
+ require "pathname"
5
+ require "yaml"
6
+ require "sea_shanty/request_serializer"
7
+
8
+ module SeaShanty
9
+ class RequestStore
10
+ def initialize(configuration, generic_responses: configuration.generic_responses, storage_dir: configuration.storage_dir)
11
+ @configuration = configuration
12
+ @generic_responses = generic_responses
13
+ @storage_dir = Pathname.new(storage_dir)
14
+ @request_serializer = RequestSerializer.new(headers_filter: configuration.request_headers_filter, body_filter: configuration.request_body_filter)
15
+ end
16
+
17
+ def fetch(request, &block)
18
+ if configuration.bypass?
19
+ raise ConfigurationError, "Bypass and readonly are both true - please set only one of them." if configuration.readonly?
20
+ yield
21
+ elsif configuration.readonly?
22
+ load_response(request)
23
+ elsif has_response_for?(request)
24
+ load_response(request)
25
+ else
26
+ response = yield
27
+ store(request, response) unless configuration.bypass?
28
+ response
29
+ end
30
+ end
31
+
32
+ def has_response_for?(request)
33
+ request_file_path(request).exist?
34
+ end
35
+
36
+ def load_response(request)
37
+ raise UnknownRequest, "SeaShanty: Unknown request #{request.method.to_s.upcase} to #{request.url}" unless has_response_for?(request)
38
+ contents = YAML.safe_load(request_file_path(request).read, permitted_classes: [Symbol])
39
+ Response.from_h(contents.fetch(:response))
40
+ end
41
+
42
+ def store(request, response)
43
+ file_path = request_file_path(request)
44
+ file_path.dirname.mkpath
45
+ file_path.open("w+") do |file|
46
+ file.write(YAML.dump(serialize(request, response)))
47
+ end
48
+ end
49
+
50
+ private
51
+
52
+ attr_reader :configuration, :generic_responses, :storage_dir, :request_serializer
53
+
54
+ def request_file_path(request)
55
+ _, generic_file_path = generic_responses.find { |matcher, path| matcher.match?(request.url.to_s) }
56
+ file_path = if generic_file_path.nil?
57
+ request_serializer.file_path(request)
58
+ else
59
+ Pathname.new(generic_file_path.to_s)
60
+ end
61
+
62
+ storage_dir.join(file_path)
63
+ end
64
+
65
+ def serialize(request, response)
66
+ {
67
+ request: request_serializer.serialize(request),
68
+ response: response.to_h,
69
+ stored_at: DateTime.now.to_s
70
+ }
71
+ end
72
+ end
73
+ end
@@ -0,0 +1,60 @@
1
+ # frozen_literal_string: true
2
+
3
+ module SeaShanty
4
+ class Response
5
+ attr_reader :body, :headers, :message, :status, :original_response
6
+
7
+ class << self
8
+ def from_h(hash)
9
+ new(
10
+ status: hash.fetch(:status).fetch(:code),
11
+ message: hash.fetch(:status).fetch(:message),
12
+ headers: hash.fetch(:headers),
13
+ body: hash.fetch(:body).fetch(:encoding).empty? ? nil : hash.fetch(:body).fetch(:string)
14
+ )
15
+ end
16
+ end
17
+
18
+ def initialize(status:, message:, headers:, body:, original_response: ORIGINAL_RESPONSE_NOT_PRESENT)
19
+ @status = Integer(status, status.is_a?(String) ? 10 : 0)
20
+ @message = message
21
+ @headers = headers
22
+ @body = body
23
+ @original_response = original_response
24
+ end
25
+
26
+ def to_h
27
+ {
28
+ status: {
29
+ code: status,
30
+ message: message
31
+ },
32
+ headers: headers,
33
+ body: {
34
+ string: body.to_s,
35
+ encoding: body.nil? ? "" : body.encoding.name
36
+ }
37
+ }
38
+ end
39
+
40
+ def was_stored?
41
+ ORIGINAL_RESPONSE_NOT_PRESENT != original_response
42
+ end
43
+
44
+ def ==(other)
45
+ self.class === other &&
46
+ status == other.status && message == other.message && headers == other.headers &&
47
+ body == other.body
48
+ end
49
+
50
+ alias_method :eql?, :==
51
+
52
+ def hash
53
+ [self.class, status, message, headers, body].hash
54
+ end
55
+
56
+ private
57
+
58
+ ORIGINAL_RESPONSE_NOT_PRESENT = :original_response_not_present
59
+ end
60
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module SeaShanty
4
+ VERSION = "0.1.0"
5
+ end
data/lib/sea_shanty.rb ADDED
@@ -0,0 +1,69 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "sea_shanty/errors"
4
+ require "sea_shanty/configuration"
5
+ require "sea_shanty/request_store"
6
+ require "sea_shanty/version"
7
+
8
+ module SeaShanty
9
+ TRUE_VALUES = %w[1 yes y true]
10
+
11
+ module_function
12
+
13
+ def configuration
14
+ @configuration ||= Configuration.new
15
+ end
16
+
17
+ def configure(&block)
18
+ yield configuration
19
+
20
+ configuration.bypass = configuration_overwrite(ENV["SEA_SHANTY_BYPASS"], configuration.bypass)
21
+ configuration.readonly = configuration_overwrite(ENV["SEA_SHANTY_READONLY"], configuration.readonly)
22
+ end
23
+
24
+ def intercept(identifier)
25
+ return if intercepting.include?(identifier)
26
+ interceptors.fetch(identifier).intercept!(request_store)
27
+ intercepting << identifier
28
+ rescue KeyError
29
+ raise(
30
+ UnknownInterceptor,
31
+ "Cannot find an interceptor for #{identifier}. Available interceptors are: [#{interceptors.keys.join(", ")}]"
32
+ )
33
+ end
34
+
35
+ def intercepting
36
+ @intercepting ||= []
37
+ end
38
+
39
+ def interceptors
40
+ @interceptors ||= {}
41
+ end
42
+
43
+ def register_interceptor(identifier, interceptor)
44
+ interceptors[identifier] = interceptor
45
+ end
46
+
47
+ def remove(identifier)
48
+ return unless intercepting.include?(identifier)
49
+ interceptors.fetch(identifier).remove
50
+ intercepting.delete(identifier)
51
+ rescue KeyError
52
+ raise(
53
+ UnknownInterceptor,
54
+ "Cannot find an interceptor for #{identifier}. Available interceptors are: [#{interceptors.keys.join(", ")}]"
55
+ )
56
+ end
57
+
58
+ def request_store
59
+ @request_store ||= RequestStore.new(configuration)
60
+ end
61
+
62
+ def configuration_overwrite(env_var, value)
63
+ if env_var.nil? || env_var.empty?
64
+ value
65
+ else
66
+ TRUE_VALUES.include?(env_var.downcase)
67
+ end
68
+ end
69
+ end
@@ -0,0 +1,39 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "lib/sea_shanty/version"
4
+
5
+ Gem::Specification.new do |spec|
6
+ spec.name = "sea_shanty"
7
+ spec.version = SeaShanty::VERSION
8
+ spec.authors = ["Rasmus Bang Grouleff"]
9
+ spec.email = ["rasmus@nerdd.dk"]
10
+
11
+ spec.summary = "SeaShanty records HTTP requests and responses and returns saved responses for requests it has seen before."
12
+ spec.description = "SeaShanty is a minimalistic library for recording HTTP requests and responses and replaying responses for already seen requests in an unobtrusive and test framework agnostic way."
13
+ spec.homepage = "https://github.com/rbgrouleff/sea_shanty"
14
+ spec.license = "MIT"
15
+ spec.required_ruby_version = ">= 2.7.0"
16
+
17
+ spec.metadata["allowed_push_host"] = "https://rubygems.org"
18
+
19
+ spec.metadata["homepage_uri"] = spec.homepage
20
+ spec.metadata["source_code_uri"] = spec.homepage
21
+ spec.metadata["changelog_uri"] = [spec.homepage, "CHANGELOG.md"].join("/")
22
+
23
+ # Specify which files should be added to the gem when it is released.
24
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
25
+ spec.files = Dir.chdir(File.expand_path(__dir__)) do
26
+ `git ls-files -z`.split("\x0").reject do |f|
27
+ (f == __FILE__) || f.match(%r{\A(?:(?:test|spec|features)/|\.(?:git|travis|circleci)|appveyor)})
28
+ end
29
+ end
30
+ spec.bindir = "exe"
31
+ spec.executables = spec.files.grep(%r{\Aexe/}) { |f| File.basename(f) }
32
+ spec.require_paths = ["lib"]
33
+
34
+ # Uncomment to register a new dependency of your gem
35
+ # spec.add_dependency "example-gem", "~> 1.0"
36
+
37
+ # For more information and examples about making a new gem, check out our
38
+ # guide at: https://bundler.io/guides/creating_gem.html
39
+ end
@@ -0,0 +1,4 @@
1
+ module SeaShanty
2
+ VERSION: String
3
+ # See the writing guide of rbs: https://github.com/ruby/rbs#guides
4
+ end
metadata ADDED
@@ -0,0 +1,74 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: sea_shanty
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Rasmus Bang Grouleff
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2023-01-04 00:00:00.000000000 Z
12
+ dependencies: []
13
+ description: SeaShanty is a minimalistic library for recording HTTP requests and responses
14
+ and replaying responses for already seen requests in an unobtrusive and test framework
15
+ agnostic way.
16
+ email:
17
+ - rasmus@nerdd.dk
18
+ executables: []
19
+ extensions: []
20
+ extra_rdoc_files: []
21
+ files:
22
+ - ".standard.yml"
23
+ - CHANGELOG.md
24
+ - CODE_OF_CONDUCT.md
25
+ - Gemfile
26
+ - Gemfile.lock
27
+ - LICENSE.txt
28
+ - README.md
29
+ - Rakefile
30
+ - bin/console
31
+ - bin/setup
32
+ - lib/sea_shanty.rb
33
+ - lib/sea_shanty/configuration.rb
34
+ - lib/sea_shanty/errors.rb
35
+ - lib/sea_shanty/faraday.rb
36
+ - lib/sea_shanty/faraday/interceptor.rb
37
+ - lib/sea_shanty/faraday/middleware.rb
38
+ - lib/sea_shanty/faraday/rack_builder.rb
39
+ - lib/sea_shanty/request.rb
40
+ - lib/sea_shanty/request_serializer.rb
41
+ - lib/sea_shanty/request_store.rb
42
+ - lib/sea_shanty/response.rb
43
+ - lib/sea_shanty/version.rb
44
+ - sea_shanty.gemspec
45
+ - sig/sea_shanty.rbs
46
+ homepage: https://github.com/rbgrouleff/sea_shanty
47
+ licenses:
48
+ - MIT
49
+ metadata:
50
+ allowed_push_host: https://rubygems.org
51
+ homepage_uri: https://github.com/rbgrouleff/sea_shanty
52
+ source_code_uri: https://github.com/rbgrouleff/sea_shanty
53
+ changelog_uri: https://github.com/rbgrouleff/sea_shanty/CHANGELOG.md
54
+ post_install_message:
55
+ rdoc_options: []
56
+ require_paths:
57
+ - lib
58
+ required_ruby_version: !ruby/object:Gem::Requirement
59
+ requirements:
60
+ - - ">="
61
+ - !ruby/object:Gem::Version
62
+ version: 2.7.0
63
+ required_rubygems_version: !ruby/object:Gem::Requirement
64
+ requirements:
65
+ - - ">="
66
+ - !ruby/object:Gem::Version
67
+ version: '0'
68
+ requirements: []
69
+ rubygems_version: 3.3.3
70
+ signing_key:
71
+ specification_version: 4
72
+ summary: SeaShanty records HTTP requests and responses and returns saved responses
73
+ for requests it has seen before.
74
+ test_files: []