def number_gauge_vote_specification_associated_to_proposal(request, test_session, discussion, graphql_request, vote_session, number_gauge_vote_specification, vote_proposal, graphql_registry): mutation = graphql_registry['createNumberGaugeVoteSpecification'] vote_session_id = to_global_id("VoteSession", vote_session.id) proposal_id = to_global_id("Idea", vote_proposal.id) template_gauge_vote_spec_id = to_global_id("NumberGaugeVoteSpecification", number_gauge_vote_specification.id) from assembl.graphql.schema import Schema as schema res = schema.execute(mutation, context_value=graphql_request, variable_values={ "voteSessionId": vote_session_id, "proposalId": proposal_id, "voteSpecTemplateId": template_gauge_vote_spec_id, "titleEntries": [ {"value": u"Comprendre les dynamiques et les enjeux", "localeCode": "fr"}, {"value": u"Understanding the dynamics and issues", "localeCode": "en"} ], "instructionsEntries": [ {"value": u"Instructions : Comprendre les dynamiques et les enjeux", "localeCode": "fr"}, {"value": u"Instructions: Understanding the dynamics and issues", "localeCode": "en"} ], "isCustom": True, "minimum": 0.0, "maximum": 60.0, "nbTicks": 7, "unit": u"M€" }) assert res.errors is None vote_spec = vote_session.vote_specifications[-1] def fin(): print "finalizer number_gauge_vote_specification_associated_to_proposal" test_session.delete(vote_spec) test_session.flush() request.addfinalizer(fin) return vote_spec
def test_query_vote_session_proposals(graphql_request, timeline_vote_session, vote_session, vote_proposal, graphql_registry): query = graphql_registry['VoteSession'] res = schema.execute(query, context_value=graphql_request, variable_values={ "ideaId": to_global_id('Idea', vote_session.idea_id), "lang": "en" }) assert res.errors is None proposal_id = to_global_id("Idea", vote_proposal.id) assert json.loads(json.dumps(res.data['voteSession']['proposals'])) == [{ u'id': proposal_id, u'order': 1.0, u'title': u'Understanding the dynamics and issues', u'description': u'Description: Understanding the dynamics and issues', u'titleEntries': [ {u'localeCode': u'en', u'value': u'Understanding the dynamics and issues'}, {u'localeCode': u'fr', u'value': u'Comprendre les dynamiques et les enjeux'}], u'descriptionEntries': [ {u'localeCode': u'en', u'value': u'Description: Understanding the dynamics and issues'}, {u'localeCode': u'fr', u'value': u'Description: Comprendre les dynamiques et les enjeux'}], u'modules': [], u'voteResults': {u'numParticipants': 0, u'participants': []} }]
def test_mutation_create_token_vote_specification(graphql_request, vote_session, graphql_registry): mutation = graphql_registry['createTokenVoteSpecification'] vote_session_id = to_global_id("VoteSession", vote_session.id) res = schema.execute(mutation, context_value=graphql_request, variable_values={ "voteSessionId": vote_session_id, "titleEntries": [ {"value": u"Comprendre les dynamiques et les enjeux", "localeCode": "fr"}, {"value": u"Understanding the dynamics and issues", "localeCode": "en"} ], "instructionsEntries": [ {"value": u"Comprendre les dynamiques et les enjeux", "localeCode": "fr"}, {"value": u"Understanding the dynamics and issues", "localeCode": "en"} ], "isCustom": False, "exclusiveCategories": True, "tokenCategories": [ {"titleEntries": [ {"value": u"Comprendre les dynamiques et les enjeux", "localeCode": "fr"}, {"value": u"Understanding the dynamics and issues", "localeCode": "en"} ], "typename": "positive", "totalNumber": 10, "color": 'red' } ] }) assert res.errors is None token_vote_spec = vote_session.vote_specifications[0] token_vote_spec_id = to_global_id("TokenVoteSpecification", token_vote_spec.id) token_category = token_vote_spec.token_categories[0] token_category_id = to_global_id("TokenCategorySpecification", token_category.id) assert json.loads(json.dumps(res.data)) == { u'createTokenVoteSpecification': {u'voteSpecification': {u'exclusiveCategories': True, u'id': token_vote_spec_id, u'instructionsEntries': [{u'localeCode': u'en', u'value': u'Understanding the dynamics and issues'}, {u'localeCode': u'fr', u'value': u'Comprendre les dynamiques et les enjeux'}], u'titleEntries': [{u'localeCode': u'en', u'value': u'Understanding the dynamics and issues'}, {u'localeCode': u'fr', u'value': u'Comprendre les dynamiques et les enjeux'}], u"isCustom": False, u'tokenCategories': [{u'color': u'red', u'id': token_category_id, u'titleEntries': [{u'localeCode': u'en', u'value': u'Understanding the dynamics and issues'}, {u'localeCode': u'fr', u'value': u'Comprendre les dynamiques et les enjeux'}], u'totalNumber': 10, # u'typename': u'positive' }], u'voteSpecTemplateId': None, u'voteSessionId': vote_session_id}}} # remove created vote specification vote_session.vote_specifications.remove(token_vote_spec) vote_session.db.flush()
def test_mutation_update_token_vote_specification(graphql_request, vote_session, token_vote_specification, graphql_registry): mutation = graphql_registry['updateTokenVoteSpecification'] vote_session_id = to_global_id("VoteSession", vote_session.id) token_vote_spec_id = to_global_id("TokenVoteSpecification", token_vote_specification.id) token_category = token_vote_specification.token_categories[0] token_category_id = to_global_id("TokenCategorySpecification", token_category.id) res = schema.execute(mutation, context_value=graphql_request, variable_values={ "id": token_vote_spec_id, "titleEntries": [ {"value": u"Comprendre les dynamiques et les enjeux (updated)", "localeCode": "fr"}, {"value": u"Understanding the dynamics and issues (updated)", "localeCode": "en"} ], "instructionsEntries": [ {"value": u"Comprendre les dynamiques et les enjeux (updated)", "localeCode": "fr"}, {"value": u"Understanding the dynamics and issues (updated)", "localeCode": "en"} ], "isCustom": False, "exclusiveCategories": True, "tokenCategories": [ { "id": token_category_id, "titleEntries": [ {"value": u"Comprendre les dynamiques et les enjeux (updated)", "localeCode": "fr"}, {"value": u"Understanding the dynamics and issues (updated)", "localeCode": "en"} ], "typename": "negative", "totalNumber": 14, "color": "blue" } ] }) assert res.errors is None assert json.loads(json.dumps(res.data)) == { u'updateTokenVoteSpecification': {u'voteSpecification': {u'exclusiveCategories': True, u'id': token_vote_spec_id, u'instructionsEntries': [{u'localeCode': u'en', u'value': u'Understanding the dynamics and issues (updated)'}, {u'localeCode': u'fr', u'value': u'Comprendre les dynamiques et les enjeux (updated)'}], u'titleEntries': [{u'localeCode': u'en', u'value': u'Understanding the dynamics and issues (updated)'}, {u'localeCode': u'fr', u'value': u'Comprendre les dynamiques et les enjeux (updated)'}], u"isCustom": False, u'tokenCategories': [{u'color': u'blue', u'id': token_category_id, u'titleEntries': [{u'localeCode': u'en', u'value': u'Understanding the dynamics and issues (updated)'}, {u'localeCode': u'fr', u'value': u'Comprendre les dynamiques et les enjeux (updated)'}], u'totalNumber': 14, # u'typename': u'negative' }], u'voteSessionId': vote_session_id}}}
def token_vote_specification_associated_to_proposal(request, test_session, discussion, graphql_request, vote_session, token_vote_specification, vote_proposal, graphql_registry): mutation = graphql_registry['createTokenVoteSpecification'] vote_session_id = to_global_id("VoteSession", vote_session.id) proposal_id = to_global_id("Idea", vote_proposal.id) # token vote spec similar to token_vote_specification fixture, but with exclusiveCategories set to False template_token_vote_spec_id = to_global_id("TokenVoteSpecification", token_vote_specification.id) from assembl.graphql.schema import Schema as schema res = schema.execute(mutation, context_value=graphql_request, variable_values={ "voteSessionId": vote_session_id, "proposalId": proposal_id, "voteSpecTemplateId": template_token_vote_spec_id, "titleEntries": [ {"value": u"Comprendre les dynamiques et les enjeux", "localeCode": "fr"}, {"value": u"Understanding the dynamics and issues", "localeCode": "en"} ], "instructionsEntries": [ {"value": u"Instructions : Comprendre les dynamiques et les enjeux", "localeCode": "fr"}, {"value": u"Instructions: Understanding the dynamics and issues", "localeCode": "en"} ], "isCustom": True, "exclusiveCategories": False, "tokenCategories": [ {"titleEntries": [ {"value": u"Pour", "localeCode": "fr"}, {"value": u"In favor", "localeCode": "en"} ], "typename": "positive", "totalNumber": 9, "color": 'green' }, {"titleEntries": [ {"value": u"Contre", "localeCode": "fr"}, {"value": u"Against", "localeCode": "en"} ], "typename": "negative", "totalNumber": 9, "color": 'red' } ] }) assert res.errors is None vote_spec = vote_session.vote_specifications[-1] def fin(): print "finalizer token_vote_specification_associated_to_proposal" test_session.delete(vote_spec) test_session.flush() request.addfinalizer(fin) return vote_spec
def test_mutation_delete_template_also_deletes_associated_vote_specifications(graphql_request, vote_session, vote_proposal, graphql_registry, test_session): mutation = graphql_registry['createTokenVoteSpecification'] vote_session_id = to_global_id("VoteSession", vote_session.id) from assembl.graphql.schema import Schema as schema res = schema.execute(mutation, context_value=graphql_request, variable_values={ "voteSessionId": vote_session_id, "titleEntries": [], "instructionsEntries": [ {"value": u"Try to copy the TCP feed, maybe it will navigate the mobile system!", "localeCode": "en"} ], "isCustom": False, "exclusiveCategories": False, "tokenCategories": [ { "titleEntries": [{"value": u"In favor", "localeCode": "en"}], "typename": "positive", "totalNumber": 9, "color": 'green' } ] }) assert res.errors is None template_id = res.data['createTokenVoteSpecification']['voteSpecification']['id'] proposal_id = to_global_id("Idea", vote_proposal.id) res = schema.execute(mutation, context_value=graphql_request, variable_values={ "voteSessionId": vote_session_id, "proposalId": proposal_id, "voteSpecTemplateId": template_id, "titleEntries": [], "instructionsEntries": [ {"value": u"I'll compress the multi-byte THX protocol, that should panel the SDD monitor!", "localeCode": "en"} ], "isCustom": True, "exclusiveCategories": False, "tokenCategories": [] }) assert res.errors is None # delete the template mutation = graphql_registry['deleteVoteSpecification'] vote_spec_id = res.data['createTokenVoteSpecification']['voteSpecification']['id'] res = schema.execute(mutation, context_value=graphql_request, variable_values={ "id": template_id }) assert res.errors is None assert res.data['deleteVoteSpecification']['success'] is True # the template and the vote spec have been deleted assert test_session.query(models.TokenVoteSpecification).count() == 0
def test_query_associate_vote_spec_to_proposal(graphql_request, timeline_vote_session, vote_session, vote_proposal, token_vote_specification, graphql_registry): mutation = graphql_registry['createTokenVoteSpecification'] vote_session_id = to_global_id("VoteSession", vote_session.id) proposal_id = to_global_id("Idea", vote_proposal.id) # token vote spec similar to token_vote_specification fixture, but with exclusiveCategories set to False template_token_vote_spec_id = to_global_id("TokenVoteSpecification", token_vote_specification.id) res = schema.execute(mutation, context_value=graphql_request, variable_values={ "voteSessionId": vote_session_id, "proposalId": proposal_id, "voteSpecTemplateId": template_token_vote_spec_id, "titleEntries": [ {"value": u"Comprendre les dynamiques et les enjeux", "localeCode": "fr"}, {"value": u"Understanding the dynamics and issues", "localeCode": "en"} ], "instructionsEntries": [ {"value": u"Comprendre les dynamiques et les enjeux", "localeCode": "fr"}, {"value": u"Understanding the dynamics and issues", "localeCode": "en"} ], "isCustom": True, "exclusiveCategories": False, "tokenCategories": [ {"titleEntries": [ {"value": u"Comprendre les dynamiques et les enjeux", "localeCode": "fr"}, {"value": u"Understanding the dynamics and issues", "localeCode": "en"} ], "typename": "positive", "totalNumber": 10, "color": 'red' } ] }) query = graphql_registry['VoteSession'] res = schema.execute(query, context_value=graphql_request, variable_values={ "ideaId": to_global_id('Idea',vote_session.idea_id), "lang": "en" }) assert res.errors is None proposal_id = to_global_id("Idea", vote_proposal.id) assert len(res.data['voteSession']['modules']) == 1 # only vote spec not associated to a proposal assert res.data['voteSession']['modules'][0]['exclusiveCategories'] == True assert len(res.data['voteSession']['proposals'][0]['modules']) == 1 assert res.data['voteSession']['proposals'][0]['modules'][0]['exclusiveCategories'] == False assert res.data['voteSession']['proposals'][0]['modules'][0]['voteSpecTemplateId'] == template_token_vote_spec_id assert res.data['voteSession']['proposals'][0]['modules'][0]['isCustom'] is True # clean up vote_session.vote_specifications[-1].delete() vote_session.db.flush()
def number_gauge_vote_specification_with_votes(graphql_participant1_request, vote_session, vote_proposal, number_gauge_vote_specification_associated_to_proposal, graphql_registry): proposal_id = to_global_id("Idea", vote_proposal.id) vote_spec_id = to_global_id("NumberGaugeVoteSpecification", number_gauge_vote_specification_associated_to_proposal.id) from assembl.graphql.schema import Schema as schema res = schema.execute( graphql_registry['addGaugeVote'], context_value=graphql_participant1_request, variable_values={ "proposalId": proposal_id, "voteSpecId": vote_spec_id, "voteValue": 40.0 } ) assert res.errors is None return number_gauge_vote_specification_associated_to_proposal
def test_mutation_update_proposal(graphql_request, discussion, vote_proposal, graphql_registry): mutation = graphql_registry['updateProposal'] proposal_id = to_global_id("Idea", vote_proposal.id) res = schema.execute(mutation, context_value=graphql_request, variable_values={ "id": proposal_id, "titleEntries": [ {"value": u"Comprendre les dynamiques et les enjeux (updated)", "localeCode": "fr"}, {"value": u"Understanding the dynamics and issues (updated)", "localeCode": "en"} ], "descriptionEntries": [ {"value": u"Description: Comprendre les dynamiques et les enjeux (updated)", "localeCode": "fr"}, {"value": u"Description: Understanding the dynamics and issues (updated)", "localeCode": "en"} ] }) assert res.errors is None assert json.loads(json.dumps(res.data)) == { u'updateProposal': { u'proposal': { u'id': proposal_id, u'order': 1.0, u'titleEntries': [ {u'localeCode': u'en', u'value': u'Understanding the dynamics and issues (updated)'}, {u'localeCode': u'fr', u'value': u'Comprendre les dynamiques et les enjeux (updated)'}], u'descriptionEntries': [ {u'localeCode': u'en', u'value': u'Description: Understanding the dynamics and issues (updated)'}, {u'localeCode': u'fr', u'value': u'Description: Comprendre les dynamiques et les enjeux (updated)'}] }}}
def test_mutation_update_extract_tags(graphql_request, extract_post_1_to_subidea_1_1): extract_graphql_db_id = to_global_id('Extract',extract_post_1_to_subidea_1_1.id) tags = ['foo', 'bar', 'tar'] variable_values = { "id": extract_graphql_db_id, "tags" : tags } res = schema.execute(u""" mutation updateExtractTags( $id: ID! $tags: [String] ) { updateExtractTags( id: $id tags: $tags ) { tags { value } } } """, context_value=graphql_request, variable_values=variable_values) assert json.loads(json.dumps(res.data)) == { u'updateExtractTags': { u'tags': [{u'value': u'foo'}, {u'value': u'bar'}, {u'value': u'tar'}] } }
def test_mutation_update_text_field(graphql_request, graphql_registry, text_field): text_field_id = to_global_id('TextField', text_field.id) res = schema.execute( graphql_registry['updateTextField'], context_value=graphql_request, variable_values={ "id": text_field_id, "lang": u"en", "titleEntries": [ { "localeCode": "en", "value": u"My new title" }, { "localeCode": "be", "value": u"Mon nouveau titre" }, ], "order": 8.0, "required": False, "hidden": False }) assert res.errors is None assert 'updateTextField' in res.data field = res.data['updateTextField']['field'] assert field[u'required'] is False assert field[u'hidden'] is False assert field[u'order'] == 8.0 title_entries = field['titleEntries'] assert title_entries[0]['localeCode'] == u'be' assert title_entries[0]['value'] == u'Mon nouveau titre' assert title_entries[1]['localeCode'] == u'en' assert title_entries[1]['value'] == u'My new title'
def test_mutation_confirm_extract(graphql_request, extract_with_range_submitted_in_reply_post_1): from assembl.models import ExtractStates state = extract_with_range_submitted_in_reply_post_1.extract_state assert ExtractStates.SUBMITTED.value == state extract_graphql_db_id = to_global_id('Extract',extract_with_range_submitted_in_reply_post_1.id) variable_values = { "extractId": extract_graphql_db_id } res = schema.execute(u""" mutation confirmExtract($extractId: ID!) { confirmExtract(extractId: $extractId) { success } } """, context_value=graphql_request, variable_values=variable_values) assert json.loads(json.dumps(res.data)) == { u'confirmExtract': { u'success': True } } state = extract_with_range_submitted_in_reply_post_1.extract_state assert ExtractStates.PUBLISHED.value == state
def vote_proposal(request, test_session, discussion, graphql_request, vote_session, graphql_registry): mutation = graphql_registry['createProposal'] vote_session_id = to_global_id("VoteSession", vote_session.id) from assembl.graphql.schema import Schema as schema res = schema.execute(mutation, context_value=graphql_request, variable_values={ "voteSessionId": vote_session_id, "titleEntries": [ {"value": u"Comprendre les dynamiques et les enjeux", "localeCode": "fr"}, {"value": u"Understanding the dynamics and issues", "localeCode": "en"} ], "descriptionEntries": [ {"value": u"Description: Comprendre les dynamiques et les enjeux", "localeCode": "fr"}, {"value": u"Description: Understanding the dynamics and issues", "localeCode": "en"} ] }) assert res.errors is None proposal = vote_session.idea.children[0] def fin(): print "finalizer vote_proposal" test_session.delete(proposal) test_session.flush() request.addfinalizer(fin) return proposal
def test_graphql_get_profile(graphql_request, participant1_user): res = schema.execute(u""" query User($id: ID!) { user: node(id: $id) { ... on AgentProfile { id name username displayName email creationDate image { externalUrl } hasPassword } } } """, context_value=graphql_request, variable_values={ "id": to_global_id('AgentProfile', participant1_user.id) }) assert res.errors is None assert res.data['user']['name'] == u'A. Barking Loon' assert res.data['user']['username'] is None assert res.data['user']['displayName'] == u'A. Barking Loon' assert res.data['user']['email'] == u'*****@*****.**' # 2018-01-04T12:08:44.735489+00:00 assert u'T' in res.data['user']['creationDate'] assert res.data['user']['image'] is None assert res.data['user']['hasPassword']
def test_mutation_create_number_gauge_vote_specification(graphql_request, vote_session, graphql_registry): mutation = graphql_registry['createNumberGaugeVoteSpecification'] vote_session_id = to_global_id("VoteSession", vote_session.id) res = schema.execute(mutation, context_value=graphql_request, variable_values={ "voteSessionId": vote_session_id, "titleEntries": [ {"value": u"Comprendre les dynamiques et les enjeux", "localeCode": "fr"}, {"value": u"Understanding the dynamics and issues", "localeCode": "en"} ], "instructionsEntries": [ {"value": u"Comprendre les dynamiques et les enjeux", "localeCode": "fr"}, {"value": u"Understanding the dynamics and issues", "localeCode": "en"} ], "isCustom": False, "minimum": 0.0, "maximum": 60.0, "nbTicks": 7, "unit": u"M€" }) assert res.errors is None vote_spec = vote_session.vote_specifications[0] vote_spec_id = to_global_id("NumberGaugeVoteSpecification", vote_spec.id) assert json.loads(json.dumps(res.data)) == { u'createNumberGaugeVoteSpecification': { u'voteSpecification': { u'id': vote_spec_id, u'instructionsEntries': [ {u'localeCode': u'en', u'value': u'Understanding the dynamics and issues'}, {u'localeCode': u'fr', u'value': u'Comprendre les dynamiques et les enjeux'}], u'titleEntries': [ {u'localeCode': u'en', u'value': u'Understanding the dynamics and issues'}, {u'localeCode': u'fr', u'value': u'Comprendre les dynamiques et les enjeux'}], u"isCustom": False, u"minimum": 0.0, u"maximum": 60.0, u"nbTicks": 7, u"unit": u"M€", u'voteSpecTemplateId': None, u'voteSessionId': vote_session_id}}} # remove created vote specification vote_session.vote_specifications.remove(vote_spec) vote_session.db.flush()
def test_mutation_update_landing_page_module(graphql_request, simple_landing_page_module): mutation = u""" mutation updateLandingPageModule ( $id: ID! $enabled: Boolean $order: Float $configuration: String $titleEntries: [LangStringEntryInput!] $subtitleEntries: [LangStringEntryInput!] ) { updateLandingPageModule ( id: $id enabled: $enabled order: $order configuration: $configuration titleEntries: $titleEntries subtitleEntries: $subtitleEntries ) { landingPageModule { titleEntries { value localeCode } subtitleEntries { value localeCode } configuration enabled moduleType { identifier title } order } } }""" res = schema.execute(mutation, context_value=graphql_request, variable_values={ 'id': to_global_id('LandingPageModule', simple_landing_page_module.id), 'enabled': False, 'order': 43.0, 'configuration': 'Standard_configuration_updated', 'titleEntries': [ {'value': "New section", 'localeCode': "en"} ], 'subtitleEntries': [ {'value': "New section with subtitle", 'localeCode': "en"} ] }) assert res.errors is None lpm = res.data[u'updateLandingPageModule']['landingPageModule'] assert lpm[u'configuration'] == 'Standard_configuration_updated' assert lpm[u'enabled'] is False assert lpm[u'order'] == 43.0 assert lpm[u'titleEntries'] == [ {'value': "New section", 'localeCode': "en"} ] assert lpm[u'subtitleEntries'] == [ {'value': "New section with subtitle", 'localeCode': "en"} ]
def test_graphq_query_accepted_cookie_by_user(graphql_request, participant2_user, agent_status_in_discussion_4, test_session, graphql_registry): from assembl.models.cookie_types import CookieTypes resp = schema.execute(graphql_registry["acceptedCookiesQuery"], context_value=graphql_request, variable_values={ "id": to_global_id("AgentProfile", participant2_user.id) }) assert resp.errors is None cookies_data = resp.data['user']['acceptedCookies'] assert CookieTypes.ACCEPT_CGU.value in cookies_data and CookieTypes.ACCEPT_SESSION_ON_DISCUSSION.value in cookies_data
def test_mutation_delete_proposal(graphql_request, vote_proposal, graphql_registry): mutation = graphql_registry['deleteProposal'] proposal_id = to_global_id("Idea", vote_proposal.id) res = schema.execute(mutation, context_value=graphql_request, variable_values={ "id": proposal_id }) assert res.errors is None assert True == res.data['deleteProposal']['success']
def test_mutation_delete_number_gauge_vote_specification(graphql_request, number_gauge_vote_specification, graphql_registry): mutation = graphql_registry['deleteVoteSpecification'] vote_spec_id = to_global_id("NumberGaugeVoteSpecification", number_gauge_vote_specification.id) res = schema.execute(mutation, context_value=graphql_request, variable_values={ "id": vote_spec_id }) assert res.errors is None assert True == res.data['deleteVoteSpecification']['success']
def resolve_actors(self, args, context, info): response = requests.get(FILMS_ENDPOINT.format(id=self.id)) data = response.json() return [relay.Node.get_node_from_global_id( to_global_id('Actor', actor_id), context, info ) for actor_id in data['actors']]
def mutate_and_get_payload(cls, input, context, info): viewer = get_viewer(context) todos = viewer.todos.filter(completed=True) deletedTodoIds = [] for todo in todos: deletedTodoIds.append(to_global_id("todo", todo.id)) todos.delete() return ClearCompletedTodo(viewer=viewer, deletedTodoIds=deletedTodoIds)
def test_mutation_delete_select_field(graphql_request, select_field, graphql_registry): mutation = graphql_registry['deleteTextField'] text_field_id = to_global_id("SelectField", select_field.id) res = schema.execute(mutation, context_value=graphql_request, variable_values={ "id": text_field_id }) assert res.errors is None assert res.data['deleteTextField']['success'] is True
def test_graphql_delete_user_with_username(graphql_request, participant1_user, test_session, participant1_username): """Testing to delete the username for participant1_user""" from assembl import models as m username = test_session.query(m.Username).filter(m.Username.user_id == participant1_user.id).first() assert username.username == "Test.Username" res = schema.execute(DELETE_USER_INFORMATION_MUTATION, context_value=graphql_request, variable_values={ "id": to_global_id('AgentProfile', participant1_user.id)}) assert res.errors is None username = test_session.query(m.Username).filter(m.Username.user_id == participant1_user.id).all() assert len(username) == 0
def test_graphql_delete_admin_user_alone(discussion_admin_user, graphql_request): """ Testing if it is possible to delete an admin user if he is the only admin user """ res = schema.execute(DELETE_USER_INFORMATION_MUTATION, context_value=graphql_request, variable_values={ "id": to_global_id('AgentProfile', discussion_admin_user.id) }) assert res.errors is not None assert res.errors[0].message == u"User can't delete his account because this is the only admin account"
def test_graphql_get_vote_session_unauthenticated(graphql_unauthenticated_request, vote_session, graphql_registry, subidea_1_1): response = schema.execute( graphql_registry['VoteSession'], context_value=graphql_unauthenticated_request, variable_values={ "ideaId": to_global_id("Idea", vote_session.idea_id), "lang": "en" } ) assert_graphql_unauthorized(response)
def test_mutation_update_number_gauge_vote_specification(graphql_request, vote_session, number_gauge_vote_specification, graphql_registry): mutation = graphql_registry['updateNumberGaugeVoteSpecification'] vote_session_id = to_global_id("VoteSession", vote_session.id) gauge_vote_spec_id = to_global_id("NumberGaugeVoteSpecification", number_gauge_vote_specification.id) res = schema.execute(mutation, context_value=graphql_request, variable_values={ "id": gauge_vote_spec_id, "titleEntries": [ {"value": u"Comprendre les dynamiques et les enjeux (updated)", "localeCode": "fr"}, {"value": u"Understanding the dynamics and issues (updated)", "localeCode": "en"} ], "instructionsEntries": [ {"value": u"Comprendre les dynamiques et les enjeux (updated)", "localeCode": "fr"}, {"value": u"Understanding the dynamics and issues (updated)", "localeCode": "en"} ], u"isCustom": False, u"minimum": 1.0, u"maximum": 80.0, u"nbTicks": 8, u"unit": u"M$", u'voteSessionId': vote_session_id }) assert res.errors is None assert json.loads(json.dumps(res.data)) == { u'updateNumberGaugeVoteSpecification': { u'voteSpecification': { u'id': gauge_vote_spec_id, u'instructionsEntries': [ {u'localeCode': u'en', u'value': u'Understanding the dynamics and issues (updated)'}, {u'localeCode': u'fr', u'value': u'Comprendre les dynamiques et les enjeux (updated)'}], u'titleEntries': [ {u'localeCode': u'en', u'value': u'Understanding the dynamics and issues (updated)'}, {u'localeCode': u'fr', u'value': u'Comprendre les dynamiques et les enjeux (updated)'}], u"isCustom": False, u"minimum": 1.0, u"maximum": 80.0, u"nbTicks": 8, u"unit": u"M$", u'voteSessionId': vote_session_id}}}
def token_vote_spec_with_votes(graphql_request, graphql_participant1_request, vote_session, vote_proposal, token_vote_specification_associated_to_proposal, graphql_registry): proposal_id = to_global_id("Idea", vote_proposal.id) token_category_id = to_global_id("TokenCategorySpecification", token_vote_specification_associated_to_proposal.token_categories[0].id) token_category2_id = to_global_id("TokenCategorySpecification", token_vote_specification_associated_to_proposal.token_categories[1].id) vote_spec_id = to_global_id("TokenVoteSpecification", token_vote_specification_associated_to_proposal.id) from assembl.graphql.schema import Schema as schema # participant1 votes on both categories res = schema.execute( graphql_registry['addTokenVote'], context_value=graphql_participant1_request, variable_values={ "proposalId": proposal_id, "tokenCategoryId": token_category_id, "voteSpecId": vote_spec_id, "voteValue": 3 } ) assert res.errors is None res = schema.execute( graphql_registry['addTokenVote'], context_value=graphql_participant1_request, variable_values={ "proposalId": proposal_id, "tokenCategoryId": token_category2_id, "voteSpecId": vote_spec_id, "voteValue": 2 } ) assert res.errors is None # admin user vote on one category res = schema.execute( graphql_registry['addTokenVote'], context_value=graphql_request, variable_values={ "proposalId": proposal_id, "tokenCategoryId": token_category2_id, "voteSpecId": vote_spec_id, "voteValue": 1 } ) assert res.errors is None return token_vote_specification_associated_to_proposal
def test_graphql_update_user_modify_password_passwords_mismatch(graphql_request, participant1_user, graphql_registry): graphql_request.authenticated_userid = participant1_user.id res = schema.execute(graphql_registry["updateUser"], context_value=graphql_request, variable_values={ "id": to_global_id('AgentProfile', participant1_user.id), "oldPassword": "******", "newPassword": "******", "newPassword2": "newsecret" # not the same password }) assert res.errors is not None assert res.errors[0].message == u"003: You entered two different passwords."
def test_graphql_delete_user_with_configurable_fields(graphql_request, participant1_user, profile_field_for_participant_user, test_session): """ Testing deletion of user with extra configurable text fields """ from assembl import models as m res = schema.execute(DELETE_USER_INFORMATION_MUTATION, context_value=graphql_request, variable_values={ "id": to_global_id('AgentProfile', participant1_user.id) }) assert res.errors is None extra_fields = test_session.query(m.ProfileField).filter(m.ProfileField.agent_profile_id == participant1_user.id).all() assert len(extra_fields) == 0
def test_graphql_update_user_modify_password_needs_to_be_different(graphql_request, participant1_user, graphql_registry): graphql_request.authenticated_userid = participant1_user.id res = schema.execute(graphql_registry["updateUser"], context_value=graphql_request, variable_values={ "id": to_global_id('AgentProfile', participant1_user.id), "oldPassword": "******", "newPassword": "******", "newPassword2": "password" }) assert res.errors is not None assert res.errors[0].message == u"004: The new password has to be different than the current password."
def test_graphql_update_user_modify_password_needs_to_be_different_from_previous_5_passwords_2( graphql_request, participant1_user, graphql_registry): graphql_request.authenticated_userid = participant1_user.id participant1_user.password_p = "password2" participant1_user.password_p = "password3" participant1_user.db.flush() res = schema.execute(graphql_registry["updateUser"], context_value=graphql_request, variable_values={ "id": to_global_id('AgentProfile', participant1_user.id), "oldPassword": "******", "newPassword": "******", "newPassword2": "password" }) assert res.errors is not None assert res.errors[ 0].message == u"005: The new password has to be different than the last 5 passwords you set."
def test_update_service_permissions(db, test_client, mocker, user_type, expected): """ ADMIN - Can update a new task service DEV - Can update a new task service USER - May not update new task services anonomous - May not update new task services """ mock_validate = mocker.patch( "coordinator.graphql.task_services.validate_endpoint") mock_validate.return_value = True service = TaskService(name="Test Service") service.save() relay_id = to_global_id("TaskServiceNode", service.kf_id) variables = { "taskService": relay_id, "input": { "name": "Test Task Service", "url": "TEST" }, } client = test_client(user_type) resp = client.post( "/graphql", format="json", data={ "query": UPDATE_SERVICE, "variables": variables }, ) if expected: assert ("kfId" in resp.json()["data"]["updateTaskService"]["taskService"]) else: assert "errors" in resp.json()
def test_client_value_reports(snapshot, request): """ Test success client value reports """ clients = ClientFactory.create_batch(size=3, created_date='2015-11-20') from_date = '2015-05-20' to_date = '2018-02-20' client = Client(schema) executed = client.execute( """ query clientValueReports( $clients:[ID], $fromDate:String, $toDate:String ) { clientValueReports( clients:$clients, fromDate:$fromDate, toDate:$toDate ) { id name value } } """, variable_values={ 'clients': [ to_global_id('ClientType', client_instance.id) for client_instance in clients ], 'fromDate': from_date, 'toDate': to_date, }, ) snapshot.assert_match(executed)
def test_mutation_delete_extract(graphql_request, extract_with_range_in_reply_post_1): extract_graphql_db_id = to_global_id('Extract', extract_with_range_in_reply_post_1.id) variable_values = {"extractId": extract_graphql_db_id} res = schema.execute(u""" mutation deleteExtract($extractId: ID!) { deleteExtract(extractId: $extractId) { success } } """, context_value=graphql_request, variable_values=variable_values) assert json.loads(json.dumps(res.data)) == { u'deleteExtract': { u'success': True } }
def test_mutation_create_proposal_no_root_thematic(graphql_request, discussion, vote_session, graphql_registry): mutation = graphql_registry['createProposal'] vote_session_id = to_global_id("VoteSession", vote_session.id) root_thematic = get_root_thematic_for_phase(vote_session.discussion_phase) vote_session.discussion_phase.root_idea = None root_thematic.delete() root_thematic.db.flush() res = schema.execute(mutation, context_value=graphql_request, variable_values={ "voteSessionId": vote_session_id, "titleEntries": [ {"value": u"Comprendre les dynamiques et les enjeux", "localeCode": "fr"}, {"value": u"Understanding the dynamics and issues", "localeCode": "en"} ], "descriptionEntries": [ {"value": u"Description: Comprendre les dynamiques et les enjeux", "localeCode": "fr"}, {"value": u"Description: Understanding the dynamics and issues", "localeCode": "en"} ] }) assert len(res.errors) == 1 assert 'no root thematic' in res.errors[0].message
def test_ws_applications_name_filter(handled_ws_application, api_client, name_filter): handled_ws_application.first_name = "John" handled_ws_application.last_name = "Doe" handled_ws_application.save() query = WS_APPLICATIONS_WITH_NAME_FILTER_QUERY % name_filter executed = api_client.execute(query) assert executed["data"] == { "winterStorageApplications": { "edges": [{ "node": { "id": to_global_id( WinterStorageApplicationNode._meta.name, handled_ws_application.id, ), } }] } }
def test_graphql_update_user_modify_password_needs_to_be_different_from_previous_5_passwords_3( graphql_request, participant1_user, graphql_registry): graphql_request.authenticated_userid = participant1_user.id participant1_user.password_p = "Puc71#0!D8" participant1_user.password_p = "Puc71#0!D83" participant1_user.password_p = "Puc71#0!D84" participant1_user.db.flush() res = schema.execute(graphql_registry["updateUser"], context_value=graphql_request, variable_values={ "id": to_global_id('AgentProfile', participant1_user.id), "oldPassword": "******", "newPassword": "******", "newPassword2": "hw5A^xYT1p&i" }) assert res.errors is not None assert res.errors[0].message == u"Please do not repeat an older password."
def test_mutation_create_batch(self): test_case_name = test_utils.get_test_case_name(self.test_case_list) self.test_case_list.append({"class": "ModelBatchOwner", "test_case": test_case_name}) # Create batch owner payload = '{"query": "mutation {createBatchOwner (input: {name:\\"%s\\"}) {batchOwner {id}}}"}' % test_case_name response = requests.post(self.base_url, headers=self.headers, data=payload) json = response.json() batch_owner_id = json['data']['createBatchOwner']['batchOwner']['id'] # Create batch status_id = to_global_id('SchemaStatus', 1) # Running input = '{batchOwnerId:\\"%s\\", statusId: \\"%s\\"}' % (batch_owner_id, status_id) payload = '{"query": "mutation {createBatch (input: %s) {batch {batchOwner {name} status {name}}}}"}' % (input) response = requests.post(self.base_url, headers=self.headers, data=payload) json = response.json() batch_owner_name = json['data']['createBatch']['batch']['batchOwner']['name'] status_name = json['data']['createBatch']['batch']['status']['name'] self.assertEqual(response.status_code, 200) self.assertEqual(batch_owner_name, test_case_name) self.assertEqual(status_name, 'Running')
def test_berth_applications_no_customer_filter_true(berth_application, api_client): berth_application.customer = None berth_application.save() query = BERTH_APPLICATIONS_WITH_NO_CUSTOMER_FILTER_QUERY % "true" executed = api_client.execute(query) assert executed["data"] == { "berthApplications": { "edges": [{ "node": { "id": to_global_id(BerthApplicationNode._meta.name, berth_application.id), "customer": None, } }] } }
def token_vote_specification(request, test_session, graphql_request, vote_session, graphql_registry): mutation = graphql_registry['createTokenVoteSpecification'] vote_session_id = to_global_id("VoteSession", vote_session.id) from assembl.graphql.schema import Schema as schema res = schema.execute(mutation, context_value=graphql_request, variable_values={ "voteSessionId": vote_session_id, "titleEntries": [ {"value": u"Comprendre les dynamiques et les enjeux", "localeCode": "fr"}, {"value": u"Understanding the dynamics and issues", "localeCode": "en"} ], "instructionsEntries": [ {"value": u"Comprendre les dynamiques et les enjeux", "localeCode": "fr"}, {"value": u"Understanding the dynamics and issues", "localeCode": "en"} ], "isCustom": False, "exclusiveCategories": True, "tokenCategories": [ {"titleEntries": [ {"value": u"Comprendre les dynamiques et les enjeux", "localeCode": "fr"}, {"value": u"Understanding the dynamics and issues", "localeCode": "en"} ], "typename": "positive", "totalNumber": 10, "color": 'red' } ] }) assert res.errors is None vote_spec = vote_session.vote_specifications[-1] def fin(): print "finalizer token_vote_specification" test_session.delete(vote_spec) test_session.flush() request.addfinalizer(fin) return vote_spec
def test_mutation_update_text_field(graphql_request, graphql_registry, text_field): text_field_id = to_global_id('TextField', text_field.id) res = schema.execute(graphql_registry['updateTextField'], context_value=graphql_request, variable_values={ "id": text_field_id, "lang": u"en", "titleEntries": [ { "localeCode": "en", "value": u"My new title" }, { "localeCode": "be", "value": u"Mon nouveau titre" }, ], "order": 8.0, "required": False, "hidden": False }) assert res.errors is None assert 'updateTextField' in res.data field = res.data['updateTextField']['field'] assert field[u'required'] is False assert field[u'hidden'] is False assert field[u'order'] == 8.0 title_entries = field['titleEntries'] assert title_entries[0]['localeCode'] == u'be' assert title_entries[0]['value'] == u'Mon nouveau titre' assert title_entries[1]['localeCode'] == u'en' assert title_entries[1]['value'] == u'My new title'
def test_normal_user_can_query_my_youth_profile(rf, user_gql_client): request = rf.post("/graphql") request.user = user_gql_client.user youth_profile = YouthProfileFactory(user=user_gql_client.user) query = """ { myYouthProfile { id schoolClass membershipNumber } } """ expected_data = { "myYouthProfile": { "id": to_global_id(type="YouthProfileNode", id=youth_profile.pk), "schoolClass": youth_profile.school_class, "membershipNumber": youth_profile.membership_number, } } executed = user_gql_client.execute(query, context=request) assert dict(executed["data"]) == expected_data
def test_publish_permissions(db, test_client, user_type, expected): """ ADMIN - Can publish a release DEV - May not publish a release USER - May not publish a relase anonomous - May not publish a release """ release = ReleaseFactory(state="staged") variables = {"release": to_global_id("ReleaseNode", release.kf_id)} client = test_client(user_type) resp = client.post( "/graphql", format="json", data={"query": PUBLISH_RELEASE, "variables": variables}, ) if expected: assert "kfId" in resp.json()["data"]["publishRelease"]["release"] else: assert "errors" in resp.json() assert "Not authenticated" in resp.json()["errors"][0]["message"]
def test_mutation_create_indicator(self): test_case_name = test_utils.get_test_case_name(self.test_case_list) self.test_case_list.append({"class": "ModelIndicator", "test_case": test_case_name}) self.test_case_list.append({"class": "ModelBatchOwner", "test_case": test_case_name}) # Create batch owner payload = '{"query": "mutation {createBatchOwner (input: {name:\\"%s\\"}) {batchOwner {id}}}"}' % test_case_name response = requests.post(self.base_url, headers=self.headers, data=payload) json = response.json() batch_owner_id = json['data']['createBatchOwner']['batchOwner']['id'] # Create indicator indicator_type_id = to_global_id('SchemaIndicatorType', 1) # Completeness input = '{name:\\"%s\\", description:\\"%s\\", indicatorTypeId:\\"%s\\", batchOwnerId:\\"%s\\", executionOrder: 1, active: true}' % (test_case_name, test_case_name, indicator_type_id, batch_owner_id) payload = '{"query": "mutation {createIndicator (input: %s) {indicator {name batchOwner {name}}}}"}' % input response = requests.post(self.base_url, headers=self.headers, data=payload) json = response.json() indicator_name = json['data']['createIndicator']['indicator']['name'] batch_owner_name = json['data']['createIndicator']['indicator']['batchOwner']['name'] self.assertEqual(response.status_code, 200) self.assertEqual(indicator_name, test_case_name) self.assertEqual(batch_owner_name, test_case_name)
def test_staff_user_can_query_own_youth_profile_by_id(rf, youth_profile, gql_client): request = rf.post("/graphql") request.user = gql_client.user profile_id = to_global_id(type="YouthProfileNode", id=youth_profile.pk) t = Template(""" { youthProfile(id: "${id}") { id schoolClass } } """) query = t.substitute(id=profile_id) expected_data = { "youthProfile": { "id": profile_id, "schoolClass": youth_profile.school_class } } executed = gql_client.execute(query, context=request) assert dict(executed["data"]) == expected_data
def test_graphql_update_user_check_username_uniqueness(graphql_request, participant1_user, participant2_user, graphql_registry): participant2_user.username_p = u"Barking.Loon" participant2_user.db.flush() res = schema.execute(graphql_registry["updateUser"], context_value=graphql_request, variable_values={ "id": to_global_id('AgentProfile', participant1_user.id), "name": u"M. Barking Loon", "username": u"Barking.Loon", }) assert res.errors is not None assert res.errors[ 0].message == u'001: We already have a user with this username.' # clean up participant2_user.username_p = None
def test_graphql_delete_user_information(participant1_user, graphql_request): from assembl.auth.password import random_string user_password = participant1_user.password_p user_username = participant1_user.username_p user_preferred_email = participant1_user.preferred_email user_last_assembl_login = participant1_user.last_assembl_login user_name = participant1_user.name user_old_passwords = participant1_user.old_passwords res = schema.execute(DELETE_USER_INFORMATION_MUTATION, context_value=graphql_request, variable_values={ "id": to_global_id('AgentProfile', participant1_user.id) }) assert res.errors is None assert participant1_user.is_deleted is True assert participant1_user.password != user_password assert participant1_user.preferred_email != user_preferred_email assert participant1_user.last_assembl_login != user_last_assembl_login assert participant1_user.name != user_name for p in participant1_user.old_passwords: for pa in user_old_passwords: assert pa != p.password
def test_notify_via_external_notification_trigger_without_permission( plugin_manager_notify_mock, staff_users, external_notification_trigger_query, staff_api_client, channel_PLN, ): variables = { "input": { "ids": [to_global_id(User.__name__, user.id) for user in staff_users], "extraPayload": "{}", "externalEventType": UserNotifyEvent.ORDER_CANCELED, }, "channel": channel_PLN.slug, "pluginId": PluginSample.PLUGIN_ID, } response = staff_api_client.post_graphql( external_notification_trigger_query, variables) assert_no_permission(response) plugin_manager_notify_mock.assert_not_called()
def test_graphql_get_profile_should_not_see_email(graphql_request, discussion_with_default_data, participant1_user, participant2_user): # participant2_user sould not see the email of participant1_user graphql_request.authenticated_userid = participant2_user.id res = schema.execute(u""" query User($id: ID!) { user: node(id: $id) { ... on AgentProfile { id name username displayName email } } } """, context_value=graphql_request, variable_values={ "id": to_global_id('AgentProfile', participant1_user.id) }) assert res.errors is None assert res.data['user']['name'] == u'A. Barking Loon' assert res.data['user']['username'] is None assert res.data['user']['displayName'] == u'A. Barking Loon' assert res.data['user']['email'] is None
def mutate_and_get_payload(cls, root, info, params): user = info.context.user # Create the bilby job bilby_job, supporting_file_details = create_bilby_job_from_ini_string(user, params) # Convert the bilby job id to a global id job_id = to_global_id("BilbyJobNode", bilby_job.id) files = [ BilbyJobSupportingFile( file_path=f['file_path'], token=f['token'] ) for f in supporting_file_details ] # Return the bilby job id to the client return BilbyJobFromIniStringMutation( result=BilbyJobCreationResult( job_id=job_id, supporting_files=files ) )
def test_graphql_vote_results(graphql_participant1_request, vote_session, vote_proposal, token_vote_spec_with_votes, gauge_vote_specification_with_votes, graphql_registry): res = schema.execute(graphql_registry['VoteSession'], context_value=graphql_participant1_request, variable_values={ "ideaId": to_global_id("Idea", vote_session.idea_id), "lang": "en" }) assert res.errors is None assert res.data['voteSession']['proposals'][0]['voteResults'][ 'numParticipants'] == 2 # names = {participant['displayName'] for participant in res.data['voteSession']['proposals'][0]['voteResults']['participants']} # assert names == set([u'A. Barking Loon', u'mr_admin_user']) # on token vote spec: assert res.data['voteSession']['proposals'][0]['modules'][0][ 'numVotes'] == 3 first_category = res.data['voteSession']['proposals'][0]['modules'][0][ 'tokenCategories'][0]['id'] second_category = res.data['voteSession']['proposals'][0]['modules'][0][ 'tokenCategories'][1]['id'] token_votes = { entry['tokenCategoryId']: entry['numToken'] for entry in res.data['voteSession']['proposals'][0]['modules'][0] ['tokenVotes'] } assert token_votes[first_category] == 3 assert token_votes[second_category] == 3 # on gauge vote spec: assert res.data['voteSession']['proposals'][0]['modules'][1][ 'numVotes'] == 1 assert res.data['voteSession']['proposals'][0]['modules'][1][ 'averageLabel'] == u'Tick 2' assert res.data['voteSession']['proposals'][0]['modules'][1][ 'averageResult'] == 20.0
def vote_proposal(request, test_session, discussion, graphql_request, vote_session, graphql_registry): mutation = graphql_registry['createProposal'] vote_session_id = to_global_id("VoteSession", vote_session.id) from assembl.graphql.schema import Schema as schema res = schema.execute( mutation, context_value=graphql_request, variable_values={ "voteSessionId": vote_session_id, "titleEntries": [{ "value": u"Comprendre les dynamiques et les enjeux", "localeCode": "fr" }, { "value": u"Understanding the dynamics and issues", "localeCode": "en" }], "descriptionEntries": [{ "value": u"Description: Comprendre les dynamiques et les enjeux", "localeCode": "fr" }, { "value": u"Description: Understanding the dynamics and issues", "localeCode": "en" }] }) assert res.errors is None proposal = vote_session.idea.children[0] def fin(): print("finalizer vote_proposal") test_session.delete(proposal) test_session.flush() request.addfinalizer(fin) return proposal
def test_graphql_update_user(graphql_request, participant1_user, graphql_registry): import os from io import BytesIO class FieldStorage(object): file = BytesIO(os.urandom(16)) def __init__(self, filename, type): self.filename = filename self.type = type graphql_request.POST['variables.img'] = FieldStorage( u'path/to/new-img.png', 'image/png') res = schema.execute(graphql_registry["updateUser"], context_value=graphql_request, variable_values={ "id": to_global_id('AgentProfile', participant1_user.id), "name": u"M. Barking Loon", "username": u"Barking.Loon", "img": u"variables.img" }) assert res.errors is None assert res.data['updateUser']['user']['name'] == u'M. Barking Loon' assert res.data['updateUser']['user']['username'] == u'Barking.Loon' assert res.data['updateUser']['user']['displayName'] == u'Barking.Loon' image = res.data['updateUser']['user']['image'] assert '/documents/' in image['externalUrl'] # clean up participant1_user.username_p = None
def test_mutation_update_extract_tags(graphql_request, extract_post_1_to_subidea_1_1): extract_graphql_db_id = to_global_id('Extract', extract_post_1_to_subidea_1_1.id) tags = ['foo', 'bar', 'tar'] variable_values = {"id": extract_graphql_db_id, "tags": tags} res = schema.execute(u""" mutation updateExtractTags( $id: ID! $tags: [String] ) { updateExtractTags( id: $id tags: $tags ) { tags { value } } } """, context_value=graphql_request, variable_values=variable_values) assert json.loads(json.dumps(res.data)) == { u'updateExtractTags': { u'tags': [{ u'value': u'foo' }, { u'value': u'bar' }, { u'value': u'tar' }] } }
def test_update_list_not_owner(client, list_, access_token): other_user = User.create(username="******", steam_id="bar") list_.user = other_user list_.save() url = url_for("graphql") list_id = to_global_id("TypeList", list_.id) res = client.post( url, headers={"Authorization": f"Bearer {access_token}"}, json={ "query": update_list_query, "variables": { "id": list_id, "name": "bar" } }, ) assert res.status_code == HTTPStatus.OK res = res.json assert not res["data"]["updateList"]
def test_graphql_update_user_modify_password_can_reuse_the_old_6th_password_set( graphql_request, participant1_user, graphql_registry): graphql_request.authenticated_userid = participant1_user.id participant1_user.password_p = "password2" participant1_user.password_p = "password3" participant1_user.password_p = "password4" participant1_user.password_p = "password5" participant1_user.db.flush() participant1_user.password_p = "password6" participant1_user.db.flush() res = schema.execute(graphql_registry["updateUser"], context_value=graphql_request, variable_values={ "id": to_global_id('AgentProfile', participant1_user.id), "oldPassword": "******", "newPassword": "******", "newPassword2": "password" }) assert res.errors is None
def test_berth_applications_statuses_filter(berth_application, api_client): berth_application.lease = BerthLeaseFactory() berth_application.status = ApplicationStatus.HANDLED berth_application.save() status_enum_str = ApplicationStatus.HANDLED.name query = BERTH_APPLICATIONS_WITH_STATUSES_FILTER_QUERY % status_enum_str executed = api_client.execute(query) assert executed["data"] == { "berthApplications": { "edges": [{ "node": { "id": to_global_id(BerthApplicationNode._meta.name, berth_application.id), "status": status_enum_str, } }] } }
def test_graphql_delete_admin_user_not_alone(discussion_admin_user, discussion_admin_user_2, graphql_request): """ Testing if is possible to delete an admin user when he is not the only admin """ from assembl.auth.password import random_string user_password = discussion_admin_user.password_p user_username = discussion_admin_user.username_p user_preferred_email = discussion_admin_user.preferred_email user_last_assembl_login = discussion_admin_user.last_assembl_login user_name = discussion_admin_user.name user_old_passwords = discussion_admin_user.old_passwords res = schema.execute(DELETE_USER_INFORMATION_MUTATION, context_value=graphql_request, variable_values={ "id": to_global_id('AgentProfile', discussion_admin_user.id) }) assert res.errors is None assert discussion_admin_user.is_deleted is True assert discussion_admin_user.password != user_password assert discussion_admin_user.preferred_email != user_preferred_email assert discussion_admin_user.last_assembl_login != user_last_assembl_login assert discussion_admin_user.name != user_name for p in discussion_admin_user.old_passwords: for pa in user_old_passwords: assert pa != p.password
def post(self, request, *args, **kwargs): serializerform = self.get_serializer(data=request.data) if not serializerform.is_valid(): raise exceptions.ParseError(detail='No valid values') user = authenticate( username=request.data['username'], password=request.data['password'], ) if user is not None: login(request, user) return response.Response({ 'user_id': to_global_id('IbisUserNode', str(user.id)), 'user_type': 'person' if models.Person.objects.filter( id=user.id) else 'nonprofit', }) else: return response.Response({ 'user_id': '', 'user_type': '', })
def test_cancel_release_from_state(db, admin_client, mocker, state, allowed): """ Test that a release is canceled correctly from any state """ mock_rq = mocker.patch("coordinator.graphql.releases.django_rq") release = ReleaseFactory(state=state) variables = {"release": to_global_id("ReleaseNode", release.kf_id)} resp = admin_client.post( "/graphql", format="json", data={"query": CANCEL_RELEASE, "variables": variables}, ) if allowed: # Check that the release task was queued assert mock_rq.enqueue.call_count == 1 assert ( resp.json()["data"]["cancelRelease"]["release"]["state"] == "canceling" ) else: assert "errors" in resp.json()