incubator-ambari-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From maha...@apache.org
Subject svn commit: r1442010 [3/29] - in /incubator/ambari/branches/branch-1.2: ./ ambari-agent/ ambari-agent/conf/unix/ ambari-agent/src/examples/ ambari-agent/src/main/puppet/modules/hdp-ganglia/files/ ambari-agent/src/main/puppet/modules/hdp-ganglia/manifes...
Date Mon, 04 Feb 2013 02:24:02 GMT
Modified: incubator/ambari/branches/branch-1.2/ambari-agent/src/test/python/TestNetUtil.py
URL: http://svn.apache.org/viewvc/incubator/ambari/branches/branch-1.2/ambari-agent/src/test/python/TestNetUtil.py?rev=1442010&r1=1442009&r2=1442010&view=diff
==============================================================================
--- incubator/ambari/branches/branch-1.2/ambari-agent/src/test/python/TestNetUtil.py (original)
+++ incubator/ambari/branches/branch-1.2/ambari-agent/src/test/python/TestNetUtil.py Mon Feb  4 02:23:55 2013
@@ -18,79 +18,60 @@ See the License for the specific languag
 limitations under the License.
 '''
 
-from unittest import TestCase
-from ambari_agent.ServerStatus import ServerStatus
-from ambari_agent.NetUtil import NetUtil
-import ambari_agent.main
-from threading import Thread
-import time
-from ambari_agent.Heartbeat import Heartbeat
-from ambari_agent.ActionQueue import ActionQueue
-from ambari_agent import AmbariConfig
-import socket
-import os
-import logging
-from ambari_agent.Controller import Controller
-import socket
-
-NON_EXISTING_DOMAIN = 'non-existing-domain43342432.com'
-BAD_URL = 'http://localhost:54222/badurl/'
-
-class TestNetUtil(TestCase):
-
-  logger = logging.getLogger()
-
-  def setUp(self):
-    self.logger.info("Starting TestConnectionRetries test")
-    self.logger.disabled = True
-    self.defaulttimeout = -1.0
-    if hasattr(socket, 'getdefaulttimeout'):
-      # get the default timeout on sockets
-      self.defaulttimeout = socket.getdefaulttimeout()
-
-
-# Test was failing: BUG-3112
-#  def test_url_checks(self):
-#    netutil = NetUtil()
-#    if hasattr(socket, 'setdefaulttimeout'):
-#      # Set the default timeout on sockets
-#      socket.setdefaulttimeout(1)
-#    self.assertEquals(netutil.checkURL('http://' + NON_EXISTING_DOMAIN), False, "Not existing domain")
-#    self.assertEquals(netutil.checkURL(BAD_URL), False, "Bad url")
-#    self.assertEquals(netutil.checkURL('http://192.168.253.177'), False, "Not reachable IP")
-#    if hasattr(socket, 'setdefaulttimeout'):
-#      # Set the default timeout on sockets
-#      socket.setdefaulttimeout(20)
-#    self.assertEquals(netutil.checkURL('http://www.iana.org/domains/example/'), True, "Good url - HTTP code 200")
-#    self.assertEquals(netutil.checkURL('https://www.iana.org/domains/example/'), True, "Good HTTPS url - HTTP code 200")
-
-
-  def test_registration_retries(self):
-    netutil = NetUtil()
-    netutil.CONNECT_SERVER_RETRY_INTERVAL_SEC=0.05
-    retries = netutil.try_to_connect(BAD_URL, 3)
-    self.assertEquals(retries, 3)
-
-  def test_infinit_registration_retries(self):
-    netutil = NetUtil()
-    netutil.CONNECT_SERVER_RETRY_INTERVAL_SEC=0.05
-    thread = Thread(target = netutil.try_to_connect, args = (BAD_URL, -1))
-    thread.start()
-    time.sleep(0.25)
-    # I have to stop the thread anyway, so I'll check results later
-    threadWasAlive = thread.isAlive()
-    netutil.DEBUG_STOP_RETRIES_FLAG = True
-    time.sleep(0.5)
-    # Checking results before thread stop
-    self.assertEquals(threadWasAlive, True, "Thread should still be retrying to connect")
-    # Checking results after thread stop
-    self.assertEquals(thread.isAlive(), False, "Thread should stop now")
-
-  def tearDown(self):
-    if self.defaulttimeout is not None and self.defaulttimeout > 0 and hasattr(socket, 'setdefaulttimeout'):
-      # Set the default timeout on sockets
-      socket.setdefaulttimeout(self.defaulttimeout)
-    self.logger.disabled = False
-    self.logger.info("Finished TestConnectionRetries test")
+from ambari_agent import NetUtil
+from mock.mock import MagicMock, patch
+import unittest
+
+class TestNetUtil(unittest.TestCase):
+
+  @patch("urlparse.urlparse")
+  @patch("httplib.HTTPSConnection")
+  def test_checkURL(self, httpsConMock, parseMock):
+
+    NetUtil.logger = MagicMock()
+    parseMock.return_value = [1, 2]
+    ca_connection = MagicMock()
+    response = MagicMock()
+    response.status = 200
+    ca_connection.getresponse.return_value = response
+    httpsConMock.return_value = ca_connection
+
+    # test 200
+    netutil = NetUtil.NetUtil()
+    self.assertTrue(netutil.checkURL("url"))
+
+    # test fail
+    response.status = 404
+    self.assertFalse(netutil.checkURL("url"))
+
+    # test Exception
+    response.status = 200
+    httpsConMock.side_effect = Exception("test")
+    self.assertFalse(netutil.checkURL("url"))
+
+
+  @patch("time.sleep")
+  def test_try_to_connect(self, sleepMock):
+
+    netutil = NetUtil.NetUtil()
+    checkURL = MagicMock(name="checkURL")
+    checkURL.return_value = True
+    netutil.checkURL = checkURL
+    l = MagicMock()
+
+    # one successful get
+    self.assertEqual(0, netutil.try_to_connect("url", 10))
+
+    # got successful after N retries
+    gets = [True, False, False]
+    def side_effect(*args):
+      return gets.pop()
+    checkURL.side_effect = side_effect
+    self.assertEqual(2, netutil.try_to_connect("url", 10))
+
+    # max retries
+    checkURL.side_effect = None
+    checkURL.return_value = False
+    self.assertEqual(5, netutil.try_to_connect("url", 5))
 
 

Added: incubator/ambari/branches/branch-1.2/ambari-agent/src/test/python/TestProcessHelper.py
URL: http://svn.apache.org/viewvc/incubator/ambari/branches/branch-1.2/ambari-agent/src/test/python/TestProcessHelper.py?rev=1442010&view=auto
==============================================================================
--- incubator/ambari/branches/branch-1.2/ambari-agent/src/test/python/TestProcessHelper.py (added)
+++ incubator/ambari/branches/branch-1.2/ambari-agent/src/test/python/TestProcessHelper.py Mon Feb  4 02:23:55 2013
@@ -0,0 +1,68 @@
+#!/usr/bin/env python2.6
+# -*- coding: utf-8 -*-
+
+'''
+Licensed to the Apache Software Foundation (ASF) under one
+or more contributor license agreements.  See the NOTICE file
+distributed with this work for additional information
+regarding copyright ownership.  The ASF licenses this file
+to you 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.
+'''
+
+import os
+import tempfile
+import unittest
+from mock.mock import patch, MagicMock
+from ambari_agent import ProcessHelper
+
+
+class TestProcessHelper(unittest.TestCase):
+
+  @patch.object(ProcessHelper, "getTempFiles")
+  def test_clean(self, getTempFilesMock):
+
+    tf1 = tempfile.NamedTemporaryFile(delete=False)
+    tf2 = tempfile.NamedTemporaryFile(delete=False)
+    tf3 = tempfile.NamedTemporaryFile(delete=False)
+
+    getTempFilesMock.return_value = [tf2.name, tf3.name]
+    ProcessHelper.pidfile = tf1.name
+    ProcessHelper.logger = MagicMock()
+
+    ProcessHelper._clean()
+
+    self.assertFalse(os.path.exists(tf1.name))
+    self.assertFalse(os.path.exists(tf2.name))
+    self.assertFalse(os.path.exists(tf3.name))
+
+
+  @patch("os._exit")
+  @patch.object(ProcessHelper, "_clean")
+  def test_stopAgent(self, _clean_mock, exitMock):
+
+    ProcessHelper.stopAgent()
+    self.assertTrue(_clean_mock.called)
+    self.assertTrue(exitMock.called)
+
+
+  @patch("os.execvp")
+  @patch.object(ProcessHelper, "_clean")
+  def test_restartAgent(self, _clean_mock, execMock):
+
+    ProcessHelper.logger = MagicMock()
+    ProcessHelper.restartAgent()
+
+    self.assertTrue(_clean_mock.called)
+    self.assertTrue(execMock.called)
+    self.assertEqual(2, len(execMock.call_args_list[0]))
+

Modified: incubator/ambari/branches/branch-1.2/ambari-agent/src/test/python/TestPuppetExecutor.py
URL: http://svn.apache.org/viewvc/incubator/ambari/branches/branch-1.2/ambari-agent/src/test/python/TestPuppetExecutor.py?rev=1442010&r1=1442009&r2=1442010&view=diff
==============================================================================
--- incubator/ambari/branches/branch-1.2/ambari-agent/src/test/python/TestPuppetExecutor.py (original)
+++ incubator/ambari/branches/branch-1.2/ambari-agent/src/test/python/TestPuppetExecutor.py Mon Feb  4 02:23:55 2013
@@ -143,6 +143,9 @@ class TestPuppetExecutor(TestCase):
       self.subprocess_mockup.tmperr = tmperr
       return self.subprocess_mockup
 
+    def runShellKillPgrp(self, puppet):
+      puppet.terminate()  # note: In real code, subprocess.terminate() is not called
+      pass
 
   class Subprocess_mockup():
 
@@ -154,6 +157,7 @@ class TestPuppetExecutor(TestCase):
     was_terminated = False
     tmpout = None
     tmperr = None
+    pid=-1
 
     def communicate(self):
       self.started_event.set()

Modified: incubator/ambari/branches/branch-1.2/ambari-agent/src/test/python/TestRegistration.py
URL: http://svn.apache.org/viewvc/incubator/ambari/branches/branch-1.2/ambari-agent/src/test/python/TestRegistration.py?rev=1442010&r1=1442009&r2=1442010&view=diff
==============================================================================
--- incubator/ambari/branches/branch-1.2/ambari-agent/src/test/python/TestRegistration.py (original)
+++ incubator/ambari/branches/branch-1.2/ambari-agent/src/test/python/TestRegistration.py Mon Feb  4 02:23:55 2013
@@ -34,4 +34,5 @@ class TestRegistration(TestCase):
     self.assertEquals(data['publicHostname'] != "", True, "publicHostname should not be empty")
     self.assertEquals(data['responseId'], 1)
     self.assertEquals(data['timestamp'] > 1353678475465L, True, "timestamp should not be empty")
-    self.assertEquals(len(data), 5)
+    self.assertEquals(len(data['agentEnv']) > 0, True, "agentEnv should not be empty")
+    self.assertEquals(len(data), 6)

Added: incubator/ambari/branches/branch-1.2/ambari-agent/src/test/python/TestRepoInstaller.py
URL: http://svn.apache.org/viewvc/incubator/ambari/branches/branch-1.2/ambari-agent/src/test/python/TestRepoInstaller.py?rev=1442010&view=auto
==============================================================================
--- incubator/ambari/branches/branch-1.2/ambari-agent/src/test/python/TestRepoInstaller.py (added)
+++ incubator/ambari/branches/branch-1.2/ambari-agent/src/test/python/TestRepoInstaller.py Mon Feb  4 02:23:55 2013
@@ -0,0 +1,52 @@
+#!/usr/bin/env python2.6
+
+'''
+Licensed to the Apache Software Foundation (ASF) under one
+or more contributor license agreements.  See the NOTICE file
+distributed with this work for additional information
+regarding copyright ownership.  The ASF licenses this file
+to you 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.
+'''
+
+from unittest import TestCase
+from ambari_agent.RepoInstaller import RepoInstaller
+import tempfile
+import json
+import shutil
+from ambari_agent.AmbariConfig import AmbariConfig
+from mock.mock import patch, MagicMock, call
+
+class TestRepoInstaller(TestCase):
+
+  def setUp(self):
+    self.dir = tempfile.mkdtemp()
+    jsonCommand = file('../../main/python/ambari_agent/test.json').read()
+    self.parsedJson= json.loads(jsonCommand)
+    self.config = AmbariConfig().getConfig()
+    self.repoInstaller = RepoInstaller(self.parsedJson, self.dir, '../../main/puppet/modules', 1, self.config)
+
+    pass
+
+  def tearDown(self):
+    shutil.rmtree(self.dir)
+    pass
+
+
+  @patch.object(RepoInstaller, 'prepareReposInfo')
+  @patch.object(RepoInstaller, 'generateFiles')
+  def testInstallRepos(self, generateFilesMock, prepareReposInfoMock):
+    result = self.repoInstaller.installRepos()
+    self.assertTrue(prepareReposInfoMock.called)
+    self.assertTrue(generateFilesMock.called)
+    print('installRepos result: ' + result.__str__())
+    pass

Modified: incubator/ambari/branches/branch-1.2/ambari-agent/src/test/python/TestStatusCheck.py
URL: http://svn.apache.org/viewvc/incubator/ambari/branches/branch-1.2/ambari-agent/src/test/python/TestStatusCheck.py?rev=1442010&r1=1442009&r2=1442010&view=diff
==============================================================================
--- incubator/ambari/branches/branch-1.2/ambari-agent/src/test/python/TestStatusCheck.py (original)
+++ incubator/ambari/branches/branch-1.2/ambari-agent/src/test/python/TestStatusCheck.py Mon Feb  4 02:23:55 2013
@@ -46,9 +46,17 @@ DEAD_PID=0
 class TestStatusCheck(TestCase):
 
   def setUp(self):
+
     self.tmpdir = tempfile.mkdtemp()
-    self.tmpdict = tempfile.NamedTemporaryFile(dir=self.tmpdir)
-    self.tmpdict = open(self.tmpdir + os.sep + MAPPING_FILE_NAME, 'w')
+    self.serviceToPidDict = {
+      COMPONENT_LIVE : COMPONENT_LIVE_PID,
+      COMPONENT_DEAD : COMPONENT_DEAD_PID
+    }
+
+    self.pidPathesVars = [
+      {'var' : '',
+      'defaultValue' : self.tmpdir}
+    ]
 
     self.sh = shellRunner()
     
@@ -56,10 +64,6 @@ class TestStatusCheck(TestCase):
     p = subprocess.Popen([COMPONENT_LIVE_CMD], stdout=subprocess.PIPE, 
                          stderr=subprocess.PIPE, shell=True, close_fds=True)
 
-    #Write mapping for pid files for both live and dead process
-    self.tmpdict.write(COMPONENT_LIVE + '=' + COMPONENT_LIVE_PID + os.linesep)
-    self.tmpdict.write(COMPONENT_DEAD + '=' + COMPONENT_DEAD_PID + os.linesep)
-    self.tmpdict.close()
 
     #Write pid of live process to file
     live_pid_file = open(self.tmpdir + os.sep + COMPONENT_LIVE_PID, 'w')
@@ -73,12 +77,7 @@ class TestStatusCheck(TestCase):
     dead_pid_file.close()
 
     #Init status checker
-    self.statusCheck = StatusCheck(self.tmpdir, self.tmpdict.name)
-
-  # Ensure that status checker throws exceptions on invalid params
-  def test_exceptions(self):
-    self.assertRaises(ValueError,StatusCheck,"tmp","tmp")
-    self.assertRaises(IOError, StatusCheck,self.tmpdir,"tmp")
+    self.statusCheck = StatusCheck(self.serviceToPidDict,self.pidPathesVars,{})
 
   # Ensure that status checker return True for running process
   def test_live(self):

Modified: incubator/ambari/branches/branch-1.2/ambari-agent/src/test/python/dummy_puppet_output_error.txt
URL: http://svn.apache.org/viewvc/incubator/ambari/branches/branch-1.2/ambari-agent/src/test/python/dummy_puppet_output_error.txt?rev=1442010&r1=1442009&r2=1442010&view=diff
==============================================================================
--- incubator/ambari/branches/branch-1.2/ambari-agent/src/test/python/dummy_puppet_output_error.txt (original)
+++ incubator/ambari/branches/branch-1.2/ambari-agent/src/test/python/dummy_puppet_output_error.txt Mon Feb  4 02:23:55 2013
@@ -41,5 +41,5 @@ debug: Storing state
 debug: Stored state in 0.01 seconds
 notice: Finished catalog run in 0.23 seconds
 debug: Finishing transaction 70171638871060
-debug: Received report to process from ambari-dmi.cybervisiontech.com.ua
-debug: Processing report from ambari-dmi.cybervisiontech.com.ua with processor Puppet::Reports::Store
+debug: Received report to process from ambari-dmi
+debug: Processing report from ambari-dmi with processor Puppet::Reports::Store

Modified: incubator/ambari/branches/branch-1.2/ambari-agent/src/test/python/dummy_puppet_output_good.txt
URL: http://svn.apache.org/viewvc/incubator/ambari/branches/branch-1.2/ambari-agent/src/test/python/dummy_puppet_output_good.txt?rev=1442010&r1=1442009&r2=1442010&view=diff
==============================================================================
--- incubator/ambari/branches/branch-1.2/ambari-agent/src/test/python/dummy_puppet_output_good.txt (original)
+++ incubator/ambari/branches/branch-1.2/ambari-agent/src/test/python/dummy_puppet_output_good.txt Mon Feb  4 02:23:55 2013
@@ -43,5 +43,5 @@ debug: Storing state
 debug: Stored state in 0.01 seconds
 notice: Finished catalog run in 0.59 seconds
 debug: Finishing transaction 70060456663980
-debug: Received report to process from ambari-dmi.cybervisiontech.com.ua
-debug: Processing report from ambari-dmi.cybervisiontech.com.ua with processor Puppet::Reports::Store
\ No newline at end of file
+debug: Received report to process from ambari-dmi
+debug: Processing report from ambari-dmi with processor Puppet::Reports::Store
\ No newline at end of file

Modified: incubator/ambari/branches/branch-1.2/ambari-agent/src/test/python/examples/debug_testcase_example.py
URL: http://svn.apache.org/viewvc/incubator/ambari/branches/branch-1.2/ambari-agent/src/test/python/examples/debug_testcase_example.py?rev=1442010&r1=1442009&r2=1442010&view=diff
==============================================================================
--- incubator/ambari/branches/branch-1.2/ambari-agent/src/test/python/examples/debug_testcase_example.py (original)
+++ incubator/ambari/branches/branch-1.2/ambari-agent/src/test/python/examples/debug_testcase_example.py Mon Feb  4 02:23:55 2013
@@ -26,18 +26,16 @@ from ambari_agent.ActionQueue import Act
 from ambari_agent import AmbariConfig
 from ambari_agent.NetUtil import NetUtil
 import socket, ConfigParser, logging
-import os, pprint, json, sys
+import os, pprint, json, sys, unittest
 from threading import Thread
 import time
 import Queue
 
-
-BAD_URL = 'http://localhost:54222/badurl/'
 logger = logging.getLogger()
 
-class TestController():
+class TestController(TestCase):
 
-# This file should be put to ambari-agent/src/main/python/debug_testcase_example.py.
+# This file should be put to ambari-agent/src/main/python/ambari-agent/debug_testcase_example.py.
 # After installing python plugin and adjusting test,
 # it may be run in IntelliJ IDEA debugger
 
@@ -68,10 +66,7 @@ def main(argv=None):
   stream_handler.setFormatter(formatter)
   logger.addHandler(stream_handler)
 
-  test = TestController()
-  test.setUp()
-  test.test_custom()
-  test.tearDown()
+  unittest.main()
 
 if __name__ == '__main__':
   main()

Added: incubator/ambari/branches/branch-1.2/ambari-common/src/test/python/mock/LICENSE.txt
URL: http://svn.apache.org/viewvc/incubator/ambari/branches/branch-1.2/ambari-common/src/test/python/mock/LICENSE.txt?rev=1442010&view=auto
==============================================================================
--- incubator/ambari/branches/branch-1.2/ambari-common/src/test/python/mock/LICENSE.txt (added)
+++ incubator/ambari/branches/branch-1.2/ambari-common/src/test/python/mock/LICENSE.txt Mon Feb  4 02:23:55 2013
@@ -0,0 +1,26 @@
+Copyright (c) 2003-2012, Michael Foord
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are
+met:
+
+    * Redistributions of source code must retain the above copyright
+      notice, this list of conditions and the following disclaimer.
+
+    * Redistributions in binary form must reproduce the above
+      copyright notice, this list of conditions and the following
+      disclaimer in the documentation and/or other materials provided
+      with the distribution.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

Added: incubator/ambari/branches/branch-1.2/ambari-common/src/test/python/mock/MANIFEST.in
URL: http://svn.apache.org/viewvc/incubator/ambari/branches/branch-1.2/ambari-common/src/test/python/mock/MANIFEST.in?rev=1442010&view=auto
==============================================================================
--- incubator/ambari/branches/branch-1.2/ambari-common/src/test/python/mock/MANIFEST.in (added)
+++ incubator/ambari/branches/branch-1.2/ambari-common/src/test/python/mock/MANIFEST.in Mon Feb  4 02:23:55 2013
@@ -0,0 +1,2 @@
+include LICENSE.txt tox.ini tests/*.py
+recursive-include docs *.txt *.py *.png *.css *.html *.js

Added: incubator/ambari/branches/branch-1.2/ambari-common/src/test/python/mock/README.txt
URL: http://svn.apache.org/viewvc/incubator/ambari/branches/branch-1.2/ambari-common/src/test/python/mock/README.txt?rev=1442010&view=auto
==============================================================================
--- incubator/ambari/branches/branch-1.2/ambari-common/src/test/python/mock/README.txt (added)
+++ incubator/ambari/branches/branch-1.2/ambari-common/src/test/python/mock/README.txt Mon Feb  4 02:23:55 2013
@@ -0,0 +1,179 @@
+mock is a library for testing in Python. It allows you to replace parts of
+your system under test with mock objects and make assertions about how they
+have been used.
+
+mock is now part of the Python standard library, available as `unittest.mock
+<http://docs.python.org/py3k/library/unittest.mock.html#module-unittest.mock>`_
+in Python 3.3 onwards.
+
+mock provides a core `MagicMock` class removing the need to create a host of
+stubs throughout your test suite. After performing an action, you can make
+assertions about which methods / attributes were used and arguments they were
+called with. You can also specify return values and set needed attributes in
+the normal way.
+
+mock is tested on Python versions 2.5-2.7 and Python 3. mock is also tested
+with the latest versions of Jython and pypy.
+
+The mock module also provides utility functions / objects to assist with
+testing, particularly monkey patching.
+
+* `PDF documentation for 1.0.1
+  <http://www.voidspace.org.uk/downloads/mock-1.0.1.pdf>`_
+* `mock on google code (repository and issue tracker)
+  <http://code.google.com/p/mock/>`_
+* `mock documentation
+  <http://www.voidspace.org.uk/python/mock/>`_
+* `mock on PyPI <http://pypi.python.org/pypi/mock/>`_
+* `Mailing list (testing-in-python@lists.idyll.org)
+  <http://lists.idyll.org/listinfo/testing-in-python>`_
+
+Mock is very easy to use and is designed for use with
+`unittest <http://pypi.python.org/pypi/unittest2>`_. Mock is based on
+the 'action -> assertion' pattern instead of 'record -> replay' used by many
+mocking frameworks. See the `mock documentation`_ for full details.
+
+Mock objects create all attributes and methods as you access them and store
+details of how they have been used. You can configure them, to specify return
+values or limit what attributes are available, and then make assertions about
+how they have been used::
+
+    >>> from mock import Mock
+    >>> real = ProductionClass()
+    >>> real.method = Mock(return_value=3)
+    >>> real.method(3, 4, 5, key='value')
+    3
+    >>> real.method.assert_called_with(3, 4, 5, key='value')
+
+`side_effect` allows you to perform side effects, return different values or
+raise an exception when a mock is called::
+
+   >>> mock = Mock(side_effect=KeyError('foo'))
+   >>> mock()
+   Traceback (most recent call last):
+    ...
+   KeyError: 'foo'
+   >>> values = {'a': 1, 'b': 2, 'c': 3}
+   >>> def side_effect(arg):
+   ...     return values[arg]
+   ...
+   >>> mock.side_effect = side_effect
+   >>> mock('a'), mock('b'), mock('c')
+   (3, 2, 1)
+   >>> mock.side_effect = [5, 4, 3, 2, 1]
+   >>> mock(), mock(), mock()
+   (5, 4, 3)
+
+Mock has many other ways you can configure it and control its behaviour. For
+example the `spec` argument configures the mock to take its specification from
+another object. Attempting to access attributes or methods on the mock that
+don't exist on the spec will fail with an `AttributeError`.
+
+The `patch` decorator / context manager makes it easy to mock classes or
+objects in a module under test. The object you specify will be replaced with a
+mock (or other object) during the test and restored when the test ends::
+
+    >>> from mock import patch
+    >>> @patch('test_module.ClassName1')
+    ... @patch('test_module.ClassName2')
+    ... def test(MockClass2, MockClass1):
+    ...     test_module.ClassName1()
+    ...     test_module.ClassName2()
+
+    ...     assert MockClass1.called
+    ...     assert MockClass2.called
+    ...
+    >>> test()
+
+.. note::
+
+   When you nest patch decorators the mocks are passed in to the decorated
+   function in the same order they applied (the normal *python* order that
+   decorators are applied). This means from the bottom up, so in the example
+   above the mock for `test_module.ClassName2` is passed in first.
+
+   With `patch` it matters that you patch objects in the namespace where they
+   are looked up. This is normally straightforward, but for a quick guide
+   read `where to patch
+   <http://www.voidspace.org.uk/python/mock/patch.html#where-to-patch>`_.
+
+As well as a decorator `patch` can be used as a context manager in a with
+statement::
+
+    >>> with patch.object(ProductionClass, 'method') as mock_method:
+    ...     mock_method.return_value = None
+    ...     real = ProductionClass()
+    ...     real.method(1, 2, 3)
+    ...
+    >>> mock_method.assert_called_once_with(1, 2, 3)
+
+There is also `patch.dict` for setting values in a dictionary just during the
+scope of a test and restoring the dictionary to its original state when the
+test ends::
+
+   >>> foo = {'key': 'value'}
+   >>> original = foo.copy()
+   >>> with patch.dict(foo, {'newkey': 'newvalue'}, clear=True):
+   ...     assert foo == {'newkey': 'newvalue'}
+   ...
+   >>> assert foo == original
+
+Mock supports the mocking of Python magic methods. The easiest way of
+using magic methods is with the `MagicMock` class. It allows you to do
+things like::
+
+    >>> from mock import MagicMock
+    >>> mock = MagicMock()
+    >>> mock.__str__.return_value = 'foobarbaz'
+    >>> str(mock)
+    'foobarbaz'
+    >>> mock.__str__.assert_called_once_with()
+
+Mock allows you to assign functions (or other Mock instances) to magic methods
+and they will be called appropriately. The MagicMock class is just a Mock
+variant that has all of the magic methods pre-created for you (well - all the
+useful ones anyway).
+
+The following is an example of using magic methods with the ordinary Mock
+class::
+
+    >>> from mock import Mock
+    >>> mock = Mock()
+    >>> mock.__str__ = Mock(return_value = 'wheeeeee')
+    >>> str(mock)
+    'wheeeeee'
+
+For ensuring that the mock objects your tests use have the same api as the
+objects they are replacing, you can use "auto-speccing". Auto-speccing can
+be done through the `autospec` argument to patch, or the `create_autospec`
+function. Auto-speccing creates mock objects that have the same attributes
+and methods as the objects they are replacing, and any functions and methods
+(including constructors) have the same call signature as the real object.
+
+This ensures that your mocks will fail in the same way as your production
+code if they are used incorrectly::
+
+   >>> from mock import create_autospec
+   >>> def function(a, b, c):
+   ...     pass
+   ...
+   >>> mock_function = create_autospec(function, return_value='fishy')
+   >>> mock_function(1, 2, 3)
+   'fishy'
+   >>> mock_function.assert_called_once_with(1, 2, 3)
+   >>> mock_function('wrong arguments')
+   Traceback (most recent call last):
+    ...
+   TypeError: <lambda>() takes exactly 3 arguments (1 given)
+
+`create_autospec` can also be used on classes, where it copies the signature of
+the `__init__` method, and on callable objects where it copies the signature of
+the `__call__` method.
+
+The distribution contains tests and documentation. The tests require
+`unittest2 <http://pypi.python.org/pypi/unittest2>`_ to run on Python 2.5, 2.6
+or 3.1. For Python 2.7 and 3.2 they can be run with
+`python -m unittest discover`.
+
+Docs from the in-development version of `mock` can be found at
+`mock.readthedocs.org <http://mock.readthedocs.org>`_.

Added: incubator/ambari/branches/branch-1.2/ambari-common/src/test/python/mock/__init__.py
URL: http://svn.apache.org/viewvc/incubator/ambari/branches/branch-1.2/ambari-common/src/test/python/mock/__init__.py?rev=1442010&view=auto
==============================================================================
--- incubator/ambari/branches/branch-1.2/ambari-common/src/test/python/mock/__init__.py (added)
+++ incubator/ambari/branches/branch-1.2/ambari-common/src/test/python/mock/__init__.py Mon Feb  4 02:23:55 2013
@@ -0,0 +1 @@
+__author__ = 'Michael Foord'

Added: incubator/ambari/branches/branch-1.2/ambari-common/src/test/python/mock/docs/changelog.txt
URL: http://svn.apache.org/viewvc/incubator/ambari/branches/branch-1.2/ambari-common/src/test/python/mock/docs/changelog.txt?rev=1442010&view=auto
==============================================================================
--- incubator/ambari/branches/branch-1.2/ambari-common/src/test/python/mock/docs/changelog.txt (added)
+++ incubator/ambari/branches/branch-1.2/ambari-common/src/test/python/mock/docs/changelog.txt Mon Feb  4 02:23:55 2013
@@ -0,0 +1,737 @@
+.. currentmodule:: mock
+
+
+CHANGELOG
+=========
+
+2012/11/05 Version 1.0.1
+------------------------
+
+* Functions decorated with `patch` variants have a `__wrapped__` attribute
+  pointing to the original function. This brings compatibility with the
+  default behaviour in Python 3.3 (due to a new feature in `functools.wraps`).
+
+Note that due to changes in `tox`, `mock` is no longer tested with Python 2.4.
+The compatibility code has not been removed so it probably still works, but
+tests are no longer run.
+
+
+2012/10/07 Version 1.0.0
+------------------------
+
+No changes since 1.0.0 beta 1. This version has feature parity with
+`unittest.mock
+<http://docs.python.org/py3k/library/unittest.mock.html#module-unittest.mock>`_
+in Python 3.3.
+
+Full list of changes since 0.8:
+
+* `mocksignature`, along with the `mocksignature` argument to `patch`, removed
+* Support for deleting attributes (accessing deleted attributes will raise an
+  `AttributeError`)
+* Added the `mock_open` helper function for mocking the builtin `open`
+* `__class__` is assignable, so a mock can pass an `isinstance` check without
+  requiring a spec
+* Addition of `PropertyMock`, for mocking properties
+* `MagicMocks` made unorderable by default (in Python 3). The comparison
+  methods (other than equality and inequality) now return `NotImplemented`
+* Propagate traceback info to support subclassing of `_patch` by other
+  libraries
+* `create_autospec` works with attributes present in results of `dir` that
+  can't be fetched from the object's class. Contributed by Konstantine Rybnikov
+* Any exceptions in an iterable `side_effect` will be raised instead of
+  returned
+* In Python 3, `create_autospec` now supports keyword only arguments
+* Added `patch.stopall` method to stop all active patches created by `start`
+* BUGFIX: calling `MagicMock.reset_mock` wouldn't reset magic method mocks
+* BUGFIX: calling `reset_mock` on a `MagicMock` created with autospec could
+  raise an exception
+* BUGFIX: passing multiple spec arguments to patchers (`spec` , `spec_set` and
+  `autospec`) had unpredictable results, now it is an error
+* BUGFIX: using `spec=True` *and* `create=True` as arguments to patchers could
+  result in using `DEFAULT` as the spec. Now it is an error instead
+* BUGFIX: using `spec` or `autospec` arguments to patchers, along with
+  `spec_set=True` did not work correctly
+* BUGFIX: using an object that evaluates to False as a spec could be ignored
+* BUGFIX: a list as the `spec` argument to a patcher would always result in a
+  non-callable mock. Now if `__call__` is in the spec the mock is callable
+
+
+2012/07/13 Version 1.0.0 beta 1
+--------------------------------
+
+* Added `patch.stopall` method to stop all active patches created by `start`
+* BUGFIX: calling `MagicMock.reset_mock` wouldn't reset magic method mocks
+* BUGFIX: calling `reset_mock` on a `MagicMock` created with autospec could
+  raise an exception
+
+
+2012/05/04 Version 1.0.0 alpha 2
+--------------------------------
+
+* `PropertyMock` attributes are now standard `MagicMocks`
+* `create_autospec` works with attributes present in results of `dir` that
+  can't be fetched from the object's class. Contributed by Konstantine Rybnikov
+* Any exceptions in an iterable `side_effect` will be raised instead of
+  returned
+* In Python 3, `create_autospec` now supports keyword only arguments
+
+
+2012/03/25 Version 1.0.0 alpha 1
+--------------------------------
+
+The standard library version!
+
+* `mocksignature`, along with the `mocksignature` argument to `patch`, removed
+* Support for deleting attributes (accessing deleted attributes will raise an
+  `AttributeError`)
+* Added the `mock_open` helper function for mocking the builtin `open`
+* `__class__` is assignable, so a mock can pass an `isinstance` check without
+  requiring a spec
+* Addition of `PropertyMock`, for mocking properties
+* `MagicMocks` made unorderable by default (in Python 3). The comparison
+  methods (other than equality and inequality) now return `NotImplemented`
+* Propagate traceback info to support subclassing of `_patch` by other
+  libraries
+* BUGFIX: passing multiple spec arguments to patchers (`spec` , `spec_set` and
+  `autospec`) had unpredictable results, now it is an error
+* BUGFIX: using `spec=True` *and* `create=True` as arguments to patchers could
+  result in using `DEFAULT` as the spec. Now it is an error instead
+* BUGFIX: using `spec` or `autospec` arguments to patchers, along with
+  `spec_set=True` did not work correctly
+* BUGFIX: using an object that evaluates to False as a spec could be ignored
+* BUGFIX: a list as the `spec` argument to a patcher would always result in a
+  non-callable mock. Now if `__call__` is in the spec the mock is callable
+
+
+2012/02/13 Version 0.8.0
+------------------------
+
+The only changes since 0.8rc2 are:
+
+* Improved repr of :data:`sentinel` objects
+* :data:`ANY` can be used for comparisons against :data:`call` objects
+* The return value of `MagicMock.__iter__` method can be set to
+  any iterable and isn't required to be an iterator
+
+Full List of changes since 0.7:
+
+mock 0.8.0 is the last version that will support Python 2.4.
+
+* Addition of :attr:`~Mock.mock_calls` list for *all* calls (including magic
+  methods and chained calls)
+* :func:`patch` and :func:`patch.object` now create a :class:`MagicMock`
+  instead of a :class:`Mock` by default
+* The patchers (`patch`, `patch.object` and `patch.dict`), plus `Mock` and
+  `MagicMock`, take arbitrary keyword arguments for configuration
+* New mock method :meth:`~Mock.configure_mock` for setting attributes and
+  return values / side effects on the mock and its attributes
+* New mock assert methods :meth:`~Mock.assert_any_call` and
+  :meth:`~Mock.assert_has_calls`
+* Implemented :ref:`auto-speccing` (recursive, lazy speccing of mocks with
+  mocked signatures for functions/methods), as the `autospec` argument to
+  `patch`
+* Added the :func:`create_autospec` function for manually creating
+  'auto-specced' mocks
+* :func:`patch.multiple` for doing multiple patches in a single call, using
+  keyword arguments
+* Setting :attr:`~Mock.side_effect` to an iterable will cause calls to the mock
+  to return the next value from the iterable
+* New `new_callable` argument to `patch` and `patch.object` allowing you to
+  pass in a class or callable object (instead of `MagicMock`) that will be
+  called to replace the object being patched
+* Addition of :class:`NonCallableMock` and :class:`NonCallableMagicMock`, mocks
+  without a `__call__` method
+* Addition of :meth:`~Mock.mock_add_spec` method for adding (or changing) a
+  spec on an existing mock
+* Protocol methods on :class:`MagicMock` are magic mocks, and are created
+  lazily on first lookup. This means the result of calling a protocol method is
+  a `MagicMock` instead of a `Mock` as it was previously
+* Addition of :meth:`~Mock.attach_mock` method
+* Added :data:`ANY` for ignoring arguments in :meth:`~Mock.assert_called_with`
+  calls
+* Addition of :data:`call` helper object
+* Improved repr for mocks
+* Improved repr for :attr:`Mock.call_args` and entries in
+  :attr:`Mock.call_args_list`, :attr:`Mock.method_calls` and
+  :attr:`Mock.mock_calls`
+* Improved repr for :data:`sentinel` objects
+* `patch` lookup is done at use time not at decoration time
+* In Python 2.6 or more recent, `dir` on a mock will report all the dynamically
+  created attributes (or the full list of attributes if there is a spec) as
+  well as all the mock methods and attributes.
+* Module level :data:`FILTER_DIR` added to control whether `dir(mock)` filters
+  private attributes. `True` by default.
+* `patch.TEST_PREFIX` for controlling how patchers recognise test methods when
+  used to decorate a class
+* Support for using Java exceptions as a :attr:`~Mock.side_effect` on Jython
+* `Mock` call lists (`call_args_list`, `method_calls` & `mock_calls`) are now
+  custom list objects that allow membership tests for "sub lists" and have
+  a nicer representation if you `str` or `print` them
+* Mocks attached as attributes or return values to other mocks have calls
+  recorded in `method_calls` and `mock_calls` of the parent (unless a name is
+  already set on the child)
+* Improved failure messages for `assert_called_with` and
+  `assert_called_once_with`
+* The return value of the :class:`MagicMock` `__iter__` method can be set to
+  any iterable and isn't required to be an iterator
+* Added the Mock API (`assert_called_with` etc) to functions created by
+  :func:`mocksignature`
+* Tuples as well as lists can be used to specify allowed methods for `spec` &
+  `spec_set` arguments
+* Calling `stop` on an unstarted patcher fails with  a more meaningful error
+  message
+* Renamed the internal classes `Sentinel` and `SentinelObject` to prevent abuse
+* BUGFIX: an error creating a patch, with nested patch decorators, won't leave
+  patches in place
+* BUGFIX: `__truediv__` and `__rtruediv__` not available as magic methods on
+  mocks in Python 3
+* BUGFIX: `assert_called_with` / `assert_called_once_with` can be used with
+  `self` as a keyword argument
+* BUGFIX: when patching a class with an explicit spec / spec_set (not a
+  boolean) it applies "spec inheritance" to the return value of the created
+  mock (the "instance")
+* BUGFIX: remove the `__unittest` marker causing traceback truncation
+* Removal of deprecated `patch_object`
+* Private attributes `_name`, `_methods`, '_children', `_wraps` and `_parent`
+  (etc) renamed to reduce likelihood of clash with user attributes.
+* Added license file to the distribution
+
+
+2012/01/10 Version 0.8.0 release candidate 2
+--------------------------------------------
+
+* Removed the `configure` keyword argument to `create_autospec` and allow
+  arbitrary keyword arguments (for the `Mock` constructor) instead
+* Fixed `ANY` equality with some types in `assert_called_with` calls
+* Switched to a standard Sphinx theme (compatible with
+  `readthedocs.org <http://mock.readthedocs.org>`_)
+
+
+2011/12/29 Version 0.8.0 release candidate 1
+--------------------------------------------
+
+* `create_autospec` on the return value of a mocked class will use `__call__`
+  for the signature rather than `__init__`
+* Performance improvement instantiating `Mock` and `MagicMock`
+* Mocks used as magic methods have the same type as their parent instead of
+  being hardcoded to `MagicMock`
+
+Special thanks to Julian Berman for his help with diagnosing and improving
+performance in this release.
+
+
+2011/10/09 Version 0.8.0 beta 4
+-------------------------------
+
+* `patch` lookup is done at use time not at decoration time
+* When attaching a Mock to another Mock as a magic method, calls are recorded
+  in mock_calls
+* Addition of `attach_mock` method
+* Renamed the internal classes `Sentinel` and `SentinelObject` to prevent abuse
+* BUGFIX: various issues around circular references with mocks (setting a mock
+  return value to be itself etc)
+
+
+2011/08/15 Version 0.8.0 beta 3
+-------------------------------
+
+* Mocks attached as attributes or return values to other mocks have calls
+  recorded in `method_calls` and `mock_calls` of the parent (unless a name is
+  already set on the child)
+* Addition of `mock_add_spec` method for adding (or changing) a spec on an
+  existing mock
+* Improved repr for `Mock.call_args` and entries in `Mock.call_args_list`,
+  `Mock.method_calls` and `Mock.mock_calls`
+* Improved repr for mocks
+* BUGFIX: minor fixes in the way `mock_calls` is worked out,
+  especially for "intermediate" mocks in a call chain
+
+
+2011/08/05 Version 0.8.0 beta 2
+-------------------------------
+
+* Setting `side_effect` to an iterable will cause calls to the mock to return
+  the next value from the iterable
+* Added `assert_any_call` method
+* Moved `assert_has_calls` from call lists onto mocks
+* BUGFIX: `call_args` and all members of `call_args_list` are two tuples of
+  `(args, kwargs)` again instead of three tuples of `(name, args, kwargs)`
+
+
+2011/07/25 Version 0.8.0 beta 1
+-------------------------------
+
+* `patch.TEST_PREFIX` for controlling how patchers recognise test methods when
+  used to decorate a class
+* `Mock` call lists (`call_args_list`, `method_calls` & `mock_calls`) are now
+  custom list objects that allow membership tests for "sub lists" and have
+  an `assert_has_calls` method for unordered call checks
+* `callargs` changed to *always* be a three-tuple of `(name, args, kwargs)`
+* Addition of `mock_calls` list for *all* calls (including magic methods and
+  chained calls)
+* Extension of `call` object to support chained calls and `callargs` for better
+  comparisons with or without names. `call` object has a `call_list` method for
+  chained calls
+* Added the public `instance` argument to `create_autospec`
+* Support for using Java exceptions as a `side_effect` on Jython
+* Improved failure messages for `assert_called_with` and
+  `assert_called_once_with`
+* Tuples as well as lists can be used to specify allowed methods for `spec` &
+  `spec_set` arguments
+* BUGFIX: Fixed bug in `patch.multiple` for argument passing when creating
+  mocks
+* Added license file to the distribution
+
+
+2011/07/16 Version 0.8.0 alpha 2
+--------------------------------
+
+* `patch.multiple` for doing multiple patches in a single call, using keyword
+  arguments
+* New `new_callable` argument to `patch` and `patch.object` allowing you to
+  pass in a class or callable object (instead of `MagicMock`) that will be
+  called to replace the object being patched
+* Addition of `NonCallableMock` and `NonCallableMagicMock`, mocks without a
+  `__call__` method
+* Mocks created by `patch` have a `MagicMock` as the `return_value` where a
+  class is being patched
+* `create_autospec` can create non-callable mocks for non-callable objects.
+  `return_value` mocks of classes will be non-callable unless the class has
+  a `__call__` method
+* `autospec` creates a `MagicMock` without a spec for properties and slot
+  descriptors, because we don't know the type of object they return
+* Removed the "inherit" argument from `create_autospec`
+* Calling `stop` on an unstarted patcher fails with  a more meaningful error
+  message
+* BUGFIX: an error creating a patch, with nested patch decorators, won't leave
+  patches in place
+* BUGFIX: `__truediv__` and `__rtruediv__` not available as magic methods on
+  mocks in Python 3
+* BUGFIX: `assert_called_with` / `assert_called_once_with` can be used with
+  `self` as a keyword argument
+* BUGFIX: autospec for functions / methods with an argument named self that
+  isn't the first argument no longer broken
+* BUGFIX: when patching a class with an explicit spec / spec_set (not a
+  boolean) it applies "spec inheritance" to the return value of the created
+  mock (the "instance")
+* BUGFIX: remove the `__unittest` marker causing traceback truncation
+
+
+2011/06/14 Version 0.8.0 alpha 1
+--------------------------------
+
+mock 0.8.0 is the last version that will support Python 2.4.
+
+* The patchers (`patch`, `patch.object` and `patch.dict`), plus `Mock` and
+  `MagicMock`, take arbitrary keyword arguments for configuration
+* New mock method `configure_mock` for setting attributes and return values /
+  side effects on the mock and its attributes
+* In Python 2.6 or more recent, `dir` on a mock will report all the dynamically
+  created attributes (or the full list of attributes if there is a spec) as
+  well as all the mock methods and attributes.
+* Module level `FILTER_DIR` added to control whether `dir(mock)` filters
+  private attributes. `True` by default. Note that `vars(Mock())` can still be
+  used to get all instance attributes and `dir(type(Mock())` will still return
+  all the other attributes (irrespective of `FILTER_DIR`)
+* `patch` and `patch.object` now create a `MagicMock` instead of a `Mock` by
+  default
+* Added `ANY` for ignoring arguments in `assert_called_with` calls
+* Addition of `call` helper object
+* Protocol methods on `MagicMock` are magic mocks, and are created lazily on
+  first lookup. This means the result of calling a protocol method is a
+  MagicMock instead of a Mock as it was previously
+* Added the Mock API (`assert_called_with` etc) to functions created by
+  `mocksignature`
+* Private attributes `_name`, `_methods`, '_children', `_wraps` and `_parent`
+  (etc) renamed to reduce likelihood of clash with user attributes.
+* Implemented auto-speccing (recursive, lazy speccing of mocks with mocked
+  signatures for functions/methods)
+
+  Limitations:
+
+  - Doesn't mock magic methods or attributes (it creates MagicMocks, so the
+    magic methods are *there*, they just don't have the signature mocked nor
+    are attributes followed)
+  - Doesn't mock function / method attributes
+  - Uses object traversal on the objects being mocked to determine types - so
+    properties etc may be triggered
+  - The return value of mocked classes (the 'instance') has the same call
+    signature as the class __init__ (as they share the same spec)
+
+  You create auto-specced mocks by passing `autospec=True` to `patch`.
+
+  Note that attributes that are None are special cased and mocked without a
+  spec (so any attribute / method can be used). This is because None is
+  typically used as a default value for attributes that may be of some other
+  type, and as we don't know what type that may be we allow all access.
+
+  Note that the `autospec` option to `patch` obsoletes the `mocksignature`
+  option.
+
+* Added the `create_autospec` function for manually creating 'auto-specced'
+  mocks
+* Removal of deprecated `patch_object`
+
+
+2011/05/30 Version 0.7.2
+------------------------
+
+* BUGFIX: instances of list subclasses can now be used as mock specs
+* BUGFIX: MagicMock equality / inequality protocol methods changed to use the
+  default equality / inequality. This is done through a `side_effect` on
+  the mocks used for `__eq__` / `__ne__`
+
+
+2011/05/06 Version 0.7.1
+------------------------
+
+Package fixes contributed by Michael Fladischer. No code changes.
+
+* Include template in package
+* Use isolated binaries for the tox tests
+* Unset executable bit on docs
+* Fix DOS line endings in getting-started.txt
+
+
+2011/03/05 Version 0.7.0
+------------------------
+
+No API changes since 0.7.0 rc1. Many documentation changes including a stylish
+new `Sphinx theme <https://github.com/coordt/ADCtheme/>`_.
+
+The full set of changes since 0.6.0 are:
+
+* Python 3 compatibility
+* Ability to mock magic methods with `Mock` and addition of `MagicMock`
+  with pre-created magic methods
+* Addition of `mocksignature` and `mocksignature` argument to `patch` and
+  `patch.object`
+* Addition of `patch.dict` for changing dictionaries during a test
+* Ability to use `patch`, `patch.object` and `patch.dict` as class decorators
+* Renamed ``patch_object`` to `patch.object` (``patch_object`` is
+  deprecated)
+* Addition of soft comparisons: `call_args`, `call_args_list` and `method_calls`
+  now return tuple-like objects which compare equal even when empty args
+  or kwargs are skipped
+* patchers (`patch`, `patch.object` and `patch.dict`) have start and stop
+  methods
+* Addition of `assert_called_once_with` method
+* Mocks can now be named (`name` argument to constructor) and the name is used
+  in the repr
+* repr of a mock with a spec includes the class name of the spec
+* `assert_called_with` works with `python -OO`
+* New `spec_set` keyword argument to `Mock` and `patch`. If used,
+  attempting to *set* an attribute on a mock not on the spec will raise an
+  `AttributeError`
+* Mocks created with a spec can now pass `isinstance` tests (`__class__`
+  returns the type of the spec)
+* Added docstrings to all objects
+* Improved failure message for `Mock.assert_called_with` when the mock
+  has not been called at all
+* Decorated functions / methods have their docstring and `__module__`
+  preserved on Python 2.4.
+* BUGFIX: `mock.patch` now works correctly with certain types of objects that
+  proxy attribute access, like the django settings object
+* BUGFIX: mocks are now copyable (thanks to Ned Batchelder for reporting and
+  diagnosing this)
+* BUGFIX: `spec=True` works with old style classes
+* BUGFIX: ``help(mock)`` works now (on the module). Can no longer use ``__bases__``
+  as a valid sentinel name (thanks to Stephen Emslie for reporting and
+  diagnosing this)
+* BUGFIX: ``side_effect`` now works with ``BaseException`` exceptions like
+  ``KeyboardInterrupt``
+* BUGFIX: `reset_mock` caused infinite recursion when a mock is set as its own
+  return value
+* BUGFIX: patching the same object twice now restores the patches correctly
+* with statement tests now skipped on Python 2.4
+* Tests require unittest2 (or unittest2-py3k) to run
+* Tested with `tox <http://pypi.python.org/pypi/tox>`_ on Python 2.4 - 3.2,
+  jython and pypy (excluding 3.0)
+* Added 'build_sphinx' command to setup.py (requires setuptools or distribute)
+  Thanks to Florian Bauer
+* Switched from subversion to mercurial for source code control
+* `Konrad Delong <http://konryd.blogspot.com/>`_ added as co-maintainer
+
+
+2011/02/16 Version 0.7.0 RC 1
+-----------------------------
+
+Changes since beta 4:
+
+* Tested with jython, pypy and Python 3.2 and 3.1
+* Decorated functions / methods have their docstring and `__module__`
+  preserved on Python 2.4
+* BUGFIX: `mock.patch` now works correctly with certain types of objects that
+  proxy attribute access, like the django settings object
+* BUGFIX: `reset_mock` caused infinite recursion when a mock is set as its own
+  return value
+
+
+2010/11/12 Version 0.7.0 beta 4
+-------------------------------
+
+* patchers (`patch`, `patch.object` and `patch.dict`) have start and stop
+  methods
+* Addition of `assert_called_once_with` method
+* repr of a mock with a spec includes the class name of the spec
+* `assert_called_with` works with `python -OO`
+* New `spec_set` keyword argument to `Mock` and `patch`. If used,
+  attempting to *set* an attribute on a mock not on the spec will raise an
+  `AttributeError`
+* Attributes and return value of a `MagicMock` are `MagicMock` objects
+* Attempting to set an unsupported magic method now raises an `AttributeError`
+* `patch.dict` works as a class decorator
+* Switched from subversion to mercurial for source code control
+* BUGFIX: mocks are now copyable (thanks to Ned Batchelder for reporting and
+  diagnosing this)
+* BUGFIX: `spec=True` works with old style classes
+* BUGFIX: `mocksignature=True` can now patch instance methods via
+  `patch.object`
+
+
+2010/09/18 Version 0.7.0 beta 3
+-------------------------------
+
+* Using spec with :class:`MagicMock` only pre-creates magic methods in the spec
+* Setting a magic method on a mock with a ``spec`` can only be done if the
+  spec has that method
+* Mocks can now be named (`name` argument to constructor) and the name is used
+  in the repr
+* `mocksignature` can now be used with classes (signature based on `__init__`)
+  and callable objects (signature based on `__call__`)
+* Mocks created with a spec can now pass `isinstance` tests (`__class__`
+  returns the type of the spec)
+* Default numeric value for MagicMock is 1 rather than zero (because the
+  MagicMock bool defaults to True and 0 is False)
+* Improved failure message for :meth:`~Mock.assert_called_with` when the mock
+  has not been called at all
+* Adding the following to the set of supported magic methods:
+
+  - ``__getformat__`` and ``__setformat__``
+  - pickle methods
+  - ``__trunc__``, ``__ceil__`` and ``__floor__``
+  - ``__sizeof__``
+
+* Added 'build_sphinx' command to setup.py (requires setuptools or distribute)
+  Thanks to Florian Bauer
+* with statement tests now skipped on Python 2.4
+* Tests require unittest2 to run on Python 2.7
+* Improved several docstrings and documentation
+
+
+2010/06/23 Version 0.7.0 beta 2
+-------------------------------
+
+* :func:`patch.dict` works as a context manager as well as a decorator
+* ``patch.dict`` takes a string to specify dictionary as well as a dictionary
+  object. If a string is supplied the name specified is imported
+* BUGFIX: ``patch.dict`` restores dictionary even when an exception is raised
+
+
+2010/06/22 Version 0.7.0 beta 1
+-------------------------------
+
+* Addition of :func:`mocksignature`
+* Ability to mock magic methods
+* Ability to use ``patch`` and ``patch.object`` as class decorators
+* Renamed ``patch_object`` to :func:`patch.object` (``patch_object`` is
+  deprecated)
+* Addition of :class:`MagicMock` class with all magic methods pre-created for you
+* Python 3 compatibility (tested with 3.2 but should work with 3.0 & 3.1 as
+  well)
+* Addition of :func:`patch.dict` for changing dictionaries during a test
+* Addition of ``mocksignature`` argument to ``patch`` and ``patch.object``
+* ``help(mock)`` works now (on the module). Can no longer use ``__bases__``
+  as a valid sentinel name (thanks to Stephen Emslie for reporting and
+  diagnosing this)
+* Addition of soft comparisons: `call_args`, `call_args_list` and `method_calls`
+  now return tuple-like objects which compare equal even when empty args
+  or kwargs are skipped
+* Added docstrings.
+* BUGFIX: ``side_effect`` now works with ``BaseException`` exceptions like
+  ``KeyboardInterrupt``
+* BUGFIX: patching the same object twice now restores the patches correctly
+* The tests now require `unittest2 <http://pypi.python.org/pypi/unittest2>`_
+  to run
+* `Konrad Delong <http://konryd.blogspot.com/>`_ added as co-maintainer
+
+
+2009/08/22 Version 0.6.0
+------------------------
+
+* New test layout compatible with test discovery
+* Descriptors (static methods / class methods etc) can now be patched and
+  restored correctly
+* Mocks can raise exceptions when called by setting ``side_effect`` to an
+  exception class or instance
+* Mocks that wrap objects will not pass on calls to the underlying object if
+  an explicit return_value is set
+
+
+2009/04/17 Version 0.5.0
+------------------------
+
+* Made DEFAULT part of the public api.
+* Documentation built with Sphinx.
+* ``side_effect`` is now called with the same arguments as the mock is called with and
+  if returns a non-DEFAULT value that is automatically set as the ``mock.return_value``.
+* ``wraps`` keyword argument used for wrapping objects (and passing calls through to the wrapped object).
+* ``Mock.reset`` renamed to ``Mock.reset_mock``, as reset is a common API name.
+* ``patch`` / ``patch_object`` are now context managers and can be used with ``with``.
+* A new 'create' keyword argument to patch and patch_object that allows them to patch
+  (and unpatch) attributes that don't exist. (Potentially unsafe to use - it can allow
+  you to have tests that pass when they are testing an API that doesn't exist - use at
+  your own risk!)
+* The methods keyword argument to Mock has been removed and merged with spec. The spec
+  argument can now be a list of methods or an object to take the spec from.
+* Nested patches may now be applied in a different order (created mocks passed
+  in the opposite order). This is actually a bugfix.
+* patch and patch_object now take a spec keyword argument. If spec is
+  passed in as 'True' then the Mock created will take the object it is replacing
+  as its spec object. If the object being replaced is a class, then the return
+  value for the mock will also use the class as a spec.
+* A Mock created without a spec will not attempt to mock any magic methods / attributes
+  (they will raise an ``AttributeError`` instead).
+
+
+2008/10/12 Version 0.4.0
+------------------------
+
+* Default return value is now a new mock rather than None
+* return_value added as a keyword argument to the constructor
+* New method 'assert_called_with'
+* Added 'side_effect' attribute / keyword argument called when mock is called
+* patch decorator split into two decorators:
+
+    - ``patch_object`` which takes an object and an attribute name to patch
+      (plus optionally a value to patch with which defaults to a mock object)
+    - ``patch`` which takes a string specifying a target to patch; in the form
+      'package.module.Class.attribute'. (plus optionally a value to
+      patch with which defaults to a mock object)
+
+* Can now patch objects with ``None``
+* Change to patch for nose compatibility with error reporting in wrapped functions
+* Reset no longer clears children / return value etc - it just resets
+  call count and call args. It also calls reset on all children (and
+  the return value if it is a mock).
+
+Thanks to Konrad Delong, Kevin Dangoor and others for patches and suggestions.
+
+
+2007/12/03  Version 0.3.1
+-------------------------
+
+``patch`` maintains the name of decorated functions for compatibility with nose
+test autodiscovery.
+
+Tests decorated with ``patch`` that use the two argument form (implicit mock
+creation) will receive the mock(s) passed in as extra arguments.
+
+Thanks to Kevin Dangoor for these changes.
+
+
+2007/11/30  Version 0.3.0
+-------------------------
+
+Removed ``patch_module``. ``patch`` can now take a string as the first
+argument for patching modules.
+
+The third argument to ``patch`` is optional - a mock will be created by
+default if it is not passed in.
+
+
+2007/11/21  Version 0.2.1
+-------------------------
+
+Bug fix, allows reuse of functions decorated with ``patch`` and ``patch_module``.
+
+
+2007/11/20  Version 0.2.0
+-------------------------
+
+Added ``spec`` keyword argument for creating ``Mock`` objects from a
+specification object.
+
+Added ``patch`` and ``patch_module`` monkey patching decorators.
+
+Added ``sentinel`` for convenient access to unique objects.
+
+Distribution includes unit tests.
+
+
+2007/11/19  Version 0.1.0
+-------------------------
+
+Initial release.
+
+
+TODO and Limitations
+====================
+
+Contributions, bug reports and comments welcomed!
+
+Feature requests and bug reports are handled on the issue tracker:
+
+ * `mock issue tracker <http://code.google.com/p/mock/issues/list>`_
+
+`wraps` is not integrated with magic methods.
+
+`patch` could auto-do the patching in the constructor and unpatch in the
+destructor. This would be useful in itself, but violates TOOWTDI and would be
+unsafe for IronPython & PyPy (non-deterministic calling of destructors).
+Destructors aren't called in CPython where there are cycles, but a weak
+reference with a callback can be used to get round this.
+
+`Mock` has several attributes. This makes it unsuitable for mocking objects
+that use these attribute names. A way round this would be to provide methods
+that *hide* these attributes when needed. In 0.8 many, but not all, of these
+attributes are renamed to gain a `_mock` prefix, making it less likely that
+they will clash. Any outstanding attributes that haven't been modified with
+the prefix should be changed.
+
+If a patch is started using `patch.start` and then not stopped correctly then
+the unpatching is not done. Using weak references it would be possible to
+detect and fix this when the patch object itself is garbage collected. This
+would be tricky to get right though.
+
+When a `Mock` is created by `patch`, arbitrary keywords can be used to set
+attributes. If `patch` is created with a `spec`, and is replacing a class, then
+a `return_value` mock is created. The keyword arguments are not applied to the
+child mock, but could be.
+
+When mocking a class with `patch`, passing in `spec=True` or `autospec=True`,
+the mock class has an instance created from the same spec. Should this be the
+default behaviour for mocks anyway (mock return values inheriting the spec
+from their parent), or should it be controlled by an additional keyword
+argument (`inherit`) to the Mock constructor? `create_autospec` does this, so
+an additional keyword argument to Mock is probably unnecessary.
+
+The `mocksignature` argument to `patch` with a non `Mock` passed into
+`new_callable` will *probably* cause an error. Should it just be invalid?
+
+Note that `NonCallableMock` and `NonCallableMagicMock` still have the unused
+(and unusable) attributes: `return_value`, `side_effect`, `call_count`,
+`call_args` and `call_args_list`. These could be removed or raise errors on
+getting / setting. They also have the `assert_called_with` and
+`assert_called_once_with` methods. Removing these would be pointless as
+fetching them would create a mock (attribute) that could be called without
+error.
+
+Some outstanding technical debt. The way autospeccing mocks function
+signatures was copied and modified from `mocksignature`. This could all be
+refactored into one set of functions instead of two. The way we tell if
+patchers are started and if a patcher is being used for a `patch.multiple`
+call are both horrible. There are now a host of helper functions that should
+be rationalised. (Probably time to split mock into a package instead of a
+module.)
+
+Passing arbitrary keyword arguments to `create_autospec`, or `patch` with
+`autospec`, when mocking a *function* works fine. However, the arbitrary
+attributes are set on the created mock - but `create_autospec` returns a
+real function (which doesn't have those attributes). However, what is the use
+case for using autospec to create functions with attributes that don't exist
+on the original?
+
+`mocksignature`, plus the `call_args_list` and `method_calls` attributes of
+`Mock` could all be deprecated.

Added: incubator/ambari/branches/branch-1.2/ambari-common/src/test/python/mock/docs/compare.txt
URL: http://svn.apache.org/viewvc/incubator/ambari/branches/branch-1.2/ambari-common/src/test/python/mock/docs/compare.txt?rev=1442010&view=auto
==============================================================================
--- incubator/ambari/branches/branch-1.2/ambari-common/src/test/python/mock/docs/compare.txt (added)
+++ incubator/ambari/branches/branch-1.2/ambari-common/src/test/python/mock/docs/compare.txt Mon Feb  4 02:23:55 2013
@@ -0,0 +1,628 @@
+=========================
+ Mock Library Comparison
+=========================
+
+
+.. testsetup::
+
+    def assertEqual(a, b):
+        assert a == b, ("%r != %r" % (a, b))
+
+    def assertRaises(Exc, func):
+        try:
+            func()
+        except Exc:
+            return
+        assert False, ("%s not raised" % Exc)
+
+    sys.modules['somemodule'] = somemodule = mock.Mock(name='somemodule')
+    class SomeException(Exception):
+        some_method = method1 = method2 = None
+    some_other_object = SomeObject = SomeException
+
+
+A side-by-side comparison of how to accomplish some basic tasks with mock and
+some other popular Python mocking libraries and frameworks.
+
+These are:
+
+* `flexmock <http://pypi.python.org/pypi/flexmock>`_
+* `mox <http://pypi.python.org/pypi/mox>`_
+* `Mocker <http://niemeyer.net/mocker>`_
+* `dingus <http://pypi.python.org/pypi/dingus>`_
+* `fudge <http://pypi.python.org/pypi/fudge>`_
+
+Popular python mocking frameworks not yet represented here include
+`MiniMock <http://pypi.python.org/pypi/MiniMock>`_.
+
+`pMock <http://pmock.sourceforge.net/>`_ (last release 2004 and doesn't import
+in recent versions of Python) and
+`python-mock <http://python-mock.sourceforge.net/>`_ (last release 2005) are
+intentionally omitted.
+
+.. note::
+
+    A more up to date, and tested for all mock libraries (only the mock
+    examples on this page can be executed as doctests) version of this
+    comparison is maintained by Gary Bernhardt:
+
+    * `Python Mock Library Comparison
+      <http://garybernhardt.github.com/python-mock-comparison/>`_
+
+This comparison is by no means complete, and also may not be fully idiomatic
+for all the libraries represented. *Please* contribute corrections, missing
+comparisons, or comparisons for additional libraries to the `mock issue
+tracker <https://code.google.com/p/mock/issues/list>`_.
+
+This comparison page was originally created by the `Mox project
+<https://code.google.com/p/pymox/wiki/MoxComparison>`_ and then extended for
+`flexmock and mock <http://has207.github.com/flexmock/compare.html>`_ by
+Herman Sheremetyev. Dingus examples written by `Gary Bernhadt
+<http://garybernhardt.github.com/python-mock-comparison/>`_. fudge examples
+provided by `Kumar McMillan <http://farmdev.com/>`_.
+
+.. note::
+
+    The examples tasks here were originally created by Mox which is a mocking
+    *framework* rather than a library like mock. The tasks shown naturally
+    exemplify tasks that frameworks are good at and not the ones they make
+    harder. In particular you can take a `Mock` or `MagicMock` object and use
+    it in any way you want with no up-front configuration. The same is also
+    true for Dingus.
+
+    The examples for mock here assume version 0.7.0.
+
+
+Simple fake object
+~~~~~~~~~~~~~~~~~~
+
+.. doctest::
+
+    >>> # mock
+    >>> my_mock = mock.Mock()
+    >>> my_mock.some_method.return_value = "calculated value"
+    >>> my_mock.some_attribute = "value"
+    >>> assertEqual("calculated value", my_mock.some_method())
+    >>> assertEqual("value", my_mock.some_attribute)
+
+::
+
+    # Flexmock
+    mock = flexmock(some_method=lambda: "calculated value", some_attribute="value")
+    assertEqual("calculated value", mock.some_method())
+    assertEqual("value", mock.some_attribute)
+
+    # Mox
+    mock = mox.MockAnything()
+    mock.some_method().AndReturn("calculated value")
+    mock.some_attribute = "value"
+    mox.Replay(mock)
+    assertEqual("calculated value", mock.some_method())
+    assertEqual("value", mock.some_attribute)
+
+    # Mocker
+    mock = mocker.mock()
+    mock.some_method()
+    mocker.result("calculated value")
+    mocker.replay()
+    mock.some_attribute = "value"
+    assertEqual("calculated value", mock.some_method())
+    assertEqual("value", mock.some_attribute)
+
+::
+
+    >>> # Dingus
+    >>> my_dingus = dingus.Dingus(some_attribute="value",
+    ...                           some_method__returns="calculated value")
+    >>> assertEqual("calculated value", my_dingus.some_method())
+    >>> assertEqual("value", my_dingus.some_attribute)
+
+::
+
+    >>> # fudge
+    >>> my_fake = (fudge.Fake()
+    ...            .provides('some_method')
+    ...            .returns("calculated value")
+    ...            .has_attr(some_attribute="value"))
+    ...
+    >>> assertEqual("calculated value", my_fake.some_method())
+    >>> assertEqual("value", my_fake.some_attribute)
+
+
+Simple mock
+~~~~~~~~~~~
+
+.. doctest::
+
+    >>> # mock
+    >>> my_mock = mock.Mock()
+    >>> my_mock.some_method.return_value = "value"
+    >>> assertEqual("value", my_mock.some_method())
+    >>> my_mock.some_method.assert_called_once_with()
+
+::
+
+    # Flexmock
+    mock = flexmock()
+    mock.should_receive("some_method").and_return("value").once
+    assertEqual("value", mock.some_method())
+
+    # Mox
+    mock = mox.MockAnything()
+    mock.some_method().AndReturn("value")
+    mox.Replay(mock)
+    assertEqual("value", mock.some_method())
+    mox.Verify(mock)
+
+    # Mocker
+    mock = mocker.mock()
+    mock.some_method()
+    mocker.result("value")
+    mocker.replay()
+    assertEqual("value", mock.some_method())
+    mocker.verify()
+
+::
+
+    >>> # Dingus
+    >>> my_dingus = dingus.Dingus(some_method__returns="value")
+    >>> assertEqual("value", my_dingus.some_method())
+    >>> assert my_dingus.some_method.calls().once()
+
+::
+
+    >>> # fudge
+    >>> @fudge.test
+    ... def test():
+    ...     my_fake = (fudge.Fake()
+    ...                .expects('some_method')
+    ...                .returns("value")
+    ...                .times_called(1))
+    ...
+    >>> test()
+    Traceback (most recent call last):
+    ...
+    AssertionError: fake:my_fake.some_method() was not called
+
+
+Creating partial mocks
+~~~~~~~~~~~~~~~~~~~~~~
+
+.. doctest::
+
+    >>> # mock
+    >>> SomeObject.some_method = mock.Mock(return_value='value')
+    >>> assertEqual("value", SomeObject.some_method())
+
+::
+
+    # Flexmock
+    flexmock(SomeObject).should_receive("some_method").and_return('value')
+    assertEqual("value", mock.some_method())
+
+    # Mox
+    mock = mox.MockObject(SomeObject)
+    mock.some_method().AndReturn("value")
+    mox.Replay(mock)
+    assertEqual("value", mock.some_method())
+    mox.Verify(mock)
+
+    # Mocker
+    mock = mocker.mock(SomeObject)
+    mock.Get()
+    mocker.result("value")
+    mocker.replay()
+    assertEqual("value", mock.some_method())
+    mocker.verify()
+
+::
+
+    >>> # Dingus
+    >>> object = SomeObject
+    >>> object.some_method = dingus.Dingus(return_value="value")
+    >>> assertEqual("value", object.some_method())
+
+::
+
+    >>> # fudge
+    >>> fake = fudge.Fake().is_callable().returns("<fudge-value>")
+    >>> with fudge.patched_context(SomeObject, 'some_method', fake):
+    ...     s = SomeObject()
+    ...     assertEqual("<fudge-value>", s.some_method())
+    ...
+
+
+Ensure calls are made in specific order
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+.. doctest::
+
+    >>> # mock
+    >>> my_mock = mock.Mock(spec=SomeObject)
+    >>> my_mock.method1()
+    <Mock name='mock.method1()' id='...'>
+    >>> my_mock.method2()
+    <Mock name='mock.method2()' id='...'>
+    >>> assertEqual(my_mock.mock_calls, [call.method1(), call.method2()])
+
+::
+
+    # Flexmock
+    mock = flexmock(SomeObject)
+    mock.should_receive('method1').once.ordered.and_return('first thing')
+    mock.should_receive('method2').once.ordered.and_return('second thing')
+
+    # Mox
+    mock = mox.MockObject(SomeObject)
+    mock.method1().AndReturn('first thing')
+    mock.method2().AndReturn('second thing')
+    mox.Replay(mock)
+    mox.Verify(mock)
+
+    # Mocker
+    mock = mocker.mock()
+    with mocker.order():
+        mock.method1()
+        mocker.result('first thing')
+        mock.method2()
+        mocker.result('second thing')
+        mocker.replay()
+        mocker.verify()
+
+::
+
+    >>> # Dingus
+    >>> my_dingus = dingus.Dingus()
+    >>> my_dingus.method1()
+    <Dingus ...>
+    >>> my_dingus.method2()
+    <Dingus ...>
+    >>> assertEqual(['method1', 'method2'], [call.name for call in my_dingus.calls])
+
+::
+
+    >>> # fudge
+    >>> @fudge.test
+    ... def test():
+    ...     my_fake = (fudge.Fake()
+    ...                .remember_order()
+    ...                .expects('method1')
+    ...                .expects('method2'))
+    ...     my_fake.method2()
+    ...     my_fake.method1()
+    ...
+    >>> test()
+    Traceback (most recent call last):
+    ...
+    AssertionError: Call #1 was fake:my_fake.method2(); Expected: #1 fake:my_fake.method1(), #2 fake:my_fake.method2(), end
+
+
+Raising exceptions
+~~~~~~~~~~~~~~~~~~
+
+.. doctest::
+
+    >>> # mock
+    >>> my_mock = mock.Mock()
+    >>> my_mock.some_method.side_effect = SomeException("message")
+    >>> assertRaises(SomeException, my_mock.some_method)
+
+::
+
+    # Flexmock
+    mock = flexmock()
+    mock.should_receive("some_method").and_raise(SomeException("message"))
+    assertRaises(SomeException, mock.some_method)
+
+    # Mox
+    mock = mox.MockAnything()
+    mock.some_method().AndRaise(SomeException("message"))
+    mox.Replay(mock)
+    assertRaises(SomeException, mock.some_method)
+    mox.Verify(mock)
+
+    # Mocker
+    mock = mocker.mock()
+    mock.some_method()
+    mocker.throw(SomeException("message"))
+    mocker.replay()
+    assertRaises(SomeException, mock.some_method)
+    mocker.verify()
+
+::
+
+    >>> # Dingus
+    >>> my_dingus = dingus.Dingus()
+    >>> my_dingus.some_method = dingus.exception_raiser(SomeException)
+    >>> assertRaises(SomeException, my_dingus.some_method)
+
+::
+
+    >>> # fudge
+    >>> my_fake = (fudge.Fake()
+    ...            .is_callable()
+    ...            .raises(SomeException("message")))
+    ...
+    >>> my_fake()
+    Traceback (most recent call last):
+    ...
+    SomeException: message
+
+
+Override new instances of a class
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+.. doctest::
+
+    >>> # mock
+    >>> with mock.patch('somemodule.Someclass') as MockClass:
+    ...     MockClass.return_value = some_other_object
+    ...     assertEqual(some_other_object, somemodule.Someclass())
+    ...
+
+
+::
+
+    # Flexmock
+    flexmock(some_module.SomeClass, new_instances=some_other_object)
+    assertEqual(some_other_object, some_module.SomeClass())
+
+    # Mox
+    # (you will probably have mox.Mox() available as self.mox in a real test)
+    mox.Mox().StubOutWithMock(some_module, 'SomeClass', use_mock_anything=True)
+    some_module.SomeClass().AndReturn(some_other_object)
+    mox.ReplayAll()
+    assertEqual(some_other_object, some_module.SomeClass())
+
+    # Mocker
+    instance = mocker.mock()
+    klass = mocker.replace(SomeClass, spec=None)
+    klass('expected', 'args')
+    mocker.result(instance)
+
+::
+
+    >>> # Dingus
+    >>> MockClass = dingus.Dingus(return_value=some_other_object)
+    >>> with dingus.patch('somemodule.SomeClass', MockClass):
+    ...     assertEqual(some_other_object, somemodule.SomeClass())
+    ...
+
+::
+
+    >>> # fudge
+    >>> @fudge.patch('somemodule.SomeClass')
+    ... def test(FakeClass):
+    ...     FakeClass.is_callable().returns(some_other_object)
+    ...     assertEqual(some_other_object, somemodule.SomeClass())
+    ...
+    >>> test()
+
+
+Call the same method multiple times
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+.. note::
+
+    You don't need to do *any* configuration to call `mock.Mock()` methods
+    multiple times. Attributes like `call_count`, `call_args_list` and
+    `method_calls` provide various different ways of making assertions about
+    how the mock was used.
+
+.. doctest::
+
+    >>> # mock
+    >>> my_mock = mock.Mock()
+    >>> my_mock.some_method()
+    <Mock name='mock.some_method()' id='...'>
+    >>> my_mock.some_method()
+    <Mock name='mock.some_method()' id='...'>
+    >>> assert my_mock.some_method.call_count >= 2
+
+::
+
+    # Flexmock # (verifies that the method gets called at least twice)
+    flexmock(some_object).should_receive('some_method').at_least.twice
+
+    # Mox
+    # (does not support variable number of calls, so you need to create a new entry for each explicit call)
+    mock = mox.MockObject(some_object)
+    mock.some_method(mox.IgnoreArg(), mox.IgnoreArg())
+    mock.some_method(mox.IgnoreArg(), mox.IgnoreArg())
+    mox.Replay(mock)
+    mox.Verify(mock)
+
+    # Mocker
+    # (TODO)
+
+::
+
+    >>> # Dingus
+    >>> my_dingus = dingus.Dingus()
+    >>> my_dingus.some_method()
+    <Dingus ...>
+    >>> my_dingus.some_method()
+    <Dingus ...>
+    >>> assert len(my_dingus.calls('some_method')) == 2
+
+::
+
+    >>> # fudge
+    >>> @fudge.test
+    ... def test():
+    ...     my_fake = fudge.Fake().expects('some_method').times_called(2)
+    ...     my_fake.some_method()
+    ...
+    >>> test()
+    Traceback (most recent call last):
+    ...
+    AssertionError: fake:my_fake.some_method() was called 1 time(s). Expected 2.
+
+
+Mock chained methods
+~~~~~~~~~~~~~~~~~~~~
+
+.. doctest::
+
+    >>> # mock
+    >>> my_mock = mock.Mock()
+    >>> method3 = my_mock.method1.return_value.method2.return_value.method3
+    >>> method3.return_value = 'some value'
+    >>> assertEqual('some value', my_mock.method1().method2().method3(1, 2))
+    >>> method3.assert_called_once_with(1, 2)
+
+::
+
+    # Flexmock
+    # (intermediate method calls are automatically assigned to temporary fake objects
+    # and can be called with any arguments)
+    flexmock(some_object).should_receive(
+        'method1.method2.method3'
+    ).with_args(arg1, arg2).and_return('some value')
+    assertEqual('some_value', some_object.method1().method2().method3(arg1, arg2))
+
+::
+
+    # Mox
+    mock = mox.MockObject(some_object)
+    mock2 = mox.MockAnything()
+    mock3 = mox.MockAnything()
+    mock.method1().AndReturn(mock1)
+    mock2.method2().AndReturn(mock2)
+    mock3.method3(arg1, arg2).AndReturn('some_value')
+    self.mox.ReplayAll()
+    assertEqual("some_value", some_object.method1().method2().method3(arg1, arg2))
+    self.mox.VerifyAll()
+
+    # Mocker
+    # (TODO)
+
+::
+
+    >>> # Dingus
+    >>> my_dingus = dingus.Dingus()
+    >>> method3 = my_dingus.method1.return_value.method2.return_value.method3
+    >>> method3.return_value = 'some value'
+    >>> assertEqual('some value', my_dingus.method1().method2().method3(1, 2))
+    >>> assert method3.calls('()', 1, 2).once()
+
+::
+
+    >>> # fudge
+    >>> @fudge.test
+    ... def test():
+    ...     my_fake = fudge.Fake()
+    ...     (my_fake
+    ...      .expects('method1')
+    ...      .returns_fake()
+    ...      .expects('method2')
+    ...      .returns_fake()
+    ...      .expects('method3')
+    ...      .with_args(1, 2)
+    ...      .returns('some value'))
+    ...     assertEqual('some value', my_fake.method1().method2().method3(1, 2))
+    ...
+    >>> test()
+
+
+Mocking a context manager
+~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Examples for mock, Dingus and fudge only (so far):
+
+.. doctest::
+
+    >>> # mock
+    >>> my_mock = mock.MagicMock()
+    >>> with my_mock:
+    ...     pass
+    ...
+    >>> my_mock.__enter__.assert_called_with()
+    >>> my_mock.__exit__.assert_called_with(None, None, None)
+
+::
+
+
+    >>> # Dingus (nothing special here; all dinguses are "magic mocks")
+    >>> my_dingus = dingus.Dingus()
+    >>> with my_dingus:
+    ...     pass
+    ...
+    >>> assert my_dingus.__enter__.calls()
+    >>> assert my_dingus.__exit__.calls('()', None, None, None)
+
+::
+
+    >>> # fudge
+    >>> my_fake = fudge.Fake().provides('__enter__').provides('__exit__')
+    >>> with my_fake:
+    ...     pass
+    ...
+
+
+Mocking the builtin open used as a context manager
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Example for mock only (so far):
+
+.. doctest::
+
+    >>> # mock
+    >>> my_mock = mock.MagicMock()
+    >>> with mock.patch('__builtin__.open', my_mock):
+    ...     manager = my_mock.return_value.__enter__.return_value
+    ...     manager.read.return_value = 'some data'
+    ...     with open('foo') as h:
+    ...         data = h.read()
+    ...
+    >>> data
+    'some data'
+    >>> my_mock.assert_called_once_with('foo')
+
+*or*:
+
+.. doctest::
+
+    >>> # mock
+    >>> with mock.patch('__builtin__.open') as my_mock:
+    ...     my_mock.return_value.__enter__ = lambda s: s
+    ...     my_mock.return_value.__exit__ = mock.Mock()
+    ...     my_mock.return_value.read.return_value = 'some data'
+    ...     with open('foo') as h:
+    ...         data = h.read()
+    ...
+    >>> data
+    'some data'
+    >>> my_mock.assert_called_once_with('foo')
+
+::
+
+    >>> # Dingus
+    >>> my_dingus = dingus.Dingus()
+    >>> with dingus.patch('__builtin__.open', my_dingus):
+    ...     file_ = open.return_value.__enter__.return_value
+    ...     file_.read.return_value = 'some data'
+    ...     with open('foo') as h:
+    ...         data = f.read()
+    ...
+    >>> data
+    'some data'
+    >>> assert my_dingus.calls('()', 'foo').once()
+
+::
+
+    >>> # fudge
+    >>> from contextlib import contextmanager
+    >>> from StringIO import StringIO
+    >>> @contextmanager
+    ... def fake_file(filename):
+    ...     yield StringIO('sekrets')
+    ...
+    >>> with fudge.patch('__builtin__.open') as fake_open:
+    ...     fake_open.is_callable().calls(fake_file)
+    ...     with open('/etc/password') as f:
+    ...         data = f.read()
+    ...
+    fake:__builtin__.open
+    >>> data
+    'sekrets'
\ No newline at end of file

Added: incubator/ambari/branches/branch-1.2/ambari-common/src/test/python/mock/docs/conf.py
URL: http://svn.apache.org/viewvc/incubator/ambari/branches/branch-1.2/ambari-common/src/test/python/mock/docs/conf.py?rev=1442010&view=auto
==============================================================================
--- incubator/ambari/branches/branch-1.2/ambari-common/src/test/python/mock/docs/conf.py (added)
+++ incubator/ambari/branches/branch-1.2/ambari-common/src/test/python/mock/docs/conf.py Mon Feb  4 02:23:55 2013
@@ -0,0 +1,209 @@
+# -*- coding: utf-8 -*-
+#
+# Mock documentation build configuration file, created by
+# sphinx-quickstart on Mon Nov 17 18:12:00 2008.
+#
+# This file is execfile()d with the current directory set to its containing dir.
+#
+# The contents of this file are pickled, so don't put values in the namespace
+# that aren't pickleable (module imports are okay, they're removed automatically).
+#
+# All configuration values have a default value; values that are commented out
+# serve to show the default value.
+
+import sys, os
+sys.path.insert(0, os.path.abspath('..'))
+from mock import __version__
+
+# If your extensions are in another directory, add it here. If the directory
+# is relative to the documentation root, use os.path.abspath to make it
+# absolute, like shown here.
+#sys.path.append(os.path.abspath('some/directory'))
+
+# General configuration
+# ---------------------
+
+# Add any Sphinx extension module names here, as strings. They can be extensions
+# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
+extensions = ['sphinx.ext.doctest']
+
+doctest_global_setup = """
+import os
+import sys
+import mock
+from mock import * # yeah, I know :-/
+import unittest2
+import __main__
+
+if os.getcwd() not in sys.path:
+    sys.path.append(os.getcwd())
+
+# keep a reference to __main__
+sys.modules['__main'] = __main__
+
+class ProxyModule(object):
+    def __init__(self):
+        self.__dict__ = globals()
+
+sys.modules['__main__'] = ProxyModule()
+"""
+
+doctest_global_cleanup = """
+sys.modules['__main__'] = sys.modules['__main']
+"""
+
+html_theme = 'nature'
+html_theme_options = {}
+
+# Add any paths that contain templates here, relative to this directory.
+#templates_path = ['_templates']
+
+# The suffix of source filenames.
+source_suffix = '.txt'
+
+# The master toctree document.
+master_doc = 'index'
+
+# General substitutions.
+project = u'Mock'
+copyright = u'2007-2012, Michael Foord & the mock team'
+
+# The default replacements for |version| and |release|, also used in various
+# other places throughout the built documents.
+#
+# The short X.Y version.
+version = __version__[:3]
+# The full version, including alpha/beta/rc tags.
+release = __version__
+
+# There are two options for replacing |today|: either, you set today to some
+# non-false value, then it is used:
+#today = ''
+# Else, today_fmt is used as the format for a strftime call.
+today_fmt = '%B %d, %Y'
+
+# List of documents that shouldn't be included in the build.
+#unused_docs = []
+
+# List of directories, relative to source directories, that shouldn't be searched
+# for source files.
+exclude_trees = []
+
+# The reST default role (used for this markup: `text`) to use for all documents.
+#default_role = None
+
+# If true, '()' will be appended to :func: etc. cross-reference text.
+#add_function_parentheses = True
+
+# If true, the current module name will be prepended to all description
+# unit titles (such as .. function::).
+add_module_names = False
+
+# If true, sectionauthor and moduleauthor directives will be shown in the
+# output. They are ignored by default.
+#show_authors = False
+
+# The name of the Pygments (syntax highlighting) style to use.
+pygments_style = 'friendly'
+
+
+# Options for HTML output
+# -----------------------
+
+# The style sheet to use for HTML and HTML Help pages. A file of that name
+# must exist either in Sphinx' static/ path, or in one of the custom paths
+# given in html_static_path.
+#html_style = 'adctheme.css'
+
+# The name for this set of Sphinx documents.  If None, it defaults to
+# "<project> v<release> documentation".
+#html_title = None
+
+# A shorter title for the navigation bar.  Default is the same as html_title.
+#html_short_title = None
+
+# The name of an image file (relative to this directory) to place at the top
+# of the sidebar.
+#html_logo = None
+
+# The name of an image file (within the static path) to use as favicon of the
+# docs.  This file should be a Windows icon file (.ico) being 16x16 or 32x32
+# pixels large.
+#html_favicon = None
+
+# Add any paths that contain custom static files (such as style sheets) here,
+# relative to this directory. They are copied after the builtin static files,
+# so a file named "default.css" will overwrite the builtin "default.css".
+#html_static_path = ['_static']
+
+# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
+# using the given strftime format.
+html_last_updated_fmt = '%b %d, %Y'
+
+# If true, SmartyPants will be used to convert quotes and dashes to
+# typographically correct entities.
+#html_use_smartypants = True
+
+# Custom sidebar templates, maps document names to template names.
+#html_sidebars = {}
+
+# Additional templates that should be rendered to pages, maps page names to
+# template names.
+#html_additional_pages = {}
+
+# If false, no module index is generated.
+html_use_modindex = False
+
+# If false, no index is generated.
+#html_use_index = True
+
+# If true, the index is split into individual pages for each letter.
+#html_split_index = False
+
+# If true, the reST sources are included in the HTML build as _sources/<name>.
+#html_copy_source = True
+
+# If true, an OpenSearch description file will be output, and all pages will
+# contain a <link> tag referring to it.  The value of this option must be the
+# base URL from which the finished HTML is served.
+#html_use_opensearch = ''
+
+# If nonempty, this is the file name suffix for HTML files (e.g. ".xhtml").
+#html_file_suffix = ''
+
+# Output file base name for HTML help builder.
+htmlhelp_basename = 'Mockdoc'
+
+
+# Options for LaTeX output
+# ------------------------
+
+# The paper size ('letter' or 'a4').
+#latex_paper_size = 'letter'
+
+# The font size ('10pt', '11pt' or '12pt').
+latex_font_size = '12pt'
+
+# Grouping the document tree into LaTeX files. List of tuples
+# (source start file, target name, title, author, document class [howto/manual]).
+latex_documents = [
+  ('index', 'Mock.tex', u'Mock Documentation',
+   u'Michael Foord', 'manual'),
+]
+
+# The name of an image file (relative to this directory) to place at the top of
+# the title page.
+#latex_logo = None
+
+# For "manual" documents, if this is true, then toplevel headings are parts,
+# not chapters.
+#latex_use_parts = False
+
+# Additional stuff for the LaTeX preamble.
+#latex_preamble = ''
+
+# Documents to append as an appendix to all manuals.
+#latex_appendices = []
+
+# If false, no module index is generated.
+latex_use_modindex = False
\ No newline at end of file



Mime
View raw message