summaryrefslogtreecommitdiffstats
path: root/test/other/transactions.rb
blob: dd5348e33e6a9b3fd1a5e0a12735982f9bd54377 (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
#!/usr/bin/env ruby

require File.dirname(__FILE__) + '/../lib/puppettest'

require 'mocha'
require 'puppet'
require 'puppettest'
require 'puppettest/support/resources'
require 'puppettest/support/utils'

class TestTransactions < Test::Unit::TestCase
    include PuppetTest::FileTesting
    include PuppetTest::Support::Resources
    include PuppetTest::Support::Utils
    class Fakeprop <Puppet::Property
        initvars()

        attr_accessor :path, :is, :should, :name
        def should_to_s(value)
            value.to_s
        end
        def insync?(foo)
            true
        end
        def info(*args)
            false
        end

        def set(value)
            # eh
        end

        def log(msg)
        end
    end


    def mkgenerator(&block)
        $finished = []
        cleanup { $finished = nil }

        # Create a bogus type that generates new instances with shorter
        type = Puppet::Type.newtype(:generator) do
            newparam(:name, :namevar => true)
            def finish
                $finished << self.name
            end
        end
        type.class_eval(&block) if block
        cleanup do
            Puppet::Type.rmtype(:generator)
        end

        type
    end

    # Create a new type that generates instances with shorter names.
    def mkreducer(&block)
        type = mkgenerator() do
            def eval_generate
                ret = []
                if title.length > 1
                    ret << self.class.new(:title => title[0..-2])
                else
                    return nil
                end
                ret
            end
        end

        type.class_eval(&block) if block

        type
    end

    def test_prefetch
        # Create a type just for testing prefetch
        name = :prefetchtesting
        $prefetched = false
        type = Puppet::Type.newtype(name) do
            newparam(:name) {}
        end

        cleanup do
            Puppet::Type.rmtype(name)
        end

        # Now create a provider
        type.provide(:prefetch) do
            def self.prefetch(resources)
                $prefetched = resources
            end
        end

        # Now create an instance
        inst = type.new :name => "yay"

        # Create a transaction
        trans = Puppet::Transaction.new(mk_catalog(inst))

        # Make sure prefetch works
        assert_nothing_raised do
            trans.prefetch
        end

        assert_equal({inst.title => inst}, $prefetched, "type prefetch was not called")

        # Now make sure it gets called from within evaluate()
        $prefetched = false
        assert_nothing_raised do
            trans.evaluate
        end

        assert_equal({inst.title => inst}, $prefetched, "evaluate did not call prefetch")
    end

    # We need to generate resources before we prefetch them, else generated
    # resources that require prefetching don't work.
    def test_generate_before_prefetch
        config = mk_catalog()
        trans = Puppet::Transaction.new(config)

        generate = nil
        prefetch = nil
        trans.expects(:generate).with { |*args| generate = Time.now; true }
        trans.expects(:prefetch).with { |*args| ! generate.nil? }
        trans.prepare
        return

        resource = Puppet::Type.type(:file).new :ensure => :present, :path => tempfile()
        other_resource = mock 'generated'
        def resource.generate
            [other_resource]
        end


        config = mk_catalog(yay, rah)
        trans = Puppet::Transaction.new(config)

        assert_nothing_raised do
            trans.generate
        end

        %w{ya ra y r}.each do |name|
            assert(trans.catalog.vertex?(Puppet::Type.type(:generator)[name]), "Generated #{name} was not a vertex")
            assert($finished.include?(name), "#{name} was not finished")
        end
    end

    def test_ignore_tags?
        config = Puppet::Resource::Catalog.new
        config.host_config = true
        transaction = Puppet::Transaction.new(config)
        assert(! transaction.ignore_tags?, "Ignoring tags when applying a host catalog")

        config.host_config = false
        transaction = Puppet::Transaction.new(config)
        assert(transaction.ignore_tags?, "Not ignoring tags when applying a non-host catalog")
    end

    def test_missing_tags?
        resource = Puppet::Type.type(:notify).new :title => "foo"
        resource.stubs(:tagged?).returns true
        config = Puppet::Resource::Catalog.new

        # Mark it as a host config so we don't care which test is first
        config.host_config = true
        transaction = Puppet::Transaction.new(config)
        assert(! transaction.missing_tags?(resource), "Considered a resource to be missing tags when none are set")

        # host catalogs pay attention to tags, no one else does.
        Puppet[:tags] = "three,four"
        config.host_config = false
        transaction = Puppet::Transaction.new(config)
        assert(! transaction.missing_tags?(resource), "Considered a resource to be missing tags when not running a host catalog")

        #
        config.host_config = true
        transaction = Puppet::Transaction.new(config)
        assert(! transaction.missing_tags?(resource), "Considered a resource to be missing tags when running a host catalog and all tags are present")

        transaction = Puppet::Transaction.new(config)
        resource.stubs :tagged? => false
        assert(transaction.missing_tags?(resource), "Considered a resource not to be missing tags when running a host catalog and tags are missing")
    end

    # Make sure changes in contained files still generate callback events.
    def test_generated_callbacks
        dir = tempfile()
        maker = tempfile()
        Dir.mkdir(dir)
        file = File.join(dir, "file")
        File.open(file, "w") { |f| f.puts "" }
        File.chmod(0644, file)
        File.chmod(0755, dir) # So only the child file causes a change

        dirobj = Puppet::Type.type(:file).new :mode => "755", :recurse => true, :path => dir
        exec = Puppet::Type.type(:exec).new :title => "make",
            :command => "touch #{maker}", :path => ENV['PATH'], :refreshonly => true,
            :subscribe => dirobj

        assert_apply(dirobj, exec)
        assert(FileTest.exists?(maker), "Did not make callback file")
    end

    # Testing #401 -- transactions are calling refresh() on classes that don't support it.
    def test_callback_availability
        $called = []
        klass = Puppet::Type.newtype(:norefresh) do
            newparam(:name, :namevar => true) {}
            def method_missing(method, *args)
                $called << method
            end
        end
        cleanup do
            $called = nil
            Puppet::Type.rmtype(:norefresh)
        end

        file = Puppet::Type.type(:file).new :path => tempfile(), :content => "yay"
        one = klass.new :name => "one", :subscribe => file

        assert_apply(file, one)

        assert(! $called.include?(:refresh), "Called refresh when it wasn't set as a method")
    end

    # Testing #437 - cyclic graphs should throw failures.
    def test_fail_on_cycle
        one = Puppet::Type.type(:exec).new(:name => "/bin/echo one")
        two = Puppet::Type.type(:exec).new(:name => "/bin/echo two")
        one[:require] = two
        two[:require] = one

        config = mk_catalog(one, two)
        trans = Puppet::Transaction.new(config)
        assert_raise(Puppet::Error) do
            trans.prepare
        end
    end

    def test_errors_during_generation
        type = Puppet::Type.newtype(:failer) do
            newparam(:name) {}
            def eval_generate
                raise ArgumentError, "Invalid value"
            end
            def generate
                raise ArgumentError, "Invalid value"
            end
        end
        cleanup { Puppet::Type.rmtype(:failer) }

        obj = type.new(:name => "testing")

        assert_apply(obj)
    end

    def test_self_refresh_causes_triggering
        type = Puppet::Type.newtype(:refresher, :self_refresh => true) do
            attr_accessor :refreshed, :testing
            newparam(:name) {}
            newproperty(:testing) do
                def retrieve
                    :eh
                end

                def sync
                    # noop
                    :ran_testing
                end
            end
            def refresh
                @refreshed = true
            end
        end
        cleanup { Puppet::Type.rmtype(:refresher)}

        obj = type.new(:name => "yay", :testing => "cool")

        assert(! obj.insync?(obj.retrieve), "fake object is already in sync")

        # Now make sure it gets refreshed when the change happens
        assert_apply(obj)
        assert(obj.refreshed, "object was not refreshed during transaction")
    end

    # Testing #433
    def test_explicit_dependencies_beat_automatic
        # Create a couple of different resource sets that have automatic relationships and make sure the manual relationships win
        rels = {}
        # Now add the explicit relationship
        # Now files
        d = tempfile()
        f = File.join(d, "file")
        file = Puppet::Type.type(:file).new(:path => f, :content => "yay")
        dir = Puppet::Type.type(:file).new(:path => d, :ensure => :directory, :require => file)

        rels[dir] = file
        rels.each do |after, before|
            config = mk_catalog(before, after)
            trans = Puppet::Transaction.new(config)
            str = "from #{before} to #{after}"

            assert_nothing_raised("Failed to create graph #{str}") do
                trans.prepare
            end

            graph = trans.relationship_graph
            assert(graph.edge?(before, after), "did not create manual relationship #{str}")
            assert(! graph.edge?(after, before), "created automatic relationship #{str}")
        end
    end

    # #542 - make sure resources in noop mode still notify their resources,
    # so that users know if a service will get restarted.
    def test_noop_with_notify
        path = tempfile
        epath = tempfile
        spath = tempfile

                    file = Puppet::Type.type(:file).new(
                :path => path, :ensure => :file,
        
            :title => "file")

                    exec = Puppet::Type.type(:exec).new(
                :command => "touch #{epath}",
            :path => ENV["PATH"], :subscribe => file, :refreshonly => true,
        
            :title => 'exec1')

                    exec2 = Puppet::Type.type(:exec).new(
                :command => "touch #{spath}",
            :path => ENV["PATH"], :subscribe => exec, :refreshonly => true,
        
            :title => 'exec2')

        Puppet[:noop] = true

        assert(file.noop, "file not in noop")
        assert(exec.noop, "exec not in noop")

        @logs.clear
        assert_apply(file, exec, exec2)

        assert(! FileTest.exists?(path), "Created file in noop")
        assert(! FileTest.exists?(epath), "Executed exec in noop")
        assert(! FileTest.exists?(spath), "Executed second exec in noop")

        assert(@logs.detect { |l|
            l.message =~ /should be/  and l.source == file.property(:ensure).path},
                "did not log file change")

                    assert(
                @logs.detect { |l|
            l.message =~ /Would have/ and l.source == exec.path },
        
                "did not log first exec trigger")

                    assert(
                @logs.detect { |l|
            l.message =~ /Would have/ and l.source == exec2.path },
        
                "did not log second exec trigger")
    end

    def test_only_stop_purging_with_relations
        files = []
        paths = []
        3.times do |i|
            path = tempfile
            paths << path

                        file = Puppet::Type.type(:file).new(
                :path => path, :ensure => :absent,
        
                :backup => false, :title => "file#{i}")
            File.open(path, "w") { |f| f.puts "" }
            files << file
        end

        files[0][:ensure] = :file
        files[0][:require] = files[1..2]

        # Mark the second as purging
        files[1].purging

        assert_apply(*files)

        assert(FileTest.exists?(paths[1]), "Deleted required purging file")
        assert(! FileTest.exists?(paths[2]), "Did not delete non-purged file")
    end

    def test_flush
        $state = :absent
        $flushed = 0
        type = Puppet::Type.newtype(:flushtest) do
            newparam(:name)
            newproperty(:ensure) do
                newvalues :absent, :present, :other
                def retrieve
                    $state
                end
                def set(value)
                    $state = value
                    :thing_changed
                end
            end

            def flush
                $flushed += 1
            end
        end

        cleanup { Puppet::Type.rmtype(:flushtest) }

        obj = type.new(:name => "test", :ensure => :present)

        # first make sure it runs through and flushes
        assert_apply(obj)

        assert_equal(:present, $state, "Object did not make a change")
        assert_equal(1, $flushed, "object was not flushed")

        # Now run a noop and make sure we don't flush
        obj[:ensure] = "other"
        obj[:noop] = true

        assert_apply(obj)
        assert_equal(:present, $state, "Object made a change in noop")
        assert_equal(1, $flushed, "object was flushed in noop")
    end
end