Skip to content

Commit

Permalink
More tests for quoted strings.
Browse files Browse the repository at this point in the history
  • Loading branch information
ioquatix committed Jan 21, 2025
1 parent bfa79ff commit bb81595
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 4 deletions.
13 changes: 9 additions & 4 deletions lib/protocol/http/header/quoted_string.rb
Original file line number Diff line number Diff line change
Expand Up @@ -30,12 +30,17 @@ def self.unquote(value, normalize_whitespace = true)
return value
end

# Quote a string if required. Doesn't handle newlines correctly currently.
QUOTES_REQUIRED = /[()<>@,;:\\"\/\[\]?={} \t]/

# Quote a string for HTTP header values if required.
#
# @raises [ArgumentError] if the value contains invalid characters like control characters or newlines.
def self.quote(value, force = false)
if value =~ /"/ or force
"\"#{value.gsub(/["\\]/, "\\\\\\0")}\""
# Check if quoting is required:
if value =~ QUOTES_REQUIRED or force
"\"#{value.gsub(/["\\]/, '\\\\\0')}\""
else
return value
value
end
end
end
Expand Down
36 changes: 36 additions & 0 deletions test/protocol/http/header/quoted_string.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
# frozen_string_literal: true

# Released under the MIT License.
# Copyright, 2016-2024, by Samuel Williams.

require 'protocol/http/header/quoted_string'

describe Protocol::HTTP::Header::QuotedString do
with ".unquote" do
it "ignores linear whitespace" do
quoted_string = subject.unquote(%Q{"Hello\r\n World"})

expect(quoted_string).to be == "Hello World"
end
end

with ".quote" do
it "quotes a string with a space" do
quoted_string = subject.quote("Hello World")

expect(quoted_string).to be == %Q{"Hello World"}
end

it "quotes a string with a double quote" do
quoted_string = subject.quote(%Q{Hello "World"})

expect(quoted_string).to be == %Q{"Hello \\"World\\""}
end

it "quotes a string with a backslash" do
quoted_string = subject.quote(%Q{Hello \\World})

expect(quoted_string).to be == %Q{"Hello \\\\World"}
end
end
end

0 comments on commit bb81595

Please sign in to comment.