summaryrefslogtreecommitdiff
path: root/spec/unit/recipe_spec.rb
blob: 88fe98c7349658671826dc593ca06fa7cb19ac4f (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
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
#
# Author:: Adam Jacob (<adam@opscode.com>)
# Author:: Christopher Walters (<cw@opscode.com>)
# Author:: Tim Hinderliter (<tim@opscode.com>)
# Author:: Seth Chisamore (<schisamo@opscode.com>)
# Copyright:: Copyright (c) 2008-2011 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'

describe Chef::Recipe do

  let(:cookbook_repo) { File.expand_path(File.join(File.dirname(__FILE__), "..", "data", "cookbooks")) }

  let(:cookbook_loader) do
    loader = Chef::CookbookLoader.new(cookbook_repo)
    loader.load_cookbooks
    loader
  end

  let(:cookbook_collection) { Chef::CookbookCollection.new(cookbook_loader) }

  let(:node) do
    Chef::Node.new.tap {|n| n.normal[:tags] = [] }
  end

  let(:events) do
    Chef::EventDispatch::Dispatcher.new
  end

  let(:run_context) do
    Chef::RunContext.new(node, cookbook_collection, events)
  end

  let(:recipe) do
    Chef::Recipe.new("hjk", "test", run_context)
  end

  describe "method_missing" do
    describe "resources" do
      it "should load a two word (zen_master) resource" do
        expect do
          recipe.zen_master "monkey" do
            peace true
          end
        end.not_to raise_error
      end

      it "should load a one word (cat) resource" do
        expect do
          recipe.cat "loulou" do
            pretty_kitty true
          end
        end.not_to raise_error
      end

      it "should load a four word (one_two_three_four) resource" do
        expect do
          recipe.one_two_three_four "numbers" do
            i_can_count true
          end
        end.not_to raise_error
      end

      it "should throw an error if you access a resource that we can't find" do
        expect { recipe.not_home("not_home_resource") }.to raise_error(NameError)
      end

      it "should require a name argument" do
        expect {
          recipe.cat
        }.to raise_error(ArgumentError, "You must supply a name when declaring a cat resource")
      end

      it "should allow regular errors (not NameErrors) to pass unchanged" do
        expect {
          recipe.cat("felix") { raise ArgumentError, "You Suck" }
        }.to raise_error(ArgumentError)
      end

      it "should add our zen_master to the collection" do
        recipe.zen_master "monkey" do
          peace true
        end
        expect(run_context.resource_collection.lookup("zen_master[monkey]").name).to eql("monkey")
      end

      it "should add our zen masters to the collection in the order they appear" do
        %w{monkey dog cat}.each do |name|
          recipe.zen_master name do
            peace true
          end
        end

        expect(run_context.resource_collection.map{|r| r.name}).to eql(["monkey", "dog", "cat"])
      end

      it "should return the new resource after creating it" do
        res = recipe.zen_master "makoto" do
          peace true
        end
        expect(res.resource_name).to eql(:zen_master)
        expect(res.name).to eql("makoto")
      end

      describe "should locate platform mapped resources" do

        it "locate resource for particular platform" do
          ShaunTheSheep = Class.new(Chef::Resource)
          ShaunTheSheep.provides :laughter, :on_platforms => ["television"]
          node.automatic[:platform] = "television"
          node.automatic[:platform_version] = "123"
          res = recipe.laughter "timmy"
          expect(res.name).to eql("timmy")
          res.kind_of?(ShaunTheSheep)
        end

        it "locate a resource for all platforms" do
          YourMom = Class.new(Chef::Resource)
          YourMom.provides :love_and_caring
          res = recipe.love_and_caring "mommy"
          expect(res.name).to eql("mommy")
          res.kind_of?(YourMom)
        end

      end
    end

    describe "creating resources via build_resource" do
      let(:zm_resource) do
        recipe.build_resource(:zen_master, "klopp") do
          something "bvb"
        end
      end

      it "applies attributes from the block to the resource" do
        expect(zm_resource.something).to eq("bvb")
      end

      it "sets contextual attributes on the resource" do
        expect(zm_resource.recipe_name).to eq("test")
        expect(zm_resource.cookbook_name).to eq("hjk")
        expect(zm_resource.source_line).to include(__FILE__)
        expect(zm_resource.declared_type).to eq(:zen_master)
      end

      it "does not add the resource to the resource collection" do
        zm_resource # force let binding evaluation
        expect { run_context.resource_collection.resources(:zen_master => "klopp") }.to raise_error(Chef::Exceptions::ResourceNotFound)
      end
    end

    describe "when cloning resources" do
      def expect_warning
        expect(Chef::Log).to receive(:warn).with(/3694/)
        expect(Chef::Log).to receive(:warn).with(/Previous/)
        expect(Chef::Log).to receive(:warn).with(/Current/)
      end

      it "should emit a 3694 warning when attributes change" do
        recipe.zen_master "klopp" do
          something "bvb"
        end
        expect_warning
        recipe.zen_master "klopp" do
          something "vbv"
        end
      end

      it "should emit a 3694 warning when attributes change" do
        recipe.zen_master "klopp" do
          something "bvb"
        end
        expect_warning
        recipe.zen_master "klopp" do
          something "bvb"
          peace true
        end
      end

      it "should emit a 3694 warning when attributes change" do
        recipe.zen_master "klopp" do
          something "bvb"
          peace true
        end
        expect_warning
        recipe.zen_master "klopp" do
          something "bvb"
        end
      end

      it "should emit a 3694 warning for non-trivial attributes (unfortunately)" do
        recipe.zen_master "klopp" do
          something "bvb"
        end
        expect_warning
        recipe.zen_master "klopp" do
          something "bvb"
        end
      end

      it "should not emit a 3694 warning for completely trivial resource cloning" do
        recipe.zen_master "klopp"
        expect(Chef::Log).to_not receive(:warn)
        recipe.zen_master "klopp"
      end

      it "should not emit a 3694 warning when attributes do not change and the first action is :nothing" do
        recipe.zen_master "klopp" do
          action :nothing
        end
        expect(Chef::Log).to_not receive(:warn)
        recipe.zen_master "klopp" do
          action :score
        end
      end

      it "should not emit a 3694 warning when attributes do not change and the second action is :nothing" do
        recipe.zen_master "klopp" do
          action :score
        end
        expect(Chef::Log).to_not receive(:warn)
        recipe.zen_master "klopp" do
          action :nothing
        end
      end
    end

    describe "creating resources via declare_resource" do
      let(:zm_resource) do
        recipe.declare_resource(:zen_master, "klopp") do
          something "bvb"
        end
      end

      it "applies attributes from the block to the resource" do
        expect(zm_resource.something).to eq("bvb")
      end

      it "sets contextual attributes on the resource" do
        expect(zm_resource.recipe_name).to eq("test")
        expect(zm_resource.cookbook_name).to eq("hjk")
        expect(zm_resource.source_line).to include(__FILE__)
      end

      it "adds the resource to the resource collection" do
        zm_resource # force let binding evaluation
        expect(run_context.resource_collection.resources(:zen_master => "klopp")).to eq(zm_resource)
      end
    end

    describe "creating a resource with short name" do
      # zen_follower resource has this:
      # provides :follower, :on_platforms => ["zen"]
      before do
        node.automatic_attrs[:platform] = "zen"
      end

      let(:resource_follower) do
        recipe.declare_resource(:follower, "srst") do
          master "none"
        end
      end

      it "defines the resource using the declaration name with short name" do
        resource_follower
        expect(run_context.resource_collection.lookup("follower[srst]")).not_to be_nil
      end
    end

    describe "creating a resource with a long name" do
      let(:resource_zn_follower) do
        recipe.declare_resource(:zen_follower, "srst") do
          master "none"
        end
      end


      it "defines the resource using the declaration name with long name" do
        resource_zn_follower
        expect(run_context.resource_collection.lookup("zen_follower[srst]")).not_to be_nil
      end
    end

    describe "when attempting to create a resource of an invalid type" do

      it "gives a sane error message when using method_missing" do
        expect do
          recipe.no_such_resource("foo")
        end.to raise_error(NoMethodError, %q[No resource or method named `no_such_resource' for `Chef::Recipe "test"'])
      end

      it "gives a sane error message when using method_missing 'bare'" do
        expect do
          recipe.instance_eval do
            # Giving an argument will change this from NameError to NoMethodError
            no_such_resource
          end
        end.to raise_error(NameError, %q[No resource, method, or local variable named `no_such_resource' for `Chef::Recipe "test"'])
      end

      it "gives a sane error message when using build_resource" do
        expect { recipe.build_resource(:no_such_resource, "foo") }.to raise_error(Chef::Exceptions::NoSuchResourceType)
      end

      it "gives a sane error message when using declare_resource" do
        expect { recipe.declare_resource(:no_such_resource, "bar") }.to raise_error(Chef::Exceptions::NoSuchResourceType)
      end

    end

    describe "when creating a resource that contains an error in the attributes block" do

      it "does not obfuscate the error source" do
        expect do
          recipe.zen_master("klopp") do
            this_method_doesnt_exist
          end
        end.to raise_error(NoMethodError, "undefined method `this_method_doesnt_exist' for Chef::Resource::ZenMaster")

      end

    end

    describe "resource cloning" do

      let(:second_recipe) do
        Chef::Recipe.new("second_cb", "second_recipe", run_context)
      end

      let(:original_resource) do
        recipe.zen_master("klopp") do
          something "bvb09"
          action :score
        end
      end

      let(:duplicated_resource) do
        original_resource
        second_recipe.zen_master("klopp") do
          # attrs should be cloned
        end
      end

      it "copies attributes from the first resource" do
        expect(duplicated_resource.something).to eq("bvb09")
      end

      it "does not copy the action from the first resource" do
        expect(original_resource.action).to eq([:score])
        expect(duplicated_resource.action).to eq(:nothing)
      end

      it "does not copy the source location of the first resource" do
        # sanity check source location:
        expect(original_resource.source_line).to include(__FILE__)
        expect(duplicated_resource.source_line).to include(__FILE__)
        # actual test:
        expect(original_resource.source_line).not_to eq(duplicated_resource.source_line)
      end

      it "sets the cookbook name on the cloned resource to that resource's cookbook" do
        expect(duplicated_resource.cookbook_name).to eq("second_cb")
      end

      it "sets the recipe name on the cloned resource to that resoure's recipe" do
        expect(duplicated_resource.recipe_name).to eq("second_recipe")
      end

    end

    describe "resource definitions" do
      it "should execute defined resources" do
        crow_define = Chef::ResourceDefinition.new
        crow_define.define :crow, :peace => false, :something => true do
          zen_master "lao tzu" do
            peace params[:peace]
            something params[:something]
          end
        end
        run_context.definitions[:crow] = crow_define
        recipe.crow "mine" do
          peace true
        end
        expect(run_context.resource_collection.resources(:zen_master => "lao tzu").name).to eql("lao tzu")
        expect(run_context.resource_collection.resources(:zen_master => "lao tzu").something).to eql(true)
      end

      it "should set the node on defined resources" do
        crow_define = Chef::ResourceDefinition.new
        crow_define.define :crow, :peace => false, :something => true do
          zen_master "lao tzu" do
            peace params[:peace]
            something params[:something]
          end
        end
        run_context.definitions[:crow] = crow_define
        node.normal[:foo] = false
        recipe.crow "mine" do
          something node[:foo]
        end
        expect(recipe.resources(:zen_master => "lao tzu").something).to eql(false)
      end

      it "should return the last statement in the definition as the retval" do
        crow_define = Chef::ResourceDefinition.new
        crow_define.define :crow, :peace => false, :something => true do
          "the return val"
        end
        run_context.definitions[:crow] = crow_define
        crow_block = recipe.crow "mine" do
          peace true
        end
        expect(crow_block).to eql("the return val")
      end
    end

  end

  describe "instance_eval" do
    it "should handle an instance_eval properly" do
      code = <<-CODE
  zen_master "gnome" do
    peace = true
  end
  CODE
      expect { recipe.instance_eval(code) }.not_to raise_error
      expect(recipe.resources(:zen_master => "gnome").name).to eql("gnome")
    end
  end

  describe "handle exec calls" do
    it "should raise ResourceNotFound error if exec is used" do
      code = <<-CODE
      exec 'do_not_try_to_exec'
      CODE
      expect { recipe.instance_eval(code) }.to raise_error(Chef::Exceptions::ResourceNotFound)
    end
  end

  describe "from_file" do
    it "should load a resource from a ruby file" do
      recipe.from_file(File.join(CHEF_SPEC_DATA, "recipes", "test.rb"))
      res = recipe.resources(:file => "/etc/nsswitch.conf")
      expect(res.name).to eql("/etc/nsswitch.conf")
      expect(res.action).to eql([:create])
      expect(res.owner).to eql("root")
      expect(res.group).to eql("root")
      expect(res.mode).to eql(0644)
    end

    it "should raise an exception if the file cannot be found or read" do
      expect { recipe.from_file("/tmp/monkeydiving") }.to raise_error(IOError)
    end
  end

  describe "include_recipe" do
    it "should evaluate another recipe with include_recipe" do
      expect(node).to receive(:loaded_recipe).with(:openldap, "gigantor")
      allow(run_context).to receive(:unreachable_cookbook?).with(:openldap).and_return(false)
      run_context.include_recipe "openldap::gigantor"
      res = run_context.resource_collection.resources(:cat => "blanket")
      expect(res.name).to eql("blanket")
      expect(res.pretty_kitty).to eql(false)
    end

    it "should load the default recipe for a cookbook if include_recipe is called without a ::" do
      expect(node).to receive(:loaded_recipe).with(:openldap, "default")
      allow(run_context).to receive(:unreachable_cookbook?).with(:openldap).and_return(false)
      run_context.include_recipe "openldap"
      res = run_context.resource_collection.resources(:cat => "blanket")
      expect(res.name).to eql("blanket")
      expect(res.pretty_kitty).to eql(true)
    end

    it "should store that it has seen a recipe in the run_context" do
      expect(node).to receive(:loaded_recipe).with(:openldap, "default")
      allow(run_context).to receive(:unreachable_cookbook?).with(:openldap).and_return(false)
      run_context.include_recipe "openldap"
      expect(run_context.loaded_recipe?("openldap")).to be_truthy
    end

    it "should not include the same recipe twice" do
      expect(node).to receive(:loaded_recipe).with(:openldap, "default").exactly(:once)
      allow(run_context).to receive(:unreachable_cookbook?).with(:openldap).and_return(false)
      expect(cookbook_collection[:openldap]).to receive(:load_recipe).with("default", run_context)
      recipe.include_recipe "openldap"
      expect(cookbook_collection[:openldap]).not_to receive(:load_recipe).with("default", run_context)
      recipe.include_recipe "openldap"
    end

    it "will load a recipe out of the current cookbook when include_recipe is called with a leading ::" do
      openldap_recipe = Chef::Recipe.new("openldap", "test", run_context)
      expect(node).to receive(:loaded_recipe).with(:openldap, "default").exactly(:once)
      allow(run_context).to receive(:unreachable_cookbook?).with(:openldap).and_return(false)
      expect(cookbook_collection[:openldap]).to receive(:load_recipe).with("default", run_context)
      openldap_recipe.include_recipe "::default"
    end
  end

  describe "tags" do
    describe "with the default node object" do
      let(:node) { Chef::Node.new }

      it "should return false for any tags" do
        expect(recipe.tagged?("foo")).to be(false)
      end
    end

    it "should set tags via tag" do
      recipe.tag "foo"
      expect(node[:tags]).to include("foo")
    end

    it "should set multiple tags via tag" do
      recipe.tag "foo", "bar"
      expect(node[:tags]).to include("foo")
      expect(node[:tags]).to include("bar")
    end

    it "should not set the same tag twice via tag" do
      recipe.tag "foo"
      recipe.tag "foo"
      expect(node[:tags]).to eql([ "foo" ])
    end

    it "should return the current list of tags from tag with no arguments" do
      recipe.tag "foo"
      expect(recipe.tag).to eql([ "foo" ])
    end

    it "should return true from tagged? if node is tagged" do
      recipe.tag "foo"
      expect(recipe.tagged?("foo")).to be(true)
    end

    it "should return false from tagged? if node is not tagged" do
      expect(recipe.tagged?("foo")).to be(false)
    end

    it "should return false from tagged? if node is not tagged" do
      expect(recipe.tagged?("foo")).to be(false)
    end

    it "should remove a tag from the tag list via untag" do
      recipe.tag "foo"
      recipe.untag "foo"
      expect(node[:tags]).to eql([])
    end

    it "should remove multiple tags from the tag list via untag" do
      recipe.tag "foo", "bar"
      recipe.untag "bar", "foo"
      expect(node[:tags]).to eql([])
    end
  end

  describe "included DSL" do
    it "should include features from Chef::DSL::Audit" do
      expect(recipe.singleton_class.included_modules).to include(Chef::DSL::Audit)
      expect(recipe.respond_to?(:controls)).to be true
    end
  end
end