/**
* Copyright 2012 Microsoft Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*   http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

exports = module.exports = {
    capture: capture,
};

function capture(action, cb) {
  var result = {
    text: '',
    errorText: ''
  }

  var processStdoutWrite = process.stdout.write
  var processStderrWrite = process.stderr.write
  var processExit = process.exit

  process.stdout.write = function(data, encoding, fd) {
    result.text += data;
  };

  process.stderr.write = function (data, encoding, fd) {
    result.errorText += data;
  };

  process.exit = function(status) {
    result.exitStatus = status;

    process.stdout.write = processStdoutWrite;
    process.stderr.write = processStderrWrite;
    process.exit = processExit;

    return cb(result);
  };

  try {
    action();
  } catch(err) {
    result.error = err;

    process.stdout.write = processStdoutWrite;
    process.stderr.write = processStderrWrite;
    process.exit = processExit;

    if (!result.exitStatus) {
        cb(result);
    }
  }
}

@@ -582,16 +582,47 @@
 se.%0A*/%0A%0A
+var sinon = require('sinon');%0A%0A
 exports 
@@ -699,16 +699,57 @@
 , cb) %7B%0A
+  var sandbox = sinon.sandbox.create();%0A%0A
   var re
@@ -800,138 +800,21 @@
 %0A%0A  
-var processStdoutWrite = process.stdout.write%0A  var processStderrWrite = process.stderr.write%0A  var processExit = process.exit%0A%0A  
+sandbox.stub(
 proc
@@ -823,24 +823,26 @@
 s.stdout
-.
+, '
 write
- =
+',
  functio
@@ -885,37 +885,51 @@
 ext += data;%0A  %7D
+)
 ;%0A%0A  
+sandbox.stub(
 process.stderr.w
@@ -926,24 +926,26 @@
 s.stderr
-.
+, '
 write
- =
+',
  functio
@@ -1006,27 +1006,43 @@
 %0A  %7D
+)
 ;%0A%0A  
+sandbox.stub(
 process
-.
+, '
 exit
- =
+',
  fun
@@ -1098,128 +1098,25 @@
     
-process.stdout.write = processStdoutWrite;%0A    process.stderr.write = processStderrWrite;%0A    process.exit = processExit
+sandbox.restore()
 ;%0A%0A 
@@ -1140,16 +1140,17 @@
 lt);%0A  %7D
+)
 ;%0A%0A  try
@@ -1216,128 +1216,25 @@
     
-process.stdout.write = processStdoutWrite;%0A    process.stderr.write = processStderrWrite;%0A    process.exit = processExit
+sandbox.restore()
 ;%0A%0A 
@@ -1262,18 +1262,16 @@
 atus) %7B%0A
-  
       cb

Improve CLI test mocking using sinon