File: handler_spec.rb

package info (click to toggle)
puppet 4.8.2-5
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 20,736 kB
  • ctags: 14,616
  • sloc: ruby: 236,754; xml: 1,586; sh: 1,178; lisp: 299; sql: 103; yacc: 72; makefile: 52
file content (182 lines) | stat: -rw-r--r-- 5,865 bytes parent folder | download | duplicates (2)
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
#! /usr/bin/env ruby
require 'spec_helper'

require 'puppet_spec/handler'

require 'puppet/indirector_testing'

require 'puppet/network/authorization'

require 'puppet/network/http'

describe Puppet::Network::HTTP::Handler do
  before :each do
    Puppet::IndirectorTesting.indirection.terminus_class = :memory
  end

  let(:indirection) { Puppet::IndirectorTesting.indirection }

  def a_request(method = "HEAD", path = "/production/#{indirection.name}/unknown")
    {
      :accept_header => "pson",
      :content_type_header => "text/pson",
      :method => method,
      :path => path,
      :params => {},
      :client_cert => nil,
      :headers => {},
      :body => nil
    }
  end

  let(:handler) { PuppetSpec::Handler.new() }

  describe "the HTTP Handler" do
    def respond(text)
      lambda { |req, res| res.respond_with(200, "text/plain", text) }
    end

    it "hands the request to the first route that matches the request path" do
      handler = PuppetSpec::Handler.new(
        Puppet::Network::HTTP::Route.path(%r{^/foo}).get(respond("skipped")),
        Puppet::Network::HTTP::Route.path(%r{^/vtest}).get(respond("used")),
        Puppet::Network::HTTP::Route.path(%r{^/vtest/foo}).get(respond("ignored")))

      req = a_request("GET", "/vtest/foo")
      res = {}

      handler.process(req, res)

      expect(res[:body]).to eq("used")
    end

    it "raises an error if multiple routes with the same path regex are registered" do
      expect do
        handler = PuppetSpec::Handler.new(
          Puppet::Network::HTTP::Route.path(%r{^/foo}).get(respond("ignored")),
          Puppet::Network::HTTP::Route.path(%r{^/foo}).post(respond("also ignored")))
      end.to raise_error(ArgumentError)
    end

    it "raises an HTTP not found error if no routes match" do
      handler = PuppetSpec::Handler.new

      req = a_request("GET", "/vtest/foo")
      res = {}

      handler.process(req, res)

      res_body = JSON(res[:body])

      expect(res[:content_type_header]).to eq("application/json")
      expect(res_body["issue_kind"]).to eq("HANDLER_NOT_FOUND")
      expect(res_body["message"]).to eq("Not Found: No route for GET /vtest/foo")
      expect(res[:status]).to eq(404)
    end

    it "returns a structured error response when the server encounters an internal error" do
      error = StandardError.new("the sky is falling!")
      original_stacktrace = ['a.rb', 'b.rb']
      error.set_backtrace(original_stacktrace)

      handler = PuppetSpec::Handler.new(
        Puppet::Network::HTTP::Route.path(/.*/).get(lambda { |_, _| raise error}))

      # Stacktraces should be included in logs
      Puppet.expects(:err).with("Server Error: the sky is falling!\na.rb\nb.rb")

      req = a_request("GET", "/vtest/foo")
      res = {}

      handler.process(req, res)

      res_body = JSON(res[:body])

      expect(res[:content_type_header]).to eq("application/json")
      expect(res_body["issue_kind"]).to eq(Puppet::Network::HTTP::Issues::RUNTIME_ERROR.to_s)
      expect(res_body["message"]).to eq("Server Error: the sky is falling!")
      expect(res_body["stacktrace"].is_a?(Array) && !res_body["stacktrace"].empty?).to be_truthy
      expect(res_body["stacktrace"][0]).to match(/The 'stacktrace' property is deprecated/)
      expect(res_body["stacktrace"] & original_stacktrace).to be_empty
      expect(res[:status]).to eq(500)
    end

  end

  describe "when processing a request" do
    let(:response) do
      { :status => 200 }
    end

    before do
      handler.stubs(:check_authorization)
      handler.stubs(:warn_if_near_expiration)
    end

    it "should setup a profiler when the puppet-profiling header exists" do
      request = a_request
      request[:headers][Puppet::Network::HTTP::HEADER_ENABLE_PROFILING.downcase] = "true"

      p = PuppetSpec::HandlerProfiler.new

      Puppet::Util::Profiler.expects(:add_profiler).with { |profiler|
        profiler.is_a? Puppet::Util::Profiler::WallClock
      }.returns(p)

      Puppet::Util::Profiler.expects(:remove_profiler).with { |profiler|
        profiler == p
      }

      handler.process(request, response)
    end

    it "should not setup profiler when the profile parameter is missing" do
      request = a_request
      request[:params] = { }

      Puppet::Util::Profiler.expects(:add_profiler).never

      handler.process(request, response)
    end

    it "should still find the correct format if content type contains charset information" do
      request = Puppet::Network::HTTP::Request.new({ 'content-type' => "text/plain; charset=UTF-8" },
                                                   {}, 'GET', '/', nil)
      expect(request.format).to eq("s")
    end

    # PUP-3272
    # This used to be for YAML, and doing a to_yaml on an array.
    # The result with to_pson is something different, the result is a string
    # Which seems correct. Looks like this was some kind of nesting option "yaml inside yaml" ?
    # Removing the test
#    it "should deserialize PSON parameters" do
#      params = {'my_param' => [1,2,3].to_pson}
#
#      decoded_params = handler.send(:decode_params, params)
#
#      decoded_params.should == {:my_param => [1,2,3]}
#    end
  end


  describe "when resolving node" do
    it "should use a look-up from the ip address" do
      Resolv.expects(:getname).with("1.2.3.4").returns("host.domain.com")

      handler.resolve_node(:ip => "1.2.3.4")
    end

    it "should return the look-up result" do
      Resolv.stubs(:getname).with("1.2.3.4").returns("host.domain.com")

      expect(handler.resolve_node(:ip => "1.2.3.4")).to eq("host.domain.com")
    end

    it "should return the ip address if resolving fails" do
      Resolv.stubs(:getname).with("1.2.3.4").raises(RuntimeError, "no such host")

      expect(handler.resolve_node(:ip => "1.2.3.4")).to eq("1.2.3.4")
    end
  end
end