def test_rolegroup(self): query = ''' { getAvailableRoleGroups{ name } } ''' expected = [] result = schema.execute(query, context=self.context) assert not result.errors, pformat(result.errors, indent=1) found = False for rolegroups in result.data['getAvailableRoleGroups']: for k, gname in rolegroups.items(): if gname == DEFAULT_ROLEGROUP_NAME: found = True assert found, pformat(result.data, indent=1) query = """ { getRolesFromRoleGroup{ handle_id name slug description } } """ result = schema.execute(query, context=self.context) assert not result.errors, pformat(result.errors, indent=1) no_args_roles = result.data['getRolesFromRoleGroup'] query = ''' {{ getRolesFromRoleGroup(name: "{default_rolegroup}"){{ handle_id name slug description }} }} '''.format(default_rolegroup=DEFAULT_ROLEGROUP_NAME) result = schema.execute(query, context=self.context) assert not result.errors, pformat(result.errors, indent=1) args_roles = result.data['getRolesFromRoleGroup'] assert args_roles == no_args_roles, "{}\n!=\n{}".format( pformat(no_args_roles, indent=1), pformat(args_roles, indent=1))
def test_check_organization_id(self): # first try and check one that exists nh = self.organization1 organization1_id = relay.Node.to_global_id(str(nh.node_type), str(nh.handle_id)) organization1_orgid = nh.get_node().data.get('organization_id') query = ''' {{ checkExistentOrganizationId(organization_id: "{organization1_orgid}") }} '''.format(organization1_orgid=organization1_orgid) expected = {'checkExistentOrganizationId': True} result = schema.execute(query, context=self.context) assert not result.errors, pformat(result.errors, indent=1) assert result.data == expected, '\n{} \n != {}'.format( pformat(result.data, indent=1), pformat(expected, indent=1)) # then check that it returns false when the id is passed query = ''' {{ checkExistentOrganizationId(organization_id: "{organization1_orgid}", id: "{organization1_id}") }} '''.format(organization1_orgid=organization1_orgid, organization1_id=organization1_id) expected = {'checkExistentOrganizationId': False} result = schema.execute(query, context=self.context) assert not result.errors, pformat(result.errors, indent=1) assert result.data == expected, '\n{} \n != {}'.format( pformat(result.data, indent=1), pformat(expected, indent=1)) # last, check that an organization id that doesn't exists organization1_orgid = "ORG3" query = ''' {{ checkExistentOrganizationId(organization_id: "{organization1_orgid}") }} '''.format(organization1_orgid=organization1_orgid) expected = {'checkExistentOrganizationId': False} result = schema.execute(query, context=self.context) assert not result.errors, pformat(result.errors, indent=1) assert result.data == expected, '\n{} \n != {}'.format( pformat(result.data, indent=1), pformat(expected, indent=1))
def check_get_byid(self, graphql_type, api_method, node_type ,\ has_errors=False, error_msg=None): # get first node and get relay id nh = self.create_node("Test node {}".format(graphql_type), node_type.slug) relay_id = relay.Node.to_global_id(str(graphql_type), str(nh.handle_id)) query = ''' {{ {api_method}(id:"{relay_id}"){{ id name }} }} '''.format(api_method=api_method, relay_id=relay_id) expected = {api_method: None} result = schema.execute(query, context=self.context) if not has_errors: assert not result.errors, pformat(result.errors, indent=1) assert result.data == expected, '\n{} \n != {}'.format( pformat(result.data, indent=1), pformat(expected, indent=1)) else: assert result.errors if error_msg: error_msg_query = getattr(result.errors[0], 'message') assert error_msg_query == error_msg, \ '\n{} != {}'.format( error_msg_query, error_msg )
def run_test_checkExistentOrganizationId(self, \ has_errors=False, error_msg=None): generator = CommunityFakeDataGenerator() org_nh = generator.create_organization() existent_orgid = org_nh.get_node() query = """ {{ checkExistentOrganizationId(organization_id:"{organization_id}") }} """.format(organization_id=existent_orgid) expected = {'checkExistentOrganizationId': False} result = schema.execute(query, context=self.context) if not has_errors: assert not result.errors, pformat(result.errors, indent=1) assert result.data == expected, '\n{} \n != {}'.format( pformat(result.data, indent=1), pformat(expected, indent=1)) else: assert result.errors if error_msg: error_msg_query = getattr(result.errors[0], 'message') assert error_msg_query == error_msg, \ '\n{} != {}'.format( error_msg_query, error_msg )
def run_test_roles(self, has_errors=False, error_msg=None): query = """ { roles{ edges{ node{ id name } } } } """ expected = {'roles': {'edges': []}} result = schema.execute(query, context=self.context) if not has_errors: assert not result.errors, pformat(result.errors, indent=1) assert result.data == expected, '\n{} \n != {}'.format( pformat(result.data, indent=1), pformat(expected, indent=1)) else: assert result.errors if error_msg: error_msg_query = getattr(result.errors[0], 'message') assert error_msg_query == error_msg, \ '\n{} != {}'.format( error_msg_query, error_msg )
def check_get_all(self, graphql_type, api_method, node_type ,\ has_errors=False, error_msg=None): # create 3 nodes for this type for i in range(0, self.create_nodes): node_name = "Test {} {}".format(graphql_type, i) nh = self.create_node(node_name.format(graphql_type), node_type.slug) query = """ {{ {api_method}{{ id name }} }} """.format(api_method=api_method) expected = {api_method: []} result = schema.execute(query, context=self.context) if not has_errors: assert not result.errors, pformat(result.errors, indent=1) assert result.data == expected, '\n{} \n != {}'.format( pformat(result.data, indent=1), pformat(expected, indent=1)) else: assert result.errors if error_msg: error_msg_query = getattr(result.errors[0], 'message') assert error_msg_query == error_msg, \ '\n{} != {}'.format( error_msg_query, error_msg )
def test_simple_list(self): # query all available types test_types = { 'organization': [self.organization1, self.organization2], 'contact': [self.contact1, self.contact2], 'group': [self.group1, self.group2], } for name, nodes in test_types.items(): query = ''' {{ all_{}s {{ handle_id node_name }} }} '''.format(name) node_list = [] for node in nodes: node_dict = OrderedDict([('handle_id', str(node.handle_id)), ('node_name', node.node_name)]) node_list.append(node_dict) expected = OrderedDict([('all_{}s'.format(name), node_list)]) result = schema.execute(query, context=self.context) assert not result.errors, pformat(result.errors, indent=1) assert result.data == expected, '{} \n != {}'.format( pformat(result.data, indent=1), pformat(expected, indent=1))
def test_contact_empty_first_name(self): # remove first_name from contact1 c1_node = self.contact1.get_node() c1_node.remove_property('first_name') contact_1_id = relay.Node.to_global_id(str(self.contact1.node_type), str(self.contact1.handle_id)) # do a simple contact query and check that there's no errors query = """ {{ getContactById(id: "{contact_1_id}"){{ id first_name }} }} """.format(contact_1_id=contact_1_id) result = schema.execute(query, context=self.context) assert not result.errors, pformat(result.errors, indent=1) expected = { 'getContactById': { 'id': contact_1_id, 'first_name': '', } } assert result.data == expected, '{} \n != {}'.format( pformat(result.data, indent=1), pformat(expected, indent=1))
def test_filter(self): ## create ## query = ''' { groups(filter: {AND: [ { name: "group1" } ]}){ edges{ node{ handle_id name outgoing { name relation { id } } } } } } ''' result = schema.execute(query, context=self.context) assert not result.errors, result.errors
def check_metatype_search(self, query_t, search_string, metatype_name, \ types_string, expected_ids, order): order_str = '' if order: order_str = 'orderBy: {}'.format(order) query = query_t.format( search_string=search_string, metatype_name=metatype_name, types_string=types_string, orderBy=order_str, ) result = schema.execute(query, context=self.context) assert not result.errors, result.errors # check expected result_nodes = result.data['{}s'.format(metatype_name)]["edges"] for node in result_nodes: node = node['node'] self.assertTrue( node['id'] in expected_ids, """{} not in expected {}\nresult_nodes: {}\nfor query: {}""" """\nfor types: '{}'""".format(node, expected_ids, result_nodes, search_string, types_string))
def query_activity(self, contextname): query = ''' {{ getContextActivity(filter: {{ context: "{contextname}" }}){{ edges{{ node{{ text actorname actor{{ id username first_name last_name email }} verb action_object{{ id name __typename }} target_object{{ id name __typename }} description }} }} }} }} '''.format(contextname=contextname) result = schema.execute(query, context=self.context) return result
def check_port_search(self, query_name): # search common pattern search = self.common query = ''' {{ {query_name}(filter:{{ query: "{search}" }}){{ edges{{ node{{ id name description }} }} }} }} '''.format(query_name=query_name, search=search) result = schema.execute(query, context=self.context) assert not result.errors, pformat(result.errors, indent=1) # check length results = result.data[query_name]['edges'] self.assertEqual(len(results), 2) # search one port search = self.port1.node_name query = ''' {{ {query_name}(filter:{{ query: "{search}" }}){{ edges{{ node{{ id name description }} }} }} }} '''.format(query_name=query_name, search=search) result = schema.execute(query, context=self.context) assert not result.errors, pformat(result.errors, indent=1) # check length results = result.data[query_name]['edges'] self.assertEqual(len(results), 1)
def test_jwt_mutations(self): ### jwt mutations ## get token test_username = "******" query = ''' mutation{{ token_auth(input: {{ username: "******", password: "******" }}) {{ token }} }} '''.format(user=test_username, password="******") result = schema.execute(query, context=self.context) assert not result.errors, pformat(result.errors, indent=1) token = result.data['token_auth']['token'] ## verify token query = ''' mutation{{ verify_token(input: {{ token: "{token}" }}) {{ payload }} }} '''.format(token=token) result = schema.execute(query, context=self.context) assert not result.errors, pformat(result.errors, indent=1) assert result.data['verify_token']['payload']['username'] == test_username, \ "The username from the jwt token doesn't match" ## refresh token query = ''' mutation{{ refresh_token(input: {{ token: "{token}" }}) {{ token payload }} }} '''.format(token=token) result = schema.execute(query, context=self.context) assert not result.errors, result.data['refresh_token']['payload'] assert result.data['refresh_token']['payload']['username'] == test_username, \ "The username from the jwt token doesn't match" assert result.data['refresh_token']['token'], result.data[ 'refresh_token']['token']
def test_query(self): from apps.nerds.lib.consumer_util import get_user from apps.noclook.tests.schema.base import TestContext # this query should be possible to execute without any privileges noc_user = get_user() nonprivileged_context = TestContext(noc_user) # as the result is a special type we can't query any relationship query = ''' { getPlainGroups{ id name } } ''' result = schema.execute(query, context=nonprivileged_context) assert not result.errors, pformat(result.errors, indent=1) plaingroups_data = result.data['getPlainGroups'] # now query as a privileged user that can query community's groups query = ''' { all_groups{ id name } } ''' result = schema.execute(query, context=self.context) assert not result.errors, pformat(result.errors, indent=1) regulargroups_data = result.data['all_groups'] self.assertEqual(plaingroups_data, regulargroups_data)
def test_dropdown(self): query = ''' { getAvailableDropdowns } ''' result = schema.execute(query, context=self.context) assert not result.errors, pformat(result.errors, indent=1) assert 'contact_type' in result.data['getAvailableDropdowns'], pformat( result.data, indent=1) query = ''' query{ getChoicesForDropdown(name:"contact_type"){ name value } } ''' result = schema.execute(query, context=self.context) assert not result.errors, pformat(result.errors, indent=1)
def test_metatype_list(self): ## simple metatype query query = ''' { getMetatypes } ''' expected = { "getMetatypes": ["Logical", "Relation", "Physical", "Location"] } result = schema.execute(query, context=self.context) assert not result.errors, result.errors self.assertEqual(result.data, expected)
def simple_type_check(self, test_f, type_name): if NodeType.objects.filter(type=type_name).exists(): nodetype = NodeType.objects.get(type=type_name) components = type_name.split(' ') # type name camelcased type_name_cc = components[0].lower() + ''.join(x.title() for x in components[1:]) graph_type_name = type_name.replace(' ', '') fmt_type_name = graph_type_name.lower() query, expected = test_f(self, nodetype, type_name_cc, graph_type_name, fmt_type_name) result = schema.execute(query, context=self.context) assert not result.errors, pformat(result.errors, indent=1) assert result.data == expected, '\n{} \n != {}'.format( pformat(result.data, indent=1), pformat(expected, indent=1))
def search_port(self, query_name, search): query = ''' {{ {query_name}(filter:{{ query: "{search}" }}){{ edges{{ node{{ id name description }} }} }} }} '''.format(query_name=query_name, search=search) result = schema.execute(query, context=self.context) assert not result.errors, pformat(result.errors, indent=1) return result.data[query_name]['edges']
def test_host_owner_types(self): ## host owner query query = ''' { getHostOwnerTypes{ type_name connection_name byid_name all_name } } ''' expected = { "getHostOwnerTypes": [{ "type_name": "Customer", "connection_name": "customers", "byid_name": "getCustomerById", "all_name": "all_customers" }, { "type_name": "EndUser", "connection_name": "endUsers", "byid_name": "getEndUserById", "all_name": "all_endusers" }, { "type_name": "Provider", "connection_name": "providers", "byid_name": "getProviderById", "all_name": "all_providers" }, { "type_name": "HostUser", "connection_name": "hostUsers", "byid_name": "getHostUserById", "all_name": "all_hostusers" }] } result = schema.execute(query, context=self.context) assert not result.errors, result.errors self.assertEqual(result.data, expected)
def test_network_organizations(self): ## network types query query = ''' { getNetworkOrgTypes{ type_name connection_name byid_name all_name } } ''' expected = { "getNetworkOrgTypes": [{ "type_name": "Customer", "connection_name": "customers", "byid_name": "getCustomerById", "all_name": "all_customers" }, { "type_name": "EndUser", "connection_name": "endUsers", "byid_name": "getEndUserById", "all_name": "all_endusers" }, { "type_name": "Provider", "connection_name": "providers", "byid_name": "getProviderById", "all_name": "all_providers" }, { "type_name": "SiteOwner", "connection_name": "siteOwners", "byid_name": "getSiteOwnerById", "all_name": "all_siteowners" }] } result = schema.execute(query, context=self.context) assert not result.errors, result.errors self.assertEqual(result.data, expected)
def test_optical_link_types(self): query = ''' { getOpticalLinkDependendenciesTypes{ type_name connection_name byid_name all_name } } ''' expected = {"getOpticalLinkDependendenciesTypes": []} for clazz in optlink_dependendencies_types: byid_name = NOCRootQuery.\ graph_by_id_type_resolvers[clazz]['field_name'] connection_name = NOCRootQuery.\ graph_connection_type_resolvers[clazz]['field_name'] all_name = NOCRootQuery.\ graph_all_type_resolvers[clazz]['field_name'] dict_obj = { "type_name": "{}".format(clazz), "connection_name": connection_name, "byid_name": byid_name, "all_name": all_name } expected["getOpticalLinkDependendenciesTypes"].append(dict_obj) result = schema.execute(query, context=self.context) assert not result.errors, result.errors self.assertEqual(result.data, expected)
def test_metatype_classes(self): ## get types for metatype query_t = ''' {{ getTypesForMetatype(metatype: {metatype_name}){{ type_name connection_name byid_name all_name }} }} ''' qlogical = query_t.format(metatype_name='Logical') qrelation = query_t.format(metatype_name='Relation') qphysical = query_t.format(metatype_name='Physical') qlocation = query_t.format(metatype_name='Location') queries = [qlogical, qrelation, qphysical, qlocation] for query in queries: result = schema.execute(query, context=self.context) assert not result.errors, result.errors
def test_service_class_connection(self): filter_t = '( filter: {{ {} }} )' order_t = '( orderBy: {} )' filter_order_t = '( filter: {{ {} }}, orderBy: {} )' query_t = """ {{ services_classes {filter_order} {{ edges{{ node{{ id name servicetype_set{{ edges{{ node{{ id name }} }} }} }} }} }} }} """ # no filter nor order filter_order = '' query = query_t.format(filter_order=filter_order) result = schema.execute(query, context=self.context) assert not result.errors, pformat(result.errors, indent=1) edges = result.data['services_classes']['edges'] res_sclasnames = [x['node']['name'] for x in edges] expected = [x.name for x in ServiceClass.objects.all()] self.assertEquals(res_sclasnames, expected) # id filter rand_serv_class = random.choice(ServiceClass.objects.all()) sclass_id = relay.Node.to_global_id('ServiceClass', str(rand_serv_class.id)) filter_order = filter_t.format('id: "{}"'.format(sclass_id)) query = query_t.format(filter_order=filter_order) result = schema.execute(query, context=self.context) assert not result.errors, pformat(result.errors, indent=1) edges = result.data['services_classes']['edges'] res_sclasnames = [x['node']['name'] for x in edges] expected = [rand_serv_class.name] self.assertEquals(res_sclasnames, expected) # name filter # so we get Ethernet, External and Internal filter_order = filter_t.format('name_contains: "er"') query = query_t.format(filter_order=filter_order) result = schema.execute(query, context=self.context) assert not result.errors, pformat(result.errors, indent=1) edges = result.data['services_classes']['edges'] res_sclasnames = [x['node']['name'] for x in edges] expected = ['Ethernet', 'External', 'Internal'] self.assertEquals(res_sclasnames, expected) # reverse alphabetical order filter_order = order_t.format('name_ASC') query = query_t.format(filter_order=filter_order) result = schema.execute(query, context=self.context) assert not result.errors, pformat(result.errors, indent=1) edges = result.data['services_classes']['edges'] res_sclasnames = [x['node']['name'] for x in edges] expected = [\ x.name for x in ServiceClass.objects.all().order_by('-name')] self.assertEquals(res_sclasnames, expected) # both name and order filter_order = filter_order_t.format('name_contains: "er"', 'name_ASC') query = query_t.format(filter_order=filter_order) result = schema.execute(query, context=self.context) assert not result.errors, pformat(result.errors, indent=1) edges = result.data['services_classes']['edges'] res_sclasnames = [x['node']['name'] for x in edges] expected = ['Internal', 'External', 'Ethernet'] self.assertEquals(res_sclasnames, expected)
def test_single_mutations(self): ### Simple entity ### ## create ## new_group_name = "New test group" query = ''' mutation create_test_group {{ create_group(input: {{name: "{new_group_name}"}}){{ group {{ handle_id name }} clientMutationId }} }} '''.format(new_group_name=new_group_name) result = schema.execute(query, context=self.context) assert not result.errors, pformat(result.errors, indent=1) create_group_result = result.data # query the api to get the handle_id of the new group query = ''' query {{ groups(filter:{{ AND:[{{ name: "{new_group_name}" }}]}}){{ edges{{ node{{ id name }} }} }} }} '''.format(new_group_name=new_group_name) result = schema.execute(query, context=self.context) assert not result.errors, pformat(result.errors, indent=1) group_handle_id = result.data['groups']['edges'][0]['node']['id'] expected = OrderedDict([ ('groups', OrderedDict([('edges', [ OrderedDict([('node', OrderedDict([('id', group_handle_id), ('name', new_group_name)]))]) ])])) ]) assert result.data == expected, '{}\n!=\n{}'.format( pformat(expected, indent=1), pformat(result.data, indent=1)) ## update ## query = """ mutation update_test_group {{ update_group(input: {{ id: "{id}", name: "A test group"}} ){{ group {{ id name }} clientMutationId }} }} """.format(id=group_handle_id) expected = OrderedDict([ ('update_group', OrderedDict([('group', OrderedDict([('id', group_handle_id), ('name', 'A test group')])), ('clientMutationId', None)])) ]) result = schema.execute(query, context=self.context) assert not result.errors, pformat(result.errors, indent=1) assert result.data == expected, pformat(result.data, indent=1) ## delete ## query = """ mutation delete_test_group {{ delete_group(input: {{ id: "{id}" }}){{ success }} }} """.format(id=group_handle_id) expected = OrderedDict([('delete_group', OrderedDict([ ('success', True), ]))]) result = schema.execute(query, context=self.context) assert not result.errors, pformat(result.errors, indent=1) assert result.data == expected ### Composite entities (Contact) ### # get the first organization query = """ { organizations(orderBy: handle_id_ASC, first: 1) { edges { node { id } } } } """ result = schema.execute(query, context=self.context) assert not result.errors, pformat(result.errors, indent=1) organization_id = result.data['organizations']['edges'][0]['node'][ 'id'] # get the first group # query the api to get the handle_id of the new group query = """ { groups(orderBy: handle_id_ASC, first: 1) { edges { node { id } } } } """ result = schema.execute(query, context=self.context) assert not result.errors, pformat(result.errors, indent=1) group_handle_id = result.data['groups']['edges'][0]['node']['id'] # get IT-manager role query = ''' { roles(filter: {name: "NOC Manager"}){ edges{ node{ id name } } } } ''' result = schema.execute(query, context=self.context) assert not result.errors, pformat(result.errors, indent=1) role_id = result.data['roles']['edges'][0]['node']['id'] ## create ## note_txt = "Lorem ipsum dolor sit amet" query = """ mutation create_test_contact {{ create_contact( input: {{ first_name: "Jane" title: "" contact_type: "person" relationship_works_for: "{organization_id}" role: "{role_id}" relationship_member_of: "{group_handle_id}" notes: "{note_txt}" }} ){{ errors{{ field messages }} contact{{ id name first_name last_name title contact_type{{ name value }} notes roles{{ name end{{ id node_name }} }} member_of_groups{{ name }} }} }} }} """.format(organization_id=organization_id, role_id=role_id, group_handle_id=group_handle_id, note_txt=note_txt) result = schema.execute(query, context=self.context) assert not result.errors, pformat(result.errors, indent=1) assert not result.data['create_contact']['errors'], \ pformat(result.data['create_contact']['errors'], indent=1) contact_id = result.data['create_contact']['contact']['id'] expected = OrderedDict([ ('create_contact', OrderedDict([ ('errors', None), ('contact', OrderedDict([ ('id', contact_id), ('name', 'Jane'), ('first_name', 'Jane'), ('last_name', None), ('title', None), ('contact_type', OrderedDict([('name', 'Person'), ('value', 'person')])), ('notes', note_txt), ('roles', [ OrderedDict([('name', 'NOC Manager'), ('end', OrderedDict([ ('id', str(organization_id)), ('node_name', 'organization1') ]))]) ]), ('member_of_groups', [OrderedDict([('name', 'group1')])]) ])) ])) ]) assert result.data == expected, pformat(result.data, indent=1) ## update ## query = """ mutation update_test_contact {{ update_contact( input: {{ id: "{contact_id}" first_name: "Janet" last_name: "Doe" contact_type: "person" relationship_works_for: "{organization_id}" role: "{role_id}" relationship_member_of: "{group_handle_id}" }} ){{ contact{{ id name first_name last_name title contact_type{{ name value }} roles{{ name end{{ id node_name }} }} member_of_groups{{ name }} }} }} }} """.format(contact_id=contact_id, organization_id=organization_id, role_id=role_id, group_handle_id=group_handle_id) expected = OrderedDict([ ('update_contact', OrderedDict([ ('contact', OrderedDict([ ('id', contact_id), ('name', 'Janet Doe'), ('first_name', 'Janet'), ('last_name', 'Doe'), ('title', None), ('contact_type', OrderedDict([('name', 'Person'), ('value', 'person')])), ('roles', [ OrderedDict([('name', 'NOC Manager'), ('end', OrderedDict([ ('id', organization_id), ('node_name', 'organization1') ]))]) ]), ('member_of_groups', [OrderedDict([('name', 'group1')])]) ])) ])) ]) result = schema.execute(query, context=self.context) assert not result.errors, pformat(result.errors, indent=1) assert result.data == expected, pformat(result.data, indent=1) # test error output query = ''' mutation{{ update_contact(input:{{ id: "{contact_id}", first_name: "Janet" last_name: "Janet" contact_type: "doesnt_exists" }}){{ contact{{ id name }} errors{{ field messages }} }} }} '''.format(contact_id=contact_id) result = schema.execute(query, context=self.context) assert not result.errors, pformat(result.errors, indent=1) assert 'errors' in result.data['update_contact'], pformat(result.data, indent=1) # test another erroneous form fake_org_id = relay.Node.to_global_id('Organization', "-1") query = ''' mutation{{ update_contact(input:{{ id: "{contact_id}", first_name: "Janet" last_name: "Janet" contact_type: "person" relationship_works_for: "{organization_id}" }}){{ contact{{ id name }} errors{{ field messages }} }} }} '''.format(contact_id=contact_id, organization_id=fake_org_id) result = schema.execute(query, context=self.context) assert 'errors' in result.data['update_contact'], pformat(result.data, indent=1) ## delete ## query = """ mutation delete_test_contact {{ delete_contact(input: {{ id: "{contact_id}" }}){{ success }} }} """.format(contact_id=contact_id) expected = OrderedDict([('delete_contact', OrderedDict([ ('success', True), ]))]) result = schema.execute(query, context=self.context) assert not result.errors, pformat(result.errors, indent=1) assert result.data == expected, pformat(result.data, indent=1)
def test_multiple_entity_mutations(self): ### Composite entities (Organization) ### # get the first organization query = """ { organizations(orderBy: handle_id_ASC, first: 1) { edges { node { id } } } } """ result = schema.execute(query, context=self.context) assert not result.errors, pformat(result.errors, indent=1) organization_id = result.data['organizations']['edges'][0]['node'][ 'id'] # get the first two contacts query = """ { contacts(orderBy: handle_id_ASC, first: 2){ edges{ node{ id } } } } """ result = schema.execute(query, context=self.context) assert not result.errors, pformat(result.errors, indent=1) contact_1_id = result.data['contacts']['edges'][0]['node']['id'] contact_2_id = result.data['contacts']['edges'][1]['node']['id'] assert contact_1_id != contact_2_id, 'The contact ids are equal' incident_management_info = "Nullam eleifend ultrices risus, ac dignissim sapien mollis id. Aenean ante nibh, pharetra ac accumsan eget, suscipit eget purus. Ut sit amet diam in arcu dapibus ultricies. Phasellus a consequat eros. Proin cursus commodo consequat. Fusce nisl metus, egestas eu blandit sit amet, condimentum vitae felis." website = "www.demo.org" organization_number = "1234A" query = """ mutation{{ create_organization( input: {{ name: "Another org", description: "This is the description of the new organization", incident_management_info: "{incident_management_info}", relationship_parent_of: "{organization_id}", abuse_contact: "{contact_1_id}", primary_contact: "{contact_2_id}", secondary_contact: "{contact_1_id}", it_technical_contact: "{contact_2_id}", it_security_contact: "{contact_1_id}", it_manager_contact: "{contact_2_id}", affiliation_provider: true, affiliation_customer: true, website: "{website}", organization_number: "{organization_number}" }} ){{ errors{{ field messages }} organization{{ id name description incident_management_info affiliation_provider affiliation_customer website organization_number incoming{{ name relation{{ id start{{ id node_name }} end{{ id node_name }} }} }} }} }} }} """.format(organization_id=organization_id, contact_1_id=contact_1_id, contact_2_id=contact_2_id, incident_management_info=incident_management_info, website=website, organization_number=organization_number) result = schema.execute(query, context=self.context) assert not result.errors, pformat(result.errors, indent=1) form_errors = result.data['create_organization']['errors'] assert not form_errors, pformat(form_errors, indent=1) organization_id_2 = result.data['create_organization']['organization'][ 'id'] incoming_relations = result.data['create_organization'][ 'organization']['incoming'] expected = OrderedDict([ ('create_organization', OrderedDict([ ('errors', None), ('organization', OrderedDict([ ('id', organization_id_2), ('name', 'Another org'), ('description', 'This is the description of the new ' 'organization'), ('incident_management_info', incident_management_info), ('affiliation_provider', True), ('affiliation_customer', True), ('website', website), ('organization_number', organization_number), ('incoming', incoming_relations) ])) ])) ]) found_offspring = False for relation in incoming_relations: for k, relation_dict in relation.items(): if k == 'name' and relation_dict == 'Parent_of': start_id = relay.Node.from_global_id( relation['relation']['start']['id'])[1] org_id = relay.Node.from_global_id(organization_id)[1] if start_id == org_id: found_offspring = True assert found_offspring, pformat(result.data, indent=1) assert not result.errors, pformat(result.errors, indent=1) assert result.data == expected, '{}\n!=\n{}'.format( pformat(result.data, indent=1), pformat(expected, indent=1)) ## edit organization query = """ mutation{{ update_organization( input: {{ id: "{organization_id}" name: "Another org", description: "This is the description of the new organization", abuse_contact: "{contact_1_id}", primary_contact: "{contact_2_id}", secondary_contact: "{contact_1_id}", it_technical_contact: "{contact_2_id}", it_security_contact: "{contact_1_id}", it_manager_contact: "{contact_2_id}", affiliation_provider: false, affiliation_partner: true, website: "{website}", organization_number: "{organization_number}" }} ){{ organization{{ id name description incident_management_info affiliation_provider affiliation_partner affiliation_customer website organization_number }} }} }} """.format(organization_id=organization_id_2, contact_1_id=contact_1_id, contact_2_id=contact_2_id, website=website, organization_number=organization_number) expected = OrderedDict([ ('update_organization', OrderedDict([ ('organization', OrderedDict([ ('id', organization_id_2), ('name', 'Another org'), ('description', 'This is the description of the new ' 'organization'), ('incident_management_info', incident_management_info), ('affiliation_provider', False), ('affiliation_partner', True), ('affiliation_customer', True), ('website', website), ('organization_number', organization_number) ])) ])) ]) result = schema.execute(query, context=self.context) assert not result.errors, pformat(result.errors, indent=1) assert result.data == expected, pformat(result.data, indent=1) ### Phone/Email tests ### ## create ## phone_num = "823-971-5606" phone_type = "work" query = """ mutation{{ create_phone(input:{{ type: "{phone_type}", name: "{phone_num}", contact: "{contact_id}" }}){{ errors{{ field messages }} phone{{ id name type{{ name value }} }} }} }} """.format(phone_type=phone_type, phone_num=phone_num, contact_id=contact_1_id) expected = OrderedDict([ ('create_phone', OrderedDict([('errors', None), ('phone', OrderedDict([('id', None), ('name', phone_num), ('type', OrderedDict([('name', 'Work'), ('value', 'work')]))])) ])) ]) result = schema.execute(query, context=self.context) assert not result.errors, pformat(result.errors, indent=1) phone_id_str = result.data['create_phone']['phone']['id'] expected['create_phone']['phone']['id'] = phone_id_str assert result.data == expected, '{} \n != {}'.format( pformat(result.data, indent=1), pformat(expected, indent=1)) ## read ## query = """ {{ getContactById(id: "{contact_id}"){{ id phones{{ id name type{{ name value }} }} }} }} """.format(contact_id=contact_1_id) expected = OrderedDict([ ('getContactById', OrderedDict([('id', contact_1_id), ('phones', [ OrderedDict([('id', phone_id_str), ('name', phone_num), ('type', OrderedDict([('name', 'Work'), ('value', 'work')]))]) ])])) ]) result = schema.execute(query, context=self.context) assert not result.errors, pformat(result.errors, indent=1) assert result.data == expected, '{} \n != {}'.format( pformat(result.data, indent=1), pformat(expected, indent=1)) ## update ## new_phone_num = "617-372-0822" query = """ mutation{{ update_phone(input:{{ id: "{phone_id}" type: "{phone_type}", name: "{phone_num}", contact: "{contact_id}" }}){{ errors{{ field messages }} phone{{ id name type{{ name value }} }} }} }} """.format(phone_id=phone_id_str, phone_type=phone_type, phone_num=new_phone_num, contact_id=contact_1_id) expected = OrderedDict([ ('update_phone', OrderedDict([('errors', None), ('phone', OrderedDict([('id', phone_id_str), ('name', new_phone_num), ('type', OrderedDict([('name', 'Work'), ('value', 'work')]))])) ])) ]) result = schema.execute(query, context=self.context) assert not result.errors, pformat(result.errors, indent=1) assert result.data == expected, '{} \n != {}'.format( pformat(result.data, indent=1), pformat(expected, indent=1)) ## delete ## query = """ mutation{{ delete_phone(input: {{ id: "{phone_id}" }}){{ errors{{ field messages }} success }} }} """.format(phone_id=phone_id_str) expected = OrderedDict([('delete_phone', OrderedDict([('errors', None), ('success', True)]))]) result = schema.execute(query, context=self.context) assert not result.errors, pformat(result.errors, indent=1) assert result.data == expected, '{} \n != {}'.format( pformat(result.data, indent=1), pformat(expected, indent=1)) ## Email ## ## create ## email_str = "*****@*****.**" email_type = "work" query = """ mutation{{ create_email(input:{{ type: "{email_type}", name: "{email_str}", contact: "{contact_id}" }}){{ errors{{ field messages }} email{{ id name type{{ name value }} }} }} }} """.format(email_type=email_type, email_str=email_str, contact_id=contact_1_id) expected = OrderedDict([ ('create_email', OrderedDict([('errors', None), ('email', OrderedDict([('id', None), ('name', email_str), ('type', OrderedDict([('name', 'Work'), ('value', 'work')]))])) ])) ]) result = schema.execute(query, context=self.context) assert not result.errors, pformat(result.errors, indent=1) email_id_str = result.data['create_email']['email']['id'] expected['create_email']['email']['id'] = email_id_str assert result.data == expected, '{} \n != {}'.format( pformat(result.data, indent=1), pformat(expected, indent=1)) ## read ## query = """ {{ getContactById(id: "{contact_id}"){{ id emails{{ id name type{{ name value }} }} }} }} """.format(contact_id=contact_1_id) expected = OrderedDict([ ('getContactById', OrderedDict([('id', str(contact_1_id)), ('emails', [ OrderedDict([('id', email_id_str), ('name', email_str), ('type', OrderedDict([('name', 'Work'), ('value', 'work')]))]) ])])) ]) result = schema.execute(query, context=self.context) assert not result.errors, pformat(result.errors, indent=1) assert result.data == expected, '{} \n != {}'.format( pformat(result.data, indent=1), pformat(expected, indent=1)) ## update ## new_email = "617-372-0822" query = """ mutation{{ update_email(input:{{ id: "{email_id}" type: "{email_type}", name: "{email_str}", contact: "{contact_id}" }}){{ errors{{ field messages }} email{{ id name type{{ name value }} }} }} }} """.format(email_id=email_id_str, email_type=email_type, email_str=new_email, contact_id=contact_1_id) expected = OrderedDict([ ('update_email', OrderedDict([('errors', None), ('email', OrderedDict([('id', email_id_str), ('name', new_email), ('type', OrderedDict([('name', 'Work'), ('value', 'work')]))])) ])) ]) result = schema.execute(query, context=self.context) assert not result.errors, pformat(result.errors, indent=1) assert result.data == expected, '{} \n != {}'.format( pformat(result.data, indent=1), pformat(expected, indent=1)) ## delete ## query = """ mutation{{ delete_email(input: {{ id: "{email_id}" }}){{ errors{{ field messages }} success }} }} """.format(email_id=email_id_str) expected = OrderedDict([('delete_email', OrderedDict([('errors', None), ('success', True)]))]) result = schema.execute(query, context=self.context) assert not result.errors, pformat(result.errors, indent=1) assert result.data == expected, '{} \n != {}'.format( pformat(result.data, indent=1), pformat(expected, indent=1)) ## Address ## ## create ## address_name = "New address" address_website = "emergya.com" address_phone = "617-372-0822" address_street = "Fake st 123" address_postal_code = "12345" address_postal_area = "Sevilla" query = """ mutation{{ create_address(input:{{ organization: "{organization_id}", name: "{address_name}", phone: "{address_phone}", street: "{address_street}", postal_code: "{address_postal_code}", postal_area: "{address_postal_area}" }}){{ errors{{ field messages }} address{{ id name phone street postal_code postal_area }} }} }} """.format(organization_id=organization_id, address_name=address_name, address_website=address_website, address_phone=address_phone, address_street=address_street, address_postal_code=address_postal_code, address_postal_area=address_postal_area) expected = OrderedDict([ ('create_address', OrderedDict([('errors', None), ('address', OrderedDict([ ('id', None), ('name', address_name), ('phone', address_phone), ('street', address_street), ('postal_code', address_postal_code), ('postal_area', address_postal_area), ]))])) ]) result = schema.execute(query, context=self.context) assert not result.errors, pformat(result.errors, indent=1) address_id_str = result.data['create_address']['address']['id'] expected['create_address']['address']['id'] = address_id_str assert result.data == expected, '{} \n != {}'.format( pformat(result.data, indent=1), pformat(expected, indent=1)) ## read ## query = """ {{ getOrganizationById(id: "{organization_id}"){{ id addresses{{ id name phone street postal_code postal_area }} }} }} """.format(organization_id=organization_id) expected = OrderedDict([ ('getOrganizationById', OrderedDict([ ('id', organization_id), ('addresses', [ OrderedDict([('id', address_id_str), ('name', address_name), ('phone', address_phone), ('street', address_street), ('postal_code', address_postal_code), ('postal_area', address_postal_area)]) ]) ])) ]) result = schema.execute(query, context=self.context) assert not result.errors, pformat(result.errors, indent=1) assert result.data == expected, '{} \n != {}'.format( pformat(result.data, indent=1), pformat(expected, indent=1)) ## update ## new_website = "www.emergyadigital.com" query = """ mutation{{ update_address(input:{{ id: "{address_id}", organization: "{organization_id}", name: "{address_name}", phone: "{address_phone}", street: "{address_street}", postal_code: "{address_postal_code}", postal_area: "{address_postal_area}" }}){{ errors{{ field messages }} address{{ id name phone street postal_code postal_area }} }} }} """.format(address_id=address_id_str, organization_id=organization_id, address_name=address_name, address_phone=address_phone, address_street=address_street, address_postal_code=address_postal_code, address_postal_area=address_postal_area) expected = OrderedDict([ ('update_address', OrderedDict([('errors', None), ('address', OrderedDict([('id', address_id_str), ('name', address_name), ('phone', address_phone), ('street', address_street), ('postal_code', address_postal_code), ('postal_area', address_postal_area)])) ])) ]) result = schema.execute(query, context=self.context) assert not result.errors, pformat(result.errors, indent=1) assert result.data == expected, '{} \n != {}'.format( pformat(result.data, indent=1), pformat(expected, indent=1)) ## delete ## query = """ mutation{{ delete_address(input: {{ id: "{address_id}" }}){{ errors{{ field messages }} success }} }} """.format(address_id=address_id_str) expected = OrderedDict([('delete_address', OrderedDict([('errors', None), ('success', True)]))]) result = schema.execute(query, context=self.context) assert not result.errors, pformat(result.errors, indent=1) assert result.data == expected, '{} \n != {}'.format( pformat(result.data, indent=1), pformat(expected, indent=1))
def test_node_validation(self): # add an abuse contact first organization_id = relay.Node.to_global_id( 'Organization', str(self.organization1.handle_id)) organization2_id = relay.Node.to_global_id( 'Organization', str(self.organization2.handle_id)) contact_1 = relay.Node.to_global_id('Contact', str(self.contact1.handle_id)) query = ''' mutation{{ update_organization(input: {{ id: "{organization_id}" name: "Organization 1" }}){{ errors{{ field messages }} organization{{ id name incoming{{ name relation{{ nidata{{ name value }} start{{ id node_name }} }} }} }} }} }} '''.format(organization_id=organization_id) result = schema.execute(query, context=self.context) assert not result.errors, pformat(result.errors, indent=1) assert not result.data['update_organization']['errors'], \ pformat(result.data['update_organization']['errors'], indent=1) # add a non valid contact (an organization) query = ''' mutation{{ update_organization(input: {{ id: "{organization_id}" name: "Organization 1" relationship_parent_of: "{organization_2}" }}){{ errors{{ field messages }} organization{{ id name incoming{{ name relation{{ nidata{{ name value }} start{{ id node_name }} }} }} }} }} }} '''.format(organization_id=organization_id, organization_2=contact_1) result = schema.execute(query, context=self.context) assert not result.errors, pformat(result.errors, indent=1) assert result.data['update_organization']['errors'], \ print('{}\n{}'.format(pformat(result.data, indent=1), pformat(result.errors, indent=1)))
def test_comments_mutations(self): ### Comments tests ### organization_id = relay.Node.to_global_id( 'Organization', str(self.organization1.handle_id)) ## create ## query = """ mutation{{ create_comment( input:{{ object_id: "{organization_id}", comment: "This comment was added using the graphql api" }} ){{ comment{{ object_id comment is_public }} }} }} """.format(organization_id=organization_id) expected = OrderedDict([ ('create_comment', OrderedDict([ ('comment', OrderedDict([('object_id', organization_id), ('comment', 'This comment was added using the ' 'graphql api'), ('is_public', True)])) ])) ]) result = schema.execute(query, context=self.context) assert not result.errors, pformat(result.errors, indent=1) assert result.data == expected, pformat(result.data, indent=1) ## read ## query = """ {{ getOrganizationById(id: "{organization_id}"){{ comments{{ id comment }} }} }} """.format(organization_id=organization_id) result = schema.execute(query, context=self.context) assert not result.errors, pformat(result.errors, indent=1) comment_id = result.data['getOrganizationById']['comments'][0]['id'] ## update ## query = """ mutation{{ update_comment( input:{{ id: "{comment_id}", comment: "This comment was added using SRI's graphql api" }} ){{ comment{{ id comment is_public }} }} }} """.format(comment_id=comment_id) expected = OrderedDict([ ('update_comment', OrderedDict([('comment', OrderedDict([('id', comment_id), ('comment', 'This comment was added using SRI\'s ' 'graphql api'), ('is_public', True)]))])) ]) result = schema.execute(query, context=self.context) assert not result.errors, pformat(result.errors, indent=1) assert result.data == expected, pformat(result.data, indent=1) ## delete ## query = """ mutation{{ delete_comment(input:{{ id: "{comment_id}" }}){{ success id }} }} """.format(comment_id=comment_id) expected = OrderedDict([('delete_comment', OrderedDict([('success', True), ('id', comment_id)]))]) result = schema.execute(query, context=self.context) assert not result.errors, pformat(result.errors, indent=1) assert result.data == expected, pformat(result.data, indent=1)
def test_global_search(self): community_generator = CommunityFakeDataGenerator() network_generator = NetworkFakeDataGenerator() # create several entities organization1 = community_generator.create_organization(name="organization-01") organization2 = community_generator.create_organization(name="organization-02") port1 = network_generator.create_port(name="port-01") port2 = network_generator.create_port(name="port-02") # search common pattern query_t = ''' {{ search_generalsearch(filter:{{query: "{search}"}}){{ edges{{ node{{ ninode{{ id name __typename }} match_txt }} }} }} }} ''' search = '-0' query = query_t.format(search=search) result = schema.execute(query, context=self.context) assert not result.errors, pformat(result.errors, indent=1) # check length expected_num = self.get_expected_length(search) results = result.data['search_generalsearch']['edges'] self.assertEqual(len(results), expected_num, \ pformat(result.data, indent=1)) # search first pattern search = '-01' query = query_t.format(search=search) result = schema.execute(query, context=self.context) assert not result.errors, pformat(result.errors, indent=1) # check length expected_num = self.get_expected_length(search) results = result.data['search_generalsearch']['edges'] self.assertEqual(len(results), expected_num, \ pformat(result.data, indent=1)) # search second pattern search = '-02' query = query_t.format(search=search) result = schema.execute(query, context=self.context) assert not result.errors, pformat(result.errors, indent=1) # check length expected_num = self.get_expected_length(search) results = result.data['search_generalsearch']['edges'] self.assertEqual(len(results), expected_num)
def test_grant_user_permissions(self): # only run mutations if we have set this value if not hasattr(self, 'test_type'): return another_user_id = self.another_user.id other_user_id = self.other_user.id for user in [self.another_user, self.other_user]: # first query another_user permissions user_id = user.id query = """ {{ getUserById(ID: {user_id}){{ id username user_permissions{{ community{{ read list write admin }} network{{ read list write admin }} contracts{{ read list write admin }} }} }} }} """.format(user_id=user_id) result = schema.execute(query, context=self.context) assert not result.errors, pformat(result.errors, indent=1) expected = { 'getUserById': { 'id': str(user_id), 'user_permissions': { 'community': { 'admin': False, 'list': False, 'read': False, 'write': False }, 'contracts': { 'admin': False, 'list': False, 'read': False, 'write': False }, 'network': { 'admin': False, 'list': False, 'read': False, 'write': False } }, 'username': user.username } } # they must be blank as we didn't set anything yet self.assert_correct(result, expected) # add read, list and write permissions over our module query_t = """ mutation{{ grant_users_permissions(input:{{ users_ids:[ {users_ids} ] context: "{context_name}" read: {read} list: {list} write: {write} {admin} }}){{ results{{ success errors{{ field messages }} user{{ id username user_permissions{{ network{{ read list write admin }} }} }} }} }} }} """ # check the user permissions query net_ctxt = sriutils.get_network_context() context_name = net_ctxt.name read = str(True).lower() list = str(True).lower() write = str(True).lower() users_ids = ", ".join(['"{}"'.format(x) \ for x in [other_user_id, another_user_id]]) query = query_t.format(users_ids=users_ids, context_name=context_name, read=read, list=list, write=write, admin="") # test vakt functions before for user in [self.other_user, self.another_user]: can_read = sriutils.authorize_read_module(user, net_ctxt) can_list = sriutils.authorize_list_module(user, net_ctxt) can_write = sriutils.authorize_create_resource(user, net_ctxt) self.assertFalse(can_read) self.assertFalse(can_list) self.assertFalse(can_write) # run mutation and check response result = schema.execute(query, context=self.context) assert not result.errors, pformat(result.errors, indent=1) expected = OrderedDict([('grant_users_permissions', { 'results': [{ 'errors': None, 'success': True, 'user': { 'id': str(other_user_id), 'user_permissions': { 'network': { 'admin': False, 'list': True, 'read': True, 'write': True } }, 'username': self.other_user.username } }, { 'errors': None, 'success': True, 'user': { 'id': str(another_user_id), 'user_permissions': { 'network': { 'admin': False, 'list': True, 'read': True, 'write': True } }, 'username': self.another_user.username } }] })]) self.assert_correct(result, expected) # after for user in [self.other_user, self.another_user]: can_read = sriutils.authorize_read_module(user, net_ctxt) can_list = sriutils.authorize_list_module(user, net_ctxt) can_write = sriutils.authorize_create_resource(user, net_ctxt) self.assertTrue(can_read) self.assertTrue(can_list) self.assertTrue(can_write) # revoke write permission write = str(False).lower() query = query_t.format(users_ids=users_ids, context_name=context_name, read=read, list=list, write=write, admin="") result = schema.execute(query, context=self.context) assert not result.errors, pformat(result.errors, indent=1) expected = OrderedDict([('grant_users_permissions', { 'results': [{ 'errors': None, 'success': True, 'user': { 'id': str(other_user_id), 'user_permissions': { 'network': { 'admin': False, 'list': True, 'read': True, 'write': False } }, 'username': self.other_user.username } }, { 'errors': None, 'success': True, 'user': { 'id': str(another_user_id), 'user_permissions': { 'network': { 'admin': False, 'list': True, 'read': True, 'write': False } }, 'username': self.another_user.username } }] })]) # check the user permissions query self.assert_correct(result, expected) # test vakt functions for user in [self.other_user, self.another_user]: can_write = sriutils.authorize_create_resource(user, net_ctxt) self.assertFalse(can_write) # grand admin rights admin = "admin: true" query = query_t.format(users_ids=users_ids, context_name=context_name, read=read, list=list, write=write, admin=admin) result = schema.execute(query, context=self.context) assert not result.errors, pformat(result.errors, indent=1) expected = None if self.test_type == "admin": # if it's not check the error expected = OrderedDict([('grant_users_permissions', { 'results': [{ 'errors': [{ 'field': '_', 'messages': ['Only superadmins can ' 'grant admin rights'] }], 'success': False, 'user': { 'id': str(other_user_id), 'user_permissions': { 'network': { 'admin': False, 'list': True, 'read': True, 'write': False } }, 'username': self.other_user.username } }, { 'errors': [{ 'field': '_', 'messages': ['Only superadmins can ' 'grant admin rights'] }], 'success': False, 'user': { 'id': str(another_user_id), 'user_permissions': { 'network': { 'admin': False, 'list': True, 'read': True, 'write': False } }, 'username': self.another_user.username } }] })]) elif self.test_type == "superadmin": # if it's superadmin test it should be possible expected = OrderedDict([('grant_users_permissions', { 'results': [{ 'errors': None, 'success': True, 'user': { 'id': str(other_user_id), 'user_permissions': { 'network': { 'admin': True, 'list': True, 'read': True, 'write': False } }, 'username': self.other_user.username } }, { 'errors': None, 'success': True, 'user': { 'id': str(another_user_id), 'user_permissions': { 'network': { 'admin': True, 'list': True, 'read': True, 'write': False } }, 'username': self.another_user.username } }] })]) self.assert_correct(result, expected)
def test_user_profile(self): if not hasattr(self, 'test_type'): return # edit user profile for the first time # check that the user profile object doesn't exist yet up_exists = UserProfile.objects.filter(user=self.another_user).exists() self.assertFalse(up_exists) # the data user_id = self.another_user.id display_name = "Another User" email = "*****@*****.**" is_staff = False is_active = False view_network = False view_services = False view_community = False # do the mutation query_t = """ mutation{{ edit_user_profile(input:{{ user_id: {user_id} display_name: "{display_name}" email: "{email}" is_staff: {is_staff} is_active: {is_active} view_network: {view_network} view_services: {view_services} view_community: {view_community} }}){{ success errors{{ field messages }} userprofile{{ id user{{ id email is_staff is_active }} display_name email landing_page view_network view_services view_community }} }} }} """ query = query_t.format(user_id=user_id, display_name=display_name, email=email, is_staff=str(is_staff).lower(), is_active=str(is_staff).lower(), view_network=str(view_network).lower(), view_services=str(view_services).lower(), view_community=str(view_community).lower()) result = schema.execute(query, context=self.context) assert not result.errors, pformat(result.errors, indent=1) # check that the user profile now exists up_exists = UserProfile.objects.filter(user=self.another_user).exists() self.assertTrue(up_exists) # check data self.another_user = User.objects.get(id=self.another_user.id) uprofile = UserProfile.objects.get(user=self.another_user) self.assertEquals(uprofile.display_name, display_name) self.assertEquals(uprofile.email, email) self.assertEquals(self.another_user.email, email) self.assertEquals(self.another_user.is_staff, is_staff) self.assertEquals(self.another_user.is_active, is_active) self.assertEquals(uprofile.view_network, view_network) self.assertEquals(uprofile.view_services, view_services) self.assertEquals(uprofile.view_community, view_community) # check query result up_data = result.data['edit_user_profile']['userprofile'] self.assertEquals(up_data["display_name"], display_name) self.assertEquals(up_data["email"], email) self.assertEquals(up_data["user"]["email"], email) self.assertEquals(up_data["user"]["is_staff"], is_staff) self.assertEquals(up_data["user"]["is_active"], is_active) self.assertEquals(up_data["landing_page"], "COMMUNITY") self.assertEquals(up_data["view_network"], view_network) self.assertEquals(up_data["view_services"], view_services) self.assertEquals(up_data["view_community"], view_community)