aboutsummaryrefslogtreecommitdiffstats
path: root/Library/Homebrew/test/utils/tty_spec.rb
blob: e6c9168f3158786cedd59e6d2d266b51c308bf4c (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
require "utils"

describe Tty do
  describe "::strip_ansi" do
    it "removes ANSI escape codes from a string" do
      expect(subject.strip_ansi("\033\[36;7mhello\033\[0m")).to eq("hello")
    end
  end

  describe "::width" do
    it "returns an Integer" do
      expect(subject.width).to be_kind_of(Integer)
    end

    it "cannot be negative" do
      expect(subject.width).to be >= 0
    end
  end

  describe "::truncate" do
    it "truncates the text to the terminal width, minus 4, to account for '==> '" do
      allow(subject).to receive(:width).and_return(15)

      expect(subject.truncate("foobar something very long")).to eq("foobar some")
      expect(subject.truncate("truncate")).to eq("truncate")
    end

    it "doesn't truncate the text if the terminal is unsupported, i.e. the width is 0" do
      allow(subject).to receive(:width).and_return(0)
      expect(subject.truncate("foobar something very long")).to eq("foobar something very long")
    end
  end

  context "when $stdout is not a TTY" do
    before(:each) do
      allow($stdout).to receive(:tty?).and_return(false)
    end

    it "returns an empty string for all colors" do
      expect(subject.to_s).to eq("")
      expect(subject.red.to_s).to eq("")
      expect(subject.green.to_s).to eq("")
      expect(subject.yellow.to_s).to eq("")
      expect(subject.blue.to_s).to eq("")
      expect(subject.magenta.to_s).to eq("")
      expect(subject.cyan.to_s).to eq("")
      expect(subject.default.to_s).to eq("")
    end
  end

  context "when $stdout is a TTY" do
    before(:each) do
      allow($stdout).to receive(:tty?).and_return(true)
    end

    it "returns ANSI escape codes for colors" do
      expect(subject.to_s).to eq("")
      expect(subject.red.to_s).to eq("\033[31m")
      expect(subject.green.to_s).to eq("\033[32m")
      expect(subject.yellow.to_s).to eq("\033[33m")
      expect(subject.blue.to_s).to eq("\033[34m")
      expect(subject.magenta.to_s).to eq("\033[35m")
      expect(subject.cyan.to_s).to eq("\033[36m")
      expect(subject.default.to_s).to eq("\033[39m")
    end

    it "returns an empty string for all colors when HOMEBREW_NO_COLOR is set" do
      ENV["HOMEBREW_NO_COLOR"] = "1"
      expect(subject.to_s).to eq("")
      expect(subject.red.to_s).to eq("")
      expect(subject.green.to_s).to eq("")
      expect(subject.yellow.to_s).to eq("")
      expect(subject.blue.to_s).to eq("")
      expect(subject.magenta.to_s).to eq("")
      expect(subject.cyan.to_s).to eq("")
      expect(subject.default.to_s).to eq("")
    end
  end
end