def test_check_argument_count(): do_f1 = MagicMock() do_f2 = MagicMock() do_f1.__name__ = 'do_f1' do_f2.__name__ = 'do_f2' class DerivedWSCli(SwitchboardWSCli): def __init__(self): self.test_func_1_arg = SwitchboardWSCli.check_argument_count(1)( do_f1) self.test_func_2_or_3_args = SwitchboardWSCli.check_argument_count( 2, 3)(do_f2) cli = DerivedWSCli() # Test incorrect number of arguments cli.test_func_1_arg(cli, '') cli.test_func_1_arg(cli, 'arg1 arg2') cli.test_func_2_or_3_args(cli, 'arg1') cli.test_func_2_or_3_args(cli, 'arg1 arg2 arg3 arg4') do_f1.assert_not_called() do_f2.assert_not_called() # Now test with correct number of arguments and make sure the functions have been called cli.test_func_1_arg(cli, 'arg1') cli.test_func_2_or_3_args(cli, 'arg1 arg2') cli.test_func_2_or_3_args(cli, 'arg1 arg2 arg3') do_f1.assert_called_once() do_f2.call_count == 2
def test_time_function_existing(self, mock_time, mock_item_stats): mock_time.side_effect = (1, 2, 5, 8) mock_func1 = MagicMock() mock_func1.__name__ = MagicMock(spec=str) mock_func2 = MagicMock() mock_func2.__name__ = MagicMock(spec=str) odict = OrderedDict() odict[mock_func1.__name__] = 1 mock_item_stats.return_value = odict stats = ht.events.stats.HoudiniEventItemStats(None) with stats.time_function(mock_func1): pass with stats.time_function(mock_func2): pass expected = OrderedDict() expected[mock_func1.__name__] = 2 expected[mock_func2.__name__] = 3 self.assertEqual(stats.item_stats, expected)
def test_setup_api_get_classes_returns_correct_result(self): # Arrange flask = MagicMock() flask.add_url_rule = MagicMock() cls1 = MagicMock() cls1.__name__ = "name1" cls2 = MagicMock() cls2.__name__ = "name2" TestClassStandardHierarchy._classes = [cls1, cls2] expected_result = {"name1": "value1", "name2": "value2"} db_structure = expected_result.copy() db_structure.update({"garbage": "1234"}) with patch("oio_common.db_structure.REAL_DB_STRUCTURE", new=db_structure): # Act self.testclass.setup_api(base_url="URL", flask=flask) # Assert flask.add_url_rule.assert_called_once() get_classes = flask.add_url_rule.call_args[0][2] with self.app.test_request_context(): actual_result = json.loads( get_classes().get_data(as_text=True)) self.assertDictEqual(actual_result, expected_result)
def test_context_is_editable(config, pyramid_request): from autonomie.views.taskaction import context_is_editable context = MagicMock() context.__name__ = "invoice" context.is_editable = lambda :True assert(context_is_editable(None, context)) context = MagicMock() context.__name__ = "notinvoice" assert(context_is_editable(None, context)) context = MagicMock() context.__name__ = 'invoice' context.is_editable = lambda :False context.is_waiting = lambda :True pyramid_request.context = context assert(context_is_editable(pyramid_request, context))
def test_context_is_editable(self): context = MagicMock() context.__name__ = "invoice" context.is_editable = lambda :True self.assertTrue(context_is_editable(None, context)) context = MagicMock() context.__name__ = "notinvoice" self.assertTrue(context_is_editable(None, context)) context = MagicMock() context.__name__ = 'invoice' context.is_editable = lambda :False context.is_waiting = lambda :True request = self.get_csrf_request() request.context = context self.assertTrue(context_is_editable(request, context))
def test_context_is_not_task(config): from autonomie.views.taskaction import context_is_task context = MagicMock() for i in ("project_invoices", "project_cancelinvoices", "project_estimations"): context.__name__ = i assert not context_is_task(context)
def test_renderSelectedItem(self): field = MagicMock() field.__name__ = 'ethel' n = NotBrokenMultiCheckBoxWidget(field, MagicMock(), MagicMock()) r = n.renderSelectedItem(0, 'Putting the boot in', 'boot', 'violence', 'frog') self.assertIn('checked="checked"', r)
def kve(): self.dev.bind() mock = MagicMock() mock.__name__ = 'magic mock' # for **kwargs self.dev.bind(kw=mock) self.dev.bind(kw=mock)
def varg(): self.dev.bind() mock = MagicMock() mock.__name__ = 'magic mock' #for *args self.dev.bind(mock) self.dev.bind(mock)
def kve(): self.dev.bind() mock = MagicMock() mock.__name__ = 'magic mock' #for **kwargs self.dev.bind(kw=mock) self.dev.bind(kw=mock)
def test_handle_expected_exceptions_throw(): mock_method = MagicMock(side_effect=ValueError('HALP')) mock_method.__name__ = 'mock_meth' decorated = handle_expected_exceptions(mock_method) assert_equals(decorated.__name__, mock_method.__name__) result = decorated(self, 1, kwarg='foo')
def test_no_kwargs(self): """Test with passing none of the optional kwarg args.""" # A fake function to wrap. mock_func = MagicMock(spec=str) mock_func.__name__ = "test" # Wrap the test function up. func = ht.logging.adapters._wrap_logger(mock_func, hou.severityType.Error) # Extra dictionary that will get the logger data added to it. extra = {} # Mock function arg. mock_arg = MagicMock() # Call the function. func(mock_arg, extra=extra) # The expected extra dict values. expected = {"severity": hou.severityType.Error} self.assertEqual(extra, expected) # Verify that the wrapped function was called with the expected data. mock_func.assert_called_with(mock_arg, extra=expected)
def test_does_not_need_refresh(self): authn = OIDCAuthentication( self.app, provider_configuration_info={'issuer': ISSUER}, client_registration_info={ 'client_id': 'foo', 'session_refresh_interval_seconds': 1 }, ) client_mock = MagicMock() callback_mock = MagicMock() now = time.time() callback_mock.__name__ = 'test_callback' # required for Python 2 authn.client = client_mock id_token = IdToken(**{'sub': 'sub1', 'nonce': 'nonce', 'exp': 0}) with self.app.test_request_context('/'): flask.session['destination'] = '/' flask.session['access_token'] = 'test token' flask.session['id_token'] = id_token.to_dict() flask.session['id_token_jwt'] = id_token.to_jwt() flask.session['last_authenticated'] = now + 100 authn.oidc_auth(callback_mock)() session = Session( flask_session=flask.session, client_registration_info=authn.client_registration_info) assert session.needs_refresh() is False
def varg(): self.dev.bind() mock = MagicMock() mock.__name__ = 'magic mock' # for *args self.dev.bind(mock) self.dev.bind(mock)
def test_in_kwargs(self): """Test with passing all optional kwarg args.""" mock_func = MagicMock(spec=str) mock_func.__name__ = "test" r = ht.logging.adapters._wrap_logger(mock_func, hou.severityType.Error) extra = {} mock_arg = MagicMock() mock_node = MagicMock(spec=hou.Node) mock_dialog = MagicMock(spec=bool) mock_status_bar = MagicMock(spec=bool) mock_title = MagicMock(spec=str) r(mock_arg, extra=extra, dialog=mock_dialog, node=mock_node, status_bar=mock_status_bar, title=mock_title) expected = { "node": mock_node, "dialog": mock_dialog, "status_bar": mock_status_bar, "severity": hou.severityType.Error, "title": mock_title, } self.assertEqual(extra, expected) mock_func.assert_called_with(mock_arg, extra=expected)
def test_device_bind_kvarg_exception(self): with self.assertRaises(ValueError): self.dev.bind() mock = MagicMock() mock.__name__ = 'magic mock' #for **kwargs self.dev.bind(kw=mock) self.dev.bind(kw=mock)
def mock_class(self, name, bases=(), _publish_attrs=None): cls = MagicMock() cls.__name__ = name cls.__bases__ = bases if _publish_attrs: cls._publish_attrs = _publish_attrs self.mock_builders.append(name) return cls
def test_wrap_unexpected_exceptions_throws_if_all_errors_fatal(): conf.override_all({'all_errors_are_fatal': True}) mock_method = MagicMock(side_effect=ValueError('~~~~~~')) mock_method.__name__ = 'tos' decorated = wrap_unexpected_exceptions(mock_method) assert_equals(decorated.__name__, mock_method.__name__) result = decorated(self, 'FOOBAR', FOOBAR='FOOBAR')
def test_drain_calls_function_modules(self): pl = Pipeline(blob=1) func_module1 = MagicMock() func_module2 = MagicMock() func_module3 = MagicMock() func_module1.__name__ = "MagicMock" func_module2.__name__ = "MagicMock" func_module3.__name__ = "MagicMock" pl.attach(func_module1, 'module1') pl.attach(func_module2, 'module2') pl.attach(func_module3, 'module3') pl.drain(1) self.assertEqual(1, pl.modules[0].call_count) self.assertEqual(1, pl.modules[1].call_count) self.assertEqual(1, pl.modules[2].call_count)
def test_from_file_when_no_file(self, path, isfile): plugin = MagicMock() plugin.directory = MagicMock(return_value="somePlugin") plugin.__name__ = "somePlugin" isfile.return_value = False path.return_value.json_load.return_value = {} c = loader.Command() c._from_file(plugin) self.assertEqual(path.called, False)
def module(self, request): module = MagicMock() module.__name__ = u"testmodule" dynamic_challenges.registry[u"testmodule"] = module def remove_module(): del dynamic_challenges.registry[u"testmodule"] request.addfinalizer(remove_module) return u"testmodule"
def test_from_file(self, path, isfile): plugin = MagicMock() plugin.directory = MagicMock(return_value="somePlugin") plugin.__name__ = "somePlugin" isfile.return_value = True path.return_value.json_load.return_value = {} c = loader.Command() c._from_file(plugin) path.assert_called_with('somePlugin/data/lookuplists/lookuplists.json')
def test_handle_expected_exceptions_throws_if_all_errors_fatal(): conf.override_all({'all_errors_are_fatal': True}) mock_method = MagicMock( side_effect=LivyUnexpectedStatusException('Oh no!')) mock_method.__name__ = 'mock_meth' decorated = handle_expected_exceptions(mock_method) assert_equals(decorated.__name__, mock_method.__name__) result = decorated(self, 1, kwarg='foo')
def test_state1_2_transition_works(self): trans = MagicMock(return_value=(VState.State2, "mess")) trans.__name__ = "my_transition" self.sm.transition(VState.State1, VEvent.Event1, trans, VState) self.sm.loop_run() self.sm.post(VEvent.Event1) cothread.Yield() self.assertEquals(self.sm.state, VState.State2) trans.assert_called_once_with()
def amazing_function(): from cache_requests import Memoize def _side_effect(*args, **kwargs): return len(args), len(kwargs) _amazing_function = MagicMock(spec=_side_effect, side_effect=_side_effect) _amazing_function.__name__ = 'amazing_function' return Memoize(_amazing_function, ex=1)
def test_wrap_unexpected_exceptions_handle(): mock_method = MagicMock(side_effect=ValueError('~~~~~~')) mock_method.__name__ = 'tos' decorated = wrap_unexpected_exceptions(mock_method) assert_equals(decorated.__name__, mock_method.__name__) result = decorated(self, 'FOOBAR', FOOBAR='FOOBAR') assert_is(result, None) assert_equals(ipython_display.send_error.call_count, 1) mock_method.assert_called_once_with(self, 'FOOBAR', FOOBAR='FOOBAR')
def test_create_a_mutable_viewset(self): serializer_class = MagicMock(name='serializer_class') model = MagicMock(name='model') model.__name__ = 'BlogPost' model.objects.all.return_value = [] viewset_class = MutableModelViewSet.create(model, serializer_class) viewset = viewset_class() self.assertEqual(viewset.queryset, []) self.assertEqual(viewset.serializer_class, serializer_class)
def test_wrap_unexpected_exceptions(): mock_method = MagicMock() mock_method.__name__ = 'tos' decorated = wrap_unexpected_exceptions(mock_method) assert_equals(decorated.__name__, mock_method.__name__) result = decorated(self, 0.0) assert_equals(result, mock_method.return_value) assert_equals(ipython_display.send_error.call_count, 0) mock_method.assert_called_once_with(self, 0.0)
def test_handle_expected_exceptions_handle(): mock_method = MagicMock(side_effect=LivyUnexpectedStatusException('ridiculous')) mock_method.__name__ = 'MockMethod2' decorated = handle_expected_exceptions(mock_method) assert_equals(decorated.__name__, mock_method.__name__) result = decorated(self, 1, kwarg='foo') assert_is(result, None) assert_equals(ipython_display.send_error.call_count, 1) mock_method.assert_called_once_with(self, 1, kwarg='foo')
def mock_class(self, name, bases=(), _publish_attrs=None): cls = MagicMock() cls.__name__ = name mro = () for base in bases: mro += base.__mro__ cls.__mro__ = (cls, ) + mro if _publish_attrs: cls._api_attrs = ggrc.models.reflection.ApiAttributes(*_publish_attrs) self.mock_builders.append(name) return cls
def test_raising_exception_with_args(self): mock_exception = MagicMock() self.sm.log_exception = mock_exception trans = MagicMock(side_effect=ValueError("My Error Message")) trans.__name__ = "my_transition" self.sm.transition(VState.State1, VEvent.Event1, trans, VState.State2) self.sm.loop_run() self.sm.post(VEvent.Event1, 3, boo="foo") cothread.Yield() mock_exception.assert_called_once_with( "Handler (called with args=(3,), kwargs={'boo': 'foo'}) raised error: My Error Message")
def test_handle_expected_exceptions_handle(): mock_method = MagicMock( side_effect=LivyUnexpectedStatusException('ridiculous')) mock_method.__name__ = 'MockMethod2' decorated = handle_expected_exceptions(mock_method) assert_equals(decorated.__name__, mock_method.__name__) result = decorated(self, 1, kwarg='foo') assert_is(result, None) assert_equals(ipython_display.send_error.call_count, 1) mock_method.assert_called_once_with(self, 1, kwarg='foo')
def mock_class(self, name, bases=(), _publish_attrs=None, parents=()): cls = MagicMock() cls.__name__ = name mro = () for base in bases: mro += base.__mro__ cls.__mro__ = (cls, ) + mro if _publish_attrs: cls._api_attrs = ggrc.models.reflection.ApiAttributes(*_publish_attrs) cls.__bases__ = parents self.mock_builders.append(name) return cls
def test_log_lambda_call(self): mock_lambda = MagicMock( side_effect=[0, wavelengthBaseException, Exception]) mock_lambda.__name__ = 'test-lambda' event_mock = MagicMock() context_mock = MagicMock() log_lambda = slog.LogLambda('test_service', event=MagicMock(), context=MagicMock()) decorator = log_lambda(mock_lambda) decorator(event_mock, context_mock) self.assertEqual(log_lambda._get_structured_logger(), None)
def test_auto_fill_invoke(kwik_e_mart_app): """Tests slot-filling invoke functionality""" app = kwik_e_mart_app request = Request( text="elm street", domain="store_info", intent="get_store_number", entities=[{ "type": "store_name", "value": [{ "cname": "23 Elm Street" }], "role": None }], ) responder = DialogueResponder() # custom eval func def test_custom_eval(r): # entity already passed in, this is to check custom eval flow. del r return True # mock handler for invoke handler_sub = MagicMock() handler_sub.__name__ = "handler_sub" form = { "entities": [ FormEntity( entity="store_name", value="23 Elm Street", default_eval=False, custom_eval=test_custom_eval, ) ], } @app.handle(domain="store_info", intent="get_store_number") def handler_main(request, responder): AutoEntityFilling(handler_sub, form, app).invoke(request, responder) handler_main(request, responder) # check whether the sub handler was invoked. handler_sub.assert_called_once_with(request, responder) # check whether new rule has been added for sub handler. assert any([ rule.dialogue_state == handler_sub.__name__ for rule in list(app.app_manager.dialogue_manager.rules) ])
def test_transition_with_no_return_gives_error(self): mock_exception = MagicMock() self.sm.log_exception = mock_exception trans = MagicMock(return_value=None) trans.__name__ = "my_transition" self.sm.transition(VState.State1, VEvent.Event1, trans, VState.State2) self.sm.loop_run() self.sm.post(VEvent.Event1) cothread.Yield() self.assertEquals(self.sm.state, VState.Err) trans.assert_called_once_with() mock_exception.assert_called_once_with( 'Handler raised error: Needed tuple or list of length 2 from my_transition, got None')
def test_run_multiple_backwards_compat(self): system = MagicMock(return_value=1) system.__name__ = MagicMock(return_value='system') list_of_dicts1 = [{'fname': system, 'args': ['ping -c 1 foo'], 'delay': 1}, {'fname': system, 'args': ['ping -c 1 foo'], 'delay': 1}] import builtins builtins.t = MagicMock(spec=init) t.background_logger = MagicMock() self.assertEqual(run_multiple(list_of_dicts1), [1, 1])
def test_dont_reauthenticate_with_valid_id_token(self): authn = OIDCAuthentication(self.app, provider_configuration_info={'issuer': ISSUER}, client_registration_info={'client_id': 'foo'}) client_mock = MagicMock() callback_mock = MagicMock() callback_mock.__name__ = 'test_callback' # required for Python 2 authn.client = client_mock with self.app.test_request_context('/'): flask.session['destination'] = '/' flask.session['id_token'] = {'exp': time.time() + 25} authn.oidc_auth(callback_mock)() assert not client_mock.construct_AuthorizationRequest.called assert callback_mock.called is True
def test_reauthenticate_if_no_session(self): authn = OIDCAuthentication( self.app, provider_configuration_info={'issuer': ISSUER}, client_registration_info={'client_id': 'foo'}) client_mock = MagicMock() callback_mock = MagicMock() callback_mock.__name__ = 'test_callback' # required for Python 2 authn.client = client_mock with self.app.test_request_context('/'): authn.oidc_auth(callback_mock)() assert client_mock.construct_AuthorizationRequest.called assert not callback_mock.called
def test_decorator(self): mocked_function = MagicMock() mocked_function.__name__ = "function" mocked_object = MagicMock() mocked_object.ignore = CachedIgnore() mocked_inspect = MagicMock() mocked_inspect.getargspec.return_value = [["file"]] with patch.multiple("gitfs.utils.decorators.not_in", inspect=mocked_inspect): not_in("ignore", check=["file"])(mocked_function)(mocked_object, "file") mocked_function.assert_called_once_with(mocked_object, "file")
def test_load_terraform_module_raise_hcl_parser_error(tmp_path: Path) -> None: """Test load_terraform_module raise HclParserError.""" tf_file = tmp_path / "module.tf" tf_file.write_text(HCL_BACKEND_S3) mock_parser = MagicMock(loads=MagicMock(side_effect=Exception)) mock_parser.__name__ = "TestParser" with pytest.raises(HclParserError) as excinfo: load_terraform_module(mock_parser, tmp_path) assert excinfo.value.file_path == tf_file assert str(tf_file) in excinfo.value.message assert "TestParser".upper() in excinfo.value.message
def test_2_transitions_works(self): self.sm.transition(VState.State1, VEvent.Event1, None, VState.State2) trans2 = MagicMock(return_value=(VState.State1, None)) trans2.__name__ = "my_transition2" self.sm.transition(VState.State2, VEvent.Event2, trans2, VState) self.sm.loop_run() self.sm.post(VEvent.Event1) cothread.Yield() self.assertEquals(self.sm.state, VState.State2) self.assertEquals(self.sm.message, "State change") self.sm.post(VEvent.Event2) cothread.Yield() self.assertEquals(self.sm.state, VState.State1) self.assertEquals(self.sm.message, "State change") trans2.assert_called_once_with()
def test_handle(self, is_file, load_lookup_lists, get_all_components): plugin = MagicMock() plugin.directory = MagicMock(return_value="somePlugin") plugin.__name__ = "somePlugin" get_all_components.return_value = [plugin] is_file.return_value = {} load_lookup_lists.return_value = (1, 2, 3) cmd = loader.Command() cmd.stdout = MagicMock() cmd.handle() self.assertEqual( cmd.stdout.write.call_args[0][0], '\nFor somePlugin\nLoaded 1 lookup lists\n\n\nNew items report:\n\n\n2 new items 3 new synonyms' )
def test_oidc_logout_handles_redirects_from_provider(self): end_session_endpoint = 'https://provider.example.com/end_session' post_logout_uri = 'https://client.example.com/post_logout' authn = OIDCAuthentication(self.app, provider_configuration_info={'issuer': ISSUER, 'end_session_endpoint': end_session_endpoint}, client_registration_info={'client_id': 'foo', 'post_logout_redirect_uris': [post_logout_uri]}) callback_mock = MagicMock() callback_mock.__name__ = 'test_callback' # required for Python 2 state = 'end_session_123' with self.app.test_request_context('/logout?state=' + state): flask.session['end_session_state'] = state authn.oidc_logout(callback_mock)() assert 'end_session_state' not in flask.session assert callback_mock.called
def test_oidc_logout_redirects_to_provider(self): end_session_endpoint = 'https://provider.example.com/end_session' post_logout_uri = 'https://client.example.com/post_logout' authn = OIDCAuthentication(self.app, provider_configuration_info={'issuer': ISSUER, 'end_session_endpoint': end_session_endpoint}, client_registration_info={'client_id': 'foo', 'post_logout_redirect_uris': [post_logout_uri]}) callback_mock = MagicMock() callback_mock.__name__ = 'test_callback' # required for Python 2 id_token = IdToken(**{'sub': 'sub1', 'nonce': 'nonce'}) with self.app.test_request_context('/logout'): flask.session['id_token_jwt'] = id_token.to_jwt() resp = authn.oidc_logout(callback_mock)() assert resp.status_code == 303 assert not callback_mock.called
def testReceivesLoggedInPermissionManagerAnonymous(self): request = self.request_factory.get("/") user = AnonymousUser() request.user = user function = MagicMock() function.__name__ = "" # For functools.wraps # decorate decorated = permission_manager.receives_loggedin_permission_manager(function) # call with request decorated(request) # Anonymous, function not called self.assertFalse(function.called)
def test_while_not(self): an_event = Event() an_event.set() mocked_method = MagicMock() mocked_time = MagicMock() mocked_time.sleep.side_effect = lambda x: an_event.clear() mocked_method.__name__ = "name" with patch.multiple('gitfs.utils.decorators.while_not', wraps=MockedWraps, time=mocked_time): not_now = while_not(an_event) not_now(mocked_method)("arg", kwarg="kwarg") mocked_time.sleep.assert_called_once_with(0.2)
def test_jsonp_returns_without_status_code_200(): """Test jsonp returns correctly when the response does not have status code 200.""" # Setup the mock view. f = MagicMock() f.__name__ = 'Wrapped View' # Setup the mock response. response = MagicMock() response.status_code = 301 # Set the response as the return value for the mock # view. f.return_value = response decorated_f = jsonp(f) assert decorated_f(1)
def test_raising_error_notifies_status(self): mock_exception = MagicMock() self.sm.log_exception = mock_exception c = HasStateMachine("C") trans = MagicMock(side_effect=ValueError("My Error Message")) trans.__name__ = "my_transition" self.sm.transition(VState.State1, VEvent.Event1, trans, VState.State2) c.add_stateMachine(self.sm) c.add_listener(self.callback) c.loop_run() self.sm.post(VEvent.Event1) cothread.Yield() self.assertEquals(self.sm.state, VState.Err) self.assertEquals(self.states, [VState.Err]) self.assertEquals(self.messages, ["My Error Message"]) mock_exception.assert_called_once_with( 'Handler raised error: My Error Message') mock_exception.reset_mock()
def test_transition_with_no_matching_func(self): mock_info = MagicMock() self.sm.log_info = mock_info trans = MagicMock(return_value=(VState.State2, "Boo")) trans.__name__ = "my_transition" self.sm.transition(VState.State1, VEvent.Event1, trans, VState.State2) self.sm.loop_run() self.sm.post(VEvent.Event2) cothread.Yield() self.assertEquals(self.sm.state, VState.State1) self.assertFalse(trans.called) mock_info.assert_called_once_with( "No handler functions for event (<VState.State1: 0>, <VEvent.Event2: 1>)") mock_info.reset_mock() self.sm.post(VEvent.Event1) cothread.Yield() self.assertEquals(self.sm.state, VState.State2) self.assertFalse(mock_info.called)
def test_jsonp_returns_with_callback(): f = MagicMock() f.__name__ = 'Wrapped View' # Setup the mock request request = MagicMock() request.GET = dict(callback='init') # Setup the mock response. json = {"id": 1, "status": 200} response = MagicMock(content=json, status_code=200) f.return_value = response decorated_f = jsonp(f) result = decorated_f(request) expected = 'init({0})'.format(json) assert expected == result.content
def test_jsonp_request_does_not_have_callback(): """Test the outcome when the input request does not contain a callback. """ f = MagicMock() f.__name__ = 'Wrapped View' request = MagicMock() # No query strings are added. request.GET = dict() json = {"id": 1, "status": 200} response = MagicMock(content=json, status_code=200) f.return_value = response decorated_f = jsonp(f) result = decorated_f(request) # Here we assert the the content was not altered # since we did not provide a callback. assert json == result.content