summaryrefslogtreecommitdiffstats
path: root/spec/integration/util/file_locking_spec.rb
blob: 1914fadf77c55c253e58f5c786f41548da773925 (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
#!/usr/bin/env ruby

require File.expand_path(File.dirname(__FILE__) + '/../../spec_helper')

require 'puppet/util/file_locking'

describe Puppet::Util::FileLocking do
  before :each do
    @file = Tempfile.new("puppetspec")
    filepath = @file.path
    @file.close!()
    @file = filepath
    @data = {:a => :b, :c => "A string", :d => "another string", :e => %w{an array of strings}}
    File.open(@file, "w") { |f| f.puts YAML.dump(@data) }
  end

  it "should be able to keep file corruption from happening when there are multiple writers threads" do
    threads = []
    sync = Sync.new
    9.times { |a|
      threads << Thread.new {
        9.times { |b|
          sync.synchronize(Sync::SH) {
            Puppet::Util::FileLocking.readlock(@file) { |f|
              YAML.load(f.read).should == @data
            }
          }
          sleep 0.01
          sync.synchronize(Sync::EX) {
            Puppet::Util::FileLocking.writelock(@file) { |f|
              f.puts YAML.dump(@data)
            }
          }
        }
      }
    }
    threads.each { |th| th.join }
  end

  it "should be able to keep file corruption from happening when there are multiple writers processes" do
    unless Process.fork
      50.times { |b|
        Puppet::Util::FileLocking.writelock(@file) { |f|
          f.puts YAML.dump(@data)
        }
        sleep 0.01
      }
      Kernel.exit!
    end

    50.times { |c|
      Puppet::Util::FileLocking.readlock(@file) { |f|
        YAML.load(f.read).should == @data
      }
    }
  end
end