aboutsummaryrefslogtreecommitdiffstats
path: root/actionpack/test/controller/raw_post_test.rb
blob: 5fd2c84ff0416da0bc700083376f63918b5628c9 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
require "#{File.dirname(__FILE__)}/../abstract_unit"

class RawPostDataTest < Test::Unit::TestCase
  def setup
    ENV.delete('RAW_POST_DATA')
    @request_body = 'a=1'
  end

  def test_post_with_urlencoded_body
    ENV['REQUEST_METHOD'] = 'POST'
    ENV['CONTENT_TYPE'] = ' apPlication/x-Www-form-urlEncoded; charset=utf-8'
    assert_equal ['1'], cgi.params['a']
    assert_raw_post_data
  end

  def test_post_with_empty_content_type_treated_as_urlencoded
    ENV['REQUEST_METHOD'] = 'POST'
    ENV['CONTENT_TYPE'] = ''
    assert_equal ['1'], cgi.params['a']
    assert_raw_post_data
  end

  def test_post_with_unrecognized_content_type_ignores_body
    ENV['REQUEST_METHOD'] = 'POST'
    ENV['CONTENT_TYPE'] = 'foo/bar'
    assert cgi.params.empty?
    assert_no_raw_post_data
  end

  def test_put_with_urlencoded_body
    ENV['REQUEST_METHOD'] = 'PUT'
    ENV['CONTENT_TYPE'] = 'application/x-www-form-urlencoded'
    assert_equal ['1'], cgi.params['a']
    assert_raw_post_data
  end

  def test_put_with_empty_content_type_ignores_body
    ENV['REQUEST_METHOD'] = 'PUT'
    ENV['CONTENT_TYPE'] = ''
    assert cgi.params.empty?
    assert_no_raw_post_data
  end

  def test_put_with_unrecognized_content_type_ignores_body
    ENV['REQUEST_METHOD'] = 'PUT'
    ENV['CONTENT_TYPE'] = 'foo/bar'
    assert cgi.params.empty?
    assert_no_raw_post_data
  end

  private
    def cgi
      unless defined? @cgi
        ENV['CONTENT_LENGTH'] = @request_body.size.to_s
        @cgi = CGI.new('query', StringIO.new(@request_body.dup))
      end

      @cgi
    end

    def assert_raw_post_data
      assert_not_nil ENV['RAW_POST_DATA']
      assert ENV['RAW_POST_DATA'].frozen?
      assert_equal @request_body, ENV['RAW_POST_DATA']

      assert_equal '', cgi.stdinput.read
    end

    def assert_no_raw_post_data
      assert_nil ENV['RAW_POST_DATA']

      assert_equal @request_body, cgi.stdinput.read
    end
end