简体   繁体   中英

How to Mock __init__ and resolvers with various arguments

I've seen a lot of examples of mock tests but none that show how one could mock something like <graphql.execution.base.ResolveInfo object at 0x106f002a8>

For instance, if I wanted to test that the two methods in this class were working properly, how would I mock the values that are being passed in?

class mySearch(graphene.ObjectType):
    my_search = graphene.Field(
       MySearchWrapper,
       query = graphene.String(description="Search query")
    )

    def __init__(self, args, context, info):
        super(mySearch, self).__init__()


    def resolve_my_search(self, args, context, info):
        return promisify(MySearchWrapper, args, context, info)

The __init__ method returns:

args: {}, context: <Request 'http://localhost:8080/graphql' [POST]>, info: <graphql.execution.base.ResolveInfo object at 0x106f000c8>

And the resolve_my_search method returns:

args: {'page_type': [u'MyCorgi', u'YourCorgi'], 'query': u'Corgi family', 'domain': u'corgidata.com'}, context: <Request 'http://localhost:8080/graphql' [POST]>, info: <graphql.execution.base.ResolveInfo object at 0x106f002a8>

I know I can mock the dictionary value with mock_args.json.return_value but... not sure about the Request and object. Any ideas? Guidance? I've already spent a week on this and have found no way out.

Use unittest.mock python package. Here is an example:

from unittest import mock

info = mock.create_autospec(graphql.execution.base.ResolveInfo)
info.context.user = AnonymousUser()

Here is how I did it. You can tweak it to mock the GraphQLResolveInfo but for this use case I only needed to mock the Request object.

from requests import Requests
from unittest.mock import patch

from starlette.authentication import AuthenticationError

@patch("grapql.type.definition.GraphQLResolveInfo.context")
def test_func(context_mock):
    with pytest.raises(AuthenticationError):
        context_mock.side_effect = Request()
        func_to_be_tested(resolver("fake_source", info_mock, data_inputs))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM