Python unittest.mock.patch() Examples
The following are 30
code examples of unittest.mock.patch().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
unittest.mock
, or try the search function
.
Example #1
Source File: test_build.py From controller with MIT License | 6 votes |
def test_release_create_failure(self, mock_requests): """ Cause an Exception in app.deploy to cause a failed release in build.create """ app_id = self.create_app() # deploy app to get a build url = "/v2/apps/{app_id}/builds".format(**locals()) body = {'image': 'autotest/example'} response = self.client.post(url, body) self.assertEqual(response.status_code, 201, response.data) self.assertEqual(response.data['image'], body['image']) with mock.patch('api.models.App.deploy') as mock_deploy: mock_deploy.side_effect = Exception('Boom!') url = "/v2/apps/{app_id}/builds".format(**locals()) body = {'image': 'autotest/example'} response = self.client.post(url, body) self.assertEqual(response.status_code, 400, response.data)
Example #2
Source File: test_app.py From controller with MIT License | 6 votes |
def test_run_failure(self, mock_requests): """Raise a KubeException via scheduler.run""" app_id = self.create_app() # create build body = {'image': 'autotest/example'} url = '/v2/apps/{app_id}/builds'.format(**locals()) response = self.client.post(url, body) self.assertEqual(response.status_code, 201, response.data) with mock.patch('scheduler.KubeHTTPClient.run') as kube_run: kube_run.side_effect = KubeException('boom!') # run command url = '/v2/apps/{}/run'.format(app_id) body = {'command': 'ls -al'} response = self.client.post(url, body) self.assertEqual(response.status_code, 503, response.data)
Example #3
Source File: test_admin.py From openwisp-users with BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_admin_add_user_with_invalid_email(self): admin = self._create_admin() self.client.force_login(admin) params = dict( username='testmail', email='test@invalid.com', password1='tester', password2='tester', ) params.update(self.add_user_inline_params) params.update(self._additional_params_add()) with patch('allauth.account.models.EmailAddress.objects.add_email') as mocked: mocked.side_effect = smtplib.SMTPSenderRefused( 501, '5.1.7 Bad sender address syntax', 'test_name@test_domain' ) self.client.post(reverse(f'admin:{self.app_label}_user_add'), params) mocked.assert_called_once()
Example #4
Source File: test-distro.py From multibootusb with GNU General Public License v2.0 | 6 votes |
def test_distro_detection(self): def os_path_exists(f): if f.endswith('multibootusb.log'): return False return True os_path_exists_mock = MM() log_mock = MM() @patch('os.path.exists', os_path_exists) @patch('scripts.distro.log', log_mock) def _(): fn = distro.detect_iso_from_file_list assert fn(['BOOT.wim', 'Sources']) == 'Windows' assert fn(['BOOT.wim', 'Sause']) is None assert fn(['config.isoclient', 'foo']) == 'opensuse' assert fn(['bar', 'dban', 'foo']) == 'slitaz' assert fn(['memtest.img']) == 'memtest' assert fn(['mt86.png','isolinux']) == 'raw_iso' assert fn(['menu.lst']) == 'grub4dos' assert fn(['bootwiz.cfg', 'bootmenu_logo.png']) == \ 'grub4dos_iso' _()
Example #5
Source File: test_views.py From pinax-documents with MIT License | 6 votes |
def test_download(self): """ Ensure the requested Document file is served. """ simple_file = SimpleUploadedFile("delicious.txt", self.file_contents) document = Document.objects.create(name="Honeycrisp", author=self.user, file=simple_file, ) document.save() with self.login(self.user): # Verify `django.views.static.serve` is called to serve up the file. # See related note in .views.DocumentDownload.get(). with mock.patch("django.views.static.serve") as serve: serve.return_value = HttpResponse() self.get_check_200(self.download_urlname, pk=document.pk) self.assertTrue(serve.called)
Example #6
Source File: test_config.py From controller with MIT License | 6 votes |
def test_config_deploy_failure(self, mock_requests): """ Cause an Exception in app.deploy to cause a release.delete """ app_id = self.create_app() # deploy app to get a build url = "/v2/apps/{}/builds".format(app_id) body = {'image': 'autotest/example'} response = self.client.post(url, body) self.assertEqual(response.status_code, 201, response.data) self.assertEqual(response.data['image'], body['image']) with mock.patch('api.models.App.deploy') as mock_deploy: mock_deploy.side_effect = Exception('Boom!') url = '/v2/apps/{app_id}/config'.format(**locals()) body = {'values': json.dumps({'test': "testvalue"})} response = self.client.post(url, body) self.assertEqual(response.status_code, 400)
Example #7
Source File: test_message.py From oslo.i18n with Apache License 2.0 | 6 votes |
def test_mod_with_wrong_field_type_in_trans(self): msgid = "Correct type %(arg1)s" params = {'arg1': 'test1'} with mock.patch('gettext.translation') as trans: # Set up ugettext to return the original message with the # correct format string. trans.return_value.ugettext.return_value = msgid # Build a message and give it some parameters. result = _message.Message(msgid) % params # Now set up ugettext to return the translated version of # the original message, with a bad format string. wrong_type = u'Wrong type %(arg1)d' if six.PY3: trans.return_value.gettext.return_value = wrong_type else: trans.return_value.ugettext.return_value = wrong_type trans_result = result.translation() expected = msgid % params self.assertEqual(expected, trans_result)
Example #8
Source File: test_domain.py From controller with MIT License | 6 votes |
def test_kubernetes_service_failure(self): """ Cause an Exception in kubernetes services """ app_id = self.create_app() # scheduler.svc.get exception with mock.patch('scheduler.resources.service.Service.get') as mock_kube: mock_kube.side_effect = KubeException('Boom!') domain = 'foo.com' url = '/v2/apps/{}/domains'.format(app_id) response = self.client.post(url, {'domain': domain}) self.assertEqual(response.status_code, 503, response.data) # scheduler.svc.update exception with mock.patch('scheduler.resources.service.Service.update') as mock_kube: domain = 'foo.com' url = '/v2/apps/{}/domains'.format(app_id) response = self.client.post(url, {'domain': domain}) self.assertEqual(response.status_code, 201, response.data) mock_kube.side_effect = KubeException('Boom!') url = '/v2/apps/{}/domains/{}'.format(app_id, domain) response = self.client.delete(url) self.assertEqual(response.status_code, 503, response.data)
Example #9
Source File: test_build.py From controller with MIT License | 6 votes |
def test_release_registry_create_failure(self, mock_requests): """ Cause a RegistryException in app.deploy to cause a failed release in build.create """ app_id = self.create_app() # deploy app to get a build url = "/v2/apps/{app_id}/builds".format(**locals()) body = {'image': 'autotest/example'} response = self.client.post(url, body) self.assertEqual(response.status_code, 201, response.data) self.assertEqual(response.data['image'], body['image']) with mock.patch('api.models.Release.publish') as mock_registry: mock_registry.side_effect = RegistryException('Boom!') url = "/v2/apps/{app_id}/builds".format(**locals()) body = {'image': 'autotest/example'} response = self.client.post(url, body) self.assertEqual(response.status_code, 400, response.data)
Example #10
Source File: test_portfolio.py From tensortrade with Apache License 2.0 | 6 votes |
def portfolio(wallet_usd, wallet_btc, wallet_eth, wallet_xrp, exchange): portfolio = Portfolio(USD, wallets=[ wallet_usd, wallet_btc, wallet_eth, wallet_xrp ]) with mock.patch.object(Portfolio, 'clock', return_value=exchange.clock) as clock: portfolio = Portfolio(USD, wallets=[ wallet_usd, wallet_btc, wallet_eth, wallet_xrp ]) return portfolio
Example #11
Source File: test_run.py From branch-protection-bot with MIT License | 6 votes |
def test_should_always_enable_force_admins_when_enabled(self, enable): # Given options = DotDict({ 'retries': 1, 'enforce_admins': 'true', 'github_repository': 'benjefferies/branch-bot-protection' }) # When with patch('run.login') as mock: mock.return_value\ .repository.return_value\ .branch.return_value\ .protection.return_value\ .enforce_admins.enabled = True toggle_enforce_admin(options) # Then enable.assert_called_once()
Example #12
Source File: test_run.py From branch-protection-bot with MIT License | 6 votes |
def test_should_always_disable_force_admins_when_disabled(self, disable): # Given options = DotDict({ 'retries': 1, 'enforce_admins': 'false', 'github_repository': 'benjefferies/branch-bot-protection' }) # When with patch('run.login') as mock: mock.return_value\ .repository.return_value\ .branch.return_value\ .protection.return_value\ .enforce_admins.enabled = False toggle_enforce_admin(options) # Then disable.assert_called_once()
Example #13
Source File: test_run.py From branch-protection-bot with MIT License | 6 votes |
def test_should_disable_force_admins(self, disable): # Given options = DotDict({ 'retries': 1, 'github_repository': 'benjefferies/branch-bot-protection' }) # When with patch('run.login') as mock: mock.return_value\ .repository.return_value\ .branch.return_value\ .protection.return_value\ .enforce_admins.enabled = True toggle_enforce_admin(options) # Then disable.assert_called_once()
Example #14
Source File: test_run.py From branch-protection-bot with MIT License | 6 votes |
def test_should_enable_force_admins(self, enable): # Given options = DotDict({ 'retries': 1, 'github_repository': 'benjefferies/branch-bot-protection' }) # When with patch('run.login') as mock: mock.return_value\ .repository.return_value\ .branch.return_value\ .protection.return_value\ .enforce_admins.enabled = False toggle_enforce_admin(options) # Then enable.assert_called_once()
Example #15
Source File: test_config.py From apsconnect-cli with Apache License 2.0 | 5 votes |
def test_unexpected_error(self): with patch(_BUILTINS_OPEN), \ patch(_BUILTINS_PRINT) as print_mock, \ patch('apsconnectcli.config.json') as json_mock, \ patch('apsconnectcli.config.sys') as sys_mock: json_mock.load.side_effect = Exception("All is lost") get_config() self.assertTrue(print_mock.called) self.assertTrue("All is lost" in print_mock.call_args[0][0]) sys_mock.exit.assert_called_with(1)
Example #16
Source File: test_package.py From apsconnect-cli with Apache License 2.0 | 5 votes |
def test_schema_without_properties(self): with patch(_BUILTINS_OPEN, mock_open(read_data=FakeData.BAD_SCHEMA_JSON)) as mock_file: self.assertRaises(SystemExit, Package._get_properties, FakeData.SCHEMA_PATH) mock_file.assert_called_once_with(FakeData.SCHEMA_PATH)
Example #17
Source File: test_package.py From apsconnect-cli with Apache License 2.0 | 5 votes |
def test_schema_with_properties_section(self): with patch(_BUILTINS_OPEN, mock_open(read_data=FakeData.SCHEMA_JSON)) as mock_file: props = Package._get_properties(FakeData.SCHEMA_PATH) mock_file.assert_called_once_with(FakeData.SCHEMA_PATH) self.assertEqual(FakeData.PROPERTIES, props)
Example #18
Source File: test_config.py From apsconnect-cli with Apache License 2.0 | 5 votes |
def test_ok(self): with patch(_BUILTINS_OPEN), \ patch(_BUILTINS_PRINT) as print_mock, \ patch('apsconnectcli.config.json') as json_mock, \ patch('apsconnectcli.config.sys') as sys_mock: json_mock.load.return_value = 'Config data' config = get_config() self.assertEqual(config, 'Config data') self.assertFalse(print_mock.called) sys_mock.exit.assert_not_called()
Example #19
Source File: test_imdb.py From lineflow with MIT License | 5 votes |
def test_get_imdb_twice(self): get_imdb() with mock.patch('lineflow.datasets.imdb.pickle', autospec=True) as mock_pickle: get_imdb() mock_pickle.dump.assert_not_called() self.assertEqual(mock_pickle.load.call_count, 1)
Example #20
Source File: test_msr_paraphrase.py From lineflow with MIT License | 5 votes |
def test_get_msr_paraphrase_twice(self): get_msr_paraphrase() with mock.patch('lineflow.datasets.msr_paraphrase.pickle', autospec=True) as mock_pickle: get_msr_paraphrase() mock_pickle.dump.assert_not_called() mock_pickle.load.assert_called_once()
Example #21
Source File: test_worker.py From sanic with MIT License | 5 votes |
def test_handle_abort(worker): with mock.patch("sanic.worker.sys") as mock_sys: worker.handle_abort(object(), object()) assert not worker.alive assert worker.exit_code == 1 mock_sys.exit.assert_called_with(1)
Example #22
Source File: test_small_parallel_enja.py From lineflow with MIT License | 5 votes |
def test_get_small_parallel_enja_twice(self): get_small_parallel_enja() with mock.patch('lineflow.datasets.small_parallel_enja.pickle', autospec=True) as mock_pickle: get_small_parallel_enja() mock_pickle.dump.assert_not_called() mock_pickle.load.assert_called_once()
Example #23
Source File: test_wikitext.py From lineflow with MIT License | 5 votes |
def test_get_wikitext_twice(self): for name in ('wikitext-2', 'wikitext-103'): with self.subTest(name=name): get_wikitext(name) with mock.patch('lineflow.datasets.wikitext.pickle', autospec=True) as mock_pickle: get_wikitext(name) mock_pickle.dump.assert_not_called() self.assertEqual(mock_pickle.load.call_count, 1)
Example #24
Source File: test_wmt14.py From lineflow with MIT License | 5 votes |
def test_get_wmt14_twice(self): get_wmt14() with mock.patch('lineflow.datasets.wmt14.pickle', autospec=True) as \ mock_pickle: get_wmt14() mock_pickle.dump.assert_not_called() self.assertEqual(mock_pickle.load.call_count, 1)
Example #25
Source File: test_squad.py From lineflow with MIT License | 5 votes |
def test_get_squad_v2_twice(self): get_squad(version=2) with mock.patch('lineflow.datasets.squad.pickle', autospec=True) as mock_pickle: get_squad(version=2) mock_pickle.dump.assert_not_called() self.assertEqual(mock_pickle.load.call_count, 1)
Example #26
Source File: test_squad.py From lineflow with MIT License | 5 votes |
def test_get_squad_v1_twice(self): get_squad(version=1) with mock.patch('lineflow.datasets.squad.pickle', autospec=True) as mock_pickle: get_squad(version=1) mock_pickle.dump.assert_not_called() self.assertEqual(mock_pickle.load.call_count, 1)
Example #27
Source File: test_cnn_dailymail.py From lineflow with MIT License | 5 votes |
def test_get_cnn_dailymail_twice(self): get_cnn_dailymail() with mock.patch('lineflow.datasets.cnn_dailymail.pickle', autospec=True) as \ mock_pickle: get_cnn_dailymail() mock_pickle.dump.assert_not_called() self.assertEqual(mock_pickle.load.call_count, 1)
Example #28
Source File: test_text_classification.py From lineflow with MIT License | 5 votes |
def get_text_classification_dataset_twice(self, name): get_text_classification_dataset(name) with mock.patch('lineflow.datasets.text_classification.pickle', autospec=True) as \ mock_pickle: get_text_classification_dataset(name) mock_pickle.dump.assert_not_called() self.assertEqual(mock_pickle.load.call_count, 1)
Example #29
Source File: test_text_classification.py From lineflow with MIT License | 5 votes |
def setUpClass(cls): cls.default_cache_root = download.get_cache_root() cls.temp_dir = tempfile.mkdtemp() download.set_cache_root(cls.temp_dir) cls.patcher = mock.patch('lineflow.datasets.text_classification.sys.maxsize', int(sys.float_info.max)) cls.patcher.start()
Example #30
Source File: test_args.py From alibuild with GNU General Public License v3.0 | 5 votes |
def test_actionParsing(self, mock_commands): mock_commands.getstatusoutput.side_effect = lambda x : GETSTATUSOUTPUT_MOCKS[x] for (env, cmd, effects) in CORRECT_BEHAVIOR: env = env if env else ("sw", ".") alibuild_helpers.args.DEFAULT_WORK_DIR = env[0] alibuild_helpers.args.DEFAULT_CHDIR = env[1] with patch.object(sys, "argv", ["alibuild"] + shlex.split(cmd)): args, parser = doParseArgs("ali") args = vars(args) for k, v in effects: self.assertEqual(args[k], v) mock_commands.mock_calls