def setQuery(self): try: nestedFields = GqlQuery().fields(self.fields, name=self.subject).generate() self.query = GqlQuery().fields([nestedFields]).query(self.operationName, input=self.variableDefinitions).operation('mutation', name=self.operationName, input=self.inputDict).generate() return True except: return False
def __set_ev(self, jid): data = GqlQuery().fields(['status: "NEW"', 'jid: "{}"'.format(jid)]).generate() qry = GqlQuery().query('setDefaultIntergreen', input={ 'data': data }).operation('mutation').generate() self.__api.execute(gql(qry))
def test_fragment(self): expected = 'fragment comparisonFields on Character { name appearsIn friends { name } }' field_friends = GqlQuery().fields(['name'], name='friends').generate() actual = GqlQuery().fields(['name', 'appearsIn', field_friends ]).fragment('comparisonFields', 'Character').generate() self.assertEqual(expected, actual)
def test_query_neting_fields(self): expected = 'query { hero { name friends { name } } }' field_friends = GqlQuery().fields(['name'], name='friends').generate() actual = GqlQuery().fields( ['name', field_friends]).query('hero').operation('query').generate() self.assertEqual(expected, actual)
def test_query_alias(self): expected = 'query { empireHero: hero(episode: EMPIRE) { name } jediHero: hero(episode: JEDI) { name } }' query_empirehero = GqlQuery().fields(['name']).query( 'hero', alias='empireHero', input={"episode": 'EMPIRE'}).generate() query_jedihero = GqlQuery().fields(['name']).query( 'hero', alias='jediHero', input={"episode": 'JEDI'}).generate() actual = GqlQuery().operation('query', queries=[query_empirehero, query_jedihero]).generate() self.assertEqual(expected, actual)
def test_refer_to_fragment(self): expected = 'query { leftComparison: hero(episode: EMPIRE) { ...comparisonFields } rightComparison: hero(episode: JEDI) { ...comparisonFields } }' query_leftComparison = GqlQuery().fields(['...comparisonFields']).query( 'hero', alias='leftComparison', input={"episode": "EMPIRE"}).generate() query_rightComparison = GqlQuery().fields(['...comparisonFields']).query( 'hero', alias='rightComparison', input={"episode": "JEDI"}).generate() actual = GqlQuery().operation('query', queries=[query_leftComparison, query_rightComparison]).generate() self.assertEqual(expected, actual)
def __remove_project(self, oid): details = GqlQuery().fields([ 'status: "NEW"', 'oid: "{}"'.format(oid) ]).generate() qry = GqlQuery().query('deleteProject', input={ 'projectDetails': details }).operation('mutation').generate() self.__api.execute(gql(qry))
def test_query_with_variables(self): expected = 'query HeroNameAndFriends($episode: Episode) { hero(episode: $episode) { name friends { name } } }' field_friends = GqlQuery().fields(['name'], name='friends').generate() actual = GqlQuery().fields(['name', field_friends]).query( 'hero', input={ "episode": "$episode" }).operation('query', name='HeroNameAndFriends', input={ "$episode": "Episode" }).generate() self.assertEqual(expected, actual)
def get_graph_edges(self) -> str: child_fields = self.get_graph_ql_prop(self.get_table_schema()) child_limit_arg = "(first:{})".format( self.child_per_page) if self.child_is_list else '' child = GqlQuery().fields(child_fields, name='{child}{limit}'.format( child=self.parent_key_access, limit=child_limit_arg)).generate() node = GqlQuery().fields(['id', child, "createdAt", "updatedAt"], name='node').generate() edges = GqlQuery().fields(['cursor', node], name='edges').generate() return edges
def test_create_user_returns_token_in_data_response(self): """User mutation test""" username = self.fake.simple_profile()['username'] email = self.fake.simple_profile()['mail'] # step 1 create the user user_field = GqlQuery().fields(['username', 'email', 'id']).query(name='user').generate() query = GqlQuery().fields([user_field]).query( "createUser", input={ "email": "\"{}\"".format(email), "password": "******"password123\"", "username": "******"{}\"".format(username) }).operation("mutation").generate() create_user_data = self.client.execute(query=query) # check user is created username_expr = 'data.createUser.user.username' email_expr = 'data.createUser.user.email' username_resp = parse(username_expr).find(create_user_data)[0].value email_resp = parse(email_expr).find(create_user_data)[0].value self.assertEqual( username_resp, username, 'Expected username {}, but got {}.'.format(username, username_resp)) self.assertEqual( email_resp, email, 'Expected email {}, but got {}.'.format(email, email_resp)) # step 2 use the user to authenticate query = GqlQuery().fields(['token' ]).query("tokenAuth", input={ "password": "******"password123\"", "username": "******"{}\"".format(username) }).operation("mutation", name="").generate() data = self.client.execute(query=query) token_expr = 'data.tokenAuth.token' token = parse(token_expr).find(data)[0].value self.assertIsNotNone(token)
def __compute_table(self, jid): qry = GqlQuery().query('computeTables', input={ 'jid': '"{}"'.format(jid), 'status': '"NEW"' }).operation('query').generate() self.__api.execute(gql(qry))
def test_query_input_with_arguments(self): expected = 'query { human(id: "1000") { name height(unit: FOOT) } }' actual = GqlQuery().fields(['name', 'height(unit: FOOT)' ]).query('human', input={ "id": '"1000"' }).operation().generate() self.assertEqual(expected, actual)
def test_workout_variable_query_for_expected_exercise_name(self): """workout query using variables test""" # set expected exercise name, as per the seeded data to db expected_exercise_name = 'straight bar military press' # create query that takes in a variable query = GqlQuery().fields(['name', 'description' ]).query('workout', input={ "level": "$level" }).operation("query", name='workout_query', input={ "$level": "String" }).generate() # Think of variables like arguments to method parameters. variables = {"level": "advanced"} # perform the request data = self.client.execute(query=query, variables=variables) # search through the response data for expected description exercise_names = [ name.value for name in parse('data.workout[*].name').find(data) ] self.assertTrue( expected_exercise_name in exercise_names, 'Expected exercise name was not found in the response data')
def test_equipment_against_snapshot(self): """Testing equipment response data""" query = GqlQuery().fields(['difficulty' ]).query('levels').operation().generate() equipment_resp = self.client.execute(query=query) self.assertMatchSnapshot(equipment_resp, 'equipment_snapshot_resp')
def test_using_variables_for_existing_user_obtains_token_auth_in_response_data( self): """User authentication test""" username = AppConfig.conf_for_current_env()['user']['username'] password = AppConfig.conf_for_current_env()['user']['password'] query = GqlQuery().fields( ['token', 'payload', 'refreshExpiresIn']) \ .query("tokenAuth", input={"username": "******"{}\"".format(username), \ "password": "******"{}\"".format( \ password)}).operation( \ "mutation", name="userAuth").generate() data = self.client.execute(query=query) token_expr = 'data.tokenAuth.token' username_expr = 'data.tokenAuth.payload.username' refresh_expires_in_expr = 'data.tokenAuth.refreshExpiresIn' response_token = parse(token_expr).find(data)[0].value response_username = parse(username_expr).find(data)[0].value response_expiry = parse(refresh_expires_in_expr).find(data)[0].value self.assertIsNotNone(response_token) self.assertEqual( response_username, username, 'Expected username {}, but got {}'.format(username, response_username)) self.assertIsNotNone(response_expiry)
def test_should_verify_all_stars_details(self): """stars query test""" expected_result = [{ 'number': 1, 'classification': 'poor' }, { 'number': 2, 'classification': 'not good' }, { 'number': 3, 'classification': 'good' }, { 'number': 4, 'classification': 'very good' }, { 'number': 5, 'classification': 'perfect' }] query = GqlQuery().fields(['number', 'classification' ]).query('stars').operation().generate() data = self.client.execute(query=query) match = parse('data.stars[*]').find(data) actual_list_dict = [result.value for result in match] # assert list of dicts are equal ignoring order (python 3 only assert) self.assertCountEqual(actual_list_dict, expected_result)
def get_graph_query(self, created_at_min: str, created_at_max: str, name: str, after: typing.Optional[str] = None) -> str: edges = self.get_graph_edges() page_info = GqlQuery().fields(['hasNextPage', 'hasPreviousPage'], name='pageInfo').generate() query_input = self.get_query_input(created_at_min, created_at_max, after) generate_query = GqlQuery().query(name, input=query_input).fields( [page_info, edges]).generate() return "{%s}" % generate_query
def __get_project(self, k): # 0 = Create NEW # 1 = Update NEW # 2 = Update PRODUCTION logger.debug('Getting data for {} in PRODUCTION status'.format(k)) qry = GqlQuery().fields(['id']).query('project', input={'oid': '"{}"'.format(k), 'status': '"PRODUCTION"'}).operation('query').generate() res = self.__api.execute(gql(qry)) if res['project']: return 2 else: logger.debug('Getting data for {} in NEW status'.format(k)) qry = GqlQuery().fields(['id']).query('project', input={'oid': '"{}"'.format(k), 'status': '"NEW"'}).operation('query').generate() res = self.__api.execute(gql(qry)) if res['project']: return 1 else: return 0
def test_levels_response_against_snapshot(self): """Test levels query response data""" query = GqlQuery().fields(['difficulty' ]).query('levels').operation().generate() levels_resp = self.client.execute(query=query) self.assertMatchSnapshot(levels_resp, 'levels_snapshot_resp')
def test_query_directives(self): expected = 'query Hero($episode: Episode, $withFriends: Boolean!) { hero(episode: $episode) { name friends @include(if: $withFriends) { name } } }' field_friends = GqlQuery().fields( ['name'], name='friends @include(if: $withFriends)').generate() actual = GqlQuery().fields(['name', field_friends ]).query('hero', input={ "episode": "$episode" }).operation('query', name='Hero', input={ "$episode": "Episode", "$withFriends": "Boolean!" }).generate() self.assertEqual(expected, actual)
def get_fragment_fields(self, prop_name: str, fields: list) -> list: if prop_name in self.fragment_cols: fragment_name = self.fragment_cols[prop_name] fields = [ GqlQuery().fields( fields, name="... on {}".format(fragment_name)).generate() ] return fields
def __read_all_new_projects(self): final_result = set() junc = GqlQuery().fields(['jid']).query('junctions').generate() otu = GqlQuery().fields([junc]).query('otu').generate() node = GqlQuery().fields([otu]).query('node').generate() edges = GqlQuery().fields([node, 'cursor']).query('edges').generate() pageInfo = GqlQuery().fields(['endCursor', 'hasNextPage' ]).query('pageInfo').generate() initial_qry = GqlQuery().fields([pageInfo, edges]).query( 'projects', input={ 'first': 40, 'metadata_Version': '"latest"', 'metadata_Status': '"NEW"' }).operation('query').generate() result = self.__api.execute(gql(initial_qry)) has_next = result['projects']['pageInfo']['hasNextPage'] final_result = final_result.union(set(self.__iterate_get_jids(result))) while has_next: last_token = result['projects']['pageInfo']['endCursor'] next_qry = GqlQuery().fields([pageInfo, edges]).query( 'projects', input={ 'first': 40, 'after': '"{}"'.format(last_token), 'metadata_Version': '"latest"', 'metadata_Status': '"NEW"' }).operation('query').generate() result = self.__api.execute(gql(next_qry)) final_result = final_result.union( set(self.__iterate_get_jids(result))) has_next = result['projects']['pageInfo']['hasNextPage'] logger.debug('We have {} junctions'.format(len(final_result))) logger.debug('Got {} junctions'.format(len(final_result))) return final_result
def test_mutation(self): expected = 'mutation CreateReviewForEpisode($ep: Episode!, $review: ReviewInput!) { createReview(episode: $ep, review: $review) { stars commentary } }' actual = GqlQuery().fields(['stars', 'commentary']).query( 'createReview', input={ "episode": "$ep", "review": "$review" }).operation('mutation', name='CreateReviewForEpisode', input={ "$ep": "Episode!", "$review": "ReviewInput!" }).generate() self.assertEqual(expected, actual)
def get_graph_ql_prop(self, schema: dict) -> list: properties = schema["properties"] ql_fields = [] for prop_name in properties: prop_obj = properties[prop_name] prop_type = prop_obj["type"] if "generated" in prop_type: continue if 'object' in prop_type: if prop_obj["properties"]: fields = self.get_fragment_fields( prop_name, self.get_graph_ql_prop(prop_obj)) ql_field = GqlQuery().fields(fields, name=prop_name).generate() ql_fields.append(ql_field) elif 'array' in prop_type: if prop_obj["items"]["properties"]: fields = self.get_fragment_fields( prop_name, self.get_graph_ql_prop(prop_obj["items"])) ql_field = GqlQuery().fields(fields, name=prop_name).generate() if prop_name in self.need_edges_cols: node = GqlQuery().fields(fields, name='node').generate() edges = GqlQuery().fields([node], "edges").generate() ql_field = GqlQuery().query(prop_name, input={ "first": 5 }).fields([edges ]).generate() ql_fields.append(ql_field) else: ql_fields.append(prop_name) return ql_fields
def test_should_get_body_parts(self): """bodypart query test""" expected_body_parts = ['upper body', 'lower body', 'cardio'] query = GqlQuery().fields( ['name']).query('bodyParts').operation().generate() data = self.client.execute(query=query) jsonpath_expr = parse('data.bodyParts[*].name') actual_body_parts = [match.value for match in jsonpath_expr.find(data)] self.assertEqual(sorted(actual_body_parts), sorted(expected_body_parts), 'expected body parts to be the same, but were not')
def test_should_get_all_equipment_types(self): """equipment query test""" expected_equipment = [ 'dumbbells', 'resistance bands', 'barbell', 'none' ] query = GqlQuery().fields( ['name']).query('equipment').operation().generate() data = self.client.execute(query=query) jsonpath_expr = parse('data.equipment[*].name') actual_equipment = [match.value for match in jsonpath_expr.find(data)] self.assertEqual(sorted(actual_equipment), sorted(expected_equipment), 'expected equipment to be the same, but were not')
def __read_all_new_projects(self): qry = GqlQuery().fields(['oid']).query('projects', input={ 'status': '"NEW"' }).operation('query').generate() result = self.__api.execute(gql(qry)) return result['projects']
# Product query builder dataSet1 = [ 'productId', 'productName', 'mediaLinks', 'cancellationType', 'cancellationCutoff', 'minGroupSize', 'duration' ] dataSet2 = [ 'destinationId', 'openDateTicket', 'collectPhysicalTicket', 'confirmationType', 'voucherType', 'guideLanguage' ] dataSet3 = [ 'priceRangeFrom', 'priceRangeTo', 'priceAdultFrom', 'priceChildFrom', 'latitude', 'longitude', 'address', 'content' ] dataSet = dataSet1 + dataSet2 + dataSet3 product_query = GqlQuery().fields(dataSet).query('product', input={ "productId": '"pgfnl"' }).operation().generate() INVALID_LOGIN_MUTATION = """mutation { login(email: "*****@*****.**", password: "******"){ accessToken } }""" def test_mutation_invalid_login(): #Build Mutation and make a post call to Graphql API over https response = requests.post(URL, json={'query': INVALID_LOGIN_MUTATION}) #Print response code print(response.status_code)
# coding: utf-8 from gql_query_builder import GqlQuery from graphqlclient import GraphQLClient if __name__ == '__main__': # create client client = GraphQLClient('https://countries.trevorblades.com/') # generate query query = GqlQuery()\ .fields(['name', 'native', 'emoji'])\ .query('country', input={"code": '"JP"'})\ .operation('query')\ .generate() # execute response = client.execute(query) print(response)
def run(self): frag_attachment_file = GqlQuery().fields(['fileID', 'fileName', 'extension', '__typename']) \ .fragment('AttachmentFile', 'PostAttachFile').generate() field_files = GqlQuery().fields(['...AttachmentFile', '__typename'], name='files').generate() field_user = GqlQuery().fields(['_id', 'name', 'nickName'], name='user').generate() frag_comment = GqlQuery().fields([ '_id', 'content', 'createdAt', 'likedCount', 'missionId', 'photoUrl', 'videoUUID', 'audioUUID', 'type', 'klassId', 'languageCode', field_files, field_user ]).fragment('PostCommentStackedList', 'Post').generate() query = GqlQuery().fields(['...PostCommentStackedList']).query( 'klassPostsForCreator', alias='posts', input={ "isAnswered": "$isAnswered", "klassId": "$klassId", "offset": "$offset", "limit": "$limit" }).operation('query', name='PostManagementListViewModelKlassPost', input={ "$isAnswered": "Boolean!", "$klassId": "ID!", "$offset": "Int!", "$limit": "Int!" }).generate() full_query = '\n'.join([query, frag_comment, frag_attachment_file]) query_json = { "operationName": "PostManagementListViewModelKlassPost", "variables": { "isAnswered": False, "limit": 10, "offset": 0, "klassId": "5e2556a44ba7b950bbd46bb4" }, "query": full_query } last_post_time = '' is_first = True temp_post = None res = self.cc.data_query(query_json).json() for reversed_post in reversed(res['data']['posts']): timestamp = datetime.datetime.strptime(reversed_post['createdAt'], '%Y-%m-%dT%H:%M:%S.%fZ') print( f"[{timestamp}] {reversed_post['user']['name']}: {reversed_post['content']}" ) last_post_time = reversed_post['createdAt'] print('-' * 20) while True: res = self.cc.data_query(query_json).json() for post in res['data']['posts']: if last_post_time < post['createdAt']: timestamp = datetime.datetime.strptime( post['createdAt'], '%Y-%m-%dT%H:%M:%S.%fZ') print( f"[{timestamp}] {post['user']['name']}: {post['content']}" ) self.alert_sound.play().wait_done() if is_first: temp_post = post is_first = False else: if temp_post: last_post_time = temp_post['createdAt'] temp_post = None is_first = True break time.sleep(3)