def test_github_oauth_token_is_valid_uses_curl(self): ctx = utils.FormattedDict({ 'BUILD_DIR': '/usr/awesome', 'PHP_VM': 'php', 'TMPDIR': tempfile.gettempdir(), 'LIBDIR': 'lib', 'CACHE_DIR': 'cache', }) instance_stub = Dingus() instance_stub._set_return_value("""{"resources": {}}""") stream_output_stub = Dingus( 'test_github_oauth_token_uses_curl : stream_output') with patch('StringIO.StringIO.getvalue', instance_stub): with patch('composer.extension.stream_output', stream_output_stub): ct = self.extension_module.ComposerExtension(ctx) ct._github_oauth_token_is_valid('MADE_UP_TOKEN_VALUE') executed_command = stream_output_stub.calls()[0].args[1] assert stream_output_stub.calls().once( ), 'stream_output() was called more than once' assert executed_command.find( 'curl' ) == 0, 'Curl was not called, executed_command was %s' % executed_command assert executed_command.find( '-H "Authorization: token MADE_UP_TOKEN_VALUE"' ) > 0, 'No token was passed to curl. Command was: %s' % executed_command assert executed_command.find( 'https://api.github.com/rate_limit' ) > 0, 'No URL was passed to curl. Command was: %s' % executed_command
def test_composer_tool_detect(self): ctx = utils.FormattedDict({ 'DOWNLOAD_URL': 'http://server/bins', 'BUILD_DIR': '/build/dir', 'CACHE_DIR': '/cache/dir' }) builder = Dingus(_ctx=ctx) listdir = Dingus(return_value=('composer.json',)) exists = Dingus(return_value=True) with patch('os.listdir', listdir): with patch('os.path.exists', exists): ct = self.ct.ComposerTool(builder) assert ct.detect() assert listdir.calls().once()
def review_open(self, node): """ Open new review """ with patch("flask.templating._render", Dingus(return_value='')): rv = self.app.post("/review", data={"node": node}, follow_redirects=True) cs = flask.templating._render.calls[0].args[1]['cs'] return cs.id
def test_sync2(self): """ We are testing for Popen calls to check how rsync was called. Maybe it would be better to create a mock rsync command and put it in the PATH. """ import subprocess with dingus.patch("subprocess.Popen"): self.setup_client() # Start recording json received from server received_json = [] with json_hooker(received_json): # Initiate sync logger.debug("about to click_sync") self.test_client.click_sync() logger.debug("finished") self.test_client.quit() # load up received json object self.assertEqual(len(received_json), 1) requested_files = self.find_files_in_json(received_json)[0] # a. check that files are requested self.assertEqual(len(requested_files), 2) self.assertEqual(requested_files[0], "runsample1_filename") self.assertEqual(requested_files[1], "runsample2_filename") # b. check that rsync was not called self.assertEqual(len(subprocess.Popen.calls), 0) self.assertTrue(True)
def test_composer_tool_run_sanity_checks(self): ctx = utils.FormattedDict({ 'DOWNLOAD_URL': 'http://server/bins', 'CACHE_HASH_ALGORITHM': 'sha1', 'BUILD_DIR': '/build/dir', 'CACHE_DIR': '/cache/dir', 'TMPDIR': tempfile.gettempdir() }) builder = Dingus(_ctx=ctx) # patch stream_output method old_stream_output = self.ct.stream_output co = Dingus() self.ct.stream_output = co # patch utils.rewrite_cfg method old_rewrite = self.ct.utils.rewrite_cfgs rewrite = Dingus() self.ct.utils.rewrite_cfgs = rewrite try: ct = self.ct.ComposerTool(builder) ct._log = Dingus() ct.run() assert len(ct._log.warning.calls()) > 0 assert ct._log.warning.calls()[0].args[0].find('PROTIP:') == 0 exists = Dingus(return_value=True) with patch('os.path.exists', exists): ct._log = Dingus() ct.run() assert len(exists.calls()) == 1 assert len(ct._log.warning.calls()) == 0 finally: self.ct.stream_output = old_stream_output self.ct.utils.rewrite_cfgs = old_rewrite
def load_data(orm, fixture_name): _get_model = lambda model_identifier: orm[model_identifier] with patch('django.core.serializers.python._get_model', _get_model): from django.core.management import call_command call_command("loaddata", fixture_name)
def test_run_vm_stat(self): check_output_dingus = dingus.Dingus() check_output_dingus.return_value = "some data here" with dingus.patch('subprocess.check_output', check_output_dingus): from usage_grapher import run_vm_stat output = run_vm_stat() eq_(output, "some data here")
def test_composer_tool_run_sanity_checks(self): ctx = utils.FormattedDict({ 'DOWNLOAD_URL': 'http://server/bins', 'CACHE_HASH_ALGORITHM': 'sha1', 'BUILD_DIR': '/build/dir', 'CACHE_DIR': '/cache/dir', 'TMPDIR': tempfile.gettempdir() }) builder = Dingus(_ctx=ctx) old_check_output = self.ct.check_output co = Dingus() self.ct.check_output = co try: ct = self.ct.ComposerTool(builder) ct._log = Dingus() ct.run() assert len(ct._log.warning.calls()) > 0 assert ct._log.warning.calls()[0].args[0].find('PROTIP:') == 0 exists = Dingus(return_value=True) with patch('os.path.exists', exists): ct._log = Dingus() ct.run() assert len(exists.calls()) == 1 assert len(ct._log.warning.calls()) == 0 finally: self.ct.check_output = old_check_output
def test_requestsync_urlopen_error(self): "test requestsync when urlopen raises an exception" with dingus.patch("urllib2.urlopen", dingus.exception_raiser(IOError("you fail"))): result = self.server.requestsync() self.assertFalse(result["success"]) self.assertEqual(result["message"], "you fail")
def new_list(self): """ Get list of new review candidates """ self.app.get("/changes/refresh") with patch("flask.templating._render", Dingus(return_value='')): rv = self.app.get("/changes/new") revisions = flask.templating._render.calls[0].args[1]['revisions'] return revisions
def patches(patch_values): patcher_collection = PatcherCollection() for object_path, new_object in patch_values.iteritems(): patcher_collection.add_patcher(patch(object_path, new_object)) return patcher_collection
def should_be_able_to_return_something(self): with patch('__builtin__.open', self.dingus): file_ = open.return_value.__enter__.return_value file_.read.return_value = 'some data' with open('foo') as h: assert 'some data' == h.read() assert self.dingus.calls('()', 'foo').once()
def rework_list(self): """ Get list of reworks for first review """ #TODO: Separate refresh method self.app.get("/changes/refresh") with patch("flask.templating._render", Dingus(return_value='')): rv = self.app.get("/review/1") revisions = flask.templating._render.calls[0].args[1]['descendants'] return revisions
def test_load_vm_stat_data(self): fp = open('tests/usage_grapher.csv', 'rb') with dingus.patch('__builtin__.open', lambda *args: fp): from usage_grapher import load_vm_stat_data vm_stat_data = load_vm_stat_data() assert len(vm_stat_data) == 18 eq_("33403871", vm_stat_data[0]["Pages zero filled"]) eq_("9004831", vm_stat_data[1]["Pageins"])
def test_close_port(self): listenTCP = Dingus() with patch('twisted.internet.reactor.listenTCP', listenTCP): config.set_config(StringIO(test_config)) collection = ConsoleCollection() collection.open_port(config.get_by_name('/dev/ttyUSB0')) self.assertEqual(1, len(listenTCP.calls)) self.assertEqual(1, len(collection)) collection.close_port('/dev/ttyUSB0')
def migration_loaddata(orm, fixture_name): """ Use this function for loading bulk data in migrations. See: http://south.aeracode.org/ticket/334 http://stackoverflow.com/a/5906258 """ _get_model = lambda model_identifier: orm[model_identifier] with patch('django.core.serializers.python._get_model', _get_model): from django.core.management import call_command call_command("loaddata", fixture_name)
def test_github_oauth_token_is_valid_interprets_github_api_401_as_false(self): ctx = utils.FormattedDict({ 'BUILD_DIR': tempfile.gettempdir(), 'PHP_VM': 'php', 'TMPDIR': tempfile.gettempdir(), 'LIBDIR': 'lib', 'CACHE_DIR': 'cache', }) instance_stub = Dingus() instance_stub._set_return_value("""{}""") stream_output_stub = Dingus('test_github_oauth_token_uses_curl : stream_output') with patch('StringIO.StringIO.getvalue', instance_stub): with patch('composer.extension.stream_output', stream_output_stub): ct = self.extension_module.ComposerExtension(ctx) result = ct._github_oauth_token_is_valid('MADE_UP_TOKEN_VALUE') assert result == False, '_github_oauth_token_is_valid returned %s, expected False' % result
def loaddata(orm, fixture_name): """ Overwrite the ``_get_model`` command in the serialiser to use the FakeORM model from south instead of the latest model. """ from dingus import patch _get_model = lambda model_identifier: orm[model_identifier] with patch('django.core.serializers.python._get_model', _get_model): from django.core.management import call_command call_command("loaddata", fixture_name)
def forwards(self, orm): # Make sure that the fixture file actually exists, because the # loaddata command does not raise an exception if no fixtures were # found which can lead to difficult to debug errors if the fixture # filename is specified incorrectly. open(self.fixture_path(), 'rb').close() _get_model = lambda model_identifier: orm[model_identifier] with patch('django.core.serializers.python._get_model', _get_model): from django.core.management import call_command call_command("loaddata", self.fixture)
def test_find_by_name(self): listenTCP = Dingus() with patch('twisted.internet.reactor.listenTCP', listenTCP): config.set_config(StringIO(test_config)) collection = ConsoleCollection() collection.open_port(config.get_by_name('/dev/ttyUSB0')) self.assertEqual(1, len(listenTCP.calls)) self.assertEqual(1, len(collection)) ch = collection.find_by_name('/dev/ttyUSB0') self.assertIsInstance(ch, ConsoleHandler) ch = collection.find_by_name('/dev/ttyUSB1') self.assertEqual(None, ch)
def test_github_oauth_token_is_valid_interprets_github_api_401_as_false( self): ctx = utils.FormattedDict({ 'BUILD_DIR': tempfile.gettempdir(), 'PHP_VM': 'php', 'TMPDIR': tempfile.gettempdir(), 'LIBDIR': 'lib', 'CACHE_DIR': 'cache', }) instance_stub = Dingus() instance_stub._set_return_value("""{}""") stream_output_stub = Dingus( 'test_github_oauth_token_uses_curl : stream_output') with patch('StringIO.StringIO.getvalue', instance_stub): with patch('composer.extension.stream_output', stream_output_stub): ct = self.extension_module.ComposerExtension(ctx) result = ct._github_oauth_token_is_valid('MADE_UP_TOKEN_VALUE') assert result == False, '_github_oauth_token_is_valid returned %s, expected False' % result
def test_requestsync_baseurl(self): "tests requestsync when configured sync url has no trailing slash" self.config["synchub"] = "http://test" self.config["sitename"] = "b" self.config["stationname"] = "c" self.config["organisation"] = "a" my_dingus = dingus.Dingus() with self.fake_urlopen('{ "success": true, "details": {} }') as d: with dingus.patch("urllib2.Request", my_dingus): result = self.server.requestsync() self.assertTrue(result["success"]) self.assertTrue(d.calls("()").once()) self.assertEqual(len(my_dingus.calls), 1) self.assertEqual(my_dingus.calls[0].args[0], "http://test/requestsync/a/b/c/")
def test_requestsync_spaces(self): self.config["synchub"] = "http://test" self.config["sitename"] = "An Interesting Site" self.config["stationname"] = "A Station Name" self.config["organisation"] = "The Organisation" my_dingus = dingus.Dingus() with self.fake_urlopen('{ "success": true, "details": {} }') as d: with dingus.patch("urllib2.Request", my_dingus): result = self.server.requestsync() self.assertTrue(result["success"]) self.assertTrue(d.calls("()").once()) self.assertEqual(len(my_dingus.calls), 1) self.assertEqual(my_dingus.calls[0].args[0], "http://test/requestsync/The%20Organisation/An%20Interesting%20Site/A%20Station%20Name/")
def test_github_oauth_token_is_valid_uses_curl(self): ctx = utils.FormattedDict({ 'BUILD_DIR': '/usr/awesome', 'PHP_VM': 'php', 'TMPDIR': tempfile.gettempdir(), 'LIBDIR': 'lib', 'CACHE_DIR': 'cache', }) instance_stub = Dingus() instance_stub._set_return_value("""{"resources": {}}""") stream_output_stub = Dingus('test_github_oauth_token_uses_curl : stream_output') with patch('StringIO.StringIO.getvalue', instance_stub): with patch('composer.extension.stream_output', stream_output_stub): ct = self.extension_module.ComposerExtension(ctx) ct._github_oauth_token_is_valid('MADE_UP_TOKEN_VALUE') executed_command = stream_output_stub.calls()[0].args[1] assert stream_output_stub.calls().once(), 'stream_output() was called more than once' assert executed_command.find('curl') == 0, 'Curl was not called, executed_command was %s' % executed_command assert executed_command.find('-H "Authorization: token MADE_UP_TOKEN_VALUE"') > 0, 'No token was passed to curl. Command was: %s' % executed_command assert executed_command.find('https://api.github.com/rate_limit') > 0, 'No URL was passed to curl. Command was: %s' % executed_command
def test_store_data(self): # get some data vm_stat_data = open('tests/vm_stat_output.txt').read() from usage_grapher import parse_vm_stat_output parsed_data = parse_vm_stat_output(vm_stat_data) # create a place for the function to write the data buf = StringIO() open_dingus = dingus.Dingus() open_dingus.return_value.__enter__.return_value = buf # run our actual method with dingus.patch('__builtin__.open', open_dingus): from usage_grapher import persist_vm_stat_data persist_vm_stat_data(parsed_data) output = buf.getvalue() assert output.startswith("74033590,") assert output.strip().endswith("384190")
def test_composer_tool_run_sanity_checks(self): ctx = utils.FormattedDict({ 'PHP_VM': 'php', 'DOWNLOAD_URL': 'http://server/bins', 'CACHE_HASH_ALGORITHM': 'sha1', 'BUILD_DIR': '/build/dir', 'CACHE_DIR': '/cache/dir', 'TMPDIR': tempfile.gettempdir(), 'LIBDIR': 'lib', 'BP_DIR': '' }) instance_stub = Dingus() instance_stub._set_return_value( """{"rate": {"limit": 60, "remaining": 60}}""") stream_output_stub = Dingus() rewrite_stub = Dingus() builder = Dingus(_ctx=ctx) exists_stub = Dingus() with patches({ 'StringIO.StringIO.getvalue': instance_stub, 'composer.extension.stream_output': stream_output_stub, 'composer.extension.utils.rewrite_cfgs': rewrite_stub }): composer_extension = \ self.extension_module.ComposerExtension(ctx) composer_extension._log = Dingus() composer_extension._builder = builder composer_extension.composer_runner = \ self.extension_module.ComposerCommandRunner(ctx, builder) composer_extension.run() composer_extension_calls = composer_extension._log.warning.calls() assert len(composer_extension_calls) > 0 assert composer_extension_calls[0].args[0].find('PROTIP:') == 0 exists = Dingus(return_value=True) with patch('os.path.exists', exists_stub): composer_extension._log = Dingus() composer_extension.run() assert len(exists_stub.calls()) == 2 assert len(composer_extension._log.warning.calls()) == 0
def test_composer_tool_run_sanity_checks(self): ctx = utils.FormattedDict({ 'PHP_VM': 'php', 'DOWNLOAD_URL': 'http://server/bins', 'CACHE_HASH_ALGORITHM': 'sha1', 'BUILD_DIR': '/build/dir', 'CACHE_DIR': '/cache/dir', 'TMPDIR': tempfile.gettempdir(), 'LIBDIR': 'lib', 'BP_DIR': '' }) instance_stub = Dingus() instance_stub._set_return_value("""{"rate": {"limit": 60, "remaining": 60}}""") stream_output_stub = Dingus() rewrite_stub = Dingus() builder = Dingus(_ctx=ctx) exists_stub = Dingus() with patches({ 'StringIO.StringIO.getvalue': instance_stub, 'composer.extension.stream_output': stream_output_stub, 'composer.extension.utils.rewrite_cfgs': rewrite_stub }): composer_extension = \ self.extension_module.ComposerExtension(ctx) composer_extension._log = Dingus() composer_extension._builder = builder composer_extension.composer_runner = \ self.extension_module.ComposerCommandRunner(ctx, builder) composer_extension.run() composer_extension_calls = composer_extension._log.warning.calls() assert len(composer_extension_calls) > 0 assert composer_extension_calls[0].args[0].find('PROTIP:') == 0 exists = Dingus(return_value=True) with patch('os.path.exists', exists_stub): composer_extension._log = Dingus() composer_extension.run() assert len(exists_stub.calls()) == 2 assert len(composer_extension._log.warning.calls()) == 0
def test_requestsync_spaces(self): self.config["synchub"] = "http://test" self.config["sitename"] = "An Interesting Site" self.config["stationname"] = "A Station Name" self.config["organisation"] = "The Organisation" my_dingus = dingus.Dingus() with self.fake_urlopen('{ "success": true, "details": {} }') as d: with dingus.patch("urllib2.Request", my_dingus): result = self.server.requestsync() self.assertTrue(result["success"]) self.assertTrue(d.calls("()").once()) self.assertEqual(len(my_dingus.calls), 1) self.assertEqual( my_dingus.calls[0].args[0], "http://test/requestsync/The%20Organisation/An%20Interesting%20Site/A%20Station%20Name/" )
def test_composer_tool_run_sanity_checks(self): ctx = utils.FormattedDict( { "PHP_VM": "php", "BUILD_DIR": "/build/dir", "CACHE_DIR": "/cache/dir", "WEBDIR": "", "TMPDIR": tempfile.gettempdir(), "LIBDIR": "lib", "BP_DIR": "", } ) instance_stub = Dingus() instance_stub._set_return_value("""{"rate": {"limit": 60, "remaining": 60}}""") stream_output_stub = Dingus() rewrite_stub = Dingus() builder = Dingus(_ctx=ctx) exists_stub = Dingus() with patches( { "StringIO.StringIO.getvalue": instance_stub, "composer.extension.stream_output": stream_output_stub, "composer.extension.utils.rewrite_cfgs": rewrite_stub, } ): composer_extension = self.extension_module.ComposerExtension(ctx) composer_extension._log = Dingus() composer_extension._builder = builder composer_extension.composer_runner = self.extension_module.ComposerCommandRunner(ctx, builder) composer_extension.run() composer_extension_calls = composer_extension._log.warning.calls() assert len(composer_extension_calls) > 0 assert composer_extension_calls[0].args[0].find("PROTIP:") == 0 exists = Dingus(return_value=True) with patch("os.path.exists", exists_stub): composer_extension._log = Dingus() composer_extension.run() assert len(composer_extension._log.warning.calls()) == 0
def test_create(self): # patch so we know the notifier config.set_config(StringIO(test_config)) inotify = Dingus() with patch('consoleserver.monitoredconsolecollection.INotify', Dingus(return_value=inotify)): collection = MonitoredConsoleCollection() name, args, kwargs, result = inotify.calls('watch')[0] self.assertEqual(2, len(args)) self.assertEqual('/dev', args[0].path) name, args, kwargs, result = inotify.calls('startReading')[0] self.assertEqual(0, len(args)) collection.created('ignored', FilePath('/dev/ttyUSB0'), 'mask') # fake the notify self.assertEqual(1, len(collection)) collection.created('ignored', FilePath('/dev/tty0'), 'mask') # fake the notify self.assertEqual(1, len(collection))
def test1_check_run_sample_files(self): """ Check that `MSDSImpl.serverCheckRunSampleFiles()` results in an API call marking complete the correct samples. """ Server = dingus.Dingus() with dingus.patch("mdatasync_client.MSDataSyncAPI.DataSyncServer", Server): self.impl.serverCheckRunSampleFiles(self.rsyncconfig, self.filename_id_map) self.assertEqual(len(Server.return_value.calls), 1, "One DataSyncServer instance is created") runsampledict, last_error = Server.return_value.calls[0][1] self.assertEqual(len(runsampledict), 2, "Two samples are marked complete") self.assertEqual(runsampledict, { 1: [10], 2: [20] }, "The correct samples are marked complete")
def test_composer_tool_run_sanity_checks(self): context = utils.FormattedDict({ 'PHP_VM': 'php', 'DOWNLOAD_URL': 'http://server/bins', 'CACHE_HASH_ALGORITHM': 'sha1', 'BUILD_DIR': '/build/dir', 'CACHE_DIR': '/cache/dir', 'TMPDIR': tempfile.gettempdir(), 'LIBDIR': 'lib' }) builder = Dingus(_ctx=context) # patch stream_output method old_stream_output = self.extension_module.stream_output stream_output_stub = Dingus() self.extension_module.stream_output = stream_output_stub # patch utils.rewrite_cfg method old_rewrite = self.extension_module.utils.rewrite_cfgs rewrite_stub = Dingus() self.extension_module.utils.rewrite_cfgs = rewrite_stub try: composer_extension = self.extension_module.ComposerExtension( context) composer_extension._log = Dingus() composer_extension._builder = builder composer_extension.run() assert len(composer_extension._log.warning.calls()) > 0 assert composer_extension._log.warning.calls()[0].args[0].find( 'PROTIP:') == 0 exists = Dingus(return_value=True) with patch('os.path.exists', exists): composer_extension._log = Dingus() composer_extension.run() assert len(exists.calls()) == 1 assert len(composer_extension._log.warning.calls()) == 0 finally: self.extension_module.stream_output = old_stream_output self.extension_module.utils.rewrite_cfgs = old_rewrite
def test_composer_tool_run_sanity_checks(self): context = utils.FormattedDict({ 'PHP_VM': 'php', 'DOWNLOAD_URL': 'http://server/bins', 'CACHE_HASH_ALGORITHM': 'sha1', 'BUILD_DIR': '/build/dir', 'CACHE_DIR': '/cache/dir', 'TMPDIR': tempfile.gettempdir(), 'LIBDIR': 'lib' }) builder = Dingus(_ctx=context) # patch stream_output method old_stream_output = self.extension_module.stream_output stream_output_stub = Dingus() self.extension_module.stream_output = stream_output_stub # patch utils.rewrite_cfg method old_rewrite = self.extension_module.utils.rewrite_cfgs rewrite_stub = Dingus() self.extension_module.utils.rewrite_cfgs = rewrite_stub try: composer_extension = self.extension_module.ComposerExtension(context) composer_extension._log = Dingus() composer_extension._builder = builder composer_extension.run() assert len(composer_extension._log.warning.calls()) > 0 assert composer_extension._log.warning.calls()[0].args[0].find('PROTIP:') == 0 exists = Dingus(return_value=True) with patch('os.path.exists', exists): composer_extension._log = Dingus() composer_extension.run() assert len(exists.calls()) == 1 assert len(composer_extension._log.warning.calls()) == 0 finally: self.extension_module.stream_output = old_stream_output self.extension_module.utils.rewrite_cfgs = old_rewrite
def test2_check_run_sample_files_temp_files(self): """ Sample is not marked incomplete if there is a TEMP file in its directory. """ # create a file called TEMP within a directory called # filename2 somewhere within the data dir self.create_data_file("test", "dir", "filename2", "TEMP") Server = dingus.Dingus() with dingus.patch("mdatasync_client.MSDataSyncAPI.DataSyncServer", Server): self.impl.serverCheckRunSampleFiles(self.rsyncconfig, self.filename_id_map) self.assertEqual(len(Server.return_value.calls), 1, "One DataSyncServer instance is created") runsampledict, last_error = Server.return_value.calls[0][1] self.assertEqual(len(runsampledict), 1, "One sample is marked complete") self.assertEqual(runsampledict, { 1: [10] }, "The correct sample is marked complete")
def test2_check_run_sample_files_temp_files(self): """ Sample is not marked incomplete if there is a TEMP file in its directory. """ # create a file called TEMP within a directory called # filename2 somewhere within the data dir self.create_data_file("test", "dir", "filename2", "TEMP") Server = dingus.Dingus() with dingus.patch("mdatasync_client.MSDataSyncAPI.DataSyncServer", Server): self.impl.serverCheckRunSampleFiles(self.rsyncconfig, self.filename_id_map) self.assertEqual(len(Server.return_value.calls), 1, "One DataSyncServer instance is created") runsampledict, last_error = Server.return_value.calls[0][1] self.assertEqual(len(runsampledict), 1, "One sample is marked complete") self.assertEqual(runsampledict, {1: [10]}, "The correct sample is marked complete")
def test_install_binary_direct_not_zipped(self): # Setup mocks installer = CloudFoundryInstaller({ 'BUILD_DIR': '/tmp/build_dir', 'CACHE_DIR': '/tmp/cache_dir', 'TMPDIR': '/tmp/temp_dir' }) installer._unzipUtil = Dingus('unzip', extract__returns='N/A') installer._hashUtil = Dingus('hash', calculate_hash__returns='1234WXYZ') installer._dcm = Dingus('dcm', get__returns='/tmp/cache/composer.phar') installer._dwn = Dingus('download') shutil_copy = Dingus() # Run test with patch('shutil.copy', shutil_copy): instDir = installer.install_binary_direct( 'scheme://PREFIX/composer.phar', 'scheme://PREFIX/composer.phar.sha1', '/tmp/build_dir/composer', extract=False) # Verify execution path, file is not cached # Check hash file is downloaded assert installer._dwn.download_direct.calls().once() # Cache manager checks for file assert installer._dcm.get.calls().once() assert '/tmp/cache/composer.phar' == \ installer._dcm.calls('get')[0].return_value # make sure download section is skipped assert 0 == len(installer._dwn.calls('download')) assert 0 == len(installer._hashUtil.calls('calculate_hash')) assert 0 == len(installer._dcm.calls('put')) # file is not extracted, but copied instead assert 0 == len(installer._unzipUtil.extract.calls()) assert shutil_copy.calls().once() eq_('/tmp/build_dir/composer', instDir)
def should_set_wrapped_on_patched_function(self): def urllib2(): pass patch_urllib2 = patch('urllib2.urlopen')(urllib2) assert patch_urllib2.__wrapped__ == urllib2
def should_name_dingus_after_patched_object(self): with patch('urllib2.urlopen'): assert str(urllib2.urlopen) == '<Dingus urllib2.urlopen>'
def should_be_able_to_provide_explicit_dingus(self): my_dingus = Dingus() with patch('urllib2.urlopen', my_dingus): assert urllib2.urlopen is my_dingus
def should_be_usable_as_context_manager(self): with patch('urllib2.urlopen'): assert isinstance(urllib2.urlopen, Dingus) assert not isinstance(urllib2.urlopen, Dingus)