Skip to content

Commit 135fcc4

Browse files
committed
More tests for quoted strings.
1 parent bfa79ff commit 135fcc4

File tree

2 files changed

+51
-4
lines changed

2 files changed

+51
-4
lines changed

lib/protocol/http/header/quoted_string.rb

+9-4
Original file line numberDiff line numberDiff line change
@@ -30,12 +30,17 @@ def self.unquote(value, normalize_whitespace = true)
3030
return value
3131
end
3232

33-
# Quote a string if required. Doesn't handle newlines correctly currently.
33+
QUOTES_REQUIRED = /[()<>@,;:\\"\/\[\]?={} \t]/
34+
35+
# Quote a string for HTTP header values if required.
36+
#
37+
# @raises [ArgumentError] if the value contains invalid characters like control characters or newlines.
3438
def self.quote(value, force = false)
35-
if value =~ /"/ or force
36-
"\"#{value.gsub(/["\\]/, "\\\\\\0")}\""
39+
# Check if quoting is required:
40+
if value =~ QUOTES_REQUIRED or force
41+
"\"#{value.gsub(/["\\]/, '\\\\\0')}\""
3742
else
38-
return value
43+
value
3944
end
4045
end
4146
end
+42
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
# frozen_string_literal: true
2+
3+
# Released under the MIT License.
4+
# Copyright, 2016-2024, by Samuel Williams.
5+
6+
require 'protocol/http/header/quoted_string'
7+
8+
describe Protocol::HTTP::Header::QuotedString do
9+
with ".unquote" do
10+
it "ignores linear whitespace" do
11+
quoted_string = subject.unquote(%Q{"Hello\r\n World"})
12+
13+
expect(quoted_string).to be == "Hello World"
14+
end
15+
end
16+
17+
with ".quote" do
18+
it "doesn't quote a string that has no special characters" do
19+
quoted_string = subject.quote("Hello")
20+
21+
expect(quoted_string).to be == "Hello"
22+
end
23+
24+
it "quotes a string with a space" do
25+
quoted_string = subject.quote("Hello World")
26+
27+
expect(quoted_string).to be == %Q{"Hello World"}
28+
end
29+
30+
it "quotes a string with a double quote" do
31+
quoted_string = subject.quote(%Q{Hello "World"})
32+
33+
expect(quoted_string).to be == %Q{"Hello \\"World\\""}
34+
end
35+
36+
it "quotes a string with a backslash" do
37+
quoted_string = subject.quote(%Q{Hello \\World})
38+
39+
expect(quoted_string).to be == %Q{"Hello \\\\World"}
40+
end
41+
end
42+
end

0 commit comments

Comments
 (0)