summaryrefslogtreecommitdiff
path: root/spec/unit/mixin/template_spec.rb
blob: 63fa81782e39e250804f5cc3e9c566ae8fb8bc94 (plain)
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
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
#
# Author:: Adam Jacob (<adam@opscode.com>)
# Copyright:: Copyright (c) 2008 Opscode, Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

require 'spec_helper'

require 'cgi'
describe Chef::Mixin::Template, "render_template" do

  let(:sep) { Chef::Platform.windows? ? "\r\n" : "\n" }

  before :each do
    @context = Chef::Mixin::Template::TemplateContext.new({})
  end

  it "should render the template evaluated in the given context" do
    @context[:foo] = "bar"
    output = @context.render_template_from_string("<%= @foo %>")
    output.should == "bar"
  end

  template_contents = [ "Fancy\r\nTemplate\r\n\r\n",
                        "Fancy\nTemplate\n\n",
                        "Fancy\r\nTemplate\n\r\n"]

  describe "when running on windows" do
    before do
      Chef::Platform.stub(:windows?).and_return(true)
    end

    it "should render the templates with windows line endings" do
      template_contents.each do |template_content|
        output = @context.render_template_from_string(template_content)
        output.each_line do |line|
          line.should end_with("\r\n")
        end
      end
    end
  end

  describe "when running on unix" do
    before do
      Chef::Platform.stub(:windows?).and_return(false)
    end

    it "should render the templates with unix line endings" do
      template_contents.each do |template_content|
        output = @context.render_template_from_string(template_content)
        output.each_line do |line|
          line.should end_with("\n")
        end
      end
    end
  end

  it "should provide a node method to access @node" do
    @context[:node] = "tehShizzle"
    output = @context.render_template_from_string("<%= @node %>")
    output.should == "tehShizzle"
  end

  describe "with a template resource" do
    before :each do
      @cookbook_repo = File.expand_path(File.join(CHEF_SPEC_DATA, "cookbooks"))
      Chef::Cookbook::FileVendor.fetch_from_disk(@cookbook_repo)

      @node = Chef::Node.new
      cl = Chef::CookbookLoader.new(@cookbook_repo)
      cl.load_cookbooks
      @cookbook_collection = Chef::CookbookCollection.new(cl)
      @events = Chef::EventDispatch::Dispatcher.new
      @run_context = Chef::RunContext.new(@node, @cookbook_collection, @events)

      @rendered_file_location = Dir.tmpdir + '/openldap_stuff.conf'

      @resource = Chef::Resource::Template.new(@rendered_file_location)
      @resource.cookbook_name = 'openldap'
      @current_resource = @resource.dup

      @content_provider = Chef::Provider::Template::Content.new(@resource, @current_resource, @run_context)

      @template_context = Chef::Mixin::Template::TemplateContext.new({})
      @template_context[:node] = @node
      @template_context[:template_finder] = Chef::Provider::TemplateFinder.new(@run_context, @resource.cookbook_name, @node)
    end

    it "should provide a render method" do
      output = @template_context.render_template_from_string("before {<%= render('test.erb').strip -%>} after")
      output.should == "before {We could be diving for pearls!} after"
    end

    it "should render local files" do
      begin
        tf = Tempfile.new("partial")
        tf.write "test"
        tf.rewind

        output = @template_context.render_template_from_string("before {<%= render '#{tf.path}', :local => true %>} after")
        output.should == "before {test} after"
      ensure
        tf.close
      end
    end

    it "should render partials from a different cookbook" do
      @template_context[:template_finder] = Chef::Provider::TemplateFinder.new(@run_context, 'apache2', @node)

      output = @template_context.render_template_from_string("before {<%= render('test.erb', :cookbook => 'openldap').strip %>} after")
      output.should == "before {We could be diving for pearls!} after"
    end

    it "should render using the source argument if provided" do
      begin
        tf = Tempfile.new("partial")
        tf.write "test"
        tf.rewind

        output = @template_context.render_template_from_string("before {<%= render 'something', :local => true, :source => '#{tf.path}' %>} after")
        output.should == "before {test} after"
      ensure
        tf.close
      end
    end

    it "should pass the node to partials" do
      @node.normal[:slappiness] = "happiness"

      output = @template_context.render_template_from_string("before {<%= render 'openldap_stuff.conf.erb' %>} after")
      output.should == "before {slappiness is happiness} after"
    end

    it "should pass the original variables to partials" do
      @template_context[:secret] = 'candy'

      output = @template_context.render_template_from_string("before {<%= render 'openldap_variable_stuff.conf.erb' %>} after")
      output == "before {super secret is candy} after"
    end

    it "should pass variables to partials" do
      output = @template_context.render_template_from_string("before {<%= render 'openldap_variable_stuff.conf.erb', :variables => {:secret => 'whatever' } %>} after")
      output.should == "before {super secret is whatever} after"
    end

    it "should pass variables to partials even if they are named the same" do
      @template_context[:secret] = 'one'

      output = @template_context.render_template_from_string("before {<%= render 'openldap_variable_stuff.conf.erb', :variables => {:secret => 'two' } %>} after <%= @secret %>")
      output.should == "before {super secret is two} after one"
    end

    it "should pass nil for missing variables in partials" do
      output = @template_context.render_template_from_string("before {<%= render 'openldap_variable_stuff.conf.erb', :variables => {} %>} after")
      output.should == "before {super secret is } after"

      output = @template_context.render_template_from_string("before {<%= render 'openldap_variable_stuff.conf.erb' %>} after")
    output.should == "before {super secret is } after"
    end

    it "should render nested partials" do
      path = File.expand_path(File.join(CHEF_SPEC_DATA, "partial_one.erb"))

      output = @template_context.render_template_from_string("before {<%= render('#{path}', :local => true).strip %>} after")
      output.should == "before {partial one We could be diving for pearls! calling home} after"
    end

    describe "when customizing the template context" do

      it "extends the context to include modules" do
        mod = Module.new do
          def hello
            "ohai"
          end
        end
        @template_context._extend_modules([mod])
        output = @template_context.render_template_from_string("<%=hello%>")
        output.should == "ohai"
      end

      it "emits a warning when overriding 'core' methods" do
        mod = Module.new do
          def render
          end
          def node
          end
          def render_template
          end
          def render_template_from_string
          end
        end
        ['node', 'render', 'render_template', 'render_template_from_string'].each do |method_name|
          Chef::Log.should_receive(:warn).with(/^Core template method `#{method_name}' overridden by extension module/)
        end
        @template_context._extend_modules([mod])
      end
    end

  end

  describe "when an exception is raised in the template" do
    def do_raise
      @context.render_template_from_string("foo\nbar\nbaz\n<%= this_is_not_defined %>\nquin\nqunx\ndunno")
    end

    it "should catch and re-raise the exception as a TemplateError" do
      lambda { do_raise }.should raise_error(Chef::Mixin::Template::TemplateError)
    end

    it "should raise an error if an attempt is made to access node but it is nil" do
      lambda {@context.render_template_from_string("<%= node %>") {|r| r}}.should raise_error(Chef::Mixin::Template::TemplateError)
    end

    describe "the raised TemplateError" do
      before :each do
        begin
          do_raise
        rescue Chef::Mixin::Template::TemplateError => e
          @exception = e
        end
      end

      it "should have the original exception" do
        @exception.original_exception.should be
        @exception.original_exception.message.should =~ /undefined local variable or method `this_is_not_defined'/
      end

      it "should determine the line number of the exception" do
        @exception.line_number.should == 4
      end

      it "should provide a source listing of the template around the exception" do
        @exception.source_listing.should == "  2: bar\n  3: baz\n  4: <%= this_is_not_defined %>\n  5: quin\n  6: qunx"
      end

      it "should provide the evaluation context of the template" do
        @exception.context.should == @context
      end

      it "should defer the message to the original exception" do
        @exception.message.should =~ /undefined local variable or method `this_is_not_defined'/
      end

      it "should provide a nice source location" do
        @exception.source_location.should == "on line #4"
      end

      it "should create a pretty output for the terminal" do
        @exception.to_s.should =~ /Chef::Mixin::Template::TemplateError/
        @exception.to_s.should =~ /undefined local variable or method `this_is_not_defined'/
        @exception.to_s.should include("  2: bar\n  3: baz\n  4: <%= this_is_not_defined %>\n  5: quin\n  6: qunx")
        @exception.to_s.should include(@exception.original_exception.backtrace.first)
      end
    end
  end
end