Projects
home:rottame:rubygems
rubygem-faraday-1.0
Log In
Username
Password
We truncated the diff of some files because they were too big. If you want to see the full diff for every file,
click here
.
Overview
Repositories
Revisions
Requests
Users
Attributes
Meta
Expand all
Collapse all
Difference Between Revision 1 and
home:rottame:rubygems
/
rubygem-faraday
View file
rubygem-faraday.changes
Deleted
@@ -1,735 +0,0 @@ -------------------------------------------------------------------- -Thu Nov 2 15:47:19 UTC 2023 - Dan ΔermΓ‘k <dan.cermak@posteo.net> - -- 2.7.11: - -## What's Changed -* Refer to correct branch ci skip by @olleolleolle in https://github.com/lostisland/faraday/pull/1516 -* π New docs π by @iMacTia in https://github.com/lostisland/faraday/pull/1517 -* Fix capitalization for Elasticsearch by @picandocodigo in https://github.com/lostisland/faraday/pull/1520 -* Fix 404 link in UPGRADING documentation by @shanempope in https://github.com/lostisland/faraday/pull/1521 -* Fix included middleware links by @edwardloveall in https://github.com/lostisland/faraday/pull/1522 -* Fix a test failure using Ruby 3.3.0dev by @koic in https://github.com/lostisland/faraday/pull/1523 -* Format code with less indent by @olleolleolle in https://github.com/lostisland/faraday/pull/1524 -* Add `base64` to runtime dependency by @koic in https://github.com/lostisland/faraday/pull/1525 -* Add option for omitting request data from Faraday exceptions by @ClaytonPassmore in https://github.com/lostisland/faraday/pull/1526 - -## New Contributors -* @picandocodigo made their first contribution in https://github.com/lostisland/faraday/pull/1520 -* @shanempope made their first contribution in https://github.com/lostisland/faraday/pull/1521 -* @edwardloveall made their first contribution in https://github.com/lostisland/faraday/pull/1522 -* @koic made their first contribution in https://github.com/lostisland/faraday/pull/1523 -* @ClaytonPassmore made their first contribution in https://github.com/lostisland/faraday/pull/1526 - -**Full Changelog**: https://github.com/lostisland/faraday/compare/v2.7.10...v2.7.11 - -2.7.10: - -## What's Changed -* Fix some logging inefficiencies by @semaperepelitsa in https://github.com/lostisland/faraday/pull/1515 - -## New Contributors -* @semaperepelitsa made their first contribution in https://github.com/lostisland/faraday/pull/1515 - -**Full Changelog**: https://github.com/lostisland/faraday/compare/v2.7.9...v2.7.10 - -2.7.9: - -## What's Changed -* Raise Error: Add Faraday::RequestTimeoutError by @tisba in https://github.com/lostisland/faraday/pull/1513 -* Include `env:headers` in `Stubs::NotFound` by @yykamei in https://github.com/lostisland/faraday/pull/1514 - -## New Contributors -* @tisba made their first contribution in https://github.com/lostisland/faraday/pull/1513 - -**Full Changelog**: https://github.com/lostisland/faraday/compare/v2.7.8...v2.7.9 - -2.7.8: - -## What's Changed -* Failing test: Logging headers & errors fails when ConnectionFailed is raised by @eikes in https://github.com/lostisland/faraday/pull/1512 - -## New Contributors -* @eikes made their first contribution in https://github.com/lostisland/faraday/pull/1512 - -**Full Changelog**: https://github.com/lostisland/faraday/compare/v2.7.7...v2.7.8 - -2.7.7: - -## What's Changed -* Fix implementation of Faraday::Error helpers. by @iMacTia in https://github.com/lostisland/faraday/pull/1510 - - -**Full Changelog**: https://github.com/lostisland/faraday/compare/v2.7.6...v2.7.7 - -2.7.6: - -## What's Changed -* Fix "method redefined" warnings introduced in Faraday 2.7.5 by @mattbrictson in https://github.com/lostisland/faraday/pull/1506 - - -**Full Changelog**: https://github.com/lostisland/faraday/compare/v2.7.5...v2.7.6 - -2.7.5: - -## What's Changed -* Subclass Options structs using a block by @bdewater in https://github.com/lostisland/faraday/pull/1489 -* Remove direct struct subclassing by @bdewater in https://github.com/lostisland/faraday/pull/1491 -* Fix incorrect use of logger middleware in docs by @mattbrictson in https://github.com/lostisland/faraday/pull/1497 -* Always assume the existence of `URI::Generic#find_proxy` by @yykamei in https://github.com/lostisland/faraday/pull/1502 -* Encode `false` to `"false"` in `Faraday::Request::Json` by @yykamei in https://github.com/lostisland/faraday/pull/1504 -* ProxyOptions should treat empty string as nil by @exoego in https://github.com/lostisland/faraday/pull/1493 - -## New Contributors -* @mattbrictson made their first contribution in https://github.com/lostisland/faraday/pull/1497 -* @exoego made their first contribution in https://github.com/lostisland/faraday/pull/1493 - -**Full Changelog**: https://github.com/lostisland/faraday/compare/v2.7.4...v2.7.5 - -2.7.4: - -## What's Changed -* Fix support for custom URI parsers by @iMacTia in https://github.com/lostisland/faraday/pull/1485 - - -**Full Changelog**: https://github.com/lostisland/faraday/compare/v2.7.3...v2.7.4 - -2.7.3: - -## What's Changed - -Fixes: -* Fix Style/ZeroLengthPredicate by @olleolleolle in https://github.com/lostisland/faraday/pull/1480 -* Connection#build_exclusive_url: replace simple syntax by @hyuraku in https://github.com/lostisland/faraday/pull/1481 -* Add URL to to_hash in Faraday::Response (#1474) by @aaronstillwell in https://github.com/lostisland/faraday/pull/1475 - -Misc: -* Clarify diff between connection settings `timeout` and `open_timeout` by @Yu-Chieh-Henry-Yang in https://github.com/lostisland/faraday/pull/1470 -* Adds Ruby 3.2 to the CI matrix. by @petergoldstein in https://github.com/lostisland/faraday/pull/1471 -* Fix typo in Adapters documentation by @henrialb in https://github.com/lostisland/faraday/pull/1473 -* docs: Update to 2023 by @frederikspang in https://github.com/lostisland/faraday/pull/1477 -* Update connection.rb documentation to use PUT in an example by @wlads in https://github.com/lostisland/faraday/pull/1482 - -## New Contributors -* @Yu-Chieh-Henry-Yang made their first contribution in https://github.com/lostisland/faraday/pull/1470 -* @henrialb made their first contribution in https://github.com/lostisland/faraday/pull/1473 -* @frederikspang made their first contribution in https://github.com/lostisland/faraday/pull/1477 -* @aaronstillwell made their first contribution in https://github.com/lostisland/faraday/pull/1475 -* @wlads made their first contribution in https://github.com/lostisland/faraday/pull/1482 - -**Full Changelog**: https://github.com/lostisland/faraday/compare/v2.7.2...v2.7.3 - -2.7.2: - -## What's Changed -* Replace actions/setup-ruby with ruby/setup-ruby by @kyoshidajp in https://github.com/lostisland/faraday/pull/1466 -* Enforce timeouts in Faraday's test adapter by @dpep in https://github.com/lostisland/faraday/pull/1465 -* Rename Faraday::Logger::Formatter#error to #exception by @iMacTia in https://github.com/lostisland/faraday/pull/1468 - -## ATTENTION -Rename Faraday::Logger::Formatter#error (#1468(https://github.com/lostisland/faraday/pull/1468)) is potentially a breaking change IF you've created a custom `Faraday::Logging::Formatter` implementing the new `error` method introduced in v2.7.0. - -We've decided to rollout this change in a fix version anyway because the name of the method was potentially causing infinite loop issues, and because the feature was very recently released. - -This should not be impacting you otherwise and you can safely upgrade. - -## New Contributors -* @kyoshidajp made their first contribution in https://github.com/lostisland/faraday/pull/1466 -* @dpep made their first contribution in https://github.com/lostisland/faraday/pull/1465 - -**Full Changelog**: https://github.com/lostisland/faraday/compare/v2.7.1...v2.7.2 - - - -------------------------------------------------------------------- -Wed Dec 7 11:20:05 UTC 2022 - Stephan Kulow <coolo@suse.com> - -updated to version 2.7.1 - see installed CHANGELOG.md - - -------------------------------------------------------------------- -Mon Oct 10 13:04:34 UTC 2022 - Stephan Kulow <coolo@suse.com> - -updated to version 2.6.0 - see installed CHANGELOG.md - - -------------------------------------------------------------------- -Fri Aug 26 16:17:08 UTC 2022 - Manuel Schnitzer <mschnitzer@suse.com> - -- updated to version 2.5.2 - - see installed CHANGELOG.md - -------------------------------------------------------------------- -Thu Aug 4 13:09:44 UTC 2022 - Stephan Kulow <coolo@suse.com> - -- updated to version 2.4.0 - see installed CHANGELOG.md - - -------------------------------------------------------------------- -Mon Jun 13 16:57:35 UTC 2022 - Manuel Schnitzer <mschnitzer@suse.com> - -- updated to version 2.3.0 - - # Features - - * Add indices when arrays are encoded by @daedric in #1399 - - # Fixes - - * Allow application/x-www-form-url_encoded POST requests to use file objects as the request body by @catlee in #1415 - - # Misc - - * CHANGELOG: add 2.2.0 section by @olleolleolle in #1394 - * docs: UPGRADE Note #dependency removed in 2.0 by @olleolleolle in #1398 - * docs: Add one more require to the quickstart to make this whole thing work immediately by @joshuabremerdexcom in #1401 - * Update custom middleware documentation by @AlexWayfer in #1404 - * Doc: Added raise_error middleware configuration by @nicosvirjt in #1412 - * docs: Correct default default_adapter value by @kuahyeow in #1414 - * CI: Update GitHub Action "checkout" to v3 by @olleolleolle in #1416 - -------------------------------------------------------------------- -Mon Feb 21 11:31:14 UTC 2022 - Stephan Kulow <coolo@suse.com> - -updated to version 2.2.0 - see installed CHANGELOG.md
View file
rubygem-faraday.spec
Changed
@@ -1,7 +1,7 @@ # # spec file for package rubygem-faraday # -# Copyright (c) 2023 SUSE LLC +# Copyright (c) 2018 SUSE LINUX GmbH, Nuernberg, Germany. # # All modifications and additions to the file contributed by third parties # remain the property of their copyright owners, unless otherwise agreed @@ -12,7 +12,7 @@ # license that conforms to the Open Source Definition (Version 1.9) # published by the Open Source Initiative. -# Please submit bugfixes or comments via https://bugs.opensuse.org/ +# Please submit bugfixes or comments via http://bugs.opensuse.org/ # @@ -24,18 +24,20 @@ # Name: rubygem-faraday -Version: 2.7.11 +Version: 1.0.0 Release: 0 %define mod_name faraday %define mod_full_name %{mod_name}-%{version} -BuildRequires: %{ruby >= 2.6} +BuildRoot: %{_tmppath}/%{name}-%{version}-build +BuildRequires: %{ruby >= 1.9} BuildRequires: %{rubygem gem2rpm} BuildRequires: ruby-macros >= 5 -URL: https://lostisland.github.io/faraday +Url: https://github.com/lostisland/faraday Source: https://rubygems.org/gems/%{mod_full_name}.gem Source1: gem2rpm.yml Summary: HTTP/REST API client library License: MIT +Group: Development/Languages/Ruby %description HTTP/REST API client library. @@ -46,7 +48,7 @@ %install %gem_install \ - --doc-files="CHANGELOG.md LICENSE.md README.md" \ + --doc-files="LICENSE.md README.md" \ -f %gem_packages
View file
faraday-2.7.11.gem/checksums.yaml.gz -> faraday-1.0.0.gem/checksums.yaml.gz
Changed
@@ -1,7 +1,7 @@ --- SHA256: - metadata.gz: 72fbb1db4fce28541cd53b5908e1fc18539ead8322d0b642069bd2e63d2a6543 - data.tar.gz: a5e4f596d8f23e00f064c9789f85fa1cb194cac85168177750b76b3a3e9c7f4d + metadata.gz: 9d3d650c5d465a0862cddd7ab2ed27fbfb4a6e5f2cfcbb54ba753bcc1ce9e40e + data.tar.gz: 953336deeb3dd2e0228368209bdffc7815b376772269c439e21374bc22b70484 SHA512: - metadata.gz: f880cdd4a42f22ac4eafeab1ddfcfb9e7a8ff0299956a279b207e4ed50d9b86fa09e44e74c4810b9ace3748db5edf6a9f62c73310d09ec1bbf73ec981356d921 - data.tar.gz: 159e971ec7168017e0053511217a8b89314cd25aaf626a3a409db800218e39b172741a1264616c7b770a3ce45e9ee9a0bd5f9dc6fd43511cc4b9f8ae5fa8304a + metadata.gz: b80c084a8714d995dec61c918891a63720dbcdddf2eb3ecb7106f40a03bb341c4f03ffe976365c5450b2dcffd0b1f52c1cd4320ea24591dfaef7d5fdbbe12562 + data.tar.gz: 67f8134fae885d3bb2e621afa701d6d535409bbb0141ad699f4d290059d61bf856915f622e214251f05e8b893a69bf68439118074712a22e75e3705b249dbb85
View file
faraday-2.7.11.gem/data/CHANGELOG.md -> faraday-1.0.0.gem/data/CHANGELOG.md
Changed
@@ -1,297 +1,6 @@ # Faraday Changelog -## The changelog has moved! - -This file is not being updated anymore. Instead, please check the Releases(https://github.com/lostisland/faraday/releases) page. - -## 2.2.0(https://github.com/lostisland/faraday/compare/v2.1.0...v2.2.0) (2022-02-03) - -* Reintroduce the possibility to register middleware with symbols, strings or procs in #1391(https://github.com/lostisland/faraday/pull/1391) - -## 2.1.0(https://github.com/lostisland/faraday/compare/v2.0.1...v2.1.0) (2022-01-15) - -* Fix test adapter thread safety by @iMacTia in #1380(https://github.com/lostisland/faraday/pull/1380) -* Add default adapter options by @hirasawayuki in #1382(https://github.com/lostisland/faraday/pull/1382) -* CI: Add Ruby 3.1 to matrix by @petergoldstein in #1374(https://github.com/lostisland/faraday/pull/1374) -* docs: fix regex pattern in logger.md examples by @hirasawayuki in #1378(https://github.com/lostisland/faraday/pull/1378) - -## 2.0.1(https://github.com/lostisland/faraday/compare/v2.0.0...v2.0.1) (2022-01-05) - -* Re-add `faraday-net_http` as default adapter by @iMacTia in #1366(https://github.com/lostisland/faraday/pull/1366) -* Updated sample format in UPGRADING.md by @vimutter in #1361(https://github.com/lostisland/faraday/pull/1361) -* docs: Make UPGRADING examples more copyable by @olleolleolle in #1363(https://github.com/lostisland/faraday/pull/1363) - -## 2.0.0(https://github.com/lostisland/faraday/compare/v1.8.0...v2.0.0) (2022-01-04) - -The next major release is here, and it comes almost 2 years after the release of v1.0! - -This release changes the way you use Faraday and embraces a new paradigm of Faraday as an ecosystem, rather than a library. - -What does that mean? It means that Faraday is less of a bundled tool and more of a framework for the community to build on top of. - -As a result, all adapters and some middleware have moved out and are now shipped as standalone gems π! - -But this doesn't mean that upgrading from Faraday 1.x to Faraday 2.0 should be hard, in fact we've listed everything you need to do in the UPGRADING.md(https://github.com/lostisland/faraday/blob/main/UPGRADING.md) doc. - -Moreover, we've setup a new awesome-faraday(https://github.com/lostisland/awesome-faraday) repository that will showcase a curated list of adapters and middleware π. - -This release was the result of the efforts of the core team and all the contributors, new and old, that have helped achieve this milestone π. - -## What's Changed - -* Autoloading, dependency loading and middleware registry cleanup by @iMacTia in #1301(https://github.com/lostisland/faraday/pull/1301) -* Move JSON middleware (request and response) from faraday_middleware by @iMacTia in #1300(https://github.com/lostisland/faraday/pull/1300) -* Remove deprecated `Faraday::Request#method` by @olleolleolle in #1303(https://github.com/lostisland/faraday/pull/1303) -* Remove deprecated `Faraday::UploadIO` by @iMacTia in #1307(https://github.com/lostisland/faraday/pull/1307) -* 1.x Deprecate Authorization helpers in `Faraday::Connection` by @iMacTia in #1306(https://github.com/lostisland/faraday/pull/1306) -* Drop deprecated auth helpers from Connection and refactor auth middleware by @iMacTia in #1308(https://github.com/lostisland/faraday/pull/1308) -* Add Faraday 1.x examples in authentication.md docs by @iMacTia in #1320(https://github.com/lostisland/faraday/pull/1320) -* Fix passing a URL with embedded basic auth by @iMacTia in #1324(https://github.com/lostisland/faraday/pull/1324) -* Register JSON middleware by @mollerhoj in #1331(https://github.com/lostisland/faraday/pull/1331) -* Retry middleware should handle string exception class name consistently by @jrochkind in #1334(https://github.com/lostisland/faraday/pull/1334) -* Improve request info in exceptions raised by RaiseError Middleware by @willianzocolau in #1335(https://github.com/lostisland/faraday/pull/1335) -* Remove net-http adapter and update docs by @iMacTia in #1336(https://github.com/lostisland/faraday/pull/1336) -* Explain plan for faraday_middleware in UPGRADING.md by @iMacTia in #1339(https://github.com/lostisland/faraday/pull/1339) -* Scripts folder cleanup by @iMacTia in #1340(https://github.com/lostisland/faraday/pull/1340) -* Replace `Hash#merge` with `Utils#deep_merge` for connection options by @xkwd in #1343(https://github.com/lostisland/faraday/pull/1343) -* Callable authorizers by @sled in #1345(https://github.com/lostisland/faraday/pull/1345) -* Default value for exc error by @DariuszMusielak in #1351(https://github.com/lostisland/faraday/pull/1351) -* Don't call `retry_block` unless a retry is going to happen by @jrochkind in #1350(https://github.com/lostisland/faraday/pull/1350) -* Improve documentation for v2 by @iMacTia in #1353(https://github.com/lostisland/faraday/pull/1353) -* Remove default `default_adapter` (yes, you read that right) by @iMacTia in #1354(https://github.com/lostisland/faraday/pull/1354) -* Remove retry middleware by @iMacTia in #1356(https://github.com/lostisland/faraday/pull/1356) -* Remove multipart middleware and all its documentation and tests by @iMacTia in #1357(https://github.com/lostisland/faraday/pull/1357) - -## 1.9.3(https://github.com/lostisland/faraday/compare/v1.9.2...v1.9.3) (2022-01-06) - -* Re-add support for Ruby 2.4+ by @iMacTia in #1371(https://github.com/lostisland/faraday/pull/1371) - -## 1.9.2(https://github.com/lostisland/faraday/compare/v1.9.1...v1.9.2) (2022-01-06) - -* Add alias with legacy name to gemified middleware by @iMacTia in #1372(https://github.com/lostisland/faraday/pull/1372) - -## 1.9.1(https://github.com/lostisland/faraday/compare/v1.9.0...v1.9.1) (2022-01-06) - -* Update adapter dependencies in Gemspec by @iMacTia in #1370(https://github.com/lostisland/faraday/pull/1370) - -## 1.9.0(https://github.com/lostisland/faraday/compare/v1.8.0...v1.9.0) (2022-01-06) - -* Use external multipart and retry middleware by @iMacTia in #1367(https://github.com/lostisland/faraday/pull/1367) - -## 1.8.0(https://github.com/lostisland/faraday/releases/tag/v1.8.0) (2021-09-18) - -### Features - -* Backport authorization procs (#1322, @jarl-dk) - -## v1.7.0(https://github.com/lostisland/faraday/releases/tag/v1.7.0) (2021-08-09) - -### Features - -* Add strict_mode to Test::Stubs (#1298, @yykamei) - -## v1.6.0(https://github.com/lostisland/faraday/releases/tag/v1.6.0) (2021-08-01) - -### Misc - -* Use external Rack adapter (#1296, @iMacTia) - -## v1.5.1(https://github.com/lostisland/faraday/releases/tag/v1.5.1) (2021-07-11) - -### Fixes - -* Fix JRuby incompatibility after moving out EM adapters (#1294, @ahorek) - -### Documentation - -* Update YARD to follow RackBuilder (#1292, @kachick) - -## v1.5.0(https://github.com/lostisland/faraday/releases/tag/v1.5.0) (2021-07-04) - -### Misc - -* Use external httpclient adapter (#1289, @iMacTia) -* Use external patron adapter (#1290, @iMacTia) - -## v1.4.3(https://github.com/lostisland/faraday/releases/tag/v1.4.3) (2021-06-24) - -### Fixes - -* Silence warning (#1286, @gurgeous) -* Always dup url_prefix in Connection#build_exclusive_url (#1288, @alexeyds) - -## v1.4.2(https://github.com/lostisland/faraday/releases/tag/v1.4.2) (2021-05-22) - -### Fixes -* Add proxy setting when url_prefix is changed (#1276, @ci) -* Default proxy scheme to http:// if necessary, fixes #1282 (#1283, @gurgeous) - -### Documentation -* Improve introduction page (#1273, @gurgeous) -* Docs: add more middleware examples (#1277, @gurgeous) - -### Misc -* Use external `em_http` and `em_synchrony` adapters (#1274, @iMacTia) - -## v1.4.1(https://github.com/lostisland/faraday/releases/tag/v1.4.1) (2021-04-18) - -### Fixes - -* Fix dependencies from external adapter gems (#1269, @iMacTia) - -## v1.4.0(https://github.com/lostisland/faraday/releases/tag/v1.4.0) (2021-04-16) - -### Highlights - -With this release, we continue the work of gradually moving out adapters into their own gems π -Thanks to @MikeRogers0 for helping the Faraday team in progressing with this quest π - -And thanks to @olleolleolle efforts, Faraday is becoming more inclusive than ever π€ -Faraday's `master` branch has been renamed into `main`, we have an official policy on inclusive language and even a rubocop plugin to check for non-inclusive words β€οΈ! -Checkout the "Misc" section below for more details π ! - -### Fixes - -* Fix NoMethodError undefined method 'coverage' (#1255, @Maroo-b) - -### Documentation - -* Some docs on EventMachine adapters. (#1232, @damau) -* CONTRIBUTING: Fix grammar and layout (#1261, @olleolleolle) - -### Misc - -* Replacing Net::HTTP::Persistent with faraday-net_http_persistent (#1250, @MikeRogers0) -* CI: Configure the regenerated Coveralls token (#1256, @olleolleolle) -* Replace Excon adapter with Faraday::Excon gem, and fix autoloading issue with Faraday::NetHttpPersistent (#1257, @iMacTia) -* Drop CodeClimate (#1259, @olleolleolle) -* CI: Rename default branch to main (#1263, @olleolleolle) -* Drop RDoc support file .document (#1264, @olleolleolle, @iMacTia) -* CONTRIBUTING: add a policy on inclusive language (#1262, @olleolleolle) -* Add rubocop-inclusivity (#1267, @olleolleolle, @iMacTia) - -## v1.3.1(https://github.com/lostisland/faraday/releases/tag/v1.3.1) (2021-04-16) - -### Fixes - -* Escape colon in path segment (#1237, @yarafan) -* Handle IPv6 address String on Faraday::Connection#proxy_from_env (#1252, @cosmo0920) - -### Documentation - -* Fix broken Rubydoc.info links (#1236, @nickcampbell18) -* Add httpx to list of external adapters (#1246, @HoneyryderChuck) - -### Misc - -* Refactor CI to remove duplicated line (#1230, @tricknotes) -* Gemspec: Pick a good ruby2_keywords release (#1241, @olleolleolle) - -## v1.3.0(https://github.com/lostisland/faraday/releases/tag/v1.3.0) (2020-12-31) - -### Highlights -Faraday v1.3.0 is the first release to officially support Ruby 3.0 in the CI pipeline π πΎ! - -This is also the first release with a previously "included" adapter (Net::HTTP) being isolated into a separate gem(https://github.com/lostisland/faraday-net_http) π! -The new adapter is added to Faraday as a dependency for now, so that means full backwards-compatibility, but just to be safe be careful when upgrading! - -This is a huge step towards are Faraday v2.0 objective of pushing adapters and middleware into separate gems. -Many thanks to the Faraday Team, @JanDintel and everyone who attended the ROSS Conf remote event(https://www.rossconf.io/event/remote/)
View file
faraday-2.7.11.gem/data/LICENSE.md -> faraday-1.0.0.gem/data/LICENSE.md
Changed
@@ -1,4 +1,4 @@ -Copyright (c) 2009-2023 Rick Olson, Zack Hobson +Copyright (c) 2009-2019 Rick Olson, Zack Hobson Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the
View file
faraday-2.7.11.gem/data/README.md -> faraday-1.0.0.gem/data/README.md
Changed
@@ -1,41 +1,27 @@ -# !Faraday(./docs/_media/home-logo.svg)website +# !Faraday(./docs/assets/img/repo-card-slim.png) !Gem Version(https://badge.fury.io/rb/faraday.svg)(https://rubygems.org/gems/faraday) -!GitHub Actions CI(https://github.com/lostisland/faraday/workflows/CI/badge.svg)(https://github.com/lostisland/faraday/actions?query=workflow%3ACI) -!GitHub Discussions(https://img.shields.io/github/discussions/lostisland/faraday?logo=github)(https://github.com/lostisland/faraday/discussions) +!GitHub Actions CI(https://github.com/lostisland/faraday/workflows/CI/badge.svg) +!Test Coverage(https://api.codeclimate.com/v1/badges/f869daab091ceef1da73/test_coverage)(https://codeclimate.com/github/lostisland/faraday/test_coverage) +!Maintainability(https://api.codeclimate.com/v1/badges/f869daab091ceef1da73/maintainability)(https://codeclimate.com/github/lostisland/faraday/maintainability) +!Gitter(https://badges.gitter.im/lostisland/faraday.svg)(https://gitter.im/lostisland/faraday?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge) -Faraday is an HTTP client library abstraction layer that provides a common interface over many -adapters (such as Net::HTTP) and embraces the concept of Rack middleware when processing the request/response cycle. -Take a look at Awesome Faradayawesome for a list of available adapters and middleware. -## Why use Faraday? - -Faraday gives you the power of Rack middleware for manipulating HTTP requests and responses, -making it easier to build sophisticated API clients or web service libraries that abstract away -the details of how HTTP requests are made. - -Faraday comes with a lot of features out of the box, such as: -* Support for multiple adapters (Net::HTTP, Typhoeus, Patron, Excon, HTTPClient, and more) -* Persistent connections (keep-alive) -* Parallel requests -* Automatic response parsing (JSON, XML, YAML) -* Customization of the request/response cycle with middleware -* Support for streaming responses -* Support for uploading files -* And much more! +Faraday is an HTTP client library that provides a common interface over many +adapters (such as Net::HTTP) and embraces the concept of Rack middleware when +processing the request/response cycle. ## Getting Started The best starting point is the Faraday Websitewebsite, with its introduction and explanation. - -Need more details? See the Faraday API Documentationapidoc to see how it works internally, or take a look at Advanced techniques for calling HTTP APIs in Ruby(https://mattbrictson.com/blog/advanced-http-techniques-in-ruby) blog post from @mattbrictson(https://github.com/mattbrictson) π +Need more details? See the Faraday API Documentationapidoc to see how it works internally. ## Supported Ruby versions -This library aims to support and is tested againstactions the currently officially supported Ruby -implementations. This means that, even without a major release, we could add or drop support for Ruby versions, -following their EOL(https://endoflife.date/ruby). -Currently that means we support Ruby 2.6+ +This library aims to support and is tested againstactions the following Ruby +implementations: + +* Ruby 2.4+ If something doesn't work on one of these Ruby versions, it's a bug. @@ -57,11 +43,13 @@ But before you start coding, please read our Contributing Guidecontributing ## Copyright - -© 2009 - 2023, the Faraday Team. Website and branding design by Elena Lo Piccolo(https://elelopic.design). - -awesome: https://github.com/lostisland/awesome-faraday/#adapters -website: https://lostisland.github.io/faraday -contributing: https://github.com/lostisland/faraday/blob/main/.github/CONTRIBUTING.md -apidoc: https://www.rubydoc.info/github/lostisland/faraday -actions: https://github.com/lostisland/faraday/actions +© 2009 - 2019, the Faraday Teamfaraday_team. Website and branding design by Elena Lo Piccolo(https://elelopic.design). + +website: https://lostisland.github.io/faraday +faraday_team: https://lostisland.github.io/faraday/team +contributing: https://github.com/lostisland/faraday/blob/master/.github/CONTRIBUTING.md +apidoc: http://www.rubydoc.info/gems/faraday +actions: https://github.com/lostisland/faraday/actions +jruby: http://jruby.org/ +rubinius: http://rubini.us/ +license: LICENSE.md
View file
faraday-2.7.11.gem/data/Rakefile -> faraday-1.0.0.gem/data/Rakefile
Changed
@@ -2,8 +2,6 @@ require 'rspec/core/rake_task' -RSpec::Core::RakeTask.new(:spec) do |task| - task.ruby_opts = %w-W -end +RSpec::Core::RakeTask.new(:spec) task default: :spec
View file
faraday-1.0.0.gem/data/UPGRADING.md
Added
@@ -0,0 +1,55 @@ +## Faraday 1.0 + +### Errors +* Removes sub-class constants definition from `Faraday::Error`. A sub-class (e.g. `ClientError`) was previously accessible +either through the `Faraday` module (e.g. `Faraday::ClientError`) or through the `Faraday::Error` class (e.g. `Faraday::Error::ClientError`). +The latter is no longer available and the former should be used instead, so check your `rescue`s. +* Introduces a new `Faraday::ServerError` (5xx status codes) alongside the existing `Faraday::ClientError` (4xx status codes). +Please note `Faraday::ClientError` was previously used for both. +* Introduces new Errors that describe the most common REST status codes: + * Faraday::BadRequestError (400) + * Faraday::UnauthorizedError (401) + * Faraday::ForbiddenError (403) + * Faraday::ProxyAuthError (407). Please note this raised a `Faraday::ConnectionFailed` before. + * Faraday::ConflictError (409) + * Faraday::UnprocessableEntityError (422) +* The following error classes have changed the hierarchy to better mirror their real-world usage and semantic meaning: + * TimeoutError < ServerError (was < ClientError) + * ConnectionFailed < Error (was < ClientError) + * SSLError < Error (was < ClientError) + * ParsingError < Error (was < ClientError) + * RetriableResponse < Error (was < ClientError) + +### Custom adapters +If you have written a custom adapter, please be aware that `env.body` is now an alias to the two new properties `request_body` and `response_body`. +This should work without you noticing if your adapter inherits from `Faraday::Adapter` and calls `save_response`, but if it doesn't, then please ensure you set the `status` BEFORE the `body` while processing the response. + +### Others +* Dropped support for jruby and Rubinius. +* Officially supports Ruby 2.4+ +* In order to specify the adapter you now MUST use the `#adapter` method on the connection builder. If you don't do so and your adapter inherits from `Faraday::Adapter` then Faraday will raise an exception. Otherwise, Faraday will automatically push the default adapter at the end of the stack causing your request to be executed twice. +```ruby +class OfficialAdapter < Faraday::Adapter + ... +end + +class MyAdapter + ... +end + +# This will raise an exception +conn = Faraday.new(...) do |f| + f.use OfficialAdapter +end + +# This will cause Faraday inserting the default adapter at the end of the stack +conn = Faraday.new(...) do |f| + f.use MyAdapter +end + +# You MUST use `adapter` method +conn = Faraday.new(...) do |f| + f.adapter AnyAdapter +end +``` +
View file
faraday-2.7.11.gem/data/examples/client_spec.rb -> faraday-1.0.0.gem/data/examples/client_spec.rb
Changed
@@ -12,108 +12,54 @@ @conn = conn end - def httpbingo(jname, params: {}) - res = @conn.get("/#{jname}", params) + def sushi(jname) + res = @conn.get("/#{jname}") data = JSON.parse(res.body) - data'origin' - end - - def foo(params) - res = @conn.post('/foo', JSON.dump(params)) - res.status + data'name' end end -RSpec.describe Client do +Rspec.describe Client do let(:stubs) { Faraday::Adapter::Test::Stubs.new } let(:conn) { Faraday.new { |b| b.adapter(:test, stubs) } } let(:client) { Client.new(conn) } - it 'parses origin' do - stubs.get('/ip') do |env| + it 'parses name' do + stubs.get('/ebi') do |env| # optional: you can inspect the Faraday::Env - expect(env.url.path).to eq('/ip') + expect(env.url.path).to eq('/ebi') 200, { 'Content-Type': 'application/javascript' }, - '{"origin": "127.0.0.1"}' + '{"name": "shrimp"}' end # uncomment to trigger stubs.verify_stubbed_calls failure # stubs.get('/unused') { 404, {}, '' } - expect(client.httpbingo('ip')).to eq('127.0.0.1') + expect(client.sushi('ebi')).to eq('shrimp') stubs.verify_stubbed_calls end it 'handles 404' do - stubs.get('/api') do + stubs.get('/ebi') do 404, { 'Content-Type': 'application/javascript' }, '{}' end - expect(client.httpbingo('api')).to be_nil + expect(client.sushi('ebi')).to be_nil stubs.verify_stubbed_calls end it 'handles exception' do - stubs.get('/api') do - raise Faraday::ConnectionFailed + stubs.get('/ebi') do + raise Faraday::ConnectionFailed, nil end - expect { client.httpbingo('api') }.to raise_error(Faraday::ConnectionFailed) + expect { client.sushi('ebi') }.to raise_error(Faraday::ConnectionFailed) stubs.verify_stubbed_calls end - - context 'When the test stub is run in strict_mode' do - let(:stubs) { Faraday::Adapter::Test::Stubs.new(strict_mode: true) } - - it 'verifies the all parameter values are identical' do - stubs.get('/api?abc=123') do - - 200, - { 'Content-Type': 'application/javascript' }, - '{"origin": "127.0.0.1"}' - - end - - # uncomment to raise Stubs::NotFound - # expect(client.httpbingo('api', params: { abc: 123, foo: 'Kappa' })).to eq('127.0.0.1') - expect(client.httpbingo('api', params: { abc: 123 })).to eq('127.0.0.1') - stubs.verify_stubbed_calls - end - end - - context 'When the Faraday connection is configured with FlatParamsEncoder' do - let(:conn) { Faraday.new(request: { params_encoder: Faraday::FlatParamsEncoder }) { |b| b.adapter(:test, stubs) } } - - it 'handles the same multiple URL parameters' do - stubs.get('/api?a=x&a=y&a=z') { 200, { 'Content-Type' => 'application/json' }, '{"origin": "127.0.0.1"}' } - - # uncomment to raise Stubs::NotFound - # expect(client.httpbingo('api', params: { a: %wx y })).to eq('127.0.0.1') - expect(client.httpbingo('api', params: { a: %wx y z })).to eq('127.0.0.1') - stubs.verify_stubbed_calls - end - end - - context 'When you want to test the body, you can use a proc as well as string' do - it 'tests with a string' do - stubs.post('/foo', '{"name":"YK"}') { 200, {}, '' } - - expect(client.foo(name: 'YK')).to eq 200 - stubs.verify_stubbed_calls - end - - it 'tests with a proc' do - check = ->(request_body) { JSON.parse(request_body).slice('name') == { 'name' => 'YK' } } - stubs.post('/foo', check) { 200, {}, '' } - - expect(client.foo(name: 'YK', created_at: Time.now)).to eq 200 - stubs.verify_stubbed_calls - end - end end
View file
faraday-2.7.11.gem/data/examples/client_test.rb -> faraday-1.0.0.gem/data/examples/client_test.rb
Changed
@@ -13,29 +13,24 @@ @conn = conn end - def httpbingo(jname, params: {}) - res = @conn.get("/#{jname}", params) + def sushi(jname) + res = @conn.get("/#{jname}") data = JSON.parse(res.body) - data'origin' - end - - def foo(params) - res = @conn.post('/foo', JSON.dump(params)) - res.status + data'name' end end # Example API client test class ClientTest < Test::Unit::TestCase - def test_httpbingo_name + def test_sushi_name stubs = Faraday::Adapter::Test::Stubs.new - stubs.get('/api') do |env| + stubs.get('/ebi') do |env| # optional: you can inspect the Faraday::Env - assert_equal '/api', env.url.path + assert_equal '/ebi', env.url.path 200, { 'Content-Type': 'application/javascript' }, - '{"origin": "127.0.0.1"}' + '{"name": "shrimp"}' end @@ -43,13 +38,13 @@ # stubs.get('/unused') { 404, {}, '' } cli = client(stubs) - assert_equal '127.0.0.1', cli.httpbingo('api') + assert_equal 'shrimp', cli.sushi('ebi') stubs.verify_stubbed_calls end - def test_httpbingo_not_found + def test_sushi_404 stubs = Faraday::Adapter::Test::Stubs.new - stubs.get('/api') do + stubs.get('/ebi') do 404, { 'Content-Type': 'application/javascript' }, @@ -58,80 +53,20 @@ end cli = client(stubs) - assert_nil cli.httpbingo('api') + assert_nil cli.sushi('ebi') stubs.verify_stubbed_calls end - def test_httpbingo_exception + def test_sushi_exception stubs = Faraday::Adapter::Test::Stubs.new - stubs.get('/api') do - raise Faraday::ConnectionFailed + stubs.get('/ebi') do + raise Faraday::ConnectionFailed, nil end cli = client(stubs) assert_raise Faraday::ConnectionFailed do - cli.httpbingo('api') - end - stubs.verify_stubbed_calls - end - - def test_strict_mode - stubs = Faraday::Adapter::Test::Stubs.new(strict_mode: true) - stubs.get('/api?abc=123') do - - 200, - { 'Content-Type': 'application/javascript' }, - '{"origin": "127.0.0.1"}' - + cli.sushi('ebi') end - - cli = client(stubs) - assert_equal '127.0.0.1', cli.httpbingo('api', params: { abc: 123 }) - - # uncomment to raise Stubs::NotFound - # assert_equal '127.0.0.1', cli.httpbingo('api', params: { abc: 123, foo: 'Kappa' }) - stubs.verify_stubbed_calls - end - - def test_non_default_params_encoder - stubs = Faraday::Adapter::Test::Stubs.new(strict_mode: true) - stubs.get('/api?a=x&a=y&a=z') do - - 200, - { 'Content-Type': 'application/javascript' }, - '{"origin": "127.0.0.1"}' - - end - conn = Faraday.new(request: { params_encoder: Faraday::FlatParamsEncoder }) do |builder| - builder.adapter :test, stubs - end - - cli = Client.new(conn) - assert_equal '127.0.0.1', cli.httpbingo('api', params: { a: %wx y z }) - - # uncomment to raise Stubs::NotFound - # assert_equal '127.0.0.1', cli.httpbingo('api', params: { a: %wx y }) - stubs.verify_stubbed_calls - end - - def test_with_string_body - stubs = Faraday::Adapter::Test::Stubs.new do |stub| - stub.post('/foo', '{"name":"YK"}') { 200, {}, '' } - end - cli = client(stubs) - assert_equal 200, cli.foo(name: 'YK') - - stubs.verify_stubbed_calls - end - - def test_with_proc_body - stubs = Faraday::Adapter::Test::Stubs.new do |stub| - check = ->(request_body) { JSON.parse(request_body).slice('name') == { 'name' => 'YK' } } - stub.post('/foo', check) { 200, {}, '' } - end - cli = client(stubs) - assert_equal 200, cli.foo(name: 'YK', created_at: Time.now) - stubs.verify_stubbed_calls end
View file
faraday-2.7.11.gem/data/lib/faraday.rb -> faraday-1.0.0.gem/data/lib/faraday.rb
Changed
@@ -1,23 +1,11 @@ # frozen_string_literal: true require 'cgi' -require 'date' require 'set' require 'forwardable' -require 'faraday/version' -require 'faraday/methods' -require 'faraday/error' require 'faraday/middleware_registry' -require 'faraday/utils' -require 'faraday/options' -require 'faraday/connection' -require 'faraday/rack_builder' -require 'faraday/parameters' -require 'faraday/middleware' -require 'faraday/adapter' -require 'faraday/request' -require 'faraday/response' -require 'faraday/net_http' +require 'faraday/dependency_loader' + # This is the main namespace for Faraday. # # It provides methods to create {Connection} objects, and HTTP-related @@ -31,7 +19,9 @@ # conn.get '/' # module Faraday - CONTENT_TYPE = 'Content-Type' + VERSION = '1.0.0' + METHODS_WITH_QUERY = %wget head delete trace.freeze + METHODS_WITH_BODY = %wpost put patch.freeze class << self # The root path that Faraday is being loaded from. @@ -54,10 +44,6 @@ # @return Symbol the new default_adapter. attr_reader :default_adapter - # Option for the default_adapter - # @return Hash default_adapter options - attr_accessor :default_adapter_options - # Documented below, see default_connection attr_writer :default_connection @@ -94,10 +80,23 @@ # params: { page: 1 } # # => Faraday::Connection to http://faraday.com?page=1 def new(url = nil, options = {}, &block) - options = Utils.deep_merge(default_connection_options, options) + options = default_connection_options.merge(options) Faraday::Connection.new(url, options, &block) end + # @private + # Internal: Requires internal Faraday libraries. + # + # @param libs Array one or more relative String names to Faraday classes. + # @return void + def require_libs(*libs) + libs.each do |lib| + require "#{lib_path}/#{lib}" + end + end + + alias require_lib require_libs + # Documented elsewhere, see default_adapter reader def default_adapter=(adapter) @default_connection = nil @@ -108,34 +107,6 @@ default_connection.respond_to?(symbol, include_private) || super end - # @overload default_connection - # Gets the default connection used for simple scripts. - # @return Faraday::Connection a connection configured with - # the default_adapter. - # @overload default_connection=(connection) - # @param connection Faraday::Connection - # Sets the default {Faraday::Connection} for simple scripts that - # access the Faraday constant directly, such as - # <code>Faraday.get "https://faraday.com"</code>. - def default_connection - @default_connection ||= Connection.new(default_connection_options) - end - - # Gets the default connection options used when calling {Faraday#new}. - # - # @return Faraday::ConnectionOptions - def default_connection_options - @default_connection_options ||= ConnectionOptions.new - end - - # Sets the default options used when calling {Faraday#new}. - # - # @param options Hash, Faraday::ConnectionOptions - def default_connection_options=(options) - @default_connection = nil - @default_connection_options = ConnectionOptions.from(options) - end - private # Internal: Proxies method calls on the Faraday constant to @@ -153,5 +124,43 @@ self.root_path = File.expand_path __dir__ self.lib_path = File.expand_path 'faraday', __dir__ self.default_adapter = :net_http - self.default_adapter_options = {} + + # @overload default_connection + # Gets the default connection used for simple scripts. + # @return Faraday::Connection a connection configured with + # the default_adapter. + # @overload default_connection=(connection) + # @param connection Faraday::Connection + # Sets the default {Faraday::Connection} for simple scripts that + # access the Faraday constant directly, such as + # <code>Faraday.get "https://faraday.com"</code>. + def self.default_connection + @default_connection ||= Connection.new(default_connection_options) + end + + # Gets the default connection options used when calling {Faraday#new}. + # + # @return Faraday::ConnectionOptions + def self.default_connection_options + @default_connection_options ||= ConnectionOptions.new + end + + # Sets the default options used when calling {Faraday#new}. + # + # @param options Hash, Faraday::ConnectionOptions + def self.default_connection_options=(options) + @default_connection = nil + @default_connection_options = ConnectionOptions.from(options) + end + + unless const_defined? :Timer + require 'timeout' + Timer = Timeout + end + + require_libs 'utils', 'options', 'connection', 'rack_builder', 'parameters', + 'middleware', 'adapter', 'request', 'response', 'error', + 'file_part', 'param_part' + + require_lib 'autoload' unless ENV'FARADAY_NO_AUTOLOAD' end
View file
faraday-2.7.11.gem/data/lib/faraday/adapter.rb -> faraday-1.0.0.gem/data/lib/faraday/adapter.rb
Changed
@@ -5,13 +5,28 @@ # responsible for fulfilling a Faraday request. class Adapter extend MiddlewareRegistry + extend DependencyLoader CONTENT_LENGTH = 'Content-Length' + register_middleware File.expand_path('adapter', __dir__), + test: :Test, 'test', + net_http: :NetHttp, 'net_http', + net_http_persistent: + :NetHttpPersistent, + 'net_http_persistent' + , + typhoeus: :Typhoeus, 'typhoeus', + patron: :Patron, 'patron', + em_synchrony: :EMSynchrony, 'em_synchrony', + em_http: :EMHttp, 'em_http', + excon: :Excon, 'excon', + rack: :Rack, 'rack', + httpclient: :HTTPClient, 'httpclient' + # This module marks an Adapter as supporting parallel requests. module Parallelism attr_writer :supports_parallel - def supports_parallel? @supports_parallel end @@ -59,7 +74,7 @@ private - def save_response(env, status, body, headers = nil, reason_phrase = nil, finished: true) + def save_response(env, status, body, headers = nil, reason_phrase = nil) env.status = status env.body = body env.reason_phrase = reason_phrase&.to_s&.strip @@ -68,7 +83,7 @@ yield(response_headers) if block_given? end - env.response.finish(env) unless env.parallel? || !finished + env.response.finish(env) unless env.parallel? env.response end @@ -78,7 +93,8 @@ # @param type Symbol Describes which timeout setting to get: :read, # :write, or :open. # @param options Hash Hash containing Symbol keys like :timeout, - # :read_timeout, :write_timeout, or :open_timeout + # :read_timeout, :write_timeout, :open_timeout, or + # :timeout # # @return Integer, nil Timeout duration in seconds, or nil if no timeout # has been set. @@ -97,5 +113,3 @@ }.freeze end end - -require 'faraday/adapter/test'
View file
faraday-1.0.0.gem/data/lib/faraday/adapter/em_http.rb
Added
@@ -0,0 +1,285 @@ +# frozen_string_literal: true + +module Faraday + class Adapter + # EventMachine adapter. This adapter is useful for either asynchronous + # requests when in an EM reactor loop, or for making parallel requests in + # synchronous code. + class EMHttp < Faraday::Adapter + # Options is a module containing helpers to convert the Faraday env object + # into options hashes for EMHTTP method calls. + module Options + # @return Hash + def connection_config(env) + options = {} + configure_proxy(options, env) + configure_timeout(options, env) + configure_socket(options, env) + configure_ssl(options, env) + options + end + + def request_config(env) + options = { + body: read_body(env), + head: env:request_headers + # keepalive: true, + # file: 'path/to/file', # stream data off disk + } + configure_compression(options, env) + options + end + + def read_body(env) + body = env:body + body.respond_to?(:read) ? body.read : body + end + + # Reads out proxy settings from env into options + def configure_proxy(options, env) + proxy = request_options(env):proxy + return unless proxy + + options:proxy = { + host: proxy:uri.host, + port: proxy:uri.port, + authorization: proxy:user, proxy:password + } + end + + # Reads out host and port settings from env into options + def configure_socket(options, env) + bind = request_options(env):bind + return unless bind + + options:bind = { + host: bind:host, + port: bind:port + } + end + + # Reads out SSL certificate settings from env into options + def configure_ssl(options, env) + return unless env:url.scheme == 'https' && env:ssl + + options:ssl = { + cert_chain_file: env:ssl:ca_file, + verify_peer: env:ssl.fetch(:verify, true) + } + end + + # Reads out timeout settings from env into options + def configure_timeout(options, env) + req = request_options(env) + options:inactivity_timeout = request_timeout(:read, req) + options:connect_timeout = request_timeout(:open, req) + end + + # Reads out compression header settings from env into options + def configure_compression(options, env) + return unless (env:method == :get) && + !options:head.key?('accept-encoding') + + options:head'accept-encoding' = 'gzip, compressed' + end + + def request_options(env) + env:request + end + end + + include Options + + dependency 'em-http' + + self.supports_parallel = true + + # @return Manager + def self.setup_parallel_manager(_options = nil) + Manager.new + end + + def call(env) + super + perform_request env + @app.call env + end + + def perform_request(env) + if parallel?(env) + manager = env:parallel_manager + manager.add do + perform_single_request(env) + .callback { env:response.finish(env) } + end + elsif EventMachine.reactor_running? + # EM is running: instruct upstream that this is an async request + env:parallel_manager = true + perform_single_request(env) + .callback { env:response.finish(env) } + .errback do + # TODO: no way to communicate the error in async mode + raise NotImplementedError + end + else + error = nil + # start EM, block until request is completed + EventMachine.run do + perform_single_request(env) + .callback { EventMachine.stop } + .errback do |client| + error = error_message(client) + EventMachine.stop + end + end + raise_error(error) if error + end + rescue EventMachine::Connectify::CONNECTError => e + if e.message.include?('Proxy Authentication Required') + raise Faraday::ConnectionFailed, + %(407 "Proxy Authentication Required ") + end + + raise Faraday::ConnectionFailed, e + rescue StandardError => e + if defined?(OpenSSL) && e.is_a?(OpenSSL::SSL::SSLError) + raise Faraday::SSLError, e + end + + raise + end + + # TODO: reuse the connection to support pipelining + def perform_single_request(env) + req = create_request(env) + req = req.setup_request(env:method, request_config(env)) + req.callback do |client| + if env:request.stream_response? + warn "Streaming downloads for #{self.class.name} " \ + 'are not yet implemented.' + env:request.on_data.call( + client.response, + client.response.bytesize + ) + end + status = client.response_header.status + reason = client.response_header.http_reason + save_response(env, status, client.response, nil, reason) do |headers| + client.response_header.each do |name, value| + headersname.to_sym = value + end + end + end + end + + def create_request(env) + EventMachine::HttpRequest.new( + env:url, connection_config(env).merge(@connection_options) + ) + end + + def error_message(client) + client.error || 'request failed' + end + + def raise_error(msg) + error_class = Faraday::ClientError + if timeout_message?(msg) + error_class = Faraday::TimeoutError + msg = 'request timed out' + elsif msg == Errno::ECONNREFUSED + error_class = Faraday::ConnectionFailed + msg = 'connection refused' + elsif msg == 'connection closed by server' + error_class = Faraday::ConnectionFailed + end + raise error_class, msg + end + + def timeout_message?(msg)
View file
faraday-1.0.0.gem/data/lib/faraday/adapter/em_http_ssl_patch.rb
Added
@@ -0,0 +1,62 @@ +# frozen_string_literal: true + +require 'openssl' +require 'em-http' + +# EventMachine patch to make SSL work. +module EmHttpSslPatch + def ssl_verify_peer(cert_string) + begin + @last_seen_cert = OpenSSL::X509::Certificate.new(cert_string) + rescue OpenSSL::X509::CertificateError + return false + end + + unless certificate_store.verify(@last_seen_cert) + raise OpenSSL::SSL::SSLError, + %(unable to verify the server certificate for "#{host}") + end + + begin + certificate_store.add_cert(@last_seen_cert) + rescue OpenSSL::X509::StoreError => e + raise e unless e.message == 'cert already in hash table' + end + true + end + + def ssl_handshake_completed + return true unless verify_peer? + + unless verified_cert_identity? + raise OpenSSL::SSL::SSLError, + %(host "#{host}" does not match the server certificate) + end + + true + end + + def verify_peer? + parent.connopts.tls:verify_peer + end + + def verified_cert_identity? + OpenSSL::SSL.verify_certificate_identity(@last_seen_cert, host) + end + + def host + parent.uri.host + end + + def certificate_store + @certificate_store ||= begin + store = OpenSSL::X509::Store.new + store.set_default_paths + ca_file = parent.connopts.tls:cert_chain_file + store.add_file(ca_file) if ca_file + store + end + end +end + +EventMachine::HttpStubConnection.include(EmHttpSslPatch)
View file
faraday-1.0.0.gem/data/lib/faraday/adapter/em_synchrony.rb
Added
@@ -0,0 +1,150 @@ +# frozen_string_literal: true + +require 'uri' + +module Faraday + class Adapter + # EventMachine Synchrony adapter. + class EMSynchrony < Faraday::Adapter + include EMHttp::Options + + dependency do + require 'em-synchrony/em-http' + require 'em-synchrony/em-multi' + require 'fiber' + end + + self.supports_parallel = true + + # @return ParallelManager + def self.setup_parallel_manager(_options = nil) + ParallelManager.new + end + + def call(env) + super + request = create_request(env) + + http_method = env:method.to_s.downcase.to_sym + + if env:parallel_manager + # Queue requests for parallel execution. + execute_parallel_request(env, request, http_method) + else + # Execute single request. + execute_single_request(env, request, http_method) + end + + @app.call env + rescue Errno::ECONNREFUSED + raise Faraday::ConnectionFailed, $ERROR_INFO + rescue EventMachine::Connectify::CONNECTError => e + if e.message.include?('Proxy Authentication Required') + raise Faraday::ConnectionFailed, + %(407 "Proxy Authentication Required") + end + + raise Faraday::ConnectionFailed, e + rescue Errno::ETIMEDOUT => e + raise Faraday::TimeoutError, e + rescue RuntimeError => e + if e.message == 'connection closed by server' + raise Faraday::ConnectionFailed, e + end + + raise Faraday::TimeoutError, e if e.message.include?('timeout error') + + raise + rescue StandardError => e + if defined?(OpenSSL) && e.is_a?(OpenSSL::SSL::SSLError) + raise Faraday::SSLError, e + end + + raise + end + + def create_request(env) + EventMachine::HttpRequest.new( + Utils::URI(env:url.to_s), + connection_config(env).merge(@connection_options) + ) + end + + private + + def execute_parallel_request(env, request, http_method) + env:parallel_manager.add(request, http_method, + request_config(env)) do |resp| + if (req = env:request).stream_response? + warn "Streaming downloads for #{self.class.name} " \ + 'are not yet implemented.' + req.on_data.call(resp.response, resp.response.bytesize) + end + + save_response(env, resp.response_header.status, + resp.response) do |resp_headers| + resp.response_header.each do |name, value| + resp_headersname.to_sym = value + end + end + + # Finalize the response object with values from `env`. + env:response.finish(env) + end + end + + def execute_single_request(env, request, http_method) + block = -> { request.send(http_method, request_config(env)) } + client = call_block(block) + + raise client.error if client&.error + + if env:request.stream_response? + warn "Streaming downloads for #{self.class.name} " \ + 'are not yet implemented.' + env:request.on_data.call( + client.response, + client.response.bytesize + ) + end + status = client.response_header.status + reason = client.response_header.http_reason + save_response(env, status, client.response, nil, reason) do |headers| + client.response_header.each do |name, value| + headersname.to_sym = value + end + end + end + + def call_block(block) + client = nil + + if EM.reactor_running? + client = block.call + else + EM.run do + Fiber.new do + client = block.call + EM.stop + end.resume + end + end + + client + end + end + end +end + +require 'faraday/adapter/em_synchrony/parallel_manager' + +if Faraday::Adapter::EMSynchrony.loaded? + begin + require 'openssl' + rescue LoadError + warn 'Warning: no such file to load -- openssl. ' \ + 'Make sure it is installed if you want HTTPS support' + else + require 'faraday/adapter/em_http_ssl_patch' + end +end
View file
faraday-1.0.0.gem/data/lib/faraday/adapter/em_synchrony/parallel_manager.rb
Added
@@ -0,0 +1,69 @@ +# frozen_string_literal: true + +module Faraday + class Adapter + class EMSynchrony < Faraday::Adapter + # A parallel manager for EMSynchrony. + class ParallelManager + # Add requests to queue. + # + # @param request EM::HttpRequest + # @param method Symbol, String HTTP method + # @param args Array the rest of the positional arguments + def add(request, method, *args, &block) + queue << { + request: request, + method: method, + args: args, + block: block + } + end + + # Run all requests on queue with `EM::Synchrony::Multi`, wrapping + # it in a reactor and fiber if needed. + def run + result = nil + if !EM.reactor_running? + EM.run do + Fiber.new do + result = perform + EM.stop + end.resume + end + else + result = perform + end + result + end + + private + + # The request queue. + def queue + @queue ||= + end + + # Main `EM::Synchrony::Multi` performer. + def perform + multi = ::EM::Synchrony::Multi.new + + queue.each do |item| + method = "a#{item:method}".to_sym + + req = item:request.send(method, *item:args) + req.callback(&item:block) + + req_name = "req_#{multi.requests.size}".to_sym + multi.add(req_name, req) + end + + # Clear the queue, so parallel manager objects can be reused. + @queue = + + # Block fiber until all requests have returned. + multi.perform + end + end + end + end +end
View file
faraday-1.0.0.gem/data/lib/faraday/adapter/excon.rb
Added
@@ -0,0 +1,124 @@ +# frozen_string_literal: true + +module Faraday + class Adapter + # Excon adapter. + class Excon < Faraday::Adapter + dependency 'excon' + + def build_connection(env) + opts = opts_from_env(env) + ::Excon.new(env:url.to_s, opts.merge(@connection_options)) + end + + def call(env) + super + + req_opts = { + method: env:method.to_s.upcase, + headers: env:request_headers, + body: read_body(env) + } + + req = env:request + if req&.stream_response? + total = 0 + req_opts:response_block = lambda do |chunk, _remain, _total| + req.on_data.call(chunk, total += chunk.size) + end + end + + resp = connection(env) { |http| http.request(req_opts) } + save_response(env, resp.status.to_i, resp.body, resp.headers, + resp.reason_phrase) + + @app.call(env) + rescue ::Excon::Errors::SocketError => e + raise Faraday::TimeoutError, e if e.message =~ /\btimeout\b/ + + raise Faraday::SSLError, e if e.message =~ /\bcertificate\b/ + + raise Faraday::ConnectionFailed, e + rescue ::Excon::Errors::Timeout => e + raise Faraday::TimeoutError, e + end + + # TODO: support streaming requests + def read_body(env) + env:body.respond_to?(:read) ? env:body.read : env:body + end + + private + + def opts_from_env(env) + opts = {} + amend_opts_with_ssl!(opts, env:ssl) if needs_ssl_settings?(env) + + if (req = env:request) + amend_opts_with_timeouts!(opts, req) + amend_opts_with_proxy_settings!(opts, req) + end + + opts + end + + def needs_ssl_settings?(env) + env:url.scheme == 'https' && env:ssl + end + + OPTS_KEYS = + %iclient_cert client_cert, + %iclient_key client_key, + %icertificate certificate, + %iprivate_key private_key, + %issl_ca_path ca_path, + %issl_ca_file ca_file, + %issl_version version, + %issl_min_version min_version, + %issl_max_version max_version + .freeze + + def amend_opts_with_ssl!(opts, ssl) + opts:ssl_verify_peer = !!ssl.fetch(:verify, true) + # https://github.com/geemus/excon/issues/106 + # https://github.com/jruby/jruby-ossl/issues/19 + opts:nonblock = false + + OPTS_KEYS.each do |(key_in_opts, key_in_ssl)| + next unless sslkey_in_ssl + + optskey_in_opts = sslkey_in_ssl + end + end + + def amend_opts_with_timeouts!(opts, req) + if (sec = request_timeout(:read, req)) + opts:read_timeout = sec + end + + if (sec = request_timeout(:write, req)) + opts:write_timeout = sec + end + + return unless (sec = request_timeout(:open, req)) + + opts:connect_timeout = sec + end + + def amend_opts_with_proxy_settings!(opts, req) + opts:proxy = proxy_settings_for_opts(req:proxy) if req:proxy + end + + def proxy_settings_for_opts(proxy) + { + host: proxy:uri.host, + hostname: proxy:uri.hostname, + port: proxy:uri.port, + scheme: proxy:uri.scheme, + user: proxy:user, + password: proxy:password + } + end + end + end +end
View file
faraday-1.0.0.gem/data/lib/faraday/adapter/httpclient.rb
Added
@@ -0,0 +1,151 @@ +# frozen_string_literal: true + +module Faraday + class Adapter + # HTTPClient adapter. + class HTTPClient < Faraday::Adapter + dependency 'httpclient' + + def build_connection(env) + @client ||= ::HTTPClient.new.tap do |cli| + # enable compression + cli.transparent_gzip_decompression = true + end + + if (req = env:request) + if (proxy = req:proxy) + configure_proxy @client, proxy + end + + if (bind = req:bind) + configure_socket @client, bind + end + + configure_timeouts @client, req + end + + if env:url.scheme == 'https' && (ssl = env:ssl) + configure_ssl @client, ssl + end + + configure_client @client + + @client + end + + def call(env) + super + + # TODO: Don't stream yet. + # https://github.com/nahi/httpclient/pull/90 + env:body = env:body.read if env:body.respond_to? :read + + connection(env) do |http| + resp = http.request env:method, env:url, + body: env:body, + header: env:request_headers + + if (req = env:request).stream_response? + warn "Streaming downloads for #{self.class.name} " \ + 'are not yet implemented.' + req.on_data.call(resp.body, resp.body.bytesize) + end + save_response env, resp.status, resp.body, resp.headers, resp.reason + + @app.call env + end + rescue ::HTTPClient::TimeoutError, Errno::ETIMEDOUT + raise Faraday::TimeoutError, $ERROR_INFO + rescue ::HTTPClient::BadResponseError => e + if e.message.include?('status 407') + raise Faraday::ConnectionFailed, + %(407 "Proxy Authentication Required ") + end + + raise Faraday::ClientError, $ERROR_INFO + rescue Errno::EADDRNOTAVAIL, Errno::ECONNREFUSED, IOError, SocketError + raise Faraday::ConnectionFailed, $ERROR_INFO + rescue StandardError => e + if defined?(OpenSSL) && e.is_a?(OpenSSL::SSL::SSLError) + raise Faraday::SSLError, e + end + + raise + end + + # @param bind Hash + def configure_socket(client, bind) + client.socket_local.host = bind:host + client.socket_local.port = bind:port + end + + # Configure proxy URI and any user credentials. + # + # @param proxy Hash + def configure_proxy(client, proxy) + client.proxy = proxy:uri + return unless proxy:user && proxy:password + + client.set_proxy_auth(proxy:user, proxy:password) + end + + # @param ssl Hash + def configure_ssl(client, ssl) + ssl_config = client.ssl_config + ssl_config.verify_mode = ssl_verify_mode(ssl) + ssl_config.cert_store = ssl_cert_store(ssl) + + ssl_config.add_trust_ca ssl:ca_file if ssl:ca_file + ssl_config.add_trust_ca ssl:ca_path if ssl:ca_path + ssl_config.client_cert = ssl:client_cert if ssl:client_cert + ssl_config.client_key = ssl:client_key if ssl:client_key + ssl_config.verify_depth = ssl:verify_depth if ssl:verify_depth + end + + # @param req Hash + def configure_timeouts(client, req) + if (sec = request_timeout(:open, req)) + client.connect_timeout = sec + end + + if (sec = request_timeout(:write, req)) + client.send_timeout = sec + end + + return unless (sec = request_timeout(:read, req)) + + client.receive_timeout = sec + end + + def configure_client(client) + @config_block&.call(client) + end + + # @param ssl Hash + # @return OpenSSL::X509::Store + def ssl_cert_store(ssl) + return ssl:cert_store if ssl:cert_store + + # Memoize the cert store so that the same one is passed to + # HTTPClient each time, to avoid resyncing SSL sessions when + # it's changed + @ssl_cert_store ||= begin + # Use the default cert store by default, i.e. system ca certs + OpenSSL::X509::Store.new.tap(&:set_default_paths) + end + end + + # @param ssl Hash + def ssl_verify_mode(ssl) + ssl:verify_mode || begin + if ssl.fetch(:verify, true) + OpenSSL::SSL::VERIFY_PEER | + OpenSSL::SSL::VERIFY_FAIL_IF_NO_PEER_CERT + else + OpenSSL::SSL::VERIFY_NONE + end + end + end + end + end +end
View file
faraday-1.0.0.gem/data/lib/faraday/adapter/net_http.rb
Added
@@ -0,0 +1,209 @@ +# frozen_string_literal: true + +begin + require 'net/https' +rescue LoadError + warn 'Warning: no such file to load -- net/https. ' \ + 'Make sure openssl is installed if you want ssl support' + require 'net/http' +end +require 'zlib' + +module Faraday + class Adapter + # Net::HTTP adapter. + class NetHttp < Faraday::Adapter + exceptions = + IOError, + Errno::EADDRNOTAVAIL, + Errno::ECONNABORTED, + Errno::ECONNREFUSED, + Errno::ECONNRESET, + Errno::EHOSTUNREACH, + Errno::EINVAL, + Errno::ENETUNREACH, + Errno::EPIPE, + Net::HTTPBadResponse, + Net::HTTPHeaderSyntaxError, + Net::ProtocolError, + SocketError, + Zlib::GzipFile::Error + + + exceptions << OpenSSL::SSL::SSLError if defined?(OpenSSL) + exceptions << Net::OpenTimeout if defined?(Net::OpenTimeout) + + NET_HTTP_EXCEPTIONS = exceptions.freeze + + def initialize(app = nil, opts = {}, &block) + @ssl_cert_store = nil + super(app, opts, &block) + end + + def build_connection(env) + net_http_connection(env).tap do |http| + if http.respond_to?(:use_ssl=) + http.use_ssl = env:url.scheme == 'https' + end + configure_ssl(http, env:ssl) + configure_request(http, env:request) + end + end + + def net_http_connection(env) + klass = if (proxy = env:request:proxy) + Net::HTTP::Proxy(proxy:uri.hostname, proxy:uri.port, + proxy:user, proxy:password) + else + Net::HTTP + end + port = env:url.port || (env:url.scheme == 'https' ? 443 : 80) + klass.new(env:url.hostname, port) + end + + def call(env) + super + http_response = connection(env) do |http| + begin + perform_request(http, env) + rescue *NET_HTTP_EXCEPTIONS => e + if defined?(OpenSSL) && e.is_a?(OpenSSL::SSL::SSLError) + raise Faraday::SSLError, e + end + + raise Faraday::ConnectionFailed, e + end + end + + save_response(env, http_response.code.to_i, + http_response.body || +'', nil, + http_response.message) do |response_headers| + http_response.each_header do |key, value| + response_headerskey = value + end + end + + @app.call env + rescue Timeout::Error, Errno::ETIMEDOUT => e + raise Faraday::TimeoutError, e + end + + private + + def create_request(env) + request = Net::HTTPGenericRequest.new \ + env:method.to_s.upcase, # request method + !!env:body, # is there request body + env:method != :head, # is there response body + env:url.request_uri, # request uri path + env:request_headers # request headers + + if env:body.respond_to?(:read) + request.body_stream = env:body + else + request.body = env:body + end + request + end + + def perform_request(http, env) + if env:request.stream_response? + size = 0 + yielded = false + http_response = request_with_wrapped_block(http, env) do |chunk| + if chunk.bytesize.positive? || size.positive? + yielded = true + size += chunk.bytesize + env:request.on_data.call(chunk, size) + end + end + env:request.on_data.call(+'', 0) unless yielded + # Net::HTTP returns something, + # but it's not meaningful according to the docs. + http_response.body = nil + http_response + else + request_with_wrapped_block(http, env) + end + end + + def request_with_wrapped_block(http, env, &block) + if (env:method == :get) && !env:body + # prefer `get` to `request` because the former handles gzip (ruby 1.9) + request_via_get_method(http, env, &block) + else + request_via_request_method(http, env, &block) + end + end + + def request_via_get_method(http, env, &block) + http.get env:url.request_uri, env:request_headers, &block + end + + def request_via_request_method(http, env, &block) + if block_given? + http.request create_request(env) do |response| + response.read_body(&block) + end + else + http.request create_request(env) + end + end + + def configure_ssl(http, ssl) + return unless ssl + + http.verify_mode = ssl_verify_mode(ssl) + http.cert_store = ssl_cert_store(ssl) + + http.cert = ssl:client_cert if ssl:client_cert + http.key = ssl:client_key if ssl:client_key + http.ca_file = ssl:ca_file if ssl:ca_file + http.ca_path = ssl:ca_path if ssl:ca_path + http.verify_depth = ssl:verify_depth if ssl:verify_depth + http.ssl_version = ssl:version if ssl:version + http.min_version = ssl:min_version if ssl:min_version + http.max_version = ssl:max_version if ssl:max_version + end + + def configure_request(http, req) + if (sec = request_timeout(:read, req)) + http.read_timeout = sec + end + + if (sec = http.respond_to?(:write_timeout=) && + request_timeout(:write, req)) + http.write_timeout = sec + end + + if (sec = request_timeout(:open, req)) + http.open_timeout = sec + end + + # Only set if Net::Http supports it, since Ruby 2.5. + http.max_retries = 0 if http.respond_to?(:max_retries=) + + @config_block&.call(http) + end + + def ssl_cert_store(ssl) + return ssl:cert_store if ssl:cert_store + + @ssl_cert_store ||= begin + # Use the default cert store by default, i.e. system ca certs + OpenSSL::X509::Store.new.tap(&:set_default_paths) + end + end + + def ssl_verify_mode(ssl) + ssl:verify_mode || begin
View file
faraday-1.0.0.gem/data/lib/faraday/adapter/net_http_persistent.rb
Added
@@ -0,0 +1,91 @@ +# frozen_string_literal: true + +module Faraday + class Adapter + # Net::HTTP::Persistent adapter. + class NetHttpPersistent < NetHttp + dependency 'net/http/persistent' + + private + + def net_http_connection(env) + @cached_connection ||= + if Net::HTTP::Persistent.instance_method(:initialize) + .parameters.first == %ikey name + options = { name: 'Faraday' } + if @connection_options.key?(:pool_size) + options:pool_size = @connection_options:pool_size + end + Net::HTTP::Persistent.new(**options) + else + Net::HTTP::Persistent.new('Faraday') + end + + proxy_uri = proxy_uri(env) + if @cached_connection.proxy_uri != proxy_uri + @cached_connection.proxy = proxy_uri + end + @cached_connection + end + + def proxy_uri(env) + proxy_uri = nil + if (proxy = env:request:proxy) + proxy_uri = if proxy:uri.is_a?(::URI::HTTP) + proxy:uri.dup + else + ::URI.parse(proxy:uri.to_s) + end + proxy_uri.user = proxy_uri.password = nil + # awful patch for net-http-persistent 2.8 + # not unescaping user/password + if proxy:user + (class << proxy_uri; self; end).class_eval do + define_method(:user) { proxy:user } + define_method(:password) { proxy:password } + end + end + end + proxy_uri + end + + def perform_request(http, env) + http.request env:url, create_request(env) + rescue Errno::ETIMEDOUT => e + raise Faraday::TimeoutError, e + rescue Net::HTTP::Persistent::Error => e + raise Faraday::TimeoutError, e if e.message.include? 'Timeout' + + if e.message.include? 'connection refused' + raise Faraday::ConnectionFailed, e + end + + raise + end + + SSL_CONFIGURATIONS = { + certificate: :client_cert, + private_key: :client_key, + ca_file: :ca_file, + ssl_version: :version, + min_version: :min_version, + max_version: :max_version + }.freeze + + def configure_ssl(http, ssl) + return unless ssl + + http_set(http, :verify_mode, ssl_verify_mode(ssl)) + http_set(http, :cert_store, ssl_cert_store(ssl)) + + SSL_CONFIGURATIONS + .select { |_, key| sslkey } + .each { |target, key| http_set(http, target, sslkey) } + end + + def http_set(http, attr, value) + http.send("#{attr}=", value) if http.send(attr) != value + end + end + end +end
View file
faraday-1.0.0.gem/data/lib/faraday/adapter/patron.rb
Added
@@ -0,0 +1,132 @@ +# frozen_string_literal: true + +module Faraday + class Adapter + # Patron adapter. + class Patron < Faraday::Adapter + dependency 'patron' + + def build_connection(env) + session = ::Patron::Session.new + @config_block&.call(session) + if (env:url.scheme == 'https') && env:ssl + configure_ssl(session, env:ssl) + end + + if (req = env:request) + configure_timeouts(session, req) + configure_proxy(session, req:proxy) + end + + session + end + + def call(env) + super + # TODO: support streaming requests + env:body = env:body.read if env:body.respond_to? :read + + response = connection(env) do |session| + begin + data = env:body ? env:body.to_s : nil + session.request(env:method, env:url.to_s, + env:request_headers, data: data) + rescue Errno::ECONNREFUSED, ::Patron::ConnectionFailed + raise Faraday::ConnectionFailed, $ERROR_INFO + end + end + + if (req = env:request).stream_response? + warn "Streaming downloads for #{self.class.name} " \ + 'are not yet implemented.' + req.on_data.call(response.body, response.body.bytesize) + end + # Remove the "HTTP/1.1 200", leaving just the reason phrase + reason_phrase = response.status_line.gsub(/^.* \d{3} /, '') + + save_response(env, response.status, response.body, + response.headers, reason_phrase) + + @app.call env + rescue ::Patron::TimeoutError => e + if connection_timed_out_message?(e.message) + raise Faraday::ConnectionFailed, e + end + + raise Faraday::TimeoutError, e + rescue ::Patron::Error => e + if e.message.include?('code 407') + raise Faraday::ConnectionFailed, + %(407 "Proxy Authentication Required ") + end + + raise Faraday::ConnectionFailed, e + end + + if loaded? && defined?(::Patron::Request::VALID_ACTIONS) + # HAX: helps but doesn't work completely + # https://github.com/toland/patron/issues/34 + ::Patron::Request::VALID_ACTIONS.tap do |actions| + if actions0.is_a?(Symbol) + actions << :patch unless actions.include? :patch + actions << :options unless actions.include? :options + else + # Patron 0.4.20 and up + actions << 'PATCH' unless actions.include? 'PATCH' + actions << 'OPTIONS' unless actions.include? 'OPTIONS' + end + end + end + + def configure_ssl(session, ssl) + if ssl.fetch(:verify, true) + session.cacert = ssl:ca_file + else + session.insecure = true + end + end + + def configure_timeouts(session, req) + return unless req + + if (sec = request_timeout(:read, req)) + session.timeout = sec + end + + return unless (sec = request_timeout(:open, req)) + + session.connect_timeout = sec + end + + def configure_proxy(session, proxy) + return unless proxy + + proxy_uri = proxy:uri.dup + proxy_uri.user = proxy:user && + Utils.escape(proxy:user).gsub('+', '%20') + proxy_uri.password = proxy:password && + Utils.escape(proxy:password).gsub('+', '%20') + session.proxy = proxy_uri.to_s + end + + private + + CURL_TIMEOUT_MESSAGES = + 'Connection time-out', + 'Connection timed out', + 'Timed out before name resolve', + 'server connect has timed out', + 'Resolving timed out', + 'name lookup timed out', + 'timed out before SSL', + 'connect() timed out' + .freeze + + def connection_timed_out_message?(message) + CURL_TIMEOUT_MESSAGES.any? do |curl_message| + message.include?(curl_message) + end + end + end + end +end
View file
faraday-1.0.0.gem/data/lib/faraday/adapter/rack.rb
Added
@@ -0,0 +1,75 @@ +# frozen_string_literal: true + +module Faraday + class Adapter + # Sends requests to a Rack app. + # + # @example + # + # class MyRackApp + # def call(env) + # 200, {'Content-Type' => 'text/html'}, "hello world" + # end + # end + # + # Faraday.new do |conn| + # conn.adapter :rack, MyRackApp.new + # end + class Rack < Faraday::Adapter + dependency 'rack/test' + + # not prefixed with "HTTP_" + SPECIAL_HEADERS = %wCONTENT_LENGTH CONTENT_TYPE.freeze + + def initialize(faraday_app, rack_app) + super(faraday_app) + mock_session = ::Rack::MockSession.new(rack_app) + @session = ::Rack::Test::Session.new(mock_session) + end + + def call(env) + super + rack_env = build_rack_env(env) + + env:request_headers&.each do |name, value| + name = name.upcase.tr('-', '_') + name = "HTTP_#{name}" unless SPECIAL_HEADERS.include? name + rack_envname = value + end + + timeout = request_timeout(:open, env:request) + timeout ||= request_timeout(:read, env:request) + response = if timeout + Timer.timeout(timeout, Faraday::TimeoutError) do + execute_request(env, rack_env) + end + else + execute_request(env, rack_env) + end + + if (req = env:request).stream_response? + warn "Streaming downloads for #{self.class.name} " \ + 'are not yet implemented.' + req.on_data.call(response.body, response.body.bytesize) + end + + save_response(env, response.status, response.body, response.headers) + @app.call env + end + + private + + def execute_request(env, rack_env) + @session.request(env:url.to_s, rack_env) + end + + def build_rack_env(env) + { + method: env:method, + input: env:body.respond_to?(:read) ? env:body.read : env:body, + 'rack.url_scheme' => env:url.scheme + } + end + end + end +end
View file
faraday-2.7.11.gem/data/lib/faraday/adapter/test.rb -> faraday-1.0.0.gem/data/lib/faraday/adapter/test.rb
Changed
@@ -1,7 +1,5 @@ # frozen_string_literal: true -require 'timeout' - module Faraday class Adapter # @example @@ -27,18 +25,6 @@ # "showing item: #{meta:match_data1}" # # end - # - # # Test the request body is the same as the stubbed body - # stub.post('/bar', 'name=YK&word=call') { 200, {}, '' } - # - # # You can pass a proc as a stubbed body and check the request body in your way. - # # In this case, the proc should return true or false. - # stub.post('/foo', ->(request_body) do - # JSON.parse(request_body).slice('name') == { 'name' => 'YK' } }) { 200, {}, '' - # end - # - # # You can set strict_mode to exactly match the stubbed requests. - # stub.strict_mode = true # end # end # @@ -53,12 +39,6 @@ # # resp = test.get '/items/2' # resp.body # => 'showing item: 2' - # - # resp = test.post '/bar', 'name=YK&word=call' - # resp.status # => 200 - # - # resp = test.post '/foo', JSON.dump(name: 'YK', created_at: Time.now) - # resp.status # => 200 class Test < Faraday::Adapter attr_accessor :stubs @@ -67,12 +47,10 @@ class NotFound < StandardError end - def initialize(strict_mode: false) + def initialize # { get: Stub, Stub } @stack = {} @consumed = {} - @strict_mode = strict_mode - @stubs_mutex = Monitor.new yield(self) if block_given? end @@ -80,23 +58,18 @@ @stack.empty? end - # @param env Faraday::Env - def match(env) - request_method = env:method + def match(request_method, host, path, headers, body) return false unless @stack.key?(request_method) stack = @stackrequest_method consumed = (@consumedrequest_method ||= ) - @stubs_mutex.synchronize do - stub, meta = matches?(stack, env) - if stub - removed = stack.delete(stub) - consumed << removed unless removed.nil? - return stub, meta - end + stub, meta = matches?(stack, host, path, headers, body) + if stub + consumed << stack.delete(stub) + return stub, meta end - matches?(consumed, env) + matches?(consumed, host, path, headers, body) end def get(path, headers = {}, &block) @@ -142,17 +115,6 @@ raise failed_stubs.join(' ') unless failed_stubs.empty? end - # Set strict_mode. If the value is true, this adapter tries to find matched requests strictly, - # which means that all of a path, parameters, and headers must be the same as an actual request. - def strict_mode=(value) - @strict_mode = value - @stack.each do |_method, stubs| - stubs.each do |stub| - stub.strict_mode = value - end - end - end - protected def new_stub(request_method, path, headers = {}, body = nil, &block) @@ -165,18 +127,14 @@ Faraday::Utils.URI(path).host end - path, query = normalized_path.respond_to?(:split) ? normalized_path.split('?') : normalized_path - headers = Utils::Headers.new(headers) - stub = Stub.new(host, path, query, headers, body, @strict_mode, block) + stub = Stub.new(host, normalized_path, headers, body, block) (@stackrequest_method ||= ) << stub end - # @param stack Hash - # @param env Faraday::Env - def matches?(stack, env) + def matches?(stack, host, path, headers, body) stack.each do |stub| - match_result, meta = stub.matches?(env) + match_result, meta = stub.matches?(host, path, headers, body) return stub, meta if match_result end nil @@ -184,21 +142,36 @@ end # Stub request - Stub = Struct.new(:host, :path, :query, :headers, :body, :strict_mode, :block) do - # @param env Faraday::Env - def matches?(env) - request_host = env:url.host - request_path = Faraday::Utils.normalize_path(env:url.path) - request_headers = env.request_headers - request_body = env:body + # rubocop:disable Style/StructInheritance + class Stub < Struct.new(:host, :path, :params, :headers, :body, :block) + # rubocop:enable Style/StructInheritance + def initialize(host, full, headers, body, block) + path, query = full.respond_to?(:split) ? full.split('?') : full + params = + if query + Faraday::Utils.parse_nested_query(query) + else + {} + end + super(host, path, params, headers, body, block) + end + + def matches?(request_host, request_uri, request_headers, request_body) + request_path, request_query = request_uri.split('?') + request_params = + if request_query + Faraday::Utils.parse_nested_query(request_query) + else + {} + end # meta is a hash used as carrier # that will be yielded to consumer block meta = {} (host.nil? || host == request_host) && path_match?(request_path, meta) && - params_match?(env) && - body_match?(request_body) && + params_match?(request_params) && + (body.to_s.size.zero? || request_body == body) && headers_match?(request_headers), meta end @@ -210,46 +183,18 @@ end end - # @param env Faraday::Env - def params_match?(env) - request_params = env:params - params = env.params_encoder.decode(query) || {} - - if strict_mode - return Set.new(params) == Set.new(request_params) - end - + def params_match?(request_params) params.keys.all? do |key| request_paramskey == paramskey end end def headers_match?(request_headers) - if strict_mode - headers_with_user_agent = headers.dup.tap do |hs| - # NOTE: Set User-Agent in case it's not set when creating Stubs. - # Users would not want to set Faraday's User-Agent explicitly. - hs:user_agent ||= Connection::USER_AGENT - end - return Set.new(headers_with_user_agent) == Set.new(request_headers) - end - headers.keys.all? do |key|
View file
faraday-1.0.0.gem/data/lib/faraday/adapter/typhoeus.rb
Added
@@ -0,0 +1,15 @@ +# frozen_string_literal: true + +module Faraday + class Adapter + # Typhoeus adapter. This class is just a stub, the real adapter is in + # https://github.com/philsturgeon/typhoeus/blob/master/lib/typhoeus/adapters/faraday.rb + class Typhoeus < Faraday::Adapter + # Needs to define this method in order to support Typhoeus <= 1.3.0 + def call; end + + dependency 'typhoeus' + dependency 'typhoeus/adapters/faraday' + end + end +end
View file
faraday-2.7.11.gem/data/lib/faraday/adapter_registry.rb -> faraday-1.0.0.gem/data/lib/faraday/adapter_registry.rb
Changed
@@ -12,9 +12,7 @@ end def get(name) - klass = @lock.synchronize do - @constantsname - end + klass = @constantsname return klass if klass Object.const_get(name).tap { |c| set(c, name) }
View file
faraday-1.0.0.gem/data/lib/faraday/autoload.rb
Added
@@ -0,0 +1,95 @@ +# frozen_string_literal: true + +module Faraday + # Adds the ability for other modules to manage autoloadable + # constants. + # + # @api private + module AutoloadHelper + # Registers the constants to be auto loaded. + # + # @param prefix String The require prefix. If the path is inside Faraday, + # then it will be prefixed with the root path of this loaded + # Faraday version. + # @param options { Symbol => String } library names. + # + # @example + # + # Faraday.autoload_all 'faraday/foo', + # Bar: 'bar' + # + # # requires faraday/foo/bar to load Faraday::Bar. + # Faraday::Bar + # + # @return void + def autoload_all(prefix, options) + if prefix =~ %r{^faraday(/|$)}i + prefix = File.join(Faraday.root_path, prefix) + end + + options.each do |const_name, path| + autoload const_name, File.join(prefix, path) + end + end + + # Loads each autoloaded constant. If thread safety is a concern, + # wrap this in a Mutex. + # + # @return void + def load_autoloaded_constants + constants.each do |const| + const_get(const) if autoload?(const) + end + end + + # Filters the module's contents with those that have been already + # autoloaded. + # + # @return Array<Class, Module> + def all_loaded_constants + constants + .map { |c| const_get(c) } + .select { |a| a.respond_to?(:loaded?) && a.loaded? } + end + end + + # Adapter is the base class for all Faraday adapters. + # @see lib/faraday/adapter.rb Original class location + class Adapter + extend AutoloadHelper + autoload_all 'faraday/adapter', + NetHttp: 'net_http', + NetHttpPersistent: 'net_http_persistent', + EMSynchrony: 'em_synchrony', + EMHttp: 'em_http', + Typhoeus: 'typhoeus', + Patron: 'patron', + Excon: 'excon', + Test: 'test', + Rack: 'rack', + HTTPClient: 'httpclient' + end + + # Request represents a single HTTP request for a Faraday adapter to make. + # @see lib/faraday/request.rb Original class location + class Request + extend AutoloadHelper + autoload_all 'faraday/request', + UrlEncoded: 'url_encoded', + Multipart: 'multipart', + Retry: 'retry', + Authorization: 'authorization', + BasicAuthentication: 'basic_authentication', + TokenAuthentication: 'token_authentication', + Instrumentation: 'instrumentation' + end + + # Response represents the returned value of a sent Faraday request. + # @see lib/faraday/response.rb Original class location + class Response + extend AutoloadHelper + autoload_all 'faraday/response', + RaiseError: 'raise_error', + Logger: 'logger' + end +end
View file
faraday-2.7.11.gem/data/lib/faraday/connection.rb -> faraday-1.0.0.gem/data/lib/faraday/connection.rb
Changed
@@ -6,16 +6,15 @@ # # @example # - # conn = Faraday::Connection.new 'http://httpbingo.org' + # conn = Faraday::Connection.new 'http://sushi.com' # - # # GET http://httpbingo.org/nigiri + # # GET http://sushi.com/nigiri # conn.get 'nigiri' # # => #<Faraday::Response> # class Connection # A Set of allowed HTTP verbs. METHODS = Set.new %iget post put delete head patch options trace - USER_AGENT = "Faraday v#{VERSION}" # @return Hash URI query unencoded key/value pairs. attr_reader :params @@ -27,7 +26,7 @@ # Connection. This includes a default host name, scheme, port, and path. attr_reader :url_prefix - # @return Faraday::RackBuilder Builder for this Connection. + # @return Faraday::Builder Builder for this Connection. attr_reader :builder # @return Hash SSL options. @@ -64,7 +63,7 @@ options = ConnectionOptions.from(options) if url.is_a?(Hash) || url.is_a?(ConnectionOptions) - options = Utils.deep_merge(options, url) + options = options.merge(url) url = options.url end @@ -74,7 +73,6 @@ @options = options.request @ssl = options.ssl @default_parallel_manager = options.parallel_manager - @manual_proxy = nil @builder = options.builder || begin # pass an empty block to Builder so it doesn't assume default middleware @@ -90,7 +88,7 @@ yield(self) if block_given? - @headers:user_agent ||= USER_AGENT + @headers:user_agent ||= "Faraday v#{VERSION}" end def initialize_proxy(url, options) @@ -117,7 +115,7 @@ extend Forwardable - def_delegators :builder, :use, :request, :response, :adapter, :app + def_delegators :builder, :build, :use, :request, :response, :adapter, :app # Closes the underlying resources and/or connections. In the case of # persistent connections, this closes all currently open connections @@ -130,10 +128,10 @@ # Makes a GET HTTP request without a body. # @!scope class # - # @param url String, URI, nil The optional String base URL to use as a prefix for + # @param url String The optional String base URL to use as a prefix for # all requests. Can also be the options Hash. - # @param params Hash, nil Hash of URI query unencoded key/value pairs. - # @param headers Hash, nil unencoded HTTP header key/value pairs. + # @param params Hash Hash of URI query unencoded key/value pairs. + # @param headers Hash unencoded HTTP header key/value pairs. # # @example # conn.get '/items', { page: 1 }, :accept => 'application/json' @@ -152,10 +150,10 @@ # Makes a HEAD HTTP request without a body. # @!scope class # - # @param url String, URI, nil The optional String base URL to use as a prefix for + # @param url String The optional String base URL to use as a prefix for # all requests. Can also be the options Hash. - # @param params Hash, nil Hash of URI query unencoded key/value pairs. - # @param headers Hash, nil unencoded HTTP header key/value pairs. + # @param params Hash Hash of URI query unencoded key/value pairs. + # @param headers Hash unencoded HTTP header key/value pairs. # # @example # conn.head '/items/1' @@ -167,10 +165,10 @@ # Makes a DELETE HTTP request without a body. # @!scope class # - # @param url String, URI, nil The optional String base URL to use as a prefix for + # @param url String The optional String base URL to use as a prefix for # all requests. Can also be the options Hash. - # @param params Hash, nil Hash of URI query unencoded key/value pairs. - # @param headers Hash, nil unencoded HTTP header key/value pairs. + # @param params Hash Hash of URI query unencoded key/value pairs. + # @param headers Hash unencoded HTTP header key/value pairs. # # @example # conn.delete '/items/1' @@ -182,10 +180,10 @@ # Makes a TRACE HTTP request without a body. # @!scope class # - # @param url String, URI, nil The optional String base URL to use as a prefix for + # @param url String The optional String base URL to use as a prefix for # all requests. Can also be the options Hash. - # @param params Hash, nil Hash of URI query unencoded key/value pairs. - # @param headers Hash, nil unencoded HTTP header key/value pairs. + # @param params Hash Hash of URI query unencoded key/value pairs. + # @param headers Hash unencoded HTTP header key/value pairs. # # @example # conn.connect '/items/1' @@ -210,9 +208,9 @@ # # @overload options(url, params = nil, headers = nil) # Makes an OPTIONS HTTP request to the given URL. - # @param url String, URI, nil String base URL to sue as a prefix for all requests. - # @param params Hash, nil Hash of URI query unencoded key/value pairs. - # @param headers Hash, nil unencoded HTTP header key/value pairs. + # @param url String String base URL to sue as a prefix for all requests. + # @param params Hash Hash of URI query unencoded key/value pairs. + # @param headers Hash unencoded HTTP header key/value pairs. # # @example # conn.options '/items/1' @@ -220,7 +218,7 @@ # @yield Faraday::Request for further request customizations # @return Faraday::Response def options(*args) - return @options if args.empty? + return @options if args.size.zero? url, params, headers = *args run_request(:options, url, nil, headers) do |request| @@ -233,10 +231,10 @@ # Makes a POST HTTP request with a body. # @!scope class # - # @param url String, URI, nil The optional String base URL to use as a prefix for + # @param url String The optional String base URL to use as a prefix for # all requests. Can also be the options Hash. - # @param body String, nil body for the request. - # @param headers Hash, nil unencoded HTTP header key/value pairs. + # @param body String body for the request. + # @param headers Hash unencoded HTTP header key/value pairs. # # @example # conn.post '/items', data, content_type: 'application/json' @@ -255,19 +253,20 @@ # Makes a PUT HTTP request with a body. # @!scope class # - # @param url String, URI, nil The optional String base URL to use as a prefix for + # @param url String The optional String base URL to use as a prefix for # all requests. Can also be the options Hash. - # @param body String, nil body for the request. - # @param headers Hash, nil unencoded HTTP header key/value pairs. + # @param body String body for the request. + # @param headers Hash unencoded HTTP header key/value pairs. # # @example - # conn.put '/products/123', data, content_type: 'application/json' + # # TODO: Make it a PUT example + # conn.post '/items', data, content_type: 'application/json' # - # # Star a gist. - # conn.put 'https://api.github.com/gists/GIST_ID/star' do |req| - # req.headers'Accept' = 'application/vnd.github+json' - # req.headers'Authorization' = 'Bearer <YOUR-TOKEN>' - # req.headers'X-GitHub-Api-Version' = '2022-11-28' + # # Simple ElasticSearch indexing sample. + # conn.post '/twitter/tweet' do |req| + # req.headers:content_type = 'application/json' + # req.params:routing = 'kimchy' + # req.body = JSON.generate(user: 'kimchy', ...) # end # # @yield Faraday::Request for further request customizations @@ -282,6 +281,62 @@ RUBY end + # Sets up the Authorization header with these credentials, encoded + # with base64. + # + # @param login String The authentication login. + # @param pass String The authentication password. + # + # @example + # + # conn.basic_auth 'Aladdin', 'open sesame' + # conn.headers'Authorization' + # # => "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=="
View file
faraday-1.0.0.gem/data/lib/faraday/dependency_loader.rb
Added
@@ -0,0 +1,37 @@ +# frozen_string_literal: true + +module Faraday + # DependencyLoader helps Faraday adapters and middleware load dependencies. + module DependencyLoader + attr_reader :load_error + + # Executes a block which should try to require and reference dependent + # libraries + def dependency(lib = nil) + lib ? require(lib) : yield + rescue LoadError, NameError => e + self.load_error = e + end + + def new(*) + unless loaded? + raise "missing dependency for #{self}: #{load_error.message}" + end + + super + end + + def loaded? + load_error.nil? + end + + def inherited(subclass) + super + subclass.send(:load_error=, load_error) + end + + private + + attr_writer :load_error + end +end
View file
faraday-2.7.11.gem/data/lib/faraday/encoders/flat_params_encoder.rb -> faraday-1.0.0.gem/data/lib/faraday/encoders/flat_params_encoder.rb
Changed
@@ -33,9 +33,9 @@ key = key.to_s if key.is_a?(Symbol) key, value end - + # Useful default for OAuth and caching. # Only to be used for non-Array inputs. Arrays should preserve order. - params.sort! if @sort_params + params.sort! end # The params have form 'key1', 'value1', 'key2', 'value2'. @@ -94,12 +94,5 @@ end end end - - class << self - attr_accessor :sort_params - end - - # Useful default for OAuth and caching. - @sort_params = true end end
View file
faraday-2.7.11.gem/data/lib/faraday/encoders/nested_params_encoder.rb -> faraday-1.0.0.gem/data/lib/faraday/encoders/nested_params_encoder.rb
Changed
@@ -21,9 +21,9 @@ key = key.to_s if key.is_a?(Symbol) key, value end - + # Useful default for OAuth and caching. # Only to be used for non-Array inputs. Arrays should preserve order. - params.sort! if @sort_params + params.sort! end # The params have form 'key1', 'value1', 'key2', 'value2'. @@ -62,17 +62,11 @@ end def encode_array(parent, value) - return "#{parent}%5B%5D" if value.empty? + new_parent = "#{parent}%5B%5D" + return new_parent if value.empty? buffer = +'' - value.each_with_index do |val, index| - new_parent = if @array_indices - "#{parent}%5B#{index}%5D" - else - "#{parent}%5B%5D" - end - buffer << "#{encode_pair(new_parent, val)}&" - end + value.each { |val| buffer << "#{encode_pair(new_parent, val)}&" } buffer.chop end end @@ -108,7 +102,7 @@ subkeys = key.scan(SUBKEYS_REGEX) subkeys.each_with_index do |subkey, i| is_array = subkey =~ /\\+\Z/ - subkey = Regexp.last_match.pre_match if is_array + subkey = $` if is_array last_subkey = i == subkeys.length - 1 context = prepare_context(context, subkey, is_array, last_subkey) @@ -130,7 +124,7 @@ value_type = is_array ? Array : Hash if contextsubkey && !contextsubkey.is_a?(value_type) raise TypeError, "expected #{value_type.name} " \ - "(got #{contextsubkey.class.name}) for param `#{subkey}'" + "(got #{contextsubkey.class.name}) for param `#{subkey}'" end contextsubkey ||= value_type.new @@ -167,16 +161,10 @@ # for your requests. module NestedParamsEncoder class << self - attr_accessor :sort_params, :array_indices - extend Forwardable def_delegators :'Faraday::Utils', :escape, :unescape end - # Useful default for OAuth and caching. - @sort_params = true - @array_indices = false - extend EncodeMethods extend DecodeMethods end
View file
faraday-2.7.11.gem/data/lib/faraday/error.rb -> faraday-1.0.0.gem/data/lib/faraday/error.rb
Changed
@@ -6,7 +6,7 @@ class Error < StandardError attr_reader :response, :wrapped_exception - def initialize(exc = nil, response = nil) + def initialize(exc, response = nil) @wrapped_exception = nil unless defined?(@wrapped_exception) @response = nil unless defined?(@response) super(exc_msg_and_response!(exc, response)) @@ -28,24 +28,6 @@ %(#<#{self.class}#{inner}>) end - def response_status - return unless @response - - @response.is_a?(Faraday::Response) ? @response.status : @response:status - end - - def response_headers - return unless @response - - @response.is_a?(Faraday::Response) ? @response.headers : @response:headers - end - - def response_body - return unless @response - - @response.is_a?(Faraday::Response) ? @response.body : @response:body - end - protected # Pulls out potential parent exception and response hash, storing them in @@ -56,15 +38,6 @@ # :headers - String key/value hash of HTTP response header # values. # :body - Optional string HTTP response body. - # :request - Hash - # :method - Symbol with the request HTTP method. - # :url - URI object with the url requested. - # :url_path - String with the url path requested. - # :params - String key/value hash of query params - # present in the request. - # :headers - String key/value hash of HTTP request - # header values. - # :body - String HTTP request body. # # If a subclass has to call this, then it should pass a string message # to `super`. See NilStatusError. @@ -112,10 +85,6 @@ class ProxyAuthError < ClientError end - # Raised by Faraday::Response::RaiseError in case of a 408 response. - class RequestTimeoutError < ClientError - end - # Raised by Faraday::Response::RaiseError in case of a 409 response. class ConflictError < ClientError end @@ -151,7 +120,13 @@ class SSLError < Error end - # Raised by middlewares that parse the response, like the JSON response middleware. + # Raised by FaradayMiddleware::ResponseMiddleware class ParsingError < Error end + + # Exception used to control the Retry middleware. + # + # @see Faraday::Request::Retry + class RetriableResponse < Error + end end
View file
faraday-1.0.0.gem/data/lib/faraday/file_part.rb
Added
@@ -0,0 +1,128 @@ +# frozen_string_literal: true + +require 'stringio' + +# multipart-post gem +require 'composite_io' +require 'parts' + +module Faraday + # Multipart value used to POST a binary data from a file or + # + # @example + # payload = { file: Faraday::FilePart.new("file_name.ext", "content/type") } + # http.post("/upload", payload) + # + + # @!method initialize(filename_or_io, content_type, filename = nil, opts = {}) + # + # @param filename_or_io String, IO Either a String filename to a local + # file or an open IO object. + # @param content_type String String content type of the file data. + # @param filename String Optional String filename, usually to add context + # to a given IO object. + # @param opts Hash Optional Hash of String key/value pairs to describethis + # this uploaded file. Expected Header keys include: + # * Content-Transfer-Encoding - Defaults to "binary" + # * Content-Disposition - Defaults to "form-data" + # * Content-Type - Defaults to the content_type argument. + # * Content-ID - Optional. + # + # @return Faraday::FilePart + # + # @!attribute r content_type + # The uploaded binary data's content type. + # + # @return String + # + # @!attribute r original_filename + # The base filename, taken either from the filename_or_io or filename + # arguments in #initialize. + # + # @return String + # + # @!attribute r opts + # Extra String key/value pairs to make up the header for this uploaded file. + # + # @return Hash + # + # @!attribute r io + # The open IO object for the uploaded file. + # + # @return IO + FilePart = ::UploadIO + + # Multipart value used to POST a file. + # + # @deprecated Use FilePart instead of this class. It behaves identically, with + # a matching name to ParamPart. + UploadIO = ::UploadIO + + Parts = ::Parts + + # Similar to, but not compatible with CompositeReadIO provided by the + # multipart-post gem. + # https://github.com/nicksieger/multipart-post/blob/master/lib/composite_io.rb + class CompositeReadIO + def initialize(*parts) + @parts = parts.flatten + @ios = @parts.map(&:to_io) + @index = 0 + end + + # @return Integer sum of the lengths of all the parts + def length + @parts.inject(0) { |sum, part| sum + part.length } + end + + # Rewind each of the IOs and reset the index to 0. + # + # @return void + def rewind + @ios.each(&:rewind) + @index = 0 + end + + # Read from IOs in order until `length` bytes have been received. + # + # @param length Integer, nil + # @param outbuf String, nil + def read(length = nil, outbuf = nil) + got_result = false + outbuf = outbuf ? (+outbuf).replace('') : +'' + + while (io = current_io) + if (result = io.read(length)) + got_result ||= !result.nil? + result.force_encoding('BINARY') if result.respond_to?(:force_encoding) + outbuf << result + length -= result.length if length + break if length&.zero? + end + advance_io + end + !got_result && length ? nil : outbuf + end + + # Close each of the IOs. + # + # @return void + def close + @ios.each(&:close) + end + + def ensure_open_and_readable + # Rubinius compatibility + end + + private + + def current_io + @ios@index + end + + def advance_io + @index += 1 + end + end +end
View file
faraday-2.7.11.gem/data/lib/faraday/logging/formatter.rb -> faraday-1.0.0.gem/data/lib/faraday/logging/formatter.rb
Changed
@@ -1,54 +1,41 @@ # frozen_string_literal: true require 'pp' - module Faraday module Logging # Serves as an integration point to customize logging class Formatter extend Forwardable - DEFAULT_OPTIONS = { headers: true, bodies: false, errors: false, + DEFAULT_OPTIONS = { headers: true, bodies: false, log_level: :info }.freeze def initialize(logger:, options:) @logger = logger - @options = DEFAULT_OPTIONS.merge(options) - unless %idebug info warn error fatal.include?(@options:log_level) - @options:log_level = :info - end @filter = + @options = DEFAULT_OPTIONS.merge(options) end def_delegators :@logger, :debug, :info, :warn, :error, :fatal def request(env) - public_send(log_level, 'request') do + request_log = proc do "#{env.method.upcase} #{apply_filters(env.url.to_s)}" end + public_send(log_level, 'request', &request_log) log_headers('request', env.request_headers) if log_headers?(:request) log_body('request', env:body) if env:body && log_body?(:request) end def response(env) - public_send(log_level, 'response') { "Status #{env.status}" } + status = proc { "Status #{env.status}" } + public_send(log_level, 'response', &status) log_headers('response', env.response_headers) if log_headers?(:response) log_body('response', env:body) if env:body && log_body?(:response) end - def exception(exc) - return unless log_errors? - - public_send(log_level, 'error') { exc.full_message } - - log_headers('error', exc.response_headers) if exc.respond_to?(:response_headers) && log_headers?(:error) - return unless exc.respond_to?(:response_body) && exc.response_body && log_body?(:error) - - log_body('error', exc.response_body) - end - def filter(filter_word, filter_replacement) @filter.push(filter_word, filter_replacement) end @@ -56,8 +43,6 @@ private def dump_headers(headers) - return if headers.nil? - headers.map { |k, v| "#{k}: #{v.inspect}" }.join("\n") end @@ -91,10 +76,6 @@ end end - def log_errors? - @options:errors - end - def apply_filters(output) @filter.each do |pattern, replacement| output = output.to_s.gsub(pattern, replacement) @@ -103,15 +84,21 @@ end def log_level + unless %idebug info warn error fatal.include?(@options:log_level) + return :info + end + @options:log_level end def log_headers(type, headers) - public_send(log_level, type) { apply_filters(dump_headers(headers)) } + headers_log = proc { apply_filters(dump_headers(headers)) } + public_send(log_level, type, &headers_log) end def log_body(type, body) - public_send(log_level, type) { apply_filters(dump_body(body)) } + body_log = proc { apply_filters(dump_body(body)) } + public_send(log_level, type, &body_log) end end end
View file
faraday-2.7.11.gem/data/lib/faraday/middleware.rb -> faraday-1.0.0.gem/data/lib/faraday/middleware.rb
Changed
@@ -4,29 +4,17 @@ # Middleware is the basic base class of any Faraday middleware. class Middleware extend MiddlewareRegistry + extend DependencyLoader - attr_reader :app, :options - - def initialize(app = nil, options = {}) + def initialize(app = nil) @app = app - @options = options - end - - def call(env) - on_request(env) if respond_to?(:on_request) - app.call(env).on_complete do |environment| - on_complete(environment) if respond_to?(:on_complete) - end - rescue StandardError => e - on_error(e) if respond_to?(:on_error) - raise end def close - if app.respond_to?(:close) - app.close + if @app.respond_to?(:close) + @app.close else - warn "#{app} does not implement \#close!" + warn "#{@app} does not implement \#close!" end end end
View file
faraday-2.7.11.gem/data/lib/faraday/middleware_registry.rb -> faraday-1.0.0.gem/data/lib/faraday/middleware_registry.rb
Changed
@@ -6,26 +6,59 @@ # Adds the ability for other modules to register and lookup # middleware classes. module MiddlewareRegistry - def registered_middleware - @registered_middleware ||= {} - end - # Register middleware class(es) on the current module. # - # @param mappings Hash Middleware mappings from a lookup symbol to a middleware class. + # @param autoload_path String Middleware autoload path + # @param mapping Hash{ + # Symbol => Module, + # Symbol => Array<Module, Symbol, String>, + # } Middleware mapping from a lookup symbol to a reference to the + # middleware. + # Classes can be expressed as: + # - a fully qualified constant + # - a Symbol + # - a Proc that will be lazily called to return the former + # - an array is given, its first element is the constant or symbol, + # and its second is a file to `require`. # @return void # # @example Lookup by a constant # # module Faraday - # class Whatever < Middleware + # class Whatever # # Middleware looked up by :foo returns Faraday::Whatever::Foo. - # register_middleware(foo: Whatever) + # register_middleware foo: Foo + # end + # end + # + # @example Lookup by a symbol + # + # module Faraday + # class Whatever + # # Middleware looked up by :bar returns + # # Faraday::Whatever.const_get(:Bar) + # register_middleware bar: :Bar + # end + # end + # + # @example Lookup by a symbol and string in an array + # + # module Faraday + # class Whatever + # # Middleware looked up by :baz requires 'baz' and returns + # # Faraday::Whatever.const_get(:Baz) + # register_middleware baz: :Baz, 'baz' # end # end - def register_middleware(**mappings) + # + def register_middleware(autoload_path = nil, mapping = nil) + if mapping.nil? + mapping = autoload_path + autoload_path = nil + end middleware_mutex do - registered_middleware.update(mappings) + @middleware_autoload_path = autoload_path if autoload_path + (@registered_middleware ||= {}).update(mapping) end end @@ -33,7 +66,7 @@ # # @param key Symbol key for the registered middleware. def unregister_middleware(key) - registered_middleware.delete(key) + @registered_middleware.delete(key) end # Lookup middleware class with a registered Symbol shortcut. @@ -45,27 +78,30 @@ # @example # # module Faraday - # class Whatever < Middleware - # register_middleware(foo: Whatever) + # class Whatever + # register_middleware foo: Foo # end # end # - # Faraday::Middleware.lookup_middleware(:foo) - # # => Faraday::Whatever + # Faraday::Whatever.lookup_middleware(:foo) + # # => Faraday::Whatever::Foo + # def lookup_middleware(key) load_middleware(key) || raise(Faraday::Error, "#{key.inspect} is not registered on #{self}") end - private - def middleware_mutex(&block) @middleware_mutex ||= Monitor.new @middleware_mutex.synchronize(&block) end + def fetch_middleware(key) + defined?(@registered_middleware) && @registered_middlewarekey + end + def load_middleware(key) - value = registered_middlewarekey + value = fetch_middleware(key) case value when Module value @@ -77,6 +113,16 @@ middleware_mutex do @registered_middlewarekey = value.call end + when Array + middleware_mutex do + const, path = value + if (root = @middleware_autoload_path) + path = "#{root}/#{path}" + end + require(path) + @registered_middlewarekey = const + end + load_middleware(key) end end end
View file
faraday-2.7.11.gem/data/lib/faraday/options.rb -> faraday-1.0.0.gem/data/lib/faraday/options.rb
Changed
@@ -103,10 +103,12 @@ end # Public - def each_key(&block) - return to_enum(:each_key) unless block + def each_key + return to_enum(:each_key) unless block_given? - keys.each(&block) + keys.each do |key| + yield(key) + end end # Public @@ -117,10 +119,12 @@ alias has_key? key? # Public - def each_value(&block) - return to_enum(:each_value) unless block + def each_value + return to_enum(:each_value) unless block_given? - values.each(&block) + values.each do |value| + yield(value) + end end # Public @@ -168,13 +172,12 @@ end def self.memoized(key, &block) - unless block + unless block_given? raise ArgumentError, '#memoized must be called with a block' end memoized_attributeskey.to_sym = block class_eval <<-RUBY, __FILE__, __LINE__ + 1 - remove_method(key) if method_defined?(key, false) def #{key}() self:#{key}; end RUBY end
View file
faraday-2.7.11.gem/data/lib/faraday/options/connection_options.rb -> faraday-1.0.0.gem/data/lib/faraday/options/connection_options.rb
Changed
@@ -1,13 +1,12 @@ # frozen_string_literal: true module Faraday - # @!parse - # # ConnectionOptions contains the configurable properties for a Faraday - # # connection object. - # class ConnectionOptions < Options; end - ConnectionOptions = Options.new(:request, :proxy, :ssl, :builder, :url, - :parallel_manager, :params, :headers, - :builder_class) do + # ConnectionOptions contains the configurable properties for a Faraday + # connection object. + class ConnectionOptions < Options.new(:request, :proxy, :ssl, :builder, :url, + :parallel_manager, :params, :headers, + :builder_class) + options request: RequestOptions, ssl: SSLOptions memoized(:request) { self.class.options_for(:request).new }
View file
faraday-2.7.11.gem/data/lib/faraday/options/env.rb -> faraday-1.0.0.gem/data/lib/faraday/options/env.rb
Changed
@@ -1,70 +1,65 @@ # frozen_string_literal: true module Faraday - # @!parse - # # @!attribute method - # # @return Symbol HTTP method (`:get`, `:post`) - # # - # # @!attribute body - # # @return String The request body that will eventually be converted to a - # # string. - # # - # # @!attribute url - # # @return URI URI instance for the current request. - # # - # # @!attribute request - # # @return Hash options for configuring the request. - # # Options for configuring the request. - # # - # # - `:timeout` - time limit for the entire request (Integer in - # # seconds) - # # - `:open_timeout` - time limit for just the connection phase (e.g. - # # handshake) (Integer in seconds) - # # - `:read_timeout` - time limit for the first response byte received from - # # the server (Integer in seconds) - # # - `:write_timeout` - time limit for the client to send the request to the - # # server (Integer in seconds) - # # - `:on_data` - Proc for streaming - # # - `:proxy` - Hash of proxy options - # # - `:uri` - Proxy server URI - # # - `:user` - Proxy server username - # # - `:password` - Proxy server password - # # - # # @!attribute request_headers - # # @return Hash HTTP Headers to be sent to the server. - # # - # # @!attribute ssl - # # @return Hash options for configuring SSL requests - # # - # # @!attribute parallel_manager - # # @return Object sent if the connection is in parallel mode - # # - # # @!attribute params - # # @return Hash - # # - # # @!attribute response - # # @return Response - # # - # # @!attribute response_headers - # # @return Hash HTTP headers from the server - # # - # # @!attribute status - # # @return Integer HTTP response status code - # # - # # @!attribute reason_phrase - # # @return String - # class Env < Options; end - Env = Options.new(:method, :request_body, :url, :request, - :request_headers, :ssl, :parallel_manager, :params, - :response, :response_headers, :status, - :reason_phrase, :response_body) do - const_set(:ContentLength, 'Content-Length') - const_set(:StatusesWithoutBody, Set.new(204, 304)) - const_set(:SuccessfulStatuses, (200..299).freeze) + # @!attribute method + # @return Symbol HTTP method (`:get`, `:post`) + # + # @!attribute body + # @return String The request body that will eventually be converted to a + # string. + # + # @!attribute url + # @return URI URI instance for the current request. + # + # @!attribute request + # @return Hash options for configuring the request. + # Options for configuring the request. + # + # - `:timeout` open/read timeout Integer in seconds + # - `:open_timeout` - read timeout Integer in seconds + # - `:on_data` - Proc for streaming + # - `:proxy` - Hash of proxy options + # - `:uri` - Proxy Server URI + # - `:user` - Proxy server username + # - `:password` - Proxy server password + # + # @!attribute request_headers + # @return Hash HTTP Headers to be sent to the server. + # + # @!attribute ssl + # @return Hash options for configuring SSL requests + # + # @!attribute parallel_manager + # @return Object sent if the connection is in parallel mode + # + # @!attribute params + # @return Hash + # + # @!attribute response + # @return Response + # + # @!attribute response_headers + # @return Hash HTTP headers from the server + # + # @!attribute status + # @return Integer HTTP response status code + # + # @!attribute reason_phrase + # @return String + class Env < Options.new(:method, :request_body, :url, :request, + :request_headers, :ssl, :parallel_manager, :params, + :response, :response_headers, :status, + :reason_phrase, :response_body) + + # rubocop:disable Naming/ConstantName + ContentLength = 'Content-Length' + StatusesWithoutBody = Set.new 204, 304 + SuccessfulStatuses = (200..299).freeze + # rubocop:enable Naming/ConstantName # A Set of HTTP verbs that typically send a body. If no body is set for # these requests, the Content-Length header is set to 0. - const_set(:MethodsWithBodies, Set.new(Faraday::METHODS_WITH_BODY.map(&:to_sym))) + MethodsWithBodies = Set.new(Faraday::METHODS_WITH_BODY.map(&:to_sym)) options request: RequestOptions, request_headers: Utils::Headers, response_headers: Utils::Headers @@ -125,25 +120,25 @@ # @return Boolean true if status is in the set of {SuccessfulStatuses}. def success? - Env::SuccessfulStatuses.include?(status) + SuccessfulStatuses.include?(status) end # @return Boolean true if there's no body yet, and the method is in the - # set of {Env::MethodsWithBodies}. + # set of {MethodsWithBodies}. def needs_body? - !body && Env::MethodsWithBodies.include?(method) + !body && MethodsWithBodies.include?(method) end # Sets content length to zero and the body to the empty string. def clear_body - request_headersEnv::ContentLength = '0' + request_headersContentLength = '0' self.body = +'' end # @return Boolean true if the status isn't in the set of - # {Env::StatusesWithoutBody}. + # {StatusesWithoutBody}. def parse_body? - !Env::StatusesWithoutBody.include?(status) + !StatusesWithoutBody.include?(status) end # @return Boolean true if there is a parallel_manager @@ -162,24 +157,6 @@ %(#<#{self.class}#{attrs.join(' ')}>) end - def stream_response? - request.stream_response? - end - - def stream_response(&block) - size = 0 - yielded = false - block_result = block.call do |chunk| # rubocop:disable Performance/RedundantBlockCall - if chunk.bytesize.positive? || size.positive? - yielded = true - size += chunk.bytesize - request.on_data.call(chunk, size, self) - end - end - request.on_data.call(+'', 0, self) unless yielded - block_result - end - # @private def custom_members @custom_members ||= {}
View file
faraday-2.7.11.gem/data/lib/faraday/options/proxy_options.rb -> faraday-1.0.0.gem/data/lib/faraday/options/proxy_options.rb
Changed
@@ -1,23 +1,16 @@ # frozen_string_literal: true module Faraday - # @!parse - # # ProxyOptions contains the configurable properties for the proxy - # # configuration used when making an HTTP request. - # class ProxyOptions < Options; end - ProxyOptions = Options.new(:uri, :user, :password) do + # ProxyOptions contains the configurable properties for the proxy + # configuration used when making an HTTP request. + class ProxyOptions < Options.new(:uri, :user, :password) extend Forwardable def_delegators :uri, :scheme, :scheme=, :host, :host=, :port, :port=, :path, :path= def self.from(value) case value - when '' - value = nil when String - # URIs without a scheme should default to http (like 'example:123'). - # This fixes #1282 and prevents a silent failure in some adapters. - value = "http://#{value}" unless value.include?('://') value = { uri: Utils.URI(value) } when URI value = { uri: value } @@ -26,7 +19,6 @@ value:uri = Utils.URI(uri) end end - super(value) end
View file
faraday-2.7.11.gem/data/lib/faraday/options/request_options.rb -> faraday-1.0.0.gem/data/lib/faraday/options/request_options.rb
Changed
@@ -1,13 +1,12 @@ # frozen_string_literal: true module Faraday - # @!parse - # # RequestOptions contains the configurable properties for a Faraday request. - # class RequestOptions < Options; end - RequestOptions = Options.new(:params_encoder, :proxy, :bind, - :timeout, :open_timeout, :read_timeout, - :write_timeout, :boundary, :oauth, - :context, :on_data) do + # RequestOptions contains the configurable properties for a Faraday request. + class RequestOptions < Options.new(:params_encoder, :proxy, :bind, + :timeout, :open_timeout, :read_timeout, + :write_timeout, :boundary, :oauth, + :context, :on_data) + def =(key, value) if key && key.to_sym == :proxy super(key, value ? ProxyOptions.from(value) : nil)
View file
faraday-2.7.11.gem/data/lib/faraday/options/ssl_options.rb -> faraday-1.0.0.gem/data/lib/faraday/options/ssl_options.rb
Changed
@@ -1,57 +1,51 @@ # frozen_string_literal: true module Faraday - # @!parse - # # SSL-related options. - # # - # # @!attribute verify - # # @return Boolean whether to verify SSL certificates or not - # # - # # @!attribute verify_hostname - # # @return Boolean whether to enable hostname verification on server certificates - # # during the handshake or not (see https://github.com/ruby/openssl/pull/60) - # # - # # @!attribute ca_file - # # @return String CA file - # # - # # @!attribute ca_path - # # @return String CA path - # # - # # @!attribute verify_mode - # # @return Integer Any `OpenSSL::SSL::` constant (see https://ruby-doc.org/stdlib-2.5.1/libdoc/openssl/rdoc/OpenSSL/SSL.html) - # # - # # @!attribute cert_store - # # @return OpenSSL::X509::Store certificate store - # # - # # @!attribute client_cert - # # @return String, OpenSSL::X509::Certificate client certificate - # # - # # @!attribute client_key - # # @return String, OpenSSL::PKey::RSA, OpenSSL::PKey::DSA client key - # # - # # @!attribute certificate - # # @return OpenSSL::X509::Certificate certificate (Excon only) - # # - # # @!attribute private_key - # # @return OpenSSL::PKey::RSA, OpenSSL::PKey::DSA private key (Excon only) - # # - # # @!attribute verify_depth - # # @return Integer maximum depth for the certificate chain verification - # # - # # @!attribute version - # # @return String, Symbol SSL version (see https://ruby-doc.org/stdlib-2.5.1/libdoc/openssl/rdoc/OpenSSL/SSL/SSLContext.html#method-i-ssl_version-3D) - # # - # # @!attribute min_version - # # @return String, Symbol minimum SSL version (see https://ruby-doc.org/stdlib-2.5.1/libdoc/openssl/rdoc/OpenSSL/SSL/SSLContext.html#method-i-min_version-3D) - # # - # # @!attribute max_version - # # @return String, Symbol maximum SSL version (see https://ruby-doc.org/stdlib-2.5.1/libdoc/openssl/rdoc/OpenSSL/SSL/SSLContext.html#method-i-max_version-3D) - # class SSLOptions < Options; end - SSLOptions = Options.new(:verify, :verify_hostname, - :ca_file, :ca_path, :verify_mode, - :cert_store, :client_cert, :client_key, - :certificate, :private_key, :verify_depth, - :version, :min_version, :max_version) do + # SSL-related options. + # + # @!attribute verify + # @return Boolean whether to verify SSL certificates or not + # + # @!attribute ca_file + # @return String CA file + # + # @!attribute ca_path + # @return String CA path + # + # @!attribute verify_mode + # @return Integer Any `OpenSSL::SSL::` constant (see https://ruby-doc.org/stdlib-2.5.1/libdoc/openssl/rdoc/OpenSSL/SSL.html) + # + # @!attribute cert_store + # @return OpenSSL::X509::Store certificate store + # + # @!attribute client_cert + # @return String, OpenSSL::X509::Certificate client certificate + # + # @!attribute client_key + # @return String, OpenSSL::PKey::RSA, OpenSSL::PKey::DSA client key + # + # @!attribute certificate + # @return OpenSSL::X509::Certificate certificate (Excon only) + # + # @!attribute private_key + # @return OpenSSL::PKey::RSA, OpenSSL::PKey::DSA private key (Excon only) + # + # @!attribute verify_depth + # @return Integer maximum depth for the certificate chain verification + # + # @!attribute version + # @return String, Symbol SSL version (see https://ruby-doc.org/stdlib-2.5.1/libdoc/openssl/rdoc/OpenSSL/SSL/SSLContext.html#method-i-ssl_version-3D) + # + # @!attribute min_version + # @return String, Symbol minimum SSL version (see https://ruby-doc.org/stdlib-2.5.1/libdoc/openssl/rdoc/OpenSSL/SSL/SSLContext.html#method-i-min_version-3D) + # + # @!attribute max_version + # @return String, Symbol maximum SSL version (see https://ruby-doc.org/stdlib-2.5.1/libdoc/openssl/rdoc/OpenSSL/SSL/SSLContext.html#method-i-max_version-3D) + class SSLOptions < Options.new(:verify, :ca_file, :ca_path, :verify_mode, + :cert_store, :client_cert, :client_key, + :certificate, :private_key, :verify_depth, + :version, :min_version, :max_version) + # @return Boolean true if should verify def verify? verify != false @@ -61,10 +55,5 @@ def disable? !verify? end - - # @return Boolean true if should verify_hostname - def verify_hostname? - verify_hostname != false - end end end
View file
faraday-1.0.0.gem/data/lib/faraday/param_part.rb
Added
@@ -0,0 +1,53 @@ +# frozen_string_literal: true + +module Faraday + # Multipart value used to POST data with a content type. + class ParamPart + # @param value String Uploaded content as a String. + # @param content_type String String content type of the value. + # @param content_id String Optional String of this value's Content-ID. + # + # @return Faraday::ParamPart + def initialize(value, content_type, content_id = nil) + @value = value + @content_type = content_type + @content_id = content_id + end + + # Converts this value to a form part. + # + # @param boundary String String multipart boundary that must not exist in + # the content exactly. + # @param key String String key name for this value. + # + # @return Faraday::Parts::Part + def to_part(boundary, key) + Faraday::Parts::Part.new(boundary, key, value, headers) + end + + # Returns a Hash of String key/value pairs. + # + # @return Hash + def headers + { + 'Content-Type' => content_type, + 'Content-ID' => content_id + } + end + + # The content to upload. + # + # @return String + attr_reader :value + + # The value's content type. + # + # @return String + attr_reader :content_type + + # The value's content ID, if given. + # + # @return String, nil + attr_reader :content_id + end +end
View file
faraday-2.7.11.gem/data/lib/faraday/rack_builder.rb -> faraday-1.0.0.gem/data/lib/faraday/rack_builder.rb
Changed
@@ -1,6 +1,5 @@ # frozen_string_literal: true -require 'ruby2_keywords' require 'faraday/adapter_registry' module Faraday @@ -8,7 +7,7 @@ # middleware stack (heavily inspired by Rack). # # @example - # Faraday::Connection.new(url: 'http://httpbingo.org') do |builder| + # Faraday::Connection.new(url: 'http://sushi.com') do |builder| # builder.request :url_encoded # Faraday::Request::UrlEncoded # builder.adapter :net_http # Faraday::Adapter::NetHttp # end @@ -28,7 +27,7 @@ attr_reader :name - ruby2_keywords def initialize(klass, *args, &block) + def initialize(klass, *args, &block) @name = klass.to_s REGISTRY.set(klass) if klass.respond_to?(:name) @args = args @@ -58,22 +57,23 @@ end end - def initialize(&block) - @adapter = nil - @handlers = - build(&block) - end - - def initialize_dup(original) - super - @adapter = original.adapter - @handlers = original.handlers.dup + def initialize(handlers = , adapter = nil, &block) + @adapter = adapter + @handlers = handlers + if block_given? + build(&block) + elsif @handlers.empty? + # default stack, if nothing else is configured + request :url_encoded + self.adapter Faraday.default_adapter + end end - def build + def build(options = {}) raise_if_locked - block_given? ? yield(self) : request(:url_encoded) - adapter(Faraday.default_adapter, **Faraday.default_adapter_options) unless @adapter + @handlers.clear unless options:keep + yield(self) if block_given? + adapter(Faraday.default_adapter) unless @adapter end def (idx) @@ -89,7 +89,7 @@ @handlers.frozen? end - ruby2_keywords def use(klass, *args, &block) + def use(klass, *args, &block) if klass.is_a? Symbol use_symbol(Faraday::Middleware, klass, *args, &block) else @@ -99,16 +99,16 @@ end end - ruby2_keywords def request(key, *args, &block) + def request(key, *args, &block) use_symbol(Faraday::Request, key, *args, &block) end - ruby2_keywords def response(key, *args, &block) + def response(key, *args, &block) use_symbol(Faraday::Response, key, *args, &block) end - ruby2_keywords def adapter(klass = NO_ARGUMENT, *args, &block) - return @adapter if klass == NO_ARGUMENT || klass.nil? + def adapter(klass = NO_ARGUMENT, *args, &block) + return @adapter if klass == NO_ARGUMENT klass = Faraday::Adapter.lookup_middleware(klass) if klass.is_a?(Symbol) @adapter = self.class::Handler.new(klass, *args, &block) @@ -116,7 +116,7 @@ ## methods to push onto the various positions in the stack: - ruby2_keywords def insert(index, *args, &block) + def insert(index, *args, &block) raise_if_locked index = assert_index(index) handler = self.class::Handler.new(*args, &block) @@ -125,12 +125,12 @@ alias insert_before insert - ruby2_keywords def insert_after(index, *args, &block) + def insert_after(index, *args, &block) index = assert_index(index) insert(index + 1, *args, &block) end - ruby2_keywords def swap(index, *args, &block) + def swap(index, *args, &block) raise_if_locked index = assert_index(index) @handlers.delete_at(index) @@ -163,7 +163,6 @@ def app @app ||= begin lock! - ensure_adapter! to_app end end @@ -182,8 +181,12 @@ @adapter == other.adapter end + def dup + self.class.new(@handlers.dup, @adapter.dup) + end + # ENV Keys - # :http_method - a symbolized request HTTP method (:get, :post) + # :method - a symbolized request method (:get, :post) # :body - the request body that will eventually be converted to a string. # :url - URI instance for the current request. # :status - HTTP response status code @@ -204,7 +207,7 @@ request.options.params_encoder ) - Env.new(request.http_method, request.body, exclusive_url, + Env.new(request.method, request.body, exclusive_url, request.options, request.headers, connection.ssl, connection.parallel_manager) end @@ -212,9 +215,6 @@ private LOCK_ERR = "can't modify middleware stack after making a request" - MISSING_ADAPTER_ERROR = "An attempt to run a request with a Faraday::Connection without adapter has been made.\n" \ - "Please set Faraday.default_adapter or provide one when initializing the connection.\n" \ - 'For more info, check https://lostisland.github.io/faraday/usage/.' def raise_if_locked raise StackLocked, LOCK_ERR if locked? @@ -226,19 +226,15 @@ raise 'Adapter should be set using the `adapter` method, not `use`' end - def ensure_adapter! - raise MISSING_ADAPTER_ERROR unless @adapter - end - def adapter_set? !@adapter.nil? end def is_adapter?(klass) # rubocop:disable Naming/PredicateName - klass <= Faraday::Adapter + klass.ancestors.include?(Faraday::Adapter) end - ruby2_keywords def use_symbol(mod, key, *args, &block) + def use_symbol(mod, key, *args, &block) use(mod.lookup_middleware(key), *args, &block) end
View file
faraday-2.7.11.gem/data/lib/faraday/request.rb -> faraday-1.0.0.gem/data/lib/faraday/request.rb
Changed
@@ -12,7 +12,7 @@ # req.body = 'abc' # end # - # @!attribute http_method + # @!attribute method # @return Symbol the HTTP method of the Request # @!attribute path # @return URI, String the path @@ -21,16 +21,30 @@ # @!attribute headers # @return Faraday::Utils::Headers headers # @!attribute body - # @return String body + # @return Hash body # @!attribute options # @return RequestOptions options - Request = Struct.new(:http_method, :path, :params, :headers, :body, :options) do + # + # rubocop:disable Style/StructInheritance + class Request < Struct.new(:method, :path, :params, :headers, :body, :options) + # rubocop:enable Style/StructInheritance + extend MiddlewareRegistry - alias_method :member_get, : - private :member_get - alias_method :member_set, := - private :member_set + register_middleware File.expand_path('request', __dir__), + url_encoded: :UrlEncoded, 'url_encoded', + multipart: :Multipart, 'multipart', + retry: :Retry, 'retry', + authorization: :Authorization, 'authorization', + basic_auth: + :BasicAuthentication, + 'basic_authentication' + , + token_auth: + :TokenAuthentication, + 'token_authentication' + , + instrumentation: :Instrumentation, 'instrumentation' # @param request_method String # @yield request for block customization, if block given @@ -42,7 +56,6 @@ end end - remove_method :params= # Replace params, preserving the existing hash type. # # @param hash Hash new params @@ -50,11 +63,10 @@ if params params.replace hash else - member_set(:params, hash) + super end end - remove_method :headers= # Replace request headers, preserving the existing hash type. # # @param hash Hash new headers @@ -62,7 +74,7 @@ if headers headers.replace hash else - member_set(:headers, hash) + super end end @@ -104,7 +116,7 @@ # @return Hash the hash ready to be serialized in Marshal. def marshal_dump { - http_method: http_method, + method: method, body: body, headers: headers, path: path, @@ -117,23 +129,18 @@ # Restores the instance variables according to the +serialised+. # @param serialised Hash the serialised object. def marshal_load(serialised) - self.http_method = serialised:http_method - self.body = serialised:body + self.method = serialised:method + self.body = serialised:body self.headers = serialised:headers - self.path = serialised:path - self.params = serialised:params + self.path = serialised:path + self.params = serialised:params self.options = serialised:options end # @return Env the Env for this Request def to_env(connection) - Env.new(http_method, body, connection.build_exclusive_url(path, params), + Env.new(method, body, connection.build_exclusive_url(path, params), options, headers, connection.ssl, connection.parallel_manager) end end end - -require 'faraday/request/authorization' -require 'faraday/request/instrumentation' -require 'faraday/request/json' -require 'faraday/request/url_encoded'
View file
faraday-2.7.11.gem/data/lib/faraday/request/authorization.rb -> faraday-1.0.0.gem/data/lib/faraday/request/authorization.rb
Changed
@@ -4,51 +4,50 @@ class Request # Request middleware for the Authorization HTTP header class Authorization < Faraday::Middleware - KEY = 'Authorization' + KEY = 'Authorization' unless defined? KEY - # @param app #call - # @param type String, Symbol Type of Authorization - # @param params Array<String, Proc, #call> parameters to build the Authorization header. - # If the type is `:basic`, then these can be a login and password pair. - # Otherwise, a single value is expected that will be appended after the type. - # This value can be a proc or an object responding to `.call`, in which case - # it will be invoked on each request. - def initialize(app, type, *params) - @type = type - @params = params - super(app) + # @param type String, Symbol + # @param token String, Symbol, Hash + # @return String a header value + def self.header(type, token) + case token + when String, Symbol + "#{type} #{token}" + when Hash + build_hash(type.to_s, token) + else + raise ArgumentError, + "Can't build an Authorization #{type}" \ + "header from #{token.inspect}" + end end - # @param env Faraday::Env - def on_request(env) - return if env.request_headersKEY - - env.request_headersKEY = header_from(@type, env, *@params) + # @param type String + # @param hash Hash + # @return String type followed by comma-separated key=value pairs + # @api private + def self.build_hash(type, hash) + comma = ', ' + values = + hash.each do |key, value| + values << "#{key}=#{value.to_s.inspect}" + end + "#{type} #{values * comma}" end - private + # @param app #call + # @param type String, Symbol Type of Authorization + # @param token String, Symbol, Hash Token value for the Authorization + def initialize(app, type, token) + @header_value = self.class.header(type, token) + super(app) + end - # @param type String, Symbol # @param env Faraday::Env - # @param params Array - # @return String a header value - def header_from(type, env, *params) - if type.to_s.casecmp('basic').zero? && params.size == 2 - Utils.basic_header_from(*params) - elsif params.size != 1 - raise ArgumentError, "Unexpected params received (got #{params.size} instead of 1)" - else - value = params.first - if (value.is_a?(Proc) && value.arity == 1) || (value.respond_to?(:call) && value.method(:call).arity == 1) - value = value.call(env) - elsif value.is_a?(Proc) || value.respond_to?(:call) - value = value.call - end - "#{type} #{value}" - end + def call(env) + env.request_headersKEY = @header_value unless env.request_headersKEY + @app.call(env) end end end end - -Faraday::Request.register_middleware(authorization: Faraday::Request::Authorization)
View file
faraday-1.0.0.gem/data/lib/faraday/request/basic_authentication.rb
Added
@@ -0,0 +1,20 @@ +# frozen_string_literal: true + +require 'base64' + +module Faraday + class Request + # Authorization middleware for Basic Authentication. + class BasicAuthentication < load_middleware(:authorization) + # @param login String + # @param pass String + # + # @return String a Basic Authentication header line + def self.header(login, pass) + value = Base64.encode64(login, pass.join(':')) + value.delete!("\n") + super(:Basic, value) + end + end + end +end
View file
faraday-2.7.11.gem/data/lib/faraday/request/instrumentation.rb -> faraday-1.0.0.gem/data/lib/faraday/request/instrumentation.rb
Changed
@@ -5,14 +5,12 @@ # Middleware for instrumenting Requests. class Instrumentation < Faraday::Middleware # Options class used in Request::Instrumentation class. - Options = Faraday::Options.new(:name, :instrumenter) do - remove_method :name + class Options < Faraday::Options.new(:name, :instrumenter) # @return String def name self:name ||= 'request.faraday' end - remove_method :instrumenter # @return Class def instrumenter self:instrumenter ||= ActiveSupport::Notifications @@ -54,5 +52,3 @@ end end end - -Faraday::Request.register_middleware(instrumentation: Faraday::Request::Instrumentation)
View file
faraday-1.0.0.gem/data/lib/faraday/request/multipart.rb
Added
@@ -0,0 +1,99 @@ +# frozen_string_literal: true + +require File.expand_path('url_encoded', __dir__) +require 'securerandom' + +module Faraday + class Request + # Middleware for supporting multi-part requests. + class Multipart < UrlEncoded + self.mime_type = 'multipart/form-data' + unless defined? DEFAULT_BOUNDARY_PREFIX + DEFAULT_BOUNDARY_PREFIX = '-----------RubyMultipartPost' + end + + # Checks for files in the payload, otherwise leaves everything untouched. + # + # @param env Faraday::Env + def call(env) + match_content_type(env) do |params| + env.request.boundary ||= unique_boundary + env.request_headersCONTENT_TYPE += + "; boundary=#{env.request.boundary}" + env.body = create_multipart(env, params) + end + @app.call env + end + + # @param env Faraday::Env + def process_request?(env) + type = request_type(env) + env.body.respond_to?(:each_key) && !env.body.empty? && ( + (type.empty? && has_multipart?(env.body)) || + (type == self.class.mime_type) + ) + end + + # Returns true if obj is an enumerable with values that are multipart. + # + # @param obj Object + # @return Boolean + def has_multipart?(obj) # rubocop:disable Naming/PredicateName + if obj.respond_to?(:each) + (obj.respond_to?(:values) ? obj.values : obj).each do |val| + return true if val.respond_to?(:content_type) || has_multipart?(val) + end + end + false + end + + # @param env Faraday::Env + # @param params Hash + def create_multipart(env, params) + boundary = env.request.boundary + parts = process_params(params) do |key, value| + part(boundary, key, value) + end + parts << Faraday::Parts::EpiloguePart.new(boundary) + + body = Faraday::CompositeReadIO.new(parts) + env.request_headersFaraday::Env::ContentLength = body.length.to_s + body + end + + def part(boundary, key, value) + if value.respond_to?(:to_part) + value.to_part(boundary, key) + else + Faraday::Parts::Part.new(boundary, key, value) + end + end + + # @return String + def unique_boundary + "#{DEFAULT_BOUNDARY_PREFIX}-#{SecureRandom.hex}" + end + + # @param params Hash + # @param prefix String + # @param pieces Array + def process_params(params, prefix = nil, pieces = nil, &block) + params.inject(pieces || ) do |all, (key, value)| + key = "#{prefix}#{key}" if prefix + + case value + when Array + values = value.inject() { |a, v| a << nil, v } + process_params(values, key, all, &block) + when Hash + process_params(value, key, all, &block) + else + # rubocop:disable Performance/RedundantBlockCall + all << block.call(key, value) + # rubocop:enable Performance/RedundantBlockCall + end + end + end + end + end +end
View file
faraday-1.0.0.gem/data/lib/faraday/request/retry.rb
Added
@@ -0,0 +1,239 @@ +# frozen_string_literal: true + +module Faraday + class Request + # Catches exceptions and retries each request a limited number of times. + # + # By default, it retries 2 times and handles only timeout exceptions. It can + # be configured with an arbitrary number of retries, a list of exceptions to + # handle, a retry interval, a percentage of randomness to add to the retry + # interval, and a backoff factor. + # + # @example Configure Retry middleware using intervals + # Faraday.new do |conn| + # conn.request(:retry, max: 2, + # interval: 0.05, + # interval_randomness: 0.5, + # backoff_factor: 2, + # exceptions: CustomException, 'Timeout::Error') + # + # conn.adapter(:net_http) # NB: Last middleware must be the adapter + # end + # + # This example will result in a first interval that is random between 0.05 + # and 0.075 and a second interval that is random between 0.1 and 0.15. + class Retry < Faraday::Middleware + DEFAULT_EXCEPTIONS = + Errno::ETIMEDOUT, 'Timeout::Error', + Faraday::TimeoutError, Faraday::RetriableResponse + .freeze + IDEMPOTENT_METHODS = %idelete get head options put.freeze + + # Options contains the configurable parameters for the Retry middleware. + class Options < Faraday::Options.new(:max, :interval, :max_interval, + :interval_randomness, + :backoff_factor, :exceptions, + :methods, :retry_if, :retry_block, + :retry_statuses) + + DEFAULT_CHECK = ->(_env, _exception) { false } + + def self.from(value) + if value.is_a?(Integer) + new(value) + else + super(value) + end + end + + def max + (self:max ||= 2).to_i + end + + def interval + (self:interval ||= 0).to_f + end + + def max_interval + (self:max_interval ||= Float::MAX).to_f + end + + def interval_randomness + (self:interval_randomness ||= 0).to_f + end + + def backoff_factor + (self:backoff_factor ||= 1).to_f + end + + def exceptions + Array(self:exceptions ||= DEFAULT_EXCEPTIONS) + end + + def methods + Array(self:methods ||= IDEMPOTENT_METHODS) + end + + def retry_if + self:retry_if ||= DEFAULT_CHECK + end + + def retry_block + self:retry_block ||= proc {} + end + + def retry_statuses + Array(self:retry_statuses ||= ) + end + end + + # @param app #call + # @param options Hash + # @option options Integer :max (2) Maximum number of retries + # @option options Integer :interval (0) Pause in seconds between retries + # @option options Integer :interval_randomness (0) The maximum random + # interval amount expressed as a float between + # 0 and 1 to use in addition to the interval. + # @option options Integer :max_interval (Float::MAX) An upper limit + # for the interval + # @option options Integer :backoff_factor (1) The amount to multiply + # each successive retry's interval amount by in order to provide backoff + # @option options Array :exceptions ( Errno::ETIMEDOUT, + # 'Timeout::Error', Faraday::TimeoutError, Faraday::RetriableResponse) + # The list of exceptions to handle. Exceptions can be given as + # Class, Module, or String. + # @option options Array :methods (the idempotent HTTP methods + # in IDEMPOTENT_METHODS) A list of HTTP methods to retry without + # calling retry_if. Pass an empty Array to call retry_if + # for all exceptions. + # @option options Block :retry_if (false) block that will receive + # the env object and the exception raised + # and should decide if the code should retry still the action or + # not independent of the retry count. This would be useful + # if the exception produced is non-recoverable or if the + # the HTTP method called is not idempotent. + # @option options Block :retry_block block that is executed after + # every retry. Request environment, middleware options, current number + # of retries and the exception is passed to the block as parameters. + # @option options Array :retry_statuses Array of Integer HTTP status + # codes or a single Integer value that determines whether to raise + # a Faraday::RetriableResponse exception based on the HTTP status code + # of an HTTP response. + def initialize(app, options = nil) + super(app) + @options = Options.from(options) + @errmatch = build_exception_matcher(@options.exceptions) + end + + def calculate_sleep_amount(retries, env) + retry_after = calculate_retry_after(env) + retry_interval = calculate_retry_interval(retries) + + return if retry_after && retry_after > @options.max_interval + + if retry_after && retry_after >= retry_interval + retry_after + else + retry_interval + end + end + + # @param env Faraday::Env + def call(env) + retries = @options.max + request_body = env:body + begin + # after failure env:body is set to the response body + env:body = request_body + @app.call(env).tap do |resp| + if @options.retry_statuses.include?(resp.status) + raise Faraday::RetriableResponse.new(nil, resp) + end + end + rescue @errmatch => e + if retries.positive? && retry_request?(env, e) + retries -= 1 + rewind_files(request_body) + @options.retry_block.call(env, @options, retries, e) + if (sleep_amount = calculate_sleep_amount(retries + 1, env)) + sleep sleep_amount + retry + end + end + + raise unless e.is_a?(Faraday::RetriableResponse) + + e.response + end + end + + # An exception matcher for the rescue clause can usually be any object + # that responds to `===`, but for Ruby 1.8 it has to be a Class or Module. + # + # @param exceptions Array + # @api private + # @return Module an exception matcher + def build_exception_matcher(exceptions) + matcher = Module.new + ( + class << matcher + self + end).class_eval do + define_method(:===) do |error| + exceptions.any? do |ex| + if ex.is_a? Module + error.is_a? ex + else + error.class.to_s == ex.to_s + end + end + end + end + matcher + end + + private + + def retry_request?(env, exception) + @options.methods.include?(env:method) || + @options.retry_if.call(env, exception)
View file
faraday-1.0.0.gem/data/lib/faraday/request/token_authentication.rb
Added
@@ -0,0 +1,20 @@ +# frozen_string_literal: true + +module Faraday + class Request + # TokenAuthentication is a middleware that adds a 'Token' header to a + # Faraday request. + class TokenAuthentication < load_middleware(:authorization) + # Public + def self.header(token, options = nil) + options ||= {} + options:token = token + super(:Token, options) + end + + def initialize(app, token, options = nil) + super(app, token, options) + end + end + end +end
View file
faraday-2.7.11.gem/data/lib/faraday/request/url_encoded.rb -> faraday-1.0.0.gem/data/lib/faraday/request/url_encoded.rb
Changed
@@ -4,9 +4,7 @@ class Request # Middleware for supporting urlencoded requests. class UrlEncoded < Faraday::Middleware - unless defined?(::Faraday::Request::UrlEncoded::CONTENT_TYPE) - CONTENT_TYPE = 'Content-Type' - end + CONTENT_TYPE = 'Content-Type' unless defined? CONTENT_TYPE class << self attr_accessor :mime_type @@ -31,9 +29,7 @@ return unless process_request?(env) env.request_headersCONTENT_TYPE ||= self.class.mime_type - return if env.body.respond_to?(:to_str) || env.body.respond_to?(:read) - - yield(env.body) + yield(env.body) unless env.body.respond_to?(:to_str) end # @param env Faraday::Env @@ -56,5 +52,3 @@ end end end - -Faraday::Request.register_middleware(url_encoded: Faraday::Request::UrlEncoded)
View file
faraday-2.7.11.gem/data/lib/faraday/response.rb -> faraday-1.0.0.gem/data/lib/faraday/response.rb
Changed
@@ -5,9 +5,28 @@ module Faraday # Response represents an HTTP response from making an HTTP request. class Response + # Used for simple response middleware. + class Middleware < Faraday::Middleware + def call(env) + @app.call(env).on_complete do |environment| + on_complete(environment) + end + end + + # Override this to modify the environment after the response has finished. + # Calls the `parse` method if defined + def on_complete(env) + env.body = parse(env.body) if respond_to?(:parse) && env.parse_body? + end + end + extend Forwardable extend MiddlewareRegistry + register_middleware File.expand_path('response', __dir__), + raise_error: :RaiseError, 'raise_error', + logger: :Logger, 'logger' + def initialize(env = nil) @env = Env.from(env) if env @on_complete_callbacks = @@ -26,7 +45,6 @@ def headers finished? ? env.response_headers : {} end - def_delegator :headers, : def body @@ -38,10 +56,10 @@ end def on_complete(&block) - if finished? - yield(env) - else + if !finished? @on_complete_callbacks << block + else + yield(env) end self end @@ -61,8 +79,7 @@ def to_hash { status: env.status, body: env.body, - response_headers: env.response_headers, - url: env.url + response_headers: env.response_headers } end @@ -85,7 +102,3 @@ end end end - -require 'faraday/response/json' -require 'faraday/response/logger' -require 'faraday/response/raise_error'
View file
faraday-2.7.11.gem/data/lib/faraday/response/logger.rb -> faraday-1.0.0.gem/data/lib/faraday/response/logger.rb
Changed
@@ -1,7 +1,6 @@ # frozen_string_literal: true require 'forwardable' -require 'logger' require 'faraday/logging/formatter' module Faraday @@ -12,7 +11,10 @@ class Logger < Middleware def initialize(app, logger = nil, options = {}) super(app) - logger ||= ::Logger.new($stdout) + logger ||= begin + require 'logger' + ::Logger.new($stdout) + end formatter_class = options.delete(:formatter) || Logging::Formatter @formatter = formatter_class.new(logger: logger, options: options) yield @formatter if block_given? @@ -26,12 +28,6 @@ def on_complete(env) @formatter.response(env) end - - def on_error(exc) - @formatter.exception(exc) if @formatter.respond_to?(:exception) - end end end end - -Faraday::Response.register_middleware(logger: Faraday::Response::Logger)
View file
faraday-2.7.11.gem/data/lib/faraday/response/raise_error.rb -> faraday-1.0.0.gem/data/lib/faraday/response/raise_error.rb
Changed
@@ -24,8 +24,6 @@ # mimic the behavior that we get with proxy requests with HTTPS msg = %(407 "Proxy Authentication Required") raise Faraday::ProxyAuthError.new(msg, response_values(env)) - when 408 - raise Faraday::RequestTimeoutError, response_values(env) when 409 raise Faraday::ConflictError, response_values(env) when 422 @@ -39,43 +37,9 @@ end end - # Returns a hash of response data with the following keys: - # - status - # - headers - # - body - # - request - # - # The `request` key is omitted when the middleware is explicitly - # configured with the option `include_request: false`. def response_values(env) - response = { - status: env.status, - headers: env.response_headers, - body: env.body - } - - # Include the request data by default. If the middleware was explicitly - # configured to _not_ include request data, then omit it. - return response unless options.fetch(:include_request, true) - - response.merge( - request: { - method: env.method, - url: env.url, - url_path: env.url.path, - params: query_params(env), - headers: env.request_headers, - body: env.request_body - } - ) - end - - def query_params(env) - env.request.params_encoder ||= Faraday::Utils.default_params_encoder - env.params_encoder.decode(env.url.query) + { status: env.status, headers: env.response_headers, body: env.body } end end end end - -Faraday::Response.register_middleware(raise_error: Faraday::Response::RaiseError)
View file
faraday-2.7.11.gem/data/lib/faraday/utils.rb -> faraday-1.0.0.gem/data/lib/faraday/utils.rb
Changed
@@ -1,7 +1,5 @@ # frozen_string_literal: true -require 'base64' -require 'uri' require 'faraday/utils/headers' require 'faraday/utils/params_hash' @@ -18,20 +16,12 @@ NestedParamsEncoder.encode(params) end - def default_space_encoding - @default_space_encoding ||= '+' - end - - class << self - attr_writer :default_space_encoding - end - ESCAPE_RE = /^a-zA-Z0-9 .~_-/.freeze def escape(str) str.to_s.gsub(ESCAPE_RE) do |match| - "%#{match.unpack('H2' * match.bytesize).join('%').upcase}" - end.gsub(' ', default_space_encoding) + '%' + match.unpack('H2' * match.bytesize).join('%').upcase + end.tr(' ', '+') end def unescape(str) @@ -53,12 +43,6 @@ @default_params_encoder ||= NestedParamsEncoder end - def basic_header_from(login, pass) - value = Base64.encode64("#{login}:#{pass}") - value.delete!("\n") - "Basic #{value}" - end - class << self attr_writer :default_params_encoder end @@ -79,7 +63,10 @@ end def default_uri_parser - @default_uri_parser ||= Kernel.method(:URI) + @default_uri_parser ||= begin + require 'uri' + Kernel.method(:URI) + end end def default_uri_parser=(parser) @@ -94,14 +81,14 @@ # the path with the query string sorted. def normalize_path(url) url = URI(url) - (url.path.start_with?('/') ? url.path : "/#{url.path}") + + (url.path.start_with?('/') ? url.path : '/' + url.path) + (url.query ? "?#{sort_query_params(url.query)}" : '') end # Recursive hash update def deep_merge!(target, hash) hash.each do |key, value| - targetkey = if value.is_a?(Hash) && (targetkey.is_a?(Hash) || targetkey.is_a?(Options)) + targetkey = if value.is_a?(Hash) && targetkey.is_a?(Hash) deep_merge(targetkey, value) else value
View file
faraday-2.7.11.gem/data/lib/faraday/utils/headers.rb -> faraday-1.0.0.gem/data/lib/faraday/utils/headers.rb
Changed
@@ -105,16 +105,16 @@ end def to_hash - {}.update(self) + ::Hash.new.update(self) end def parse(header_string) return unless header_string && !header_string.empty? - headers = header_string.split("\r\n") + headers = header_string.split(/\r\n/) # Find the last set of response headers. - start_index = headers.rindex { |x| x.start_with?('HTTP/') } || 0 + start_index = headers.rindex { |x| x.match(%r{^HTTP/}) } || 0 last_response = headers.slice(start_index, headers.size) last_response @@ -132,12 +132,7 @@ # Join multiple values with a comma. def add_parsed(key, value) - if key?(key) - selfkey = selfkey.to_s - selfkey << ', ' << value - else - selfkey = value - end + selfkey ? selfkey << ', ' << value : selfkey = value end end end
View file
faraday-1.0.0.gem/data/spec/faraday/adapter/em_http_spec.rb
Added
@@ -0,0 +1,47 @@ +# frozen_string_literal: true + +RSpec.describe Faraday::Adapter::EMHttp do + features :request_body_on_query_methods, :reason_phrase_parse, :trace_method, + :skip_response_body_on_head, :parallel, :local_socket_binding + + it_behaves_like 'an adapter' + + it 'allows to provide adapter specific configs' do + url = URI('https://example.com:1234') + adapter = described_class.new nil, inactivity_timeout: 20 + req = adapter.create_request(url: url, request: {}) + + expect(req.connopts.inactivity_timeout).to eq(20) + end + + context 'Options' do + let(:request) { Faraday::RequestOptions.new } + let(:env) { { request: request } } + let(:options) { {} } + let(:adapter) { Faraday::Adapter::EMHttp.new } + + it 'configures timeout' do + request.timeout = 5 + adapter.configure_timeout(options, env) + expect(options:inactivity_timeout).to eq(5) + expect(options:connect_timeout).to eq(5) + end + + it 'configures timeout and open_timeout' do + request.timeout = 5 + request.open_timeout = 1 + adapter.configure_timeout(options, env) + expect(options:inactivity_timeout).to eq(5) + expect(options:connect_timeout).to eq(1) + end + + it 'configures all timeout settings' do + request.timeout = 5 + request.read_timeout = 3 + request.open_timeout = 1 + adapter.configure_timeout(options, env) + expect(options:inactivity_timeout).to eq(3) + expect(options:connect_timeout).to eq(1) + end + end +end
View file
faraday-1.0.0.gem/data/spec/faraday/adapter/em_synchrony_spec.rb
Added
@@ -0,0 +1,16 @@ +# frozen_string_literal: true + +RSpec.describe Faraday::Adapter::EMSynchrony do + features :request_body_on_query_methods, :reason_phrase_parse, + :skip_response_body_on_head, :parallel, :local_socket_binding + + it_behaves_like 'an adapter' + + it 'allows to provide adapter specific configs' do + url = URI('https://example.com:1234') + adapter = described_class.new nil, inactivity_timeout: 20 + req = adapter.create_request(url: url, request: {}) + + expect(req.connopts.inactivity_timeout).to eq(20) + end +end
View file
faraday-1.0.0.gem/data/spec/faraday/adapter/excon_spec.rb
Added
@@ -0,0 +1,49 @@ +# frozen_string_literal: true + +RSpec.describe Faraday::Adapter::Excon do + features :request_body_on_query_methods, :reason_phrase_parse, :trace_method + + it_behaves_like 'an adapter' + + it 'allows to provide adapter specific configs' do + url = URI('https://example.com:1234') + + adapter = described_class.new(nil, debug_request: true) + + conn = adapter.build_connection(url: url) + + expect(conn.data:debug_request).to be_truthy + end + + context 'config' do + let(:adapter) { Faraday::Adapter::Excon.new } + let(:request) { Faraday::RequestOptions.new } + let(:uri) { URI.parse('https://example.com') } + let(:env) { { request: request, url: uri } } + + it 'sets timeout' do + request.timeout = 5 + options = adapter.send(:opts_from_env, env) + expect(options:read_timeout).to eq(5) + expect(options:write_timeout).to eq(5) + expect(options:connect_timeout).to eq(5) + end + + it 'sets timeout and open_timeout' do + request.timeout = 5 + request.open_timeout = 3 + options = adapter.send(:opts_from_env, env) + expect(options:read_timeout).to eq(5) + expect(options:write_timeout).to eq(5) + expect(options:connect_timeout).to eq(3) + end + + it 'sets open_timeout' do + request.open_timeout = 3 + options = adapter.send(:opts_from_env, env) + expect(options:read_timeout).to eq(nil) + expect(options:write_timeout).to eq(nil) + expect(options:connect_timeout).to eq(3) + end + end +end
View file
faraday-1.0.0.gem/data/spec/faraday/adapter/httpclient_spec.rb
Added
@@ -0,0 +1,73 @@ +# frozen_string_literal: true + +RSpec.describe Faraday::Adapter::HTTPClient do + # ruby gem defaults for testing purposes + HTTPCLIENT_OPEN = 60 + HTTPCLIENT_READ = 60 + HTTPCLIENT_WRITE = 120 + + features :request_body_on_query_methods, :reason_phrase_parse, :compression, + :trace_method, :local_socket_binding + + it_behaves_like 'an adapter' + + it 'allows to provide adapter specific configs' do + adapter = described_class.new do |client| + client.keep_alive_timeout = 20 + client.ssl_config.timeout = 25 + end + + client = adapter.build_connection(url: URI.parse('https://example.com')) + expect(client.keep_alive_timeout).to eq(20) + expect(client.ssl_config.timeout).to eq(25) + end + + context 'Options' do + let(:request) { Faraday::RequestOptions.new } + let(:env) { { request: request } } + let(:options) { {} } + let(:adapter) { Faraday::Adapter::HTTPClient.new } + let(:client) { adapter.connection(url: URI.parse('https://example.com')) } + + it 'configures timeout' do + assert_default_timeouts! + + request.timeout = 5 + adapter.configure_timeouts(client, request) + + expect(client.connect_timeout).to eq(5) + expect(client.send_timeout).to eq(5) + expect(client.receive_timeout).to eq(5) + end + + it 'configures open timeout' do + assert_default_timeouts! + + request.open_timeout = 1 + adapter.configure_timeouts(client, request) + + expect(client.connect_timeout).to eq(1) + expect(client.send_timeout).to eq(HTTPCLIENT_WRITE) + expect(client.receive_timeout).to eq(HTTPCLIENT_READ) + end + + it 'configures multiple timeouts' do + assert_default_timeouts! + + request.open_timeout = 1 + request.write_timeout = 10 + request.read_timeout = 5 + adapter.configure_timeouts(client, request) + + expect(client.connect_timeout).to eq(1) + expect(client.send_timeout).to eq(10) + expect(client.receive_timeout).to eq(5) + end + + def assert_default_timeouts! + expect(client.connect_timeout).to eq(HTTPCLIENT_OPEN) + expect(client.send_timeout).to eq(HTTPCLIENT_WRITE) + expect(client.receive_timeout).to eq(HTTPCLIENT_READ) + end + end +end
View file
faraday-1.0.0.gem/data/spec/faraday/adapter/net_http_persistent_spec.rb
Added
@@ -0,0 +1,57 @@ +# frozen_string_literal: true + +RSpec.describe Faraday::Adapter::NetHttpPersistent do + features :request_body_on_query_methods, :reason_phrase_parse, :compression, :trace_method + + it_behaves_like 'an adapter' + + it 'allows to provide adapter specific configs' do + url = URI('https://example.com') + + adapter = described_class.new do |http| + http.idle_timeout = 123 + end + + http = adapter.send(:connection, url: url, request: {}) + adapter.send(:configure_request, http, {}) + + expect(http.idle_timeout).to eq(123) + end + + it 'sets max_retries to 0' do + url = URI('http://example.com') + + adapter = described_class.new + + http = adapter.send(:connection, url: url, request: {}) + adapter.send(:configure_request, http, {}) + + # `max_retries=` is only present in Ruby 2.5 + expect(http.max_retries).to eq(0) if http.respond_to?(:max_retries=) + end + + it 'allows to set pool_size on initialize' do + url = URI('https://example.com') + + adapter = described_class.new(nil, pool_size: 5) + + http = adapter.send(:connection, url: url, request: {}) + + # `pool` is only present in net_http_persistent >= 3.0 + expect(http.pool.size).to eq(5) if http.respond_to?(:pool) + end + + context 'min_version' do + it 'allows to set min_version in SSL settings' do + url = URI('https://example.com') + + adapter = described_class.new(nil) + + http = adapter.send(:connection, url: url, request: {}) + adapter.send(:configure_ssl, http, min_version: :TLS1_2) + + # `min_version` is only present in net_http_persistent >= 3.1 (UNRELEASED) + expect(http.min_version).to eq(:TLS1_2) if http.respond_to?(:min_version) + end + end +end
View file
faraday-1.0.0.gem/data/spec/faraday/adapter/net_http_spec.rb
Added
@@ -0,0 +1,64 @@ +# frozen_string_literal: true + +RSpec.describe Faraday::Adapter::NetHttp do + features :request_body_on_query_methods, :reason_phrase_parse, :compression, :streaming, :trace_method + + it_behaves_like 'an adapter' + + context 'checking http' do + let(:url) { URI('http://example.com') } + let(:adapter) { described_class.new } + let(:http) { adapter.send(:connection, url: url, request: {}) } + + it { expect(http.port).to eq(80) } + + it 'sets max_retries to 0' do + adapter.send(:configure_request, http, {}) + + expect(http.max_retries).to eq(0) if http.respond_to?(:max_retries=) + end + + it 'supports write_timeout' do + adapter.send(:configure_request, http, write_timeout: 10) + + expect(http.write_timeout).to eq(10) if http.respond_to?(:write_timeout=) + end + + it 'supports open_timeout' do + adapter.send(:configure_request, http, open_timeout: 10) + + expect(http.open_timeout).to eq(10) + end + + it 'supports read_timeout' do + adapter.send(:configure_request, http, read_timeout: 10) + + expect(http.read_timeout).to eq(10) + end + + context 'with https url' do + let(:url) { URI('https://example.com') } + + it { expect(http.port).to eq(443) } + end + + context 'with http url including port' do + let(:url) { URI('https://example.com:1234') } + + it { expect(http.port).to eq(1234) } + end + + context 'with custom adapter config' do + let(:adapter) do + described_class.new do |http| + http.continue_timeout = 123 + end + end + + it do + adapter.send(:configure_request, http, {}) + expect(http.continue_timeout).to eq(123) + end + end + end +end
View file
faraday-1.0.0.gem/data/spec/faraday/adapter/patron_spec.rb
Added
@@ -0,0 +1,18 @@ +# frozen_string_literal: true + +RSpec.describe Faraday::Adapter::Patron do + features :reason_phrase_parse + + it_behaves_like 'an adapter' + + it 'allows to provide adapter specific configs' do + conn = Faraday.new do |f| + f.adapter :patron do |session| + session.max_redirects = 10 + raise 'Configuration block called' + end + end + + expect { conn.get('/') }.to raise_error(RuntimeError, 'Configuration block called') + end +end
View file
faraday-1.0.0.gem/data/spec/faraday/adapter/rack_spec.rb
Added
@@ -0,0 +1,8 @@ +# frozen_string_literal: true + +RSpec.describe Faraday::Adapter::Rack do + features :request_body_on_query_methods, :trace_method, + :skip_response_body_on_head + + it_behaves_like 'an adapter', adapter_options: WebmockRackApp.new +end
View file
faraday-1.0.0.gem/data/spec/faraday/adapter/typhoeus_spec.rb
Added
@@ -0,0 +1,7 @@ +# frozen_string_literal: true + +RSpec.describe Faraday::Adapter::Typhoeus do + features :request_body_on_query_methods, :parallel, :trace_method + + it_behaves_like 'an adapter' +end
View file
faraday-1.0.0.gem/data/spec/faraday/composite_read_io_spec.rb
Added
@@ -0,0 +1,80 @@ +# frozen_string_literal: true + +require 'stringio' + +RSpec.describe Faraday::CompositeReadIO do + Part = Struct.new(:to_io) do + def length + to_io.string.length + end + end + + def part(str) + Part.new StringIO.new(str) + end + + def composite_io(*parts) + Faraday::CompositeReadIO.new(*parts) + end + + context 'with empty composite_io' do + subject { composite_io } + + it { expect(subject.length).to eq(0) } + it { expect(subject.read).to eq('') } + it { expect(subject.read(1)).to be_nil } + end + + context 'with empty parts' do + subject { composite_io(part(''), part('')) } + + it { expect(subject.length).to eq(0) } + it { expect(subject.read).to eq('') } + it { expect(subject.read(1)).to be_nil } + end + + context 'with 2 parts' do + subject { composite_io(part('abcd'), part('1234')) } + + it { expect(subject.length).to eq(8) } + it { expect(subject.read).to eq('abcd1234') } + it 'allows to read in chunks' do + expect(subject.read(3)).to eq('abc') + expect(subject.read(3)).to eq('d12') + expect(subject.read(3)).to eq('34') + expect(subject.read(3)).to be_nil + end + it 'allows to rewind while reading in chunks' do + expect(subject.read(3)).to eq('abc') + expect(subject.read(3)).to eq('d12') + subject.rewind + expect(subject.read(3)).to eq('abc') + expect(subject.read(5)).to eq('d1234') + expect(subject.read(3)).to be_nil + subject.rewind + expect(subject.read(2)).to eq('ab') + end + end + + context 'with mix of empty and non-empty parts' do + subject { composite_io(part(''), part('abcd'), part(''), part('1234'), part('')) } + + it 'allows to read in chunks' do + expect(subject.read(6)).to eq('abcd12') + expect(subject.read(6)).to eq('34') + expect(subject.read(6)).to be_nil + end + end + + context 'with utf8 multibyte part' do + subject { composite_io(part("\x86"), part('γγ‘γ€γ«')) } + + it { expect(subject.read).to eq(String.new("\x86\xE3\x83\x95\xE3\x82\xA1\xE3\x82\xA4\xE3\x83\xAB", encoding: 'BINARY')) } + it 'allows to read in chunks' do + expect(subject.read(3)).to eq(String.new("\x86\xE3\x83", encoding: 'BINARY')) + expect(subject.read(3)).to eq(String.new("\x95\xE3\x82", encoding: 'BINARY')) + expect(subject.read(8)).to eq(String.new("\xA1\xE3\x82\xA4\xE3\x83\xAB", encoding: 'BINARY')) + expect(subject.read(3)).to be_nil + end + end +end
View file
faraday-2.7.11.gem/data/spec/faraday/connection_spec.rb -> faraday-1.0.0.gem/data/spec/faraday/connection_spec.rb
Changed
@@ -1,20 +1,10 @@ # frozen_string_literal: true -class CustomEncoder - def encode(params) - params.map { |k, v| "#{k.upcase}-#{v.to_s.upcase}" }.join(',') - end - - def decode(params) - params.split(',').to_h { |pair| pair.split('-') } - end -end - shared_examples 'initializer with url' do context 'with simple url' do - let(:address) { 'http://httpbingo.org' } + let(:address) { 'http://sushi.com' } - it { expect(subject.host).to eq('httpbingo.org') } + it { expect(subject.host).to eq('sushi.com') } it { expect(subject.port).to eq(80) } it { expect(subject.scheme).to eq('http') } it { expect(subject.path_prefix).to eq('/') } @@ -22,36 +12,29 @@ end context 'with complex url' do - let(:address) { 'http://httpbingo.org:815/fish?a=1' } + let(:address) { 'http://sushi.com:815/fish?a=1' } it { expect(subject.port).to eq(815) } it { expect(subject.path_prefix).to eq('/fish') } it { expect(subject.params).to eq('a' => '1') } end - - context 'with IPv6 address' do - let(:address) { 'http://::1:85/' } - - it { expect(subject.host).to eq('::1') } - it { expect(subject.port).to eq(85) } - end end shared_examples 'default connection options' do after { Faraday.default_connection_options = nil } it 'works with implicit url' do - conn = Faraday.new 'http://httpbingo.org/foo' + conn = Faraday.new 'http://sushi.com/foo' expect(conn.options.timeout).to eq(10) end it 'works with option url' do - conn = Faraday.new url: 'http://httpbingo.org/foo' + conn = Faraday.new url: 'http://sushi.com/foo' expect(conn.options.timeout).to eq(10) end it 'works with instance connection options' do - conn = Faraday.new 'http://httpbingo.org/foo', request: { open_timeout: 1 } + conn = Faraday.new 'http://sushi.com/foo', request: { open_timeout: 1 } expect(conn.options.timeout).to eq(10) expect(conn.options.open_timeout).to eq(1) end @@ -61,7 +44,7 @@ conn.options.timeout = 1 expect(Faraday.default_connection_options.request.timeout).to eq(10) - other = Faraday.new url: 'https://httpbingo.org/foo' + other = Faraday.new url: 'https://sushi.com/foo' other.options.timeout = 1 expect(Faraday.default_connection_options.request.timeout).to eq(10) @@ -81,14 +64,14 @@ subject { conn } context 'with implicit url param' do - # Faraday::Connection.new('http://httpbingo.org') + # Faraday::Connection.new('http://sushi.com') let(:url) { address } it_behaves_like 'initializer with url' end context 'with explicit url param' do - # Faraday::Connection.new(url: 'http://httpbingo.org') + # Faraday::Connection.new(url: 'http://sushi.com') let(:url) { { url: address } } it_behaves_like 'initializer with url' @@ -108,17 +91,11 @@ end context 'with custom params and params in url' do - let(:url) { 'http://httpbingo.org/fish?a=1&b=2' } + let(:url) { 'http://sushi.com/fish?a=1&b=2' } let(:options) { { params: { a: 3 } } } it { expect(subject.params).to eq('a' => 3, 'b' => '2') } end - context 'with basic_auth in url' do - let(:url) { 'http://Aladdin:open%20sesame@httpbingo.org/fish' } - - it { expect(subject.headers'Authorization').to eq('Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==') } - end - context 'with custom headers' do let(:options) { { headers: { user_agent: 'Faraday' } } } @@ -131,12 +108,6 @@ it { expect(subject.ssl.verify?).to be_falsey } end - context 'with verify_hostname false' do - let(:options) { { ssl: { verify_hostname: false } } } - - it { expect(subject.ssl.verify_hostname?).to be_falsey } - end - context 'with empty block' do let(:conn) { Faraday::Connection.new {} } @@ -146,8 +117,8 @@ context 'with block' do let(:conn) do Faraday::Connection.new(params: { 'a' => '1' }) do |faraday| - faraday.adapter :test - faraday.url_prefix = 'http://httpbingo.org/omnom' + faraday.adapter :net_http + faraday.url_prefix = 'http://sushi.com/omnom' end end @@ -157,22 +128,41 @@ end describe '#close' do - before { Faraday.default_adapter = :test } - after { Faraday.default_adapter = nil } - it 'can close underlying app' do expect(conn.app).to receive(:close) conn.close end end + describe 'basic_auth' do + subject { conn } + + context 'calling the #basic_auth method' do + before { subject.basic_auth 'Aladdin', 'open sesame' } + + it { expect(subject.headers'Authorization').to eq('Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==') } + end + + context 'adding basic auth info to url' do + let(:url) { 'http://Aladdin:open%20sesame@sushi.com/fish' } + + it { expect(subject.headers'Authorization').to eq('Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==') } + end + end + + describe '#token_auth' do + before { subject.token_auth('abcdef', nonce: 'abc') } + + it { expect(subject.headers'Authorization').to eq('Token nonce="abc", token="abcdef"') } + end + describe '#build_exclusive_url' do context 'with relative path' do subject { conn.build_exclusive_url('sake.html') } it 'uses connection host as default host' do - conn.host = 'httpbingo.org' - expect(subject.host).to eq('httpbingo.org') + conn.host = 'sushi.com' + expect(subject.host).to eq('sushi.com') expect(subject.scheme).to eq('http') end @@ -209,10 +199,10 @@ end context 'with complete url' do - subject { conn.build_exclusive_url('http://httpbingo.org/sake.html?a=1') } + subject { conn.build_exclusive_url('http://sushi.com/sake.html?a=1') } it { expect(subject.scheme).to eq('http') } - it { expect(subject.host).to eq('httpbingo.org') } + it { expect(subject.host).to eq('sushi.com') } it { expect(subject.port).to eq(80) } it { expect(subject.path).to eq('/sake.html') } it { expect(subject.query).to eq('a=1') } @@ -220,35 +210,35 @@ it 'overrides connection port for absolute url' do conn.port = 23 - uri = conn.build_exclusive_url('http://httpbingo.org') + uri = conn.build_exclusive_url('http://sushi.com') expect(uri.port).to eq(80)
View file
faraday-2.7.11.gem/data/spec/faraday/error_spec.rb -> faraday-1.0.0.gem/data/spec/faraday/error_spec.rb
Changed
@@ -1,6 +1,6 @@ # frozen_string_literal: true -RSpec.describe Faraday::Error do +RSpec.describe Faraday::ClientError do describe '.initialize' do subject { described_class.new(exception, response) } let(:response) { nil } @@ -12,10 +12,7 @@ it { expect(subject.response).to be_nil } it { expect(subject.message).to eq(exception.message) } it { expect(subject.backtrace).to eq(exception.backtrace) } - it { expect(subject.inspect).to eq('#<Faraday::Error wrapped=#<RuntimeError: test>>') } - it { expect(subject.response_status).to be_nil } - it { expect(subject.response_headers).to be_nil } - it { expect(subject.response_body).to be_nil } + it { expect(subject.inspect).to eq('#<Faraday::ClientError wrapped=#<RuntimeError: test>>') } end context 'with response hash' do @@ -24,10 +21,7 @@ it { expect(subject.wrapped_exception).to be_nil } it { expect(subject.response).to eq(exception) } it { expect(subject.message).to eq('the server responded with status 400') } - it { expect(subject.inspect).to eq('#<Faraday::Error response={:status=>400}>') } - it { expect(subject.response_status).to eq(400) } - it { expect(subject.response_headers).to be_nil } - it { expect(subject.response_body).to be_nil } + it { expect(subject.inspect).to eq('#<Faraday::ClientError response={:status=>400}>') } end context 'with string' do @@ -36,10 +30,7 @@ it { expect(subject.wrapped_exception).to be_nil } it { expect(subject.response).to be_nil } it { expect(subject.message).to eq('custom message') } - it { expect(subject.inspect).to eq('#<Faraday::Error #<Faraday::Error: custom message>>') } - it { expect(subject.response_status).to be_nil } - it { expect(subject.response_headers).to be_nil } - it { expect(subject.response_body).to be_nil } + it { expect(subject.inspect).to eq('#<Faraday::ClientError #<Faraday::ClientError: custom message>>') } end context 'with anything else #to_s' do @@ -48,38 +39,7 @@ it { expect(subject.wrapped_exception).to be_nil } it { expect(subject.response).to be_nil } it { expect(subject.message).to eq('"error1", "error2"') } - it { expect(subject.inspect).to eq('#<Faraday::Error #<Faraday::Error: "error1", "error2">>') } - it { expect(subject.response_status).to be_nil } - it { expect(subject.response_headers).to be_nil } - it { expect(subject.response_body).to be_nil } - end - - context 'with exception string and response hash' do - let(:exception) { 'custom message' } - let(:response) { { status: 400 } } - - it { expect(subject.wrapped_exception).to be_nil } - it { expect(subject.response).to eq(response) } - it { expect(subject.message).to eq('custom message') } - it { expect(subject.inspect).to eq('#<Faraday::Error response={:status=>400}>') } - it { expect(subject.response_status).to eq(400) } - it { expect(subject.response_headers).to be_nil } - it { expect(subject.response_body).to be_nil } - end - - context 'with exception and response object' do - let(:exception) { RuntimeError.new('test') } - let(:body) { { test: 'test' } } - let(:headers) { { 'Content-Type' => 'application/json' } } - let(:response) { Faraday::Response.new(status: 400, response_headers: headers, response_body: body) } - - it { expect(subject.wrapped_exception).to eq(exception) } - it { expect(subject.response).to eq(response) } - it { expect(subject.message).to eq(exception.message) } - it { expect(subject.backtrace).to eq(exception.backtrace) } - it { expect(subject.response_status).to eq(400) } - it { expect(subject.response_headers).to eq(headers) } - it { expect(subject.response_body).to eq(body) } + it { expect(subject.inspect).to eq('#<Faraday::ClientError #<Faraday::ClientError: "error1", "error2">>') } end end end
View file
faraday-2.7.11.gem/data/spec/faraday/middleware_spec.rb -> faraday-1.0.0.gem/data/spec/faraday/middleware_spec.rb
Changed
@@ -2,67 +2,23 @@ RSpec.describe Faraday::Middleware do subject { described_class.new(app) } - let(:app) { double } - - describe 'options' do - context 'when options are passed to the middleware' do - subject { described_class.new(app, options) } - let(:options) { { field: 'value' } } - - it 'accepts options when initialized' do - expect(subject.options:field).to eq('value') - end - end - end - - describe '#on_request' do - subject do - Class.new(described_class) do - def on_request(env) - # do nothing - end - end.new(app) - end - - it 'is called by #call' do - expect(app).to receive(:call).and_return(app) - expect(app).to receive(:on_complete) - is_expected.to receive(:call).and_call_original - is_expected.to receive(:on_request) - subject.call(double) - end - end - - describe '#on_error' do - subject do - Class.new(described_class) do - def on_error(error) - # do nothing - end - end.new(app) - end - - it 'is called by #call' do - expect(app).to receive(:call).and_raise(Faraday::ConnectionFailed) - is_expected.to receive(:call).and_call_original - is_expected.to receive(:on_error) - - expect { subject.call(double) }.to raise_error(Faraday::ConnectionFailed) - end - end describe '#close' do context "with app that doesn't support \#close" do + let(:app) { double } + it 'should issue warning' do - is_expected.to receive(:warn) + expect(subject).to receive(:warn) subject.close end end context "with app that supports \#close" do + let(:app) { double } + it 'should issue warning' do expect(app).to receive(:close) - is_expected.to_not receive(:warn) + expect(subject).to_not receive(:warn) subject.close end end
View file
faraday-2.7.11.gem/data/spec/faraday/options/env_spec.rb -> faraday-1.0.0.gem/data/spec/faraday/options/env_spec.rb
Changed
@@ -27,20 +27,14 @@ expect(ssl.fetch(:verify, true)).to be_falsey end - it 'handle verify_hostname when fetching' do - ssl = Faraday::SSLOptions.new - ssl.verify_hostname = true - expect(ssl.fetch(:verify_hostname, false)).to be_truthy - end - it 'retains custom members' do env:foo = 'custom 1' - env:bar = :custom2 + env:bar = :custom_2 env2 = Faraday::Env.from(env) env2:baz = 'custom 3' expect(env2:foo).to eq('custom 1') - expect(env2:bar).to eq(:custom2) + expect(env2:bar).to eq(:custom_2) expect(env:baz).to be_nil end
View file
faraday-2.7.11.gem/data/spec/faraday/options/options_spec.rb -> faraday-1.0.0.gem/data/spec/faraday/options/options_spec.rb
Changed
@@ -2,7 +2,7 @@ RSpec.describe Faraday::Options do SubOptions = Class.new(Faraday::Options.new(:sub_a, :sub_b)) - ParentOptions = Faraday::Options.new(:a, :b, :c) do + class ParentOptions < Faraday::Options.new(:a, :b, :c) options c: SubOptions end
View file
faraday-2.7.11.gem/data/spec/faraday/options/proxy_options_spec.rb -> faraday-1.0.0.gem/data/spec/faraday/options/proxy_options_spec.rb
Changed
@@ -14,13 +14,6 @@ expect(options.inspect).to match('#<Faraday::ProxyOptions uri=') end - it 'defaults to http' do - options = Faraday::ProxyOptions.from 'example.org' - expect(options.port).to eq(80) - expect(options.host).to eq('example.org') - expect(options.scheme).to eq('http') - end - it 'works with nil' do options = Faraday::ProxyOptions.from nil expect(options).to be_a_kind_of(Faraday::ProxyOptions) @@ -32,14 +25,6 @@ expect(proxy.user).to be_nil expect(proxy.password).to be_nil end - - it 'treats empty string as nil' do - proxy = nil - proxy_string = proxy.to_s # => empty string - options = Faraday::ProxyOptions.from proxy_string - expect(options).to be_a_kind_of(Faraday::ProxyOptions) - expect(options.inspect).to eq('#<Faraday::ProxyOptions (empty)>') - end end it 'allows hash access' do
View file
faraday-2.7.11.gem/data/spec/faraday/params_encoders/flat_spec.rb -> faraday-1.0.0.gem/data/spec/faraday/params_encoders/flat_spec.rb
Changed
@@ -31,12 +31,4 @@ params = { a: } expect(subject.encode(params)).to eq('a=') end - - it 'encodes unsorted when asked' do - params = { b: false, a: true } - expect(subject.encode(params)).to eq('a=true&b=false') - Faraday::FlatParamsEncoder.sort_params = false - expect(subject.encode(params)).to eq('b=false&a=true') - Faraday::FlatParamsEncoder.sort_params = true - end end
View file
faraday-2.7.11.gem/data/spec/faraday/params_encoders/nested_spec.rb -> faraday-1.0.0.gem/data/spec/faraday/params_encoders/nested_spec.rb
Changed
@@ -94,22 +94,6 @@ expect(subject.encode(params)).to eq('a%5B%5D=true&a%5B%5D=false') end - it 'encodes unsorted when asked' do - params = { b: false, a: true } - expect(subject.encode(params)).to eq('a=true&b=false') - Faraday::NestedParamsEncoder.sort_params = false - expect(subject.encode(params)).to eq('b=false&a=true') - Faraday::NestedParamsEncoder.sort_params = true - end - - it 'encodes arrays indices when asked' do - params = { a: 0, 1, 2 } - expect(subject.encode(params)).to eq('a%5B%5D=0&a%5B%5D=1&a%5B%5D=2') - Faraday::NestedParamsEncoder.array_indices = true - expect(subject.encode(params)).to eq('a%5B0%5D=0&a%5B1%5D=1&a%5B2%5D=2') - Faraday::NestedParamsEncoder.array_indices = false - end - shared_examples 'a wrong decoding' do it do expect { subject.decode(query) }.to raise_error(TypeError) do |e|
View file
faraday-2.7.11.gem/data/spec/faraday/rack_builder_spec.rb -> faraday-1.0.0.gem/data/spec/faraday/rack_builder_spec.rb
Changed
@@ -12,16 +12,16 @@ class Apple < Handler end - class Orange < Handler end - class Banana < Handler end + class Broken < Faraday::Middleware + dependency 'zomg/i_dont/exist' + end + subject { conn.builder } - before { Faraday.default_adapter = :test } - after { Faraday.default_adapter = nil } context 'with default stack' do let(:conn) { Faraday::Connection.new } @@ -88,6 +88,13 @@ it { expect(subject.handlers).to eq(Apple) } + it 'allows rebuilding' do + subject.build do |builder| + builder.use(Orange) + end + expect(subject.handlers).to eq(Orange) + end + it 'allows use' do subject.use(Orange) expect(subject.handlers).to eq(Apple, Orange) @@ -110,6 +117,36 @@ end end + context 'with custom registered middleware' do + let(:conn) { Faraday::Connection.new {} } + + after { Faraday::Middleware.unregister_middleware(:apple) } + + it 'allows to register with constant' do + Faraday::Middleware.register_middleware(apple: Apple) + subject.use(:apple) + expect(subject.handlers).to eq(Apple) + end + + it 'allows to register with symbol' do + Faraday::Middleware.register_middleware(apple: :Apple) + subject.use(:apple) + expect(subject.handlers).to eq(Apple) + end + + it 'allows to register with string' do + Faraday::Middleware.register_middleware(apple: 'Apple') + subject.use(:apple) + expect(subject.handlers).to eq(Apple) + end + + it 'allows to register with Proc' do + Faraday::Middleware.register_middleware(apple: -> { Apple }) + subject.use(:apple) + expect(subject.handlers).to eq(Apple) + end + end + context 'when having two handlers' do let(:conn) { Faraday::Connection.new {} } @@ -139,179 +176,21 @@ end end - context 'when adapter is added with named options' do - after { Faraday.default_adapter_options = {} } - let(:conn) { Faraday::Connection.new {} } - - let(:cat_adapter) do - Class.new(Faraday::Adapter) do - attr_accessor :name - - def initialize(app, name:) - super(app) - @name = name - end - end - end - - let(:cat) { subject.adapter.build } - - it 'adds a handler to construct adapter with named options' do - Faraday.default_adapter = cat_adapter - Faraday.default_adapter_options = { name: 'Chloe' } - expect { cat }.to_not output( - /warning: Using the last argument as keyword parameters is deprecated/ - ).to_stderr - expect(cat.name).to eq 'Chloe' - end - end - - context 'when middleware is added with named arguments' do - let(:conn) { Faraday::Connection.new {} } - - let(:dog_middleware) do - Class.new(Faraday::Middleware) do - attr_accessor :name - - def initialize(app, name:) - super(app) - @name = name - end - end - end - let(:dog) do - subject.handlers.find { |handler| handler == dog_middleware }.build - end - - it 'adds a handler to construct middleware with options passed to use' do - subject.use dog_middleware, name: 'Rex' - expect { dog }.to_not output( - /warning: Using the last argument as keyword parameters is deprecated/ - ).to_stderr - expect(dog.name).to eq('Rex') - end - end - - context 'when a middleware is added with named arguments' do - let(:conn) { Faraday::Connection.new {} } - - let(:cat_request) do - Class.new(Faraday::Middleware) do - attr_accessor :name - - def initialize(app, name:) - super(app) - @name = name - end - end - end - let(:cat) do - subject.handlers.find { |handler| handler == cat_request }.build - end - - it 'adds a handler to construct request adapter with options passed to request' do - Faraday::Request.register_middleware cat_request: cat_request - subject.request :cat_request, name: 'Felix' - expect { cat }.to_not output( - /warning: Using the last argument as keyword parameters is deprecated/ - ).to_stderr - expect(cat.name).to eq('Felix') - end - end - - context 'when a middleware is added with named arguments' do - let(:conn) { Faraday::Connection.new {} } - - let(:fish_response) do - Class.new(Faraday::Middleware) do - attr_accessor :name - - def initialize(app, name:) - super(app) - @name = name - end - end - end - let(:fish) do - subject.handlers.find { |handler| handler == fish_response }.build - end - - it 'adds a handler to construct response adapter with options passed to response' do - Faraday::Response.register_middleware fish_response: fish_response - subject.response :fish_response, name: 'Bubbles' - expect { fish }.to_not output( - /warning: Using the last argument as keyword parameters is deprecated/ - ).to_stderr - expect(fish.name).to eq('Bubbles') - end - end - - context 'when a plain adapter is added with named arguments' do - let(:conn) { Faraday::Connection.new {} } - - let(:rabbit_adapter) do - Class.new(Faraday::Adapter) do - attr_accessor :name - - def initialize(app, name:) - super(app) - @name = name + context 'when having a handler with broken dependency' do + let(:conn) do + Faraday::Connection.new do |builder| + builder.adapter :test do |stub| + stub.get('/') { |_| 200, {}, '' } end end
View file
faraday-2.7.11.gem/data/spec/faraday/request/authorization_spec.rb -> faraday-1.0.0.gem/data/spec/faraday/request/authorization_spec.rb
Changed
@@ -3,7 +3,7 @@ RSpec.describe Faraday::Request::Authorization do let(:conn) do Faraday.new do |b| - b.request :authorization, auth_type, *auth_config + b.request auth_type, *auth_config b.adapter :test do |stub| stub.get('/auth-echo') do |env| 200, {}, env:request_headers'Authorization' @@ -14,10 +14,10 @@ shared_examples 'does not interfere with existing authentication' do context 'and request already has an authentication header' do - let(:response) { conn.get('/auth-echo', nil, authorization: 'OAuth oauth_token') } + let(:response) { conn.get('/auth-echo', nil, authorization: 'Token token="bar"') } it 'does not interfere with existing authorization' do - expect(response.body).to eq('OAuth oauth_token') + expect(response.body).to eq('Token token="bar"') end end end @@ -25,7 +25,7 @@ let(:response) { conn.get('/auth-echo') } describe 'basic_auth' do - let(:auth_type) { :basic } + let(:auth_type) { :basic_auth } context 'when passed correct params' do let(:auth_config) { %waladdin opensesame } @@ -44,73 +44,43 @@ end end - describe 'authorization' do - let(:auth_type) { :Bearer } - - context 'when passed a string' do - let(:auth_config) { 'custom' } - - it { expect(response.body).to eq('Bearer custom') } - - include_examples 'does not interfere with existing authentication' - end + describe 'token_auth' do + let(:auth_type) { :token_auth } - context 'when passed a proc' do - let(:auth_config) { -> { 'custom_from_proc' } } + context 'when passed correct params' do + let(:auth_config) { 'quux' } - it { expect(response.body).to eq('Bearer custom_from_proc') } + it { expect(response.body).to eq('Token token="quux"') } include_examples 'does not interfere with existing authentication' end - context 'when passed a callable' do - let(:callable) { double('Callable Authorizer', call: 'custom_from_callable') } - let(:auth_config) { callable } + context 'when other values are provided' do + let(:auth_config) { 'baz', foo: 42 } - it { expect(response.body).to eq('Bearer custom_from_callable') } + it { expect(response.body).to match(/^Token /) } + it { expect(response.body).to match(/token="baz"/) } + it { expect(response.body).to match(/foo="42"/) } include_examples 'does not interfere with existing authentication' end + end - context 'with an argument' do - let(:response) { conn.get('/auth-echo', nil, 'middle' => 'crunchy surprise') } - - context 'when passed a proc' do - let(:auth_config) { proc { |env| "proc #{env.request_headers'middle'}" } } - - it { expect(response.body).to eq('Bearer proc crunchy surprise') } - - include_examples 'does not interfere with existing authentication' - end - - context 'when passed a lambda' do - let(:auth_config) { ->(env) { "lambda #{env.request_headers'middle'}" } } - - it { expect(response.body).to eq('Bearer lambda crunchy surprise') } - - include_examples 'does not interfere with existing authentication' - end + describe 'authorization' do + let(:auth_type) { :authorization } - context 'when passed a callable with an argument' do - let(:callable) do - Class.new do - def call(env) - "callable #{env.request_headers'middle'}" - end - end.new - end - let(:auth_config) { callable } + context 'when passed two strings' do + let(:auth_config) { 'custom', 'abc def' } - it { expect(response.body).to eq('Bearer callable crunchy surprise') } + it { expect(response.body).to eq('custom abc def') } - include_examples 'does not interfere with existing authentication' - end + include_examples 'does not interfere with existing authentication' end - context 'when passed too many arguments' do - let(:auth_config) { %wbaz foo } + context 'when passed a string and a hash' do + let(:auth_config) { 'baz', foo: 42 } - it { expect { response }.to raise_error(ArgumentError) } + it { expect(response.body).to eq('baz foo="42"') } include_examples 'does not interfere with existing authentication' end
View file
faraday-2.7.11.gem/data/spec/faraday/request/instrumentation_spec.rb -> faraday-1.0.0.gem/data/spec/faraday/request/instrumentation_spec.rb
Changed
@@ -30,11 +30,13 @@ it { expect(options.name).to eq('request.faraday') } it 'defaults to ActiveSupport::Notifications' do - res = options.instrumenter - rescue NameError => e - expect(e.to_s).to match('ActiveSupport') - else - expect(res).to eq(ActiveSupport::Notifications) + begin + res = options.instrumenter + rescue NameError => e + expect(e.to_s).to match('ActiveSupport') + else + expect(res).to eq(ActiveSupport::Notifications) + end end it 'instruments with default name' do
View file
faraday-1.0.0.gem/data/spec/faraday/request/multipart_spec.rb
Added
@@ -0,0 +1,274 @@ +# frozen_string_literal: true + +RSpec.describe Faraday::Request::Multipart do + let(:conn) do + Faraday.new do |b| + b.request :multipart + b.request :url_encoded + b.adapter :test do |stub| + stub.post('/echo') do |env| + posted_as = env:request_headers'Content-Type' + expect(env:body).to be_a_kind_of(Faraday::CompositeReadIO) + 200, { 'Content-Type' => posted_as }, env:body.read + end + end + end + end + + shared_examples 'a multipart request' do + it 'generates a unique boundary for each request' do + response1 = conn.post('/echo', payload) + response2 = conn.post('/echo', payload) + + b1 = parse_multipart_boundary(response1.headers'Content-Type') + b2 = parse_multipart_boundary(response2.headers'Content-Type') + expect(b1).to_not eq(b2) + end + end + + context 'FilePart: when multipart objects in param' do + let(:payload) do + { + a: 1, + b: { + c: Faraday::FilePart.new(__FILE__, 'text/x-ruby', nil, + 'Content-Disposition' => 'form-data; foo=1'), + d: 2 + } + } + end + it_behaves_like 'a multipart request' + + it 'forms a multipart request' do + response = conn.post('/echo', payload) + + boundary = parse_multipart_boundary(response.headers'Content-Type') + result = parse_multipart(boundary, response.body) + expect(result:errors).to be_empty + + part_a, body_a = result.part('a') + expect(part_a).to_not be_nil + expect(part_a.filename).to be_nil + expect(body_a).to eq('1') + + part_bc, body_bc = result.part('bc') + expect(part_bc).to_not be_nil + expect(part_bc.filename).to eq('multipart_spec.rb') + expect(part_bc.headers'content-disposition').to eq( + 'form-data; foo=1; name="bc"; filename="multipart_spec.rb"' + ) + expect(part_bc.headers'content-type').to eq('text/x-ruby') + expect(part_bc.headers'content-transfer-encoding').to eq('binary') + expect(body_bc).to eq(File.read(__FILE__)) + + part_bd, body_bd = result.part('bd') + expect(part_bd).to_not be_nil + expect(part_bd.filename).to be_nil + expect(body_bd).to eq('2') + end + end + + context 'FilePart: when providing json and IO content in the same payload' do + let(:io) { StringIO.new('io-content') } + let(:json) do + { + b: 1, + c: 2 + }.to_json + end + + let(:payload) do + { + json: Faraday::ParamPart.new(json, 'application/json'), + io: Faraday::FilePart.new(io, 'application/pdf') + } + end + + it_behaves_like 'a multipart request' + + it 'forms a multipart request' do + response = conn.post('/echo', payload) + + boundary = parse_multipart_boundary(response.headers'Content-Type') + result = parse_multipart(boundary, response.body) + expect(result:errors).to be_empty + + part_json, body_json = result.part('json') + expect(part_json).to_not be_nil + expect(part_json.mime).to eq('application/json') + expect(part_json.filename).to be_nil + expect(body_json).to eq(json) + + part_io, body_io = result.part('io') + expect(part_io).to_not be_nil + expect(part_io.mime).to eq('application/pdf') + expect(part_io.filename).to eq('local.path') + expect(body_io).to eq(io.string) + end + end + + context 'FilePart: when multipart objects in array param' do + let(:payload) do + { + a: 1, + b: { + c: Faraday::FilePart.new(__FILE__, 'text/x-ruby'), + d: 2 + } + } + end + + it_behaves_like 'a multipart request' + + it 'forms a multipart request' do + response = conn.post('/echo', payload) + + boundary = parse_multipart_boundary(response.headers'Content-Type') + result = parse_multipart(boundary, response.body) + expect(result:errors).to be_empty + + part_a, body_a = result.part('a') + expect(part_a).to_not be_nil + expect(part_a.filename).to be_nil + expect(body_a).to eq('1') + + part_bc, body_bc = result.part('bc') + expect(part_bc).to_not be_nil + expect(part_bc.filename).to eq('multipart_spec.rb') + expect(part_bc.headers'content-disposition').to eq( + 'form-data; name="bc"; filename="multipart_spec.rb"' + ) + expect(part_bc.headers'content-type').to eq('text/x-ruby') + expect(part_bc.headers'content-transfer-encoding').to eq('binary') + expect(body_bc).to eq(File.read(__FILE__)) + + part_bd, body_bd = result.part('bd') + expect(part_bd).to_not be_nil + expect(part_bd.filename).to be_nil + expect(body_bd).to eq('2') + end + end + + context 'UploadIO: when multipart objects in param' do + let(:payload) do + { + a: 1, + b: { + c: Faraday::UploadIO.new(__FILE__, 'text/x-ruby', nil, + 'Content-Disposition' => 'form-data; foo=1'), + d: 2 + } + } + end + it_behaves_like 'a multipart request' + + it 'forms a multipart request' do + response = conn.post('/echo', payload) + + boundary = parse_multipart_boundary(response.headers'Content-Type') + result = parse_multipart(boundary, response.body) + expect(result:errors).to be_empty + + part_a, body_a = result.part('a') + expect(part_a).to_not be_nil + expect(part_a.filename).to be_nil + expect(body_a).to eq('1') + + part_bc, body_bc = result.part('bc') + expect(part_bc).to_not be_nil + expect(part_bc.filename).to eq('multipart_spec.rb') + expect(part_bc.headers'content-disposition').to eq( + 'form-data; foo=1; name="bc"; filename="multipart_spec.rb"' + ) + expect(part_bc.headers'content-type').to eq('text/x-ruby') + expect(part_bc.headers'content-transfer-encoding').to eq('binary') + expect(body_bc).to eq(File.read(__FILE__)) + + part_bd, body_bd = result.part('bd') + expect(part_bd).to_not be_nil + expect(part_bd.filename).to be_nil + expect(body_bd).to eq('2') + end + end + + context 'UploadIO: when providing json and IO content in the same payload' do + let(:io) { StringIO.new('io-content') } + let(:json) do + { + b: 1, + c: 2
View file
faraday-1.0.0.gem/data/spec/faraday/request/retry_spec.rb
Added
@@ -0,0 +1,242 @@ +# frozen_string_literal: true + +RSpec.describe Faraday::Request::Retry do + let(:calls) { } + let(:times_called) { calls.size } + let(:options) { } + let(:conn) do + Faraday.new do |b| + b.request :retry, *options + + b.adapter :test do |stub| + %wget post.each do |method| + stub.send(method, '/unstable') do |env| + calls << env.dup + env:body = nil # simulate blanking out response body + callback.call + end + end + end + end + end + + context 'when an unexpected error happens' do + let(:callback) { -> { raise 'boom!' } } + + before { expect { conn.get('/unstable') }.to raise_error(RuntimeError) } + + it { expect(times_called).to eq(1) } + + context 'and this is passed as a custom exception' do + let(:options) { { exceptions: StandardError } } + + it { expect(times_called).to eq(3) } + end + end + + context 'when an expected error happens' do + let(:callback) { -> { raise Errno::ETIMEDOUT } } + + before do + @started = Time.now + expect { conn.get('/unstable') }.to raise_error(Errno::ETIMEDOUT) + end + + it { expect(times_called).to eq(3) } + + context 'and legacy max_retry set to 1' do + let(:options) { 1 } + + it { expect(times_called).to eq(2) } + end + + context 'and legacy max_retry set to -9' do + let(:options) { -9 } + + it { expect(times_called).to eq(1) } + end + + context 'and new max_retry set to 3' do + let(:options) { { max: 3 } } + + it { expect(times_called).to eq(4) } + end + + context 'and new max_retry set to -9' do + let(:options) { { max: -9 } } + + it { expect(times_called).to eq(1) } + end + + context 'and both max_retry and interval are set' do + let(:options) { { max: 2, interval: 0.1 } } + + it { expect(Time.now - @started).to be_within(0.04).of(0.2) } + end + end + + context 'when no exception raised' do + let(:options) { { max: 1, retry_statuses: 429 } } + + before { conn.get('/unstable') } + + context 'and response code is in retry_statuses' do + let(:callback) { -> { 429, {}, '' } } + + it { expect(times_called).to eq(2) } + end + + context 'and response code is not in retry_statuses' do + let(:callback) { -> { 503, {}, '' } } + + it { expect(times_called).to eq(1) } + end + end + + describe '#calculate_retry_interval' do + context 'with exponential backoff' do + let(:options) { { max: 5, interval: 0.1, backoff_factor: 2 } } + let(:middleware) { Faraday::Request::Retry.new(nil, options) } + + it { expect(middleware.send(:calculate_retry_interval, 5)).to eq(0.1) } + it { expect(middleware.send(:calculate_retry_interval, 4)).to eq(0.2) } + it { expect(middleware.send(:calculate_retry_interval, 3)).to eq(0.4) } + end + + context 'with exponential backoff and max_interval' do + let(:options) { { max: 5, interval: 0.1, backoff_factor: 2, max_interval: 0.3 } } + let(:middleware) { Faraday::Request::Retry.new(nil, options) } + + it { expect(middleware.send(:calculate_retry_interval, 5)).to eq(0.1) } + it { expect(middleware.send(:calculate_retry_interval, 4)).to eq(0.2) } + it { expect(middleware.send(:calculate_retry_interval, 3)).to eq(0.3) } + it { expect(middleware.send(:calculate_retry_interval, 2)).to eq(0.3) } + end + + context 'with exponential backoff and interval_randomness' do + let(:options) { { max: 2, interval: 0.1, interval_randomness: 0.05 } } + let(:middleware) { Faraday::Request::Retry.new(nil, options) } + + it { expect(middleware.send(:calculate_retry_interval, 2)).to be_between(0.1, 0.15) } + end + end + + context 'when method is not idempotent' do + let(:callback) { -> { raise Errno::ETIMEDOUT } } + + before { expect { conn.post('/unstable') }.to raise_error(Errno::ETIMEDOUT) } + + it { expect(times_called).to eq(1) } + end + + describe 'retry_if option' do + let(:callback) { -> { raise Errno::ETIMEDOUT } } + let(:options) { { retry_if: @check } } + + it 'retries if retry_if block always returns true' do + body = { foo: :bar } + @check = ->(_, _) { true } + expect { conn.post('/unstable', body) }.to raise_error(Errno::ETIMEDOUT) + expect(times_called).to eq(3) + expect(calls.all? { |env| env:body == body }).to be_truthy + end + + it 'does not retry if retry_if block returns false checking env' do + @check = ->(env, _) { env:method != :post } + expect { conn.post('/unstable') }.to raise_error(Errno::ETIMEDOUT) + expect(times_called).to eq(1) + end + + it 'does not retry if retry_if block returns false checking exception' do + @check = ->(_, exception) { !exception.is_a?(Errno::ETIMEDOUT) } + expect { conn.post('/unstable') }.to raise_error(Errno::ETIMEDOUT) + expect(times_called).to eq(1) + end + + it 'FilePart: should rewind files on retry' do + io = StringIO.new('Test data') + filepart = Faraday::FilePart.new(io, 'application/octet/stream') + + rewound = 0 + rewind = -> { rewound += 1 } + + @check = ->(_, _) { true } + allow(filepart).to receive(:rewind, &rewind) + expect { conn.post('/unstable', file: filepart) }.to raise_error(Errno::ETIMEDOUT) + expect(times_called).to eq(3) + expect(rewound).to eq(2) + end + + it 'UploadIO: should rewind files on retry' do + io = StringIO.new('Test data') + upload_io = Faraday::UploadIO.new(io, 'application/octet/stream') + + rewound = 0 + rewind = -> { rewound += 1 } + + @check = ->(_, _) { true } + allow(upload_io).to receive(:rewind, &rewind) + expect { conn.post('/unstable', file: upload_io) }.to raise_error(Errno::ETIMEDOUT) + expect(times_called).to eq(3) + expect(rewound).to eq(2) + end + + context 'when explicitly specifying methods to retry' do + let(:options) { { retry_if: @check, methods: :post } } + + it 'does not call retry_if for specified methods' do + @check = ->(_, _) { raise 'this should have never been called' } + expect { conn.post('/unstable') }.to raise_error(Errno::ETIMEDOUT) + expect(times_called).to eq(3) + end + end + + context 'with empty list of methods to retry' do + let(:options) { { retry_if: @check, methods: } } + + it 'calls retry_if for all methods' do + @check = ->(_, _) { calls.size < 2 } + expect { conn.get('/unstable') }.to raise_error(Errno::ETIMEDOUT)
View file
faraday-2.7.11.gem/data/spec/faraday/request/url_encoded_spec.rb -> faraday-1.0.0.gem/data/spec/faraday/request/url_encoded_spec.rb
Changed
@@ -1,19 +1,14 @@ # frozen_string_literal: true -require 'stringio' - RSpec.describe Faraday::Request::UrlEncoded do let(:conn) do Faraday.new do |b| + b.request :multipart b.request :url_encoded b.adapter :test do |stub| stub.post('/echo') do |env| posted_as = env:request_headers'Content-Type' - body = env:body - if body.respond_to?(:read) - body = body.read - end - 200, { 'Content-Type' => posted_as }, body + 200, { 'Content-Type' => posted_as }, env:body end end end @@ -72,22 +67,4 @@ response = conn.post('/echo', 'a' => { 'b' => { 'c' => 'd' } }) expect(response.body).to eq('a%5Bb%5D%5Bc%5D%5B%5D=d') end - - it 'works with files' do - response = conn.post('/echo', StringIO.new('str=apple')) - expect(response.body).to eq('str=apple') - end - - context 'customising default_space_encoding' do - around do |example| - Faraday::Utils.default_space_encoding = '%20' - example.run - Faraday::Utils.default_space_encoding = nil - end - - it 'uses the custom character to encode spaces' do - response = conn.post('/echo', str: 'apple banana') - expect(response.body).to eq('str=apple%20banana') - end - end end
View file
faraday-2.7.11.gem/data/spec/faraday/request_spec.rb -> faraday-1.0.0.gem/data/spec/faraday/request_spec.rb
Changed
@@ -2,25 +2,24 @@ RSpec.describe Faraday::Request do let(:conn) do - Faraday.new(url: 'http://httpbingo.org/api', + Faraday.new(url: 'http://sushi.com/api', headers: { 'Mime-Version' => '1.0' }, request: { oauth: { consumer_key: 'anonymous' } }) end - let(:http_method) { :get } + let(:method) { :get } let(:block) { nil } - subject { conn.build_request(http_method, &block) } + subject { conn.build_request(method, &block) } context 'when nothing particular is configured' do - it { expect(subject.http_method).to eq(:get) } + it { expect(subject.method).to eq(:get) } it { expect(subject.to_env(conn).ssl.verify).to be_falsey } - it { expect(subject.to_env(conn).ssl.verify_hostname).to be_falsey } end - context 'when HTTP method is post' do - let(:http_method) { :post } + context 'when method is post' do + let(:method) { :post } - it { expect(subject.http_method).to eq(:post) } + it { expect(subject.method).to eq(:post) } end context 'when setting the url on setup with a URI' do @@ -28,7 +27,7 @@ it { expect(subject.path).to eq(URI.parse('foo.json')) } it { expect(subject.params).to eq('a' => '1') } - it { expect(subject.to_env(conn).url.to_s).to eq('http://httpbingo.org/api/foo.json?a=1') } + it { expect(subject.to_env(conn).url.to_s).to eq('http://sushi.com/api/foo.json?a=1') } end context 'when setting the url on setup with a string path and params' do @@ -36,7 +35,7 @@ it { expect(subject.path).to eq('foo.json') } it { expect(subject.params).to eq('a' => 1) } - it { expect(subject.to_env(conn).url.to_s).to eq('http://httpbingo.org/api/foo.json?a=1') } + it { expect(subject.to_env(conn).url.to_s).to eq('http://sushi.com/api/foo.json?a=1') } end context 'when setting the url on setup with a path including params' do @@ -44,7 +43,7 @@ it { expect(subject.path).to eq('foo.json') } it { expect(subject.params).to eq('a' => '1', 'b' => '2') } - it { expect(subject.to_env(conn).url.to_s).to eq('http://httpbingo.org/api/foo.json?a=1&b=2') } + it { expect(subject.to_env(conn).url.to_s).to eq('http://sushi.com/api/foo.json?a=1&b=2') } end context 'when setting a header on setup with = syntax' do
View file
faraday-2.7.11.gem/data/spec/faraday/response/logger_spec.rb -> faraday-1.0.0.gem/data/spec/faraday/response/logger_spec.rb
Changed
@@ -25,7 +25,6 @@ stubs.get('/filtered_headers') { 200, { 'Content-Type' => 'text/html' }, 'headers response' } stubs.get('/filtered_params') { 200, { 'Content-Type' => 'text/html' }, 'params response' } stubs.get('/filtered_url') { 200, { 'Content-Type' => 'text/html' }, 'url response' } - stubs.get('/connection_failed') { raise Faraday::ConnectionFailed, 'Failed to open TCP connection' } end end end @@ -65,15 +64,6 @@ expect(formatter).to receive(:response).with(an_instance_of(Faraday::Env)) conn.get '/hello' end - - context 'when no route' do - it 'delegates logging to the formatter' do - expect(formatter).to receive(:request).with(an_instance_of(Faraday::Env)) - expect(formatter).to receive(:exception).with(an_instance_of(Faraday::Adapter::Test::Stubs::NotFound)) - - expect { conn.get '/noroute' }.to raise_error(Faraday::Adapter::Test::Stubs::NotFound) - end - end end context 'with custom formatter' do @@ -104,16 +94,6 @@ expect(string_io.string).to match('GET http:/hello') end - it 'logs status' do - conn.get '/hello', nil, accept: 'text/html' - expect(string_io.string).to match('Status 200') - end - - it 'does not log error message by default' do - expect { conn.get '/noroute' }.to raise_error(Faraday::Adapter::Test::Stubs::NotFound) - expect(string_io.string).not_to match(%(no stubbed request for get http:/noroute)) - end - it 'logs request headers by default' do conn.get '/hello', nil, accept: 'text/html' expect(string_io.string).to match(%(Accept: "text/html)) @@ -208,24 +188,6 @@ end end - context 'when logging errors' do - let(:logger_options) { { errors: true } } - - it 'logs error message' do - expect { conn.get '/noroute' }.to raise_error(Faraday::Adapter::Test::Stubs::NotFound) - expect(string_io.string).to match(%(no stubbed request for get http:/noroute)) - end - end - - context 'when logging headers and errors' do - let(:logger_options) { { headers: true, errors: true } } - - it 'logs error message' do - expect { conn.get '/connection_failed' }.to raise_error(Faraday::ConnectionFailed) - expect(string_io.string).to match(%(Failed to open TCP connection)) - end - end - context 'when using log_level' do let(:logger_options) { { bodies: true, log_level: :debug } }
View file
faraday-1.0.0.gem/data/spec/faraday/response/middleware_spec.rb
Added
@@ -0,0 +1,52 @@ +# frozen_string_literal: true + +RSpec.describe Faraday::Response::Middleware do + let(:conn) do + Faraday.new do |b| + b.use custom_middleware + b.adapter :test do |stub| + stub.get('ok') { 200, { 'Content-Type' => 'text/html' }, '<body></body>' } + stub.get('not_modified') { 304, nil, nil } + stub.get('no_content') { 204, nil, nil } + end + end + end + + context 'with a custom ResponseMiddleware' do + let(:custom_middleware) do + Class.new(Faraday::Response::Middleware) do + def parse(body) + body.upcase + end + end + end + + it 'parses the response' do + expect(conn.get('ok').body).to eq('<BODY></BODY>') + end + end + + context 'with a custom ResponseMiddleware but empty response' do + let(:custom_middleware) do + Class.new(Faraday::Response::Middleware) do + def parse(_body) + raise 'this should not be called' + end + end + end + + it 'raises exception for 200 responses' do + expect { conn.get('ok') }.to raise_error(StandardError) + end + + it 'doesn\'t call the middleware for 204 responses' do + expect_any_instance_of(custom_middleware).not_to receive(:parse) + expect(conn.get('no_content').body).to be_nil + end + + it 'doesn\'t call the middleware for 304 responses' do + expect_any_instance_of(custom_middleware).not_to receive(:parse) + expect(conn.get('not_modified').body).to be_nil + end + end +end
View file
faraday-2.7.11.gem/data/spec/faraday/response/raise_error_spec.rb -> faraday-1.0.0.gem/data/spec/faraday/response/raise_error_spec.rb
Changed
@@ -11,7 +11,6 @@ stub.get('forbidden') { 403, { 'X-Reason' => 'because' }, 'keep looking' } stub.get('not-found') { 404, { 'X-Reason' => 'because' }, 'keep looking' } stub.get('proxy-error') { 407, { 'X-Reason' => 'because' }, 'keep looking' } - stub.get('request-timeout') { 408, { 'X-Reason' => 'because' }, 'keep looking' } stub.get('conflict') { 409, { 'X-Reason' => 'because' }, 'keep looking' } stub.get('unprocessable-entity') { 422, { 'X-Reason' => 'because' }, 'keep looking' } stub.get('4xx') { 499, { 'X-Reason' => 'because' }, 'keep looking' } @@ -30,9 +29,6 @@ expect(ex.message).to eq('the server responded with status 400') expect(ex.response:headers'X-Reason').to eq('because') expect(ex.response:status).to eq(400) - expect(ex.response_status).to eq(400) - expect(ex.response_body).to eq('keep looking') - expect(ex.response_headers'X-Reason').to eq('because') end end @@ -41,9 +37,6 @@ expect(ex.message).to eq('the server responded with status 401') expect(ex.response:headers'X-Reason').to eq('because') expect(ex.response:status).to eq(401) - expect(ex.response_status).to eq(401) - expect(ex.response_body).to eq('keep looking') - expect(ex.response_headers'X-Reason').to eq('because') end end @@ -52,9 +45,6 @@ expect(ex.message).to eq('the server responded with status 403') expect(ex.response:headers'X-Reason').to eq('because') expect(ex.response:status).to eq(403) - expect(ex.response_status).to eq(403) - expect(ex.response_body).to eq('keep looking') - expect(ex.response_headers'X-Reason').to eq('because') end end @@ -63,9 +53,6 @@ expect(ex.message).to eq('the server responded with status 404') expect(ex.response:headers'X-Reason').to eq('because') expect(ex.response:status).to eq(404) - expect(ex.response_status).to eq(404) - expect(ex.response_body).to eq('keep looking') - expect(ex.response_headers'X-Reason').to eq('because') end end @@ -74,20 +61,6 @@ expect(ex.message).to eq('407 "Proxy Authentication Required"') expect(ex.response:headers'X-Reason').to eq('because') expect(ex.response:status).to eq(407) - expect(ex.response_status).to eq(407) - expect(ex.response_body).to eq('keep looking') - expect(ex.response_headers'X-Reason').to eq('because') - end - end - - it 'raises Faraday::RequestTimeoutError for 408 responses' do - expect { conn.get('request-timeout') }.to raise_error(Faraday::RequestTimeoutError) do |ex| - expect(ex.message).to eq('the server responded with status 408') - expect(ex.response:headers'X-Reason').to eq('because') - expect(ex.response:status).to eq(408) - expect(ex.response_status).to eq(408) - expect(ex.response_body).to eq('keep looking') - expect(ex.response_headers'X-Reason').to eq('because') end end @@ -96,9 +69,6 @@ expect(ex.message).to eq('the server responded with status 409') expect(ex.response:headers'X-Reason').to eq('because') expect(ex.response:status).to eq(409) - expect(ex.response_status).to eq(409) - expect(ex.response_body).to eq('keep looking') - expect(ex.response_headers'X-Reason').to eq('because') end end @@ -107,9 +77,6 @@ expect(ex.message).to eq('the server responded with status 422') expect(ex.response:headers'X-Reason').to eq('because') expect(ex.response:status).to eq(422) - expect(ex.response_status).to eq(422) - expect(ex.response_body).to eq('keep looking') - expect(ex.response_headers'X-Reason').to eq('because') end end @@ -118,9 +85,6 @@ expect(ex.message).to eq('http status could not be derived from the server response') expect(ex.response:headers'X-Reason').to eq('nil') expect(ex.response:status).to be_nil - expect(ex.response_status).to be_nil - expect(ex.response_body).to eq('fail') - expect(ex.response_headers'X-Reason').to eq('nil') end end @@ -129,9 +93,6 @@ expect(ex.message).to eq('the server responded with status 499') expect(ex.response:headers'X-Reason').to eq('because') expect(ex.response:status).to eq(499) - expect(ex.response_status).to eq(499) - expect(ex.response_body).to eq('keep looking') - expect(ex.response_headers'X-Reason').to eq('because') end end @@ -140,60 +101,6 @@ expect(ex.message).to eq('the server responded with status 500') expect(ex.response:headers'X-Error').to eq('bailout') expect(ex.response:status).to eq(500) - expect(ex.response_status).to eq(500) - expect(ex.response_body).to eq('fail') - expect(ex.response_headers'X-Error').to eq('bailout') - end - end - - describe 'request info' do - let(:conn) do - Faraday.new do |b| - b.response :raise_error, **middleware_options - b.adapter :test do |stub| - stub.post(url, request_body, request_headers) do - 400, { 'X-Reason' => 'because' }, 'keep looking' - end - end - end - end - let(:middleware_options) { {} } - let(:request_body) { JSON.generate({ 'item' => 'sth' }) } - let(:request_headers) { { 'Authorization' => 'Basic 123' } } - let(:url_path) { 'request' } - let(:query_params) { 'full=true' } - let(:url) { "#{url_path}?#{query_params}" } - - subject(:perform_request) do - conn.post url do |req| - req.headers'Authorization' = 'Basic 123' - req.body = request_body - end - end - - it 'returns the request info in the exception' do - expect { perform_request }.to raise_error(Faraday::BadRequestError) do |ex| - expect(ex.response:request:method).to eq(:post) - expect(ex.response:request:url).to eq(URI("http:/#{url}")) - expect(ex.response:request:url_path).to eq("/#{url_path}") - expect(ex.response:request:params).to eq({ 'full' => 'true' }) - expect(ex.response:request:headers).to match(a_hash_including(request_headers)) - expect(ex.response:request:body).to eq(request_body) - end - end - - context 'when the include_request option is set to false' do - let(:middleware_options) { { include_request: false } } - - it 'does not include request info in the exception' do - expect { perform_request }.to raise_error(Faraday::BadRequestError) do |ex| - expect(ex.response.keys).to contain_exactly( - :status, - :headers, - :body - ) - end - end end end end
View file
faraday-2.7.11.gem/data/spec/faraday/response_spec.rb -> faraday-1.0.0.gem/data/spec/faraday/response_spec.rb
Changed
@@ -4,7 +4,7 @@ subject { Faraday::Response.new(env) } let(:env) do - Faraday::Env.from(status: 404, body: 'yikes', url: Faraday::Utils.URI('https://lostisland.github.io/faraday'), + Faraday::Env.from(status: 404, body: 'yikes', response_headers: { 'Content-Type' => 'text/plain' }) end @@ -30,7 +30,6 @@ it { expect(hash:status).to eq(subject.status) } it { expect(hash:response_headers).to eq(subject.headers) } it { expect(hash:body).to eq(subject.body) } - it { expect(hash:url).to eq(subject.env.url) } end describe 'marshal serialization support' do @@ -46,7 +45,6 @@ it { expect(loaded.env:body).to eq(env:body) } it { expect(loaded.env:response_headers).to eq(env:response_headers) } it { expect(loaded.env:status).to eq(env:status) } - it { expect(loaded.env:url).to eq(env:url) } end describe '#on_complete' do
View file
faraday-2.7.11.gem/data/spec/faraday/utils/headers_spec.rb -> faraday-1.0.0.gem/data/spec/faraday/utils/headers_spec.rb
Changed
@@ -57,44 +57,26 @@ end describe '#parse' do + before { subject.parse(headers) } + context 'when response headers leave http status line out' do let(:headers) { "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n" } - before { subject.parse(headers) } - it { expect(subject.keys).to eq(%wContent-Type) } it { expect(subject'Content-Type').to eq('text/html') } it { expect(subject'content-type').to eq('text/html') } end context 'when response headers values include a colon' do - let(:headers) { "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nLocation: http://httpbingo.org/\r\n\r\n" } + let(:headers) { "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nLocation: http://sushi.com/\r\n\r\n" } - before { subject.parse(headers) } - - it { expect(subject'location').to eq('http://httpbingo.org/') } + it { expect(subject'location').to eq('http://sushi.com/') } end context 'when response headers include a blank line' do let(:headers) { "HTTP/1.1 200 OK\r\n\r\nContent-Type: text/html\r\n\r\n" } - before { subject.parse(headers) } - it { expect(subject'content-type').to eq('text/html') } end - - context 'when response headers include already stored keys' do - let(:headers) { "HTTP/1.1 200 OK\r\nX-Numbers: 123\r\n\r\n" } - - before do - h = subject - h:x_numbers = 8 - h.parse(headers) - end - - it do - expect(subject:x_numbers).to eq('8, 123') - end - end end end
View file
faraday-2.7.11.gem/data/spec/faraday/utils_spec.rb -> faraday-1.0.0.gem/data/spec/faraday/utils_spec.rb
Changed
@@ -4,7 +4,7 @@ describe 'headers parsing' do let(:multi_response_headers) do "HTTP/1.x 500 OK\r\nContent-Type: text/html; charset=UTF-8\r\n" \ - "HTTP/1.x 200 OK\r\nContent-Type: application/json; charset=UTF-8\r\n\r\n" + "HTTP/1.x 200 OK\r\nContent-Type: application/json; charset=UTF-8\r\n\r\n" end it 'parse headers for aggregated responses' do @@ -53,66 +53,4 @@ expect(headers).not_to have_key('authorization') end end - - describe '.deep_merge!' do - let(:connection_options) { Faraday::ConnectionOptions.new } - let(:url) do - { - url: 'http://example.com/abc', - headers: { 'Mime-Version' => '1.0' }, - request: { oauth: { consumer_key: 'anonymous' } }, - ssl: { version: '2' } - } - end - - it 'recursively merges the headers' do - connection_options.headers = { user_agent: 'My Agent 1.0' } - deep_merge = Faraday::Utils.deep_merge!(connection_options, url) - - expect(deep_merge.headers).to eq('Mime-Version' => '1.0', user_agent: 'My Agent 1.0') - end - - context 'when a target hash has an Options Struct value' do - let(:request) do - { - params_encoder: nil, - proxy: nil, - bind: nil, - timeout: nil, - open_timeout: nil, - read_timeout: nil, - write_timeout: nil, - boundary: nil, - oauth: { consumer_key: 'anonymous' }, - context: nil, - on_data: nil - } - end - let(:ssl) do - { - verify: nil, - ca_file: nil, - ca_path: nil, - verify_mode: nil, - cert_store: nil, - client_cert: nil, - client_key: nil, - certificate: nil, - private_key: nil, - verify_depth: nil, - version: '2', - min_version: nil, - max_version: nil, - verify_hostname: nil - } - end - - it 'does not overwrite an Options Struct value' do - deep_merge = Faraday::Utils.deep_merge!(connection_options, url) - - expect(deep_merge.request.to_h).to eq(request) - expect(deep_merge.ssl.to_h).to eq(ssl) - end - end - end end
View file
faraday-2.7.11.gem/data/spec/faraday_spec.rb -> faraday-1.0.0.gem/data/spec/faraday_spec.rb
Changed
@@ -18,14 +18,10 @@ end it 'uses method_missing on Faraday if there is no proxyable method' do - expected_message = - if RUBY_VERSION >= '3.3' - "undefined method `this_method_does_not_exist' for module Faraday" - else - "undefined method `this_method_does_not_exist' for Faraday:Module" - end - - expect { Faraday.this_method_does_not_exist }.to raise_error(NoMethodError, expected_message) + expect { Faraday.this_method_does_not_exist }.to raise_error( + NoMethodError, + "undefined method `this_method_does_not_exist' for Faraday:Module" + ) end it 'proxied methods can be accessed' do
View file
faraday-2.7.11.gem/data/spec/support/fake_safe_buffer.rb -> faraday-1.0.0.gem/data/spec/support/fake_safe_buffer.rb
Changed
@@ -8,7 +8,7 @@ def gsub(regex) string.gsub(regex) do - match, = Regexp.last_match(0), '' =~ /a/ # rubocop:disable Performance/StringInclude + match, = $&, '' =~ /a/ yield(match) end end
View file
faraday-2.7.11.gem/data/spec/support/helper_methods.rb -> faraday-1.0.0.gem/data/spec/support/helper_methods.rb
Changed
@@ -1,5 +1,7 @@ # frozen_string_literal: true +require 'multipart_parser/reader' + module Faraday module HelperMethods def self.included(base) @@ -84,6 +86,41 @@ end end + def multipart_file + Faraday::FilePart.new(__FILE__, 'text/x-ruby') + end + + # parse boundary out of a Content-Type header like: + # Content-Type: multipart/form-data; boundary=gc0p4Jq0M2Yt08jU534c0p + def parse_multipart_boundary(ctype) + MultipartParser::Reader.extract_boundary_value(ctype) + end + + # parse a multipart MIME message, returning a hash of any multipart errors + def parse_multipart(boundary, body) + reader = MultipartParser::Reader.new(boundary) + result = { errors: , parts: } + def result.part(name) + hash = self:parts.detect { |h| h:part.name == name } + hash:part, hash:body.join + end + + reader.on_part do |part| + result:parts << thispart = { + part: part, + body: + } + part.on_data do |chunk| + thispart:body << chunk + end + end + reader.on_error do |msg| + result:errors << msg + end + reader.write(body) + result + end + def method_with_body?(method) self.class.method_with_body?(method) end
View file
faraday-2.7.11.gem/data/spec/support/shared_examples/adapter.rb -> faraday-1.0.0.gem/data/spec/support/shared_examples/adapter.rb
Changed
@@ -33,21 +33,20 @@ let(:protocol) { ssl_mode? ? 'https' : 'http' } let(:remote) { "#{protocol}://example.com" } - let(:stub_remote) { remote } let(:conn) do conn_options:ssl ||= {} - conn_options:ssl:ca_file ||= ENV.fetch('SSL_FILE', nil) - conn_options:ssl:verify_hostname ||= ENV'SSL_VERIFY_HOSTNAME' == 'yes' + conn_options:ssl:ca_file ||= ENV'SSL_FILE' Faraday.new(remote, conn_options) do |conn| + conn.request :multipart conn.request :url_encoded conn.response :raise_error conn.adapter described_class, *adapter_options end end - let!(:request_stub) { stub_request(http_method, stub_remote) } + let!(:request_stub) { stub_request(http_method, remote) } after do expect(request_stub).to have_been_requested unless request_stub.disabled?
View file
faraday-2.7.11.gem/data/spec/support/shared_examples/request_method.rb -> faraday-1.0.0.gem/data/spec/support/shared_examples/request_method.rb
Changed
@@ -1,19 +1,5 @@ # frozen_string_literal: true -shared_examples 'proxy examples' do - it 'handles requests with proxy' do - res = conn.public_send(http_method, '/') - - expect(res.status).to eq(200) - end - - it 'handles proxy failures' do - request_stub.to_return(status: 407) - - expect { conn.public_send(http_method, '/') }.to raise_error(Faraday::ProxyAuthError) - end -end - shared_examples 'a request method' do |http_method| let(:query_or_body) { method_with_body?(http_method) ? :body : :query } let(:response) { conn.public_send(http_method, '/') } @@ -27,8 +13,8 @@ end it 'handles headers with multiple values' do - request_stub.to_return(headers: { 'Set-Cookie' => 'name=value' }) - expect(response.headers'set-cookie').to eq('name=value') + request_stub.to_return(headers: { 'Set-Cookie' => 'one, two' }) + expect(response.headers'set-cookie').to eq('one, two') end it 'retrieves the response headers' do @@ -79,7 +65,7 @@ on_feature :request_body_on_query_methods do it 'sends request body' do - request_stub.with({ body: 'test' }) + request_stub.with(Hash:body, 'test') res = if query_or_body == :body conn.public_send(http_method, '/', 'test') else @@ -93,7 +79,7 @@ it 'sends url encoded parameters' do payload = { name: 'zack' } - request_stub.with({ query_or_body => payload }) + request_stub.with(Hashquery_or_body, payload) res = conn.public_send(http_method, '/', payload) if query_or_body == :query expect(res.env.request_body).to be_nil @@ -104,7 +90,7 @@ it 'sends url encoded nested parameters' do payload = { name: { first: 'zack' } } - request_stub.with({ query_or_body => payload }) + request_stub.with(Hashquery_or_body, payload) conn.public_send(http_method, '/', payload) end @@ -126,6 +112,19 @@ expect { conn.public_send(http_method, '/') }.to raise_error(exc) end + # Can't send files on get, head and delete methods + if method_with_body?(http_method) + it 'sends files' do + payload = { uploaded_file: multipart_file } + request_stub.with(headers: { 'Content-Type' => %r{\Amultipart/form-data} }) do |request| + # WebMock does not support matching body for multipart/form-data requests yet :( + # https://github.com/bblimke/webmock/issues/623 + request.body =~ /RubyMultipartPost/ + end + conn.public_send(http_method, '/', payload) + end + end + on_feature :reason_phrase_parse do it 'parses the reason phrase' do request_stub.to_return(status: 200, 'OK') @@ -153,19 +152,12 @@ let(:streamed) { } context 'when response is empty' do - it 'handles streaming' do - env = nil + it do conn.public_send(http_method, '/') do |req| - req.options.on_data = proc do |chunk, size, block_env| - streamed << chunk, size - env ||= block_env - end + req.options.on_data = proc { |*args| streamed << args } end expect(streamed).to eq('', 0) - # TODO: enable this after updating all existing adapters to the new streaming API - # expect(env).to be_a(Faraday::Env) - # expect(env.status).to eq(200) end end @@ -173,19 +165,12 @@ before { request_stub.to_return(body: big_string) } it 'handles streaming' do - env = nil response = conn.public_send(http_method, '/') do |req| - req.options.on_data = proc do |chunk, size, block_env| - streamed << chunk, size - env ||= block_env - end + req.options.on_data = proc { |*args| streamed << args } end expect(response.body).to eq('') check_streaming_response(streamed, chunk_size: 16 * 1024) - # TODO: enable this after updating all existing adapters to the new streaming API - # expect(env).to be_a(Faraday::Env) - # expect(env.status).to eq(200) end end end @@ -200,11 +185,11 @@ @payload2 = { b: '2' } request_stub - .with({ query_or_body => @payload1 }) + .with(Hashquery_or_body, @payload1) .to_return(body: @payload1.to_json) stub_request(http_method, remote) - .with({ query_or_body => @payload2 }) + .with(Hashquery_or_body, @payload2) .to_return(body: @payload2.to_json) conn.in_parallel do @@ -233,31 +218,17 @@ end end - context 'when a proxy is provided as option' do - before do - conn_options:proxy = 'http://env-proxy.com:80' - end + it 'handles requests with proxy' do + conn_options:proxy = 'http://google.co.uk' - include_examples 'proxy examples' + res = conn.public_send(http_method, '/') + expect(res.status).to eq(200) end - context 'when http_proxy env variable is set' do - let(:proxy_url) { 'http://env-proxy.com:80' } - - around do |example| - with_env 'http_proxy' => proxy_url do - example.run - end - end - - include_examples 'proxy examples' - - context 'when the env proxy is ignored' do - around do |example| - with_env_proxy_disabled(&example) - end + it 'handles proxy failures' do + conn_options:proxy = 'http://google.co.uk' + request_stub.to_return(status: 407) - include_examples 'proxy examples' - end + expect { conn.public_send(http_method, '/') }.to raise_error(Faraday::ProxyAuthError) end end
View file
faraday-1.0.0.gem/data/spec/support/webmock_rack_app.rb
Added
@@ -0,0 +1,68 @@ +# frozen_string_literal: true + +# Rack app used to test the Rack adapter. +# Uses Webmock to check if requests are registered, in which case it returns +# the registered response. +class WebmockRackApp + def call(env) + req_signature = WebMock::RequestSignature.new( + req_method(env), + req_uri(env), + body: req_body(env), + headers: req_headers(env) + ) + + WebMock::RequestRegistry + .instance + .requested_signatures + .put(req_signature) + + process_response(req_signature) + end + + def req_method(env) + env'REQUEST_METHOD'.downcase.to_sym + end + + def req_uri(env) + scheme = env'rack.url_scheme' + host = env'SERVER_NAME' + port = env'SERVER_PORT' + path = env'PATH_INFO' + query = env'QUERY_STRING' + + url = +"#{scheme}://#{host}:#{port}#{path}" + url += "?#{query}" if query + + uri = WebMock::Util::URI.heuristic_parse(url) + uri.path = uri.normalized_path.gsub('^://', '/') + uri + end + + def req_headers(env) + http_headers = env.select { |k, _| k.start_with?('HTTP_') } + .map { |k, v| k5..-1, v } + .to_h + + special_headers = Faraday::Adapter::Rack::SPECIAL_HEADERS + http_headers.merge(env.select { |k, _| special_headers.include?(k) }) + end + + def req_body(env) + env'rack.input'.read + end + + def process_response(req_signature) + res = WebMock::StubRegistry.instance.response_for_request(req_signature) + + if res.nil? && req_signature.uri.host == 'localhost' + raise Faraday::ConnectionFailed, 'Trying to connect to localhost' + end + + raise WebMock::NetConnectNotAllowedError, req_signature unless res + + raise Faraday::TimeoutError if res.should_timeout + + res.status0, res.headers || {}, res.body || '' + end +end
View file
faraday-2.7.11.gem/metadata.gz -> faraday-1.0.0.gem/metadata.gz
Changed
@@ -1,7 +1,7 @@ --- !ruby/object:Gem::Specification name: faraday version: !ruby/object:Gem::Version - version: 2.7.11 + version: 1.0.0 platform: ruby authors: - "@technoweenie" @@ -10,56 +10,28 @@ autorequire: bindir: bin cert_chain: -date: 2023-09-12 00:00:00.000000000 Z +date: 2020-01-01 00:00:00.000000000 Z dependencies: - !ruby/object:Gem::Dependency - name: base64 + name: multipart-post requirement: !ruby/object:Gem::Requirement requirements: - - ">=" - !ruby/object:Gem::Version - version: '0' - type: :runtime - prerelease: false - version_requirements: !ruby/object:Gem::Requirement - requirements: - - - ">=" - - !ruby/object:Gem::Version - version: '0' -- !ruby/object:Gem::Dependency - name: faraday-net_http - requirement: !ruby/object:Gem::Requirement - requirements: - - - ">=" - - !ruby/object:Gem::Version - version: '2.0' + version: '1.2' - - "<" - !ruby/object:Gem::Version - version: '3.1' + version: '3' type: :runtime prerelease: false version_requirements: !ruby/object:Gem::Requirement requirements: - - ">=" - !ruby/object:Gem::Version - version: '2.0' + version: '1.2' - - "<" - !ruby/object:Gem::Version - version: '3.1' -- !ruby/object:Gem::Dependency - name: ruby2_keywords - requirement: !ruby/object:Gem::Requirement - requirements: - - - ">=" - - !ruby/object:Gem::Version - version: 0.0.4 - type: :runtime - prerelease: false - version_requirements: !ruby/object:Gem::Requirement - requirements: - - - ">=" - - !ruby/object:Gem::Version - version: 0.0.4 + version: '3' description: email: technoweenie@gmail.com executables: @@ -70,18 +42,32 @@ - LICENSE.md - README.md - Rakefile +- UPGRADING.md - examples/client_spec.rb - examples/client_test.rb - lib/faraday.rb - lib/faraday/adapter.rb +- lib/faraday/adapter/em_http.rb +- lib/faraday/adapter/em_http_ssl_patch.rb +- lib/faraday/adapter/em_synchrony.rb +- lib/faraday/adapter/em_synchrony/parallel_manager.rb +- lib/faraday/adapter/excon.rb +- lib/faraday/adapter/httpclient.rb +- lib/faraday/adapter/net_http.rb +- lib/faraday/adapter/net_http_persistent.rb +- lib/faraday/adapter/patron.rb +- lib/faraday/adapter/rack.rb - lib/faraday/adapter/test.rb +- lib/faraday/adapter/typhoeus.rb - lib/faraday/adapter_registry.rb +- lib/faraday/autoload.rb - lib/faraday/connection.rb +- lib/faraday/dependency_loader.rb - lib/faraday/encoders/flat_params_encoder.rb - lib/faraday/encoders/nested_params_encoder.rb - lib/faraday/error.rb +- lib/faraday/file_part.rb - lib/faraday/logging/formatter.rb -- lib/faraday/methods.rb - lib/faraday/middleware.rb - lib/faraday/middleware_registry.rb - lib/faraday/options.rb @@ -90,28 +76,38 @@ - lib/faraday/options/proxy_options.rb - lib/faraday/options/request_options.rb - lib/faraday/options/ssl_options.rb +- lib/faraday/param_part.rb - lib/faraday/parameters.rb - lib/faraday/rack_builder.rb - lib/faraday/request.rb - lib/faraday/request/authorization.rb +- lib/faraday/request/basic_authentication.rb - lib/faraday/request/instrumentation.rb -- lib/faraday/request/json.rb +- lib/faraday/request/multipart.rb +- lib/faraday/request/retry.rb +- lib/faraday/request/token_authentication.rb - lib/faraday/request/url_encoded.rb - lib/faraday/response.rb -- lib/faraday/response/json.rb - lib/faraday/response/logger.rb - lib/faraday/response/raise_error.rb - lib/faraday/utils.rb - lib/faraday/utils/headers.rb - lib/faraday/utils/params_hash.rb -- lib/faraday/version.rb - spec/external_adapters/faraday_specs_setup.rb -- spec/faraday/adapter/test_spec.rb +- spec/faraday/adapter/em_http_spec.rb +- spec/faraday/adapter/em_synchrony_spec.rb +- spec/faraday/adapter/excon_spec.rb +- spec/faraday/adapter/httpclient_spec.rb +- spec/faraday/adapter/net_http_persistent_spec.rb +- spec/faraday/adapter/net_http_spec.rb +- spec/faraday/adapter/patron_spec.rb +- spec/faraday/adapter/rack_spec.rb +- spec/faraday/adapter/typhoeus_spec.rb - spec/faraday/adapter_registry_spec.rb - spec/faraday/adapter_spec.rb +- spec/faraday/composite_read_io_spec.rb - spec/faraday/connection_spec.rb - spec/faraday/error_spec.rb -- spec/faraday/middleware_registry_spec.rb - spec/faraday/middleware_spec.rb - spec/faraday/options/env_spec.rb - spec/faraday/options/options_spec.rb @@ -122,11 +118,12 @@ - spec/faraday/rack_builder_spec.rb - spec/faraday/request/authorization_spec.rb - spec/faraday/request/instrumentation_spec.rb -- spec/faraday/request/json_spec.rb +- spec/faraday/request/multipart_spec.rb +- spec/faraday/request/retry_spec.rb - spec/faraday/request/url_encoded_spec.rb - spec/faraday/request_spec.rb -- spec/faraday/response/json_spec.rb - spec/faraday/response/logger_spec.rb +- spec/faraday/response/middleware_spec.rb - spec/faraday/response/raise_error_spec.rb - spec/faraday/response_spec.rb - spec/faraday/utils/headers_spec.rb @@ -140,31 +137,31 @@ - spec/support/shared_examples/params_encoder.rb - spec/support/shared_examples/request_method.rb - spec/support/streaming_response_checker.rb +- spec/support/webmock_rack_app.rb homepage: https://lostisland.github.io/faraday licenses: - MIT metadata: homepage_uri: https://lostisland.github.io/faraday - changelog_uri: https://github.com/lostisland/faraday/releases/tag/v2.7.11 + changelog_uri: https://github.com/lostisland/faraday/releases/tag/v1.0.0 source_code_uri: https://github.com/lostisland/faraday bug_tracker_uri: https://github.com/lostisland/faraday/issues post_install_message: rdoc_options: require_paths: - lib -- spec/external_adapters required_ruby_version: !ruby/object:Gem::Requirement requirements: - - ">=" - !ruby/object:Gem::Version - version: '2.6' + version: '2.3' required_rubygems_version: !ruby/object:Gem::Requirement requirements: - - ">=" - !ruby/object:Gem::Version version: '0' requirements: -rubygems_version: 3.1.6 +rubygems_version: 3.1.2 signing_key: specification_version: 4
View file
faraday-2.7.11.gem/data/lib/faraday/methods.rb
Deleted
@@ -1,6 +0,0 @@ -# frozen_string_literal: true - -module Faraday - METHODS_WITH_QUERY = %wget head delete trace.freeze - METHODS_WITH_BODY = %wpost put patch.freeze -end
View file
faraday-2.7.11.gem/data/lib/faraday/request/json.rb
Deleted
@@ -1,64 +0,0 @@ -# frozen_string_literal: true - -require 'json' - -module Faraday - class Request - # Request middleware that encodes the body as JSON. - # - # Processes only requests with matching Content-type or those without a type. - # If a request doesn't have a type but has a body, it sets the Content-type - # to JSON MIME-type. - # - # Doesn't try to encode bodies that already are in string form. - class Json < Middleware - MIME_TYPE = 'application/json' - MIME_TYPE_REGEX = %r{^application/(vnd\..+\+)?json$}.freeze - - def on_request(env) - match_content_type(env) do |data| - env:body = encode(data) - end - end - - private - - def encode(data) - ::JSON.generate(data) - end - - def match_content_type(env) - return unless process_request?(env) - - env:request_headersCONTENT_TYPE ||= MIME_TYPE - yield env:body unless env:body.respond_to?(:to_str) - end - - def process_request?(env) - type = request_type(env) - body?(env) && (type.empty? || type.match?(MIME_TYPE_REGEX)) - end - - def body?(env) - body = env:body - case body - when true, false - true - when nil - # NOTE: nil can be converted to `"null"`, but this middleware doesn't process `nil` for the compatibility. - false - else - !(body.respond_to?(:to_str) && body.empty?) - end - end - - def request_type(env) - type = env:request_headersCONTENT_TYPE.to_s - type = type.split(';', 2).first if type.index(';') - type - end - end - end -end - -Faraday::Request.register_middleware(json: Faraday::Request::Json)
View file
faraday-2.7.11.gem/data/lib/faraday/response/json.rb
Deleted
@@ -1,54 +0,0 @@ -# frozen_string_literal: true - -require 'json' - -module Faraday - class Response - # Parse response bodies as JSON. - class Json < Middleware - def initialize(app = nil, parser_options: nil, content_type: /\bjson$/, preserve_raw: false) - super(app) - @parser_options = parser_options - @content_types = Array(content_type) - @preserve_raw = preserve_raw - end - - def on_complete(env) - process_response(env) if parse_response?(env) - end - - private - - def process_response(env) - env:raw_body = env:body if @preserve_raw - env:body = parse(env:body) - rescue StandardError, SyntaxError => e - raise Faraday::ParsingError.new(e, env:response) - end - - def parse(body) - ::JSON.parse(body, @parser_options || {}) unless body.strip.empty? - end - - def parse_response?(env) - process_response_type?(env) && - env:body.respond_to?(:to_str) - end - - def process_response_type?(env) - type = response_type(env) - @content_types.empty? || @content_types.any? do |pattern| - pattern.is_a?(Regexp) ? type.match?(pattern) : type == pattern - end - end - - def response_type(env) - type = env:response_headersCONTENT_TYPE.to_s - type = type.split(';', 2).first if type.index(';') - type - end - end - end -end - -Faraday::Response.register_middleware(json: Faraday::Response::Json)
View file
faraday-2.7.11.gem/data/lib/faraday/version.rb
Deleted
@@ -1,5 +0,0 @@ -# frozen_string_literal: true - -module Faraday - VERSION = '2.7.11' -end
View file
faraday-2.7.11.gem/data/spec/faraday/adapter/test_spec.rb
Deleted
@@ -1,442 +0,0 @@ -# frozen_string_literal: true - -RSpec.describe Faraday::Adapter::Test do - let(:stubs) do - described_class::Stubs.new do |stub| - stub.get('http://domain.test/hello') do - 200, { 'Content-Type' => 'text/html' }, 'domain: hello' - end - - stub.get('http://wrong.test/hello') do - 200, { 'Content-Type' => 'text/html' }, 'wrong: hello' - end - - stub.get('http://wrong.test/bait') do - 404, { 'Content-Type' => 'text/html' } - end - - stub.get('/hello') do - 200, { 'Content-Type' => 'text/html' }, 'hello' - end - - stub.get('/method-echo') do |env| - 200, { 'Content-Type' => 'text/html' }, env:method.to_s - end - - stub.get(%r{\A/resources/\d+(?:\?|\z)}) do - 200, { 'Content-Type' => 'text/html' }, 'show' - end - - stub.get(%r{\A/resources/(specified)\z}) do |_env, meta| - 200, { 'Content-Type' => 'text/html' }, "show #{meta:match_data1}" - end - end - end - - let(:connection) do - Faraday.new do |builder| - builder.adapter :test, stubs - end - end - - let(:response) { connection.get('/hello') } - - context 'with simple path sets status' do - subject { response.status } - - it { is_expected.to eq 200 } - end - - context 'with simple path sets headers' do - subject { response.headers'Content-Type' } - - it { is_expected.to eq 'text/html' } - end - - context 'with simple path sets body' do - subject { response.body } - - it { is_expected.to eq 'hello' } - end - - context 'with host points to the right stub' do - subject { connection.get('http://domain.test/hello').body } - - it { is_expected.to eq 'domain: hello' } - end - - describe 'can be called several times' do - subject { connection.get('/hello').body } - - it { is_expected.to eq 'hello' } - end - - describe 'can handle regular expression path' do - subject { connection.get('/resources/1').body } - - it { is_expected.to eq 'show' } - end - - describe 'can handle single parameter block' do - subject { connection.get('/method-echo').body } - - it { is_expected.to eq 'get' } - end - - describe 'can handle regular expression path with captured result' do - subject { connection.get('/resources/specified').body } - - it { is_expected.to eq 'show specified' } - end - - context 'with get params' do - subject { connection.get('/param?a=1').body } - - before do - stubs.get('/param?a=1') { 200, {}, 'a' } - end - - it { is_expected.to eq 'a' } - end - - describe 'ignoring unspecified get params' do - before do - stubs.get('/optional?a=1') { 200, {}, 'a' } - end - - context 'with multiple params' do - subject { connection.get('/optional?a=1&b=1').body } - - it { is_expected.to eq 'a' } - end - - context 'with single param' do - subject { connection.get('/optional?a=1').body } - - it { is_expected.to eq 'a' } - end - - context 'without params' do - subject(:request) { connection.get('/optional') } - - it do - expect { request }.to raise_error( - Faraday::Adapter::Test::Stubs::NotFound - ) - end - end - end - - context 'with http headers' do - before do - stubs.get('/yo', 'X-HELLO' => 'hello') { 200, {}, 'a' } - stubs.get('/yo') { 200, {}, 'b' } - end - - context 'with header' do - subject do - connection.get('/yo') { |env| env.headers'X-HELLO' = 'hello' }.body - end - - it { is_expected.to eq 'a' } - end - - context 'without header' do - subject do - connection.get('/yo').body - end - - it { is_expected.to eq 'b' } - end - end - - describe 'different outcomes for the same request' do - def make_request - connection.get('/foo') - end - - subject(:request) { make_request.body } - - before do - stubs.get('/foo') { 200, { 'Content-Type' => 'text/html' }, 'hello' } - stubs.get('/foo') { 200, { 'Content-Type' => 'text/html' }, 'world' } - end - - context 'the first request' do - it { is_expected.to eq 'hello' } - end - - context 'the second request' do - before do - make_request - end - - it { is_expected.to eq 'world' } - end - end - - describe 'yielding env to stubs' do - subject { connection.get('http://foo.com/foo?a=1').body } - - before do - stubs.get '/foo' do |env| - expect(env:url.path).to eq '/foo' - expect(env:url.host).to eq 'foo.com' - expect(env:params'a').to eq '1' - expect(env:request_headers'Accept').to eq 'text/plain' - 200, {}, 'a' - end - - connection.headers'Accept' = 'text/plain' - end - - it { is_expected.to eq 'a' } - end - - describe 'params parsing' do - subject { connection.get('http://foo.com/foo?ab=1').body } - - context 'with default encoder' do
View file
faraday-2.7.11.gem/data/spec/faraday/middleware_registry_spec.rb
Deleted
@@ -1,31 +0,0 @@ -# frozen_string_literal: true - -RSpec.describe Faraday::MiddlewareRegistry do - before do - stub_const('CustomMiddleware', custom_middleware_klass) - end - let(:custom_middleware_klass) { Class.new(Faraday::Middleware) } - let(:dummy) { Class.new { extend Faraday::MiddlewareRegistry } } - - after { dummy.unregister_middleware(:custom) } - - it 'allows to register with constant' do - dummy.register_middleware(custom: custom_middleware_klass) - expect(dummy.lookup_middleware(:custom)).to eq(custom_middleware_klass) - end - - it 'allows to register with symbol' do - dummy.register_middleware(custom: :CustomMiddleware) - expect(dummy.lookup_middleware(:custom)).to eq(custom_middleware_klass) - end - - it 'allows to register with string' do - dummy.register_middleware(custom: 'CustomMiddleware') - expect(dummy.lookup_middleware(:custom)).to eq(custom_middleware_klass) - end - - it 'allows to register with Proc' do - dummy.register_middleware(custom: -> { custom_middleware_klass }) - expect(dummy.lookup_middleware(:custom)).to eq(custom_middleware_klass) - end -end
View file
faraday-2.7.11.gem/data/spec/faraday/request/json_spec.rb
Deleted
@@ -1,135 +0,0 @@ -# frozen_string_literal: true - -RSpec.describe Faraday::Request::Json do - let(:middleware) { described_class.new(->(env) { Faraday::Response.new(env) }) } - - def process(body, content_type = nil) - env = { body: body, request_headers: Faraday::Utils::Headers.new } - env:request_headers'content-type' = content_type if content_type - middleware.call(Faraday::Env.from(env)).env - end - - def result_body - result:body - end - - def result_type - result:request_headers'content-type' - end - - context 'no body' do - let(:result) { process(nil) } - - it "doesn't change body" do - expect(result_body).to be_nil - end - - it "doesn't add content type" do - expect(result_type).to be_nil - end - end - - context 'empty body' do - let(:result) { process('') } - - it "doesn't change body" do - expect(result_body).to be_empty - end - - it "doesn't add content type" do - expect(result_type).to be_nil - end - end - - context 'string body' do - let(:result) { process('{"a":1}') } - - it "doesn't change body" do - expect(result_body).to eq('{"a":1}') - end - - it 'adds content type' do - expect(result_type).to eq('application/json') - end - end - - context 'object body' do - let(:result) { process(a: 1) } - - it 'encodes body' do - expect(result_body).to eq('{"a":1}') - end - - it 'adds content type' do - expect(result_type).to eq('application/json') - end - end - - context 'empty object body' do - let(:result) { process({}) } - - it 'encodes body' do - expect(result_body).to eq('{}') - end - end - - context 'true body' do - let(:result) { process(true) } - - it 'encodes body' do - expect(result_body).to eq('true') - end - - it 'adds content type' do - expect(result_type).to eq('application/json') - end - end - - context 'false body' do - let(:result) { process(false) } - - it 'encodes body' do - expect(result_body).to eq('false') - end - - it 'adds content type' do - expect(result_type).to eq('application/json') - end - end - - context 'object body with json type' do - let(:result) { process({ a: 1 }, 'application/json; charset=utf-8') } - - it 'encodes body' do - expect(result_body).to eq('{"a":1}') - end - - it "doesn't change content type" do - expect(result_type).to eq('application/json; charset=utf-8') - end - end - - context 'object body with vendor json type' do - let(:result) { process({ a: 1 }, 'application/vnd.myapp.v1+json; charset=utf-8') } - - it 'encodes body' do - expect(result_body).to eq('{"a":1}') - end - - it "doesn't change content type" do - expect(result_type).to eq('application/vnd.myapp.v1+json; charset=utf-8') - end - end - - context 'object body with incompatible type' do - let(:result) { process({ a: 1 }, 'application/xml; charset=utf-8') } - - it "doesn't change body" do - expect(result_body).to eq(a: 1) - end - - it "doesn't change content type" do - expect(result_type).to eq('application/xml; charset=utf-8') - end - end -end
View file
faraday-2.7.11.gem/data/spec/faraday/response/json_spec.rb
Deleted
@@ -1,117 +0,0 @@ -# frozen_string_literal: true - -RSpec.describe Faraday::Response::Json, type: :response do - let(:options) { {} } - let(:headers) { {} } - let(:middleware) do - described_class.new(lambda { |env| - Faraday::Response.new(env) - }, **options) - end - - def process(body, content_type = 'application/json', options = {}) - env = { - body: body, request: options, - request_headers: Faraday::Utils::Headers.new, - response_headers: Faraday::Utils::Headers.new(headers) - } - env:response_headers'content-type' = content_type if content_type - yield(env) if block_given? - middleware.call(Faraday::Env.from(env)) - end - - context 'no type matching' do - it "doesn't change nil body" do - expect(process(nil).body).to be_nil - end - - it 'nullifies empty body' do - expect(process('').body).to be_nil - end - - it 'parses json body' do - response = process('{"a":1}') - expect(response.body).to eq('a' => 1) - expect(response.env:raw_body).to be_nil - end - end - - context 'with preserving raw' do - let(:options) { { preserve_raw: true } } - - it 'parses json body' do - response = process('{"a":1}') - expect(response.body).to eq('a' => 1) - expect(response.env:raw_body).to eq('{"a":1}') - end - end - - context 'with default regexp type matching' do - it 'parses json body of correct type' do - response = process('{"a":1}', 'application/x-json') - expect(response.body).to eq('a' => 1) - end - - it 'ignores json body of incorrect type' do - response = process('{"a":1}', 'text/json-xml') - expect(response.body).to eq('{"a":1}') - end - end - - context 'with array type matching' do - let(:options) { { content_type: %wa/b c/d } } - - it 'parses json body of correct type' do - expect(process('{"a":1}', 'a/b').body).to be_a(Hash) - expect(process('{"a":1}', 'c/d').body).to be_a(Hash) - end - - it 'ignores json body of incorrect type' do - expect(process('{"a":1}', 'a/d').body).not_to be_a(Hash) - end - end - - it 'chokes on invalid json' do - expect { process('{!') }.to raise_error(Faraday::ParsingError) - end - - it 'includes the response on the ParsingError instance' do - process('{') { |env| env:response = Faraday::Response.new } - raise 'Parsing should have failed.' - rescue Faraday::ParsingError => e - expect(e.response).to be_a(Faraday::Response) - end - - context 'HEAD responses' do - it "nullifies the body if it's only one space" do - response = process(' ') - expect(response.body).to be_nil - end - - it "nullifies the body if it's two spaces" do - response = process(' ') - expect(response.body).to be_nil - end - end - - context 'JSON options' do - let(:body) { '{"a": 1}' } - let(:result) { { a: 1 } } - let(:options) do - { - parser_options: { - symbolize_names: true - } - } - end - - it 'passes relevant options to JSON parse' do - expect(::JSON).to receive(:parse) - .with(body, options:parser_options) - .and_return(result) - - response = process(body) - expect(response.body).to eq(result) - end - end -end
Locations
Projects
Search
Status Monitor
Help
Open Build Service
OBS Manuals
API Documentation
OBS Portal
Reporting a Bug
Contact
Mailing List
Forums
Chat (IRC)
Twitter
Open Build Service (OBS)
is an
openSUSE project
.