def test_arango_list_field_all_resolve_method_args(schema, cleanup): client = Client(schema) result = client.execute(introspect_queries) # logger.debug(json.dumps(result, indent=4, sort_keys=True)) query_fields = result['data']['__schema']['queryType']['fields'] query_field = [ field for field in query_fields if field['name'] == 'testPeople' ][0] assert len(query_field['args']) == 2 assert query_field['args'][0]['name'] == 'skip' assert query_field['args'][1]['name'] == 'limit'
def test_series_x_limit(log_dir): query = """ query LineChartsQuery( $prefix: String $xKey: String $yKey: String $yKeys: [String] $metricsFiles: [String]! ) { series( metricsFiles: $metricsFiles, prefix: $prefix, k: 10, xLow: 100, xKey: $xKey, yKey: $yKey, yKeys: $yKeys ) { id xKey yKey xData yMean yCount } } """ from ml_dash.config import Args Args.logdir = log_dir client = Client(schema) variables = { "prefix": None, "xKey": "epoch", "yKey": "slow_sine", "yKeys": None, "metricsFiles": ["/episodeyang/cpc-belief/mdp/experiment_01/metrics.pkl"] } r = client.execute(query, variables=variables) print(r['data']['series']['xData']) assert r['data']['series']['xData'].__len__() == 10 variables = { "prefix": None, "yKey": "slow_sine", "yKeys": None, "metricsFiles": ["/episodeyang/cpc-belief/mdp/experiment_01/metrics.pkl"] } r = client.execute(query, variables=variables) print(r['data']['series']['xData']) assert r['data']['series']['xData'].__len__() == 10
def setUp(self): self.main_user = User.objects.create( first_name="Jhon", last_name="Doe", email="*****@*****.**", profile_image="/profile/image.png", profile="This is the profile John Doe", username="******") self.main_user.set_password("123admin123") self.main_user.save() self.client = Client(schema)
def test_schema(log_dir): from ml_dash.config import Args Args.logdir = log_dir client = Client(schema) query = """ query AppQuery ($username:String) { user (username: $username) { username name projects(first: 1) { edges { node { id name experiments(first:10) { edges { node { id name parameters {value keys flat raw} metrics { id keys value (keys: ["__timestamp", "sine"]) } } } } directories(first:10){ edges { node { id name files(first:10){ edges { node { name } } } directories(first:10){ edges { node { name } } } } } } } } } } } """ r = client.execute(query, variables=dict(username="******")) if 'errors' in r: raise RuntimeError(r['errors']) else: _ = r['data']['user'] show(_)
def test_auth(): client = Client(schema) response = client.execute("""mutation a { auth(email: "*****@*****.**", password:"******") { accessToken message } }""") assert response["data"]["auth"] return response["data"]["auth"]
def test_country_type(db): Person.objects.create(name="Skippy", country="AU") client = Client(schema) executed = client.execute("""{ people { name, country {name} } }""") returned_person = executed["data"]["people"][0] assert returned_person == { "name": "Skippy", "country": { "name": "Australia" } }
def test_directory(log_dir): from ml_dash.config import Args Args.logdir = log_dir client = Client(schema) query = """ query AppQuery ($id: ID!) { directory ( id: $id ) { id name readme { id name path text(stop:11) } dashConfigs(first:10) { edges { node { id name path yaml text(stop:11) } } } directories (first:10) { edges { node { id name path directories (first:10) { edges { node { id name } } } } } } experiments (first:10) { edges { node { id name path parameters {keys flat} files (first:10) { edges { node { id, name} } } } } } } } """ path = "/episodeyang/cpc-belief/mdp" r = client.execute(query, variables=dict(id=to_global_id("Directory", path))) if 'errors' in r: raise RuntimeError(r['errors']) else: print(">>") show(r['data'])
def test_create_person_mutation2(snapshot): """ Test create person mutation with required fields only""" client = Client(schema) executed = client.execute(create_person_gql, variable_values={ 'firstName': "Test first name", 'lastName': "Test last name" }) snapshot.assert_match(executed)
def test_all_songs__one_song(db_session): fake_song = schemas.SongCreate(name="Let me go", release="2021-01-01") song_instance = crud.create_song(db=db_session, song=fake_song) client = Client(schema) query = """{ songs {name, release} }""" executed = client.execute(query, context_value={"session": db_session}) assert executed == { "data": {"songs": [{"name": "Let me go", "release": "2021-01-01"}]} }
def test_query_id(self): client = Client(schema) executed = client.execute(''' query { responsePlans(responsePlanId: %s) { id } } ''' % self.response_plans[0].id) self.assertEqual(executed['data']['responsePlans'][0]['id'], str(self.response_plans[0].id))
def test_query(self): client = Client(schema) executed = client.execute(''' query { responsePlans(operator: "%s") { operator } } ''' % (self.response_plans[0].operator)) for x in executed['data']['responsePlans']: self.assertEqual(x['operator'], 'AND')
def test_delete_exception(self): client = Client(schema) executed = client.execute(''' mutation { deleteResponsePlan(id: -99) { id } } ''') self.assertEqual(executed['errors'][0]['message'], "Response plan with id = -99 does not exist!")
def setUp(self): self.client = Client(schema) self.sell_data = {'margin': 0.2, 'type_': 'sell', 'exchange_rate': 10} self.buy_data = {'margin': 0.2, 'type_': 'buy', 'exchange_rate': 10} self.ivalid_data = { 'margin': -0.2, 'type_': 'buy', 'exchange_rate': -10 }
def test_fetch_luke_query(): swsetup() hpsetup() client = Client(schema) query = """ query FetchLukeQuery { human(id: "1000") { name } } """ client.execute(query)
def test_create_person_mutation3(snapshot): """ Test create person mutation with incorrect data""" client = Client(schema) executed = client.execute(create_person_gql, variable_values={ 'firstName': "Test first name", 'lastName': "Test last name", 'companyId': -1 }) snapshot.assert_match(executed)
def test_create_exception(self): operator = 'OR' client = Client(schema) executed = client.execute(''' mutation { createResponsePlan(operator: "%s", roadSegmentId: -99) { operator } } ''' % operator) self.assertEqual(executed['errors'][0]['message'], "Roadsegment with id = -99 does not exist!")
def test_create_response_plan(self): operator = 'OR' client = Client(schema) executed = client.execute(''' mutation { createResponsePlan(operator: "%s", roadSegmentId: %s) { operator } } ''' % (operator, self.segments[0].id)) self.assertEqual(executed['data']['createResponsePlan']['operator'], operator)
def setUpClass(cls): if not User.objects.filter(username='******').exists(): User.objects.create_superuser(username='******', password='******') cls.user = User.objects.filter(username='******').first() cls.test_contribution_plan_bundle = create_test_contribution_plan_bundle( custom_props={'code': 'SuperContributionPlan mutations!'}) cls.schema = Schema(query=contribution_plan_schema.Query, mutation=contribution_plan_schema.Mutation) cls.graph_client = Client(cls.schema)
def setUp(self): self.maxDiff = None self.user1 = User.objects.create(username="******") self.user2 = User.objects.create(username="******") self.anon = AnonymousUser() self.entries = Entry.objects.bulk_create([ Entry(content=content, posted_by=posted_by) for content, posted_by in product(['entry1', 'entry2', 'entry3'], [self.user1, self.user2]) ]) self.schema = Schema(query=Query) self.client = Client(self.schema)
def test_time_entries_query(snapshot, request): """ Test get time entries query""" staff_member = UserFactory(id=1) TimeEntryFactory.create_batch( size=1, rate=0, status=1, gst_status=0, units_to_bill=25, staff_member=staff_member, ) TimeEntryFactory.create_batch( size=1, rate=0, status=1, gst_status=0, units_to_bill=25, staff_member=None, ) TimeEntryFactory.create_batch( size=1, rate=503.40, status=1, gst_status=0, units_to_bill=25, staff_member=staff_member, ) request.user = staff_member client = Client(schema, context=request) query = client.execute(""" query getTimeEntries { timeEntries(first: 3) { edges { node { statusDisplay gstStatus gstStatusDisplay cost status billedValue rate isBilled entryType } } } } """) snapshot.assert_match(query)
def setUp(self): self.event_creator = create_user("creatorId") self.non_event_creator = create_user("ncreatorId") self.admin = create_admin_user("adminId") self.category = create_category() self.request = request_factory.get('/graphql') self.client = Client(schema, format_error=DRF.format_error) self.user_event = create_event(self.event_creator, self.category) self.admin_event = create_event(self.admin, self.category, active=False, id=2)
def test_country_type(): client = Client(schema) executed = client.execute( """{ newZealand {code, name, iocCode, numeric, alpha3} }""") returned_country = executed["data"]["newZealand"] assert returned_country == { "code": "NZ", "name": "New Zealand", "iocCode": "NZL", "numeric": 554, "alpha3": "NZL", }
def test_me_query_1(snapshot, request): """ Test a me query without profile""" user = UserFactory(latitude=0, longitude=0) request.user = user client = Client(schema, context=request) executed = client.execute(''' query me { me { categories { id name posts { id } } id geoLocationAllowed email isVerified lastVerificationCode fullName gallery { id image } profiles { id name avatar { id image source { id image } } age gender isActive user { id fullName email } } } } ''', variables={}) snapshot.assert_match(executed)
def test_userbyid(): initdata_users() client = Client(schema) executed = client.execute("""query { user(userid:5) { username } }""") expected = {"data": {"user": {"username": "******"}}} assert executed == expected
def test_info(self): client = Client(schema.schema) executed = client.execute('''{ info { id name description } }''') assert executed == { 'data': { 'info': { 'id': '7560bd6b-6a7f-45f9-97e5-38ee65982ae5', 'name': 'Maana Python Template', 'description': 'This is a python template for using MaanaQ.' } } }
def test_query_events(self): self.create() client = Client(self.schema) executed = client.execute( ''' query { events(name: "test") { name } } ''', context_value=MockContext(self.user), ) self.assertTrue(len(executed.get('data')) > 0)
def test_arango_list_field_all_resolve_method_as_obj(schema, data, cleanup): client = Client(schema) result = client.execute(''' { testPeopleObj { docs { id name age } total } } ''') # logger.debug(result) assert len(result['data']['testPeopleObj']['docs']) == 4 assert result['data']['testPeopleObj']['docs'][0]['name'] == 'bozo' assert result['data']['testPeopleObj']['docs'][1]['name'] == "pennywise" assert result['data']['testPeopleObj']['docs'][2]['age'] == 45 assert result['data']['testPeopleObj']['docs'][3]['age'] == 73 assert result['data']['testPeopleObj']['total'] == 4 client = Client(schema) result = client.execute(''' { testPeopleObj(skip: 1, limit: 2) { docs { id name age } total } } ''') # logger.debug(result) assert len(result['data']['testPeopleObj']['docs']) == 2 assert result['data']['testPeopleObj']['docs'][0]['name'] == 'pennywise' assert result['data']['testPeopleObj']['docs'][1]['name'] == "joker" assert result['data']['testPeopleObj']['total'] == 4
def test_staff_matter_report2(snapshot, request): """ Test matter report query with billable status 2 must return empty data, there are no matter with this status""" manager = UserFactory(is_staff=True, is_active=True) MatterFactory.create_batch(size=3, manager=manager, billable_status=1) request.user = manager client = Client(schema, context=request) executed = client.execute(""" query staffMatterReportMatter( $after: String $staffName: String $billableStatus: String $billableStatusExclude: Float ) { matters( first: 15 after: $after staffName: $staffName billableStatus: $billableStatus billableStatusExclude: $billableStatusExclude ) { edges { cursor node { id name totalTimeValue totalTimeInvoiced wip billableStatusDisplay daysOpen matterStatusDisplay client { id name } } } pageInfo { endCursor hasNextPage } } } """, variable_values={ 'staffName': manager.full_name, 'billableStatus': 2, 'billableStatusExclude': 3, }) snapshot.assert_match(executed)
def test_bookmarks_first_2_items_query(fixtures_data): query = """ { bookmarks(first: 2){ edges { node { name url category { name color } tags } } } }""" expected = { "data": { "bookmarks": { "edges": [ { "node": { "name": "Travel tips", "url": "https://www.traveltips.test", "category": { "name": "Travel", "color": "#ed008c" }, "tags": ["travel", "tips", "howto"], } }, { "node": { "name": "DIY vacation", "url": "https://www.diyvacation.test", "category": { "name": "Travel", "color": "#ed008c" }, "tags": ["travel", "diy", "holiday", "vacation"], } }, ] } } } client = Client(schema) result = client.execute(query) assert result == expected
def add_fields(fields): client = Client(schema) for field in fields: client.execute( """ mutation AddField {{ addField(name: "{field_name}") {{ ok }} }} """.format(field_name=field), context=Context(user=User( name='An On', shortname='anon', roles=['VolumetricAdmin'])))