diff --git a/CHANGELOG.md b/CHANGELOG.md index 435d8bc4f..9eed888b4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,7 @@ Inspired from [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) ### Deprecated ### Removed ### Fixed +- Fixed the response body being force-encoded when it was already in UTF-8 ([#212](https://github.com/opensearch-project/opensearch-ruby/issues/212)) ### Security ## [3.0.1] diff --git a/lib/opensearch/transport/transport/response.rb b/lib/opensearch/transport/transport/response.rb index 69a71d10f..0759f6120 100644 --- a/lib/opensearch/transport/transport/response.rb +++ b/lib/opensearch/transport/transport/response.rb @@ -39,7 +39,7 @@ def initialize(status, body, headers = {}) @status = status @body = body @headers = headers - @body = body.force_encoding('UTF-8') if body.respond_to?(:force_encoding) + @body = body.force_encoding('UTF-8') if body.respond_to?(:force_encoding) && body.encoding != Encoding::UTF_8 end end end diff --git a/test/transport/unit/response_test.rb b/test/transport/unit/response_test.rb index a71246e85..060db4bfe 100644 --- a/test/transport/unit/response_test.rb +++ b/test/transport/unit/response_test.rb @@ -28,8 +28,7 @@ class OpenSearch::Transport::Transport::ResponseTest < Minitest::Test context "Response" do - - should "force-encode the body into UTF" do + should "force-encode the body into UTF-8" do body = "Hello Encoding!".encode(Encoding::ISO_8859_1) assert_equal 'ISO-8859-1', body.encoding.name @@ -37,5 +36,11 @@ class OpenSearch::Transport::Transport::ResponseTest < Minitest::Test assert_equal 'UTF-8', response.body.encoding.name end + should "not force-encode the body if it is already encoded as UTF-8" do + body = "Hello Frozen!".freeze + response = OpenSearch::Transport::Transport::Response.new 200, body + + assert_equal body, response.body + end end end