def mock_request(self, username, task): """ Patch get_object_or_404 to return given task. Yield Mock request as context variable. """ patch("scores.views.get_object_or_404", Mock(side_effect=lambda *a, **k: task)).start() yield Mock(user=self.users[username], method="GET", is_ajax=lambda: True, GET={"task_id": 1}) patch.stopall()
def teardown_scenario(scenario): """ Empty the temporary directory and restore the working directory. """ # remove the scenario variables del world.scenario # Remove the fixtures directory shutil.rmtree(world.fixtures_dir) # Restore the current working directory os.chdir(world.old_cwd) # Uninstall all mocks patch.stopall()
def _patched(*args, **kwargs): try: for patch in patches: mock = patch.start() if isinstance(mock.kwargs_field, str): kwargs[mock.kwargs_field] = mock # Merge additional fields into kwargs with kwargs taking precedence kwargs = dict(additional_fields.items() + kwargs.items()) retval = func(*args, **kwargs) finally: Patch.stopall() return retval
def test__method(self): """ Test Api._method rest submission """ ret = {'test': 'val'} ret_val = RequestRet(content=json_dumps(ret).encode('utf-8'), status_code=200) post = patch('requests.post', return_value=ret_val).start() delete = patch('requests.delete', return_value=ret_val).start() get = patch('requests.get', return_value=ret_val).start() # pylint:disable=protected-access _auth = Mock() # call get ret = rest.Api._method(self._url) get.assert_called_with(self._url, auth=None) self.assertEquals(ret, ret) ret = rest.Api._method(self._url, method='GET', auth=_auth) get.assert_called_with(self._url, auth=_auth) self.assertEquals(ret, ret) # call delete ret = rest.Api._method(self._url, method='DELETE') delete.assert_called_with(self._url, auth=None) self.assertEquals(ret, ret) # call post ret = rest.Api._method(self._url, method='POST', data={}) post.assert_called_with( self._url, data='{}'.encode('utf-8'), headers={'content-type': 'application/json'}, auth=None) self.assertEquals(ret, ret) # call multipart _files = {'entry': '{}'} ret = rest.Api._method(self._url, method='MULTIPART', data=_files) post.assert_called_with(self._url, files=_files, auth=None) self.assertEquals(ret, ret) patch.stopall()
def tearDown(self): super(FakeFSTest, self).tearDown() patch.stopall()
def tearDown(self): cache.clear() patch.stopall()
def tearDown(self): super(TestBasicAuthPolicy, self).tearDown() patch.stopall()
def tearDown(self): """ Undo all patches. """ patch.stopall()
def tearDown(self): super(TestAuth, self).tearDown() patch.stopall()
def teardown_module(module): """Stop patches and enable logging output""" patch.stopall() logging.disable(logging.NOTSET)
def tearDown(self): """Tear down of test cases.""" patch.stopall()
def tearDown(self): cache.clear() db.drop_all() patch.stopall()
def tearDown(self): try: os.remove(TEST_RC_FILE) except OSError: pass patch.stopall()
def tearDown(self): patch.stopall() if path.exists(TEST_WORKSPACE): shutil.rmtree(TEST_WORKSPACE)
def tearDown(self): unittest.TestCase.tearDown(self) patch.stopall()
def kill_patches( ): # Create a cleanup callback that undoes our patches patch.stopall() # Stops all patches started with start() imp.reload( implement ) # Reload our UUT module which restores the original decorator
def tearDownModule(): patch.stopall()
def tearDown(self): super(TestGoogleCloudStorage, self).tearDown() patch.stopall()
def tearDown(self): db.drop_all() patch.stopall()
def tearDown(self): # to destroy patch of a structure patch.stopall()
def teardown(self): super(BaseDealerTest, self).teardown() patch.stopall() # Reset dealer instance. self.dealer = None
def tearDown(self): patch.stopall() sys.stderr = sys.__stderr__
def tearDown(self): """ Undo patches. """ super(TestCoachDashboard, self).tearDown() patch.stopall()
def tearDown(self): self.client._connected = False self.client.destroy() patch.stopall()
def tearDown(self): """ Undo all patches and reset the cwd """ patch.stopall() os.chdir(self._old_cwd)
def kill_patches(): patch.stopall() imp.reload(repository_module)
def tearDownClass(cls): patch.stopall()
def teardown_module(): patch.stopall()
def tearDown(self): """ Test teardowns: clean up test-wide patches. """ patch.stopall()
def test_solve_captcha(app): m = 'controllers.solve' check_request = _patch("%s.check_request" % m) decaptcher_response = _patch("%s.decaptcher_response" % m) solvers = _patch("%s.solvers" % m) check_solver = _patch("%s.check_solver" % m) storage = _patch("%s.RedisStorage" % m)() solve = MagicMock() solvers.get_highest_notblocked.return_value.__getitem__.return_value\ = solvers.get_by_name.return_value.__getitem__.return_value\ = solvers.get_next.return_value.__getitem__.return_value\ = solve pict = Upload('captcha.png', 'picture_binary_data') some_data = {'pict': pict} # моделирование запроса с невалидными POST-данными check_request.return_value = "error description" decaptcher_response.return_value = "error" app.post('/', some_data) # assert check_request.called assert decaptcher_response.called assert not solve.called reset_mocks(locals()) # моделирование запроса с валидными POST-данными # без явного указания сервиса-расшифровщика check_request.return_value = None check_solver.side_effect = ["errcode", None] solve.side_effect = [SolverError, "captchacode1"] decaptcher_response.return_value = "resp1" app.post('/', some_data) # assert solvers.get_highest_notblocked.call_count == 2 assert not solvers.get_by_name.called assert check_solver.call_count == 2 assert storage.block.call_count == 1 assert storage.incr_uses.call_count == 2 assert solve.call_count == 2 assert storage.incr_fails.call_count == 1 assert solvers.get_next.call_count == 1 assert decaptcher_response.called reset_mocks(locals()) check_solver.side_effect = None # моделирование запроса с валидными POST-данными # с явным указанием сервиса-расшифровщика check_request.return_value = None decaptcher_response.return_value = "resp2" solve.side_effect = ["captchacode2"] app.post('/?upstream_service=captchabot', some_data) # assert solvers.get_by_name.called assert not solvers.get_highest_notblocked.called assert not check_solver.called assert storage.incr_uses.call_count == 1 assert solve.call_count == 1 assert not storage.incr_fails.called assert not solvers.get_next.called assert decaptcher_response.called reset_mocks(locals()) check_solver.side_effect = None # моделирование случая, при котором число попыток # расшифровать капчу превышает допустимое check_request.return_value = None check_solver.return_value = None solve.side_effect = SolverError decaptcher_response.return_value = "resp1" app.post('/', some_data) # assert storage.incr_uses.call_count\ == storage.incr_fails.call_count\ == solve.call_count\ == solvers.get_next.call_count\ == settings.MAX_ATTEMPTS_TO_SOLVE assert decaptcher_response.called reset_mocks(locals()) # проверяем, что параметры "pict_type" и "pict" передаются в расшифровщик some_data = {'pict': pict, 'pict_type': 'some_type'} check_request.return_value = None check_solver.return_value = None solve.side_effect = None decaptcher_response.return_value = "resp1" app.post('/', some_data) # assert solve.call_args[1]['pict_type'] == some_data['pict_type'] reset_mocks(locals()) patch.stopall()
def tearDown(self): patch.stopall() self.testbed.deactivate()
def tearDown(self): patch.stopall()
def tearDown(self): super(TestS3Storage, self).tearDown() patch.stopall() self.s3_mock.stop()
def tearDown(self): super(TestGoogleCloudStorage, self).tearDown() patch.stopall() os.remove(self._config_file)
def remove_patches(): patch.stopall() # Reload module again after removing patch. imp.reload(module)
def tearDown(self): HelperMixin.tearDown(self) patch.stopall() shutil.rmtree(self.symbol_dir)
def tearDown(self): patch.stopall() self.controller = None
def api_mock_stop(): """ Stop all patches started by api_mock. Actually it stops everything but not a problem """ patch.stopall()
def tearDown(self): api_mock_stop() patch.stopall()
def tearDown(self): os.remove(self.node.TTY) patch.stopall()
def tearDown(self): super(TestBaseBackend, self).tearDown() patch.stopall()
def tearDown(self): self.smtp_server_thread.stop() patch.stopall()
def tearDown(self) -> None: patch.stopall()
def tearDown(self): super().tearDown() patch.stopall()