1require 'stringio'
2require 'rubygems/user_interaction'
3
4##
5# This Gem::StreamUI subclass records input and output to StringIO for
6# retrieval during tests.
7
8class Gem::MockGemUi < Gem::StreamUI
9  ##
10  # Raised when you haven't provided enough input to your MockGemUi
11
12  class InputEOFError < RuntimeError
13
14    def initialize question
15      super "Out of input for MockGemUi on #{question.inspect}"
16    end
17
18  end
19
20  class TermError < RuntimeError
21    attr_reader :exit_code
22
23    def initialize exit_code
24      super
25      @exit_code = exit_code
26    end
27  end
28  class SystemExitException < RuntimeError; end
29
30  module TTY
31
32    attr_accessor :tty
33
34    def tty?()
35      @tty = true unless defined?(@tty)
36      @tty
37    end
38
39    def noecho
40      yield self
41    end
42  end
43
44  def initialize(input = "")
45    ins = StringIO.new input
46    outs = StringIO.new
47    errs = StringIO.new
48
49    ins.extend TTY
50    outs.extend TTY
51    errs.extend TTY
52
53    super ins, outs, errs, true
54
55    @terminated = false
56  end
57
58  def ask question
59    raise InputEOFError, question if @ins.eof?
60
61    super
62  end
63
64  def input
65    @ins.string
66  end
67
68  def output
69    @outs.string
70  end
71
72  def error
73    @errs.string
74  end
75
76  def terminated?
77    @terminated
78  end
79
80  def terminate_interaction(status=0)
81    @terminated = true
82
83    raise TermError, status if status != 0
84    raise SystemExitException
85  end
86
87end
88
89