File: flock_spec.rb

package info (click to toggle)
jruby 1.7.26-1%2Bdeb9u1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 84,572 kB
  • sloc: ruby: 669,910; java: 253,056; xml: 35,152; ansic: 9,187; yacc: 7,267; cpp: 5,244; sh: 1,036; makefile: 345; jsp: 48; tcl: 40
file content (96 lines) | stat: -rw-r--r-- 2,093 bytes parent folder | download
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
require File.expand_path('../../../spec_helper', __FILE__)

describe "File#flock" do
  before :each do
    ScratchPad.record []

    @name = tmp("flock_test")
    touch(@name)

    @file = File.open @name, "w+"
  end

  after :each do
    @file.flock File::LOCK_UN
    @file.close

    rm_r @name
  end

  it "exclusively locks a file" do
    @file.flock(File::LOCK_EX).should == 0
    @file.flock(File::LOCK_UN).should == 0
  end

  it "non-exclusively locks a file" do
    @file.flock(File::LOCK_SH).should == 0
    @file.flock(File::LOCK_UN).should == 0
  end

  it "returns false if trying to lock an exclusively locked file" do
    @file.flock File::LOCK_EX

    File.open(@name, "w") do |f2|
      f2.flock(File::LOCK_EX | File::LOCK_NB).should == false
    end
  end

  it "blocks if trying to lock an exclusively locked file" do
    @file.flock File::LOCK_EX

    running = false
    t = Thread.new do
      ScratchPad << :before

      running = true
      File.open(@name, "w") do |f2|
        f2.flock(File::LOCK_EX)
      end

      ScratchPad << :after
    end

    Thread.pass until running
    sleep 0.5

    t.kill
    t.join

    ScratchPad.recorded.should == [:before]
  end

  it "returns 0 if trying to lock a non-exclusively locked file" do
    @file.flock File::LOCK_SH

    File.open(@name, "r") do |f2|
      f2.flock(File::LOCK_SH | File::LOCK_NB).should == 0
      f2.flock(File::LOCK_UN).should == 0
    end
  end

  platform_is :solaris do
    before :each do
      @read_file = File.open @name, "r"
      @write_file = File.open @name, "w"
    end

    after :each do
      @read_file.flock File::LOCK_UN
      @read_file.close
      @write_file.flock File::LOCK_UN
      @write_file.close
    end

    it "fails with EBADF acquiring exclusive lock on read-only File" do
      lambda do
        @read_file.flock File::LOCK_EX
      end.should raise_error(Errno::EBADF)
    end

    it "fails with EBADF acquiring shared lock on read-only File" do
      lambda do
        @write_file.flock File::LOCK_SH
      end.should raise_error(Errno::EBADF)
    end
  end
end