def test_mutation_add_extracts(graphql_request, top_post_in_thread_phase):
  post_db_id = int(from_global_id(top_post_in_thread_phase)[1])
  
  extract_body = u"manger des choux à la crème"
  xpathStart = u"//div[@id='message-body-local:Content/%s']/" % post_db_id
  xpathEnd = xpathStart
  offsetStart = 17
  offsetEnd = 44

  variable_values = {
    "extracts": [
      {
        "postId": top_post_in_thread_phase,
        "body": extract_body,
        "xpathStart": xpathStart,  
        "xpathEnd": xpathEnd,
        "offsetStart": offsetStart,
        "offsetEnd": offsetEnd,
        "lang": "fr"
      }
    ],
    "extractState": "SUBMITTED",
    "extractNature": "actionable_solution" 
  }

  post = models.AssemblPost.get(post_db_id)
  db = post.db
  def get_extracts():
      return db.query(
        models.Extract
        ).join(
        models.Content, models.Extract.content == post
        ).options(joinedload(models.Extract.text_fragment_identifiers)).all()

  assert len(get_extracts()) == 0
  res = schema.execute(u"""
mutation AddPostsExtract($extracts: [PostExtractEntryInput]!, $extractState: ExtractStates, $extractNature: ExtractNatures) {
  addPostsExtract(extracts: $extracts, extractState: $extractState, extractNature: $extractNature) {
    status
  }
}
""", context_value=graphql_request, variable_values=variable_values)

  assert json.loads(json.dumps(res.data)) == {
    u'addPostsExtract': {
      u'status': True
    }
  }
  assert len(get_extracts()) == 1

  # add the same extract
  res = schema.execute(u"""
mutation AddPostsExtract($extracts: [PostExtractEntryInput]!, $extractState: ExtractStates, $extractNature: ExtractNatures) {
  addPostsExtract(extracts: $extracts, extractState: $extractState, extractNature: $extractNature) {
    status
  }
}
""", context_value=graphql_request, variable_values=variable_values)
  # The extract must be ignored
  assert len(get_extracts()) == 1
def test_delete_resource(graphql_registry, graphql_request, resource):
    resource_id = to_global_id('Resource', resource.id)
    res = schema.execute(
        graphql_registry['deleteResource'],
        variable_values={
            "resourceId": resource_id
        },
        context_value=graphql_request)
    assert res.data['deleteResource']['success'] is True
    res = schema.execute(
        u'query { resources { id } }', context_value=graphql_request)
    assert json.loads(json.dumps(res.data)) == {u'resources': []}
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()
Beispiel #5
0
def test_query_tags(graphql_request, extract_post_1_to_subidea_1_1):
  variable_values = {
    "filter": ''
  }

  res = schema.execute(u"""
query tags($filter: String) {
  tags(filter: $filter) {
    value
  }
}
""", context_value=graphql_request, variable_values=variable_values)

  assert json.loads(json.dumps(res.data)) == {
    u'tags': [{u'value': u'foo'}, {u'value': u'bar'}]
  }

  variable_values = {
    "filter": 'f'
  }

  res = schema.execute(u"""
query tags($filter: String) {
  tags(filter: $filter) {
    value
  }
}
""", context_value=graphql_request, variable_values=variable_values)

  assert json.loads(json.dumps(res.data)) == {
    u'tags': [{u'value': u'foo'}]
  }

  variable_values = {
    "filter": 'test'
  }

  res = schema.execute(u"""
query tags($filter: String) {
  tags(filter: $filter) {
    value
  }
}
""", context_value=graphql_request, variable_values=variable_values)

  assert json.loads(json.dumps(res.data)) == {
    u'tags': []
  }
def test_query_landing_page_module_types(graphql_request):
    query = u"""query LandingPageModuleTypes($lang: String!) {
        landingPageModuleTypes {
            titleEntries {
                localeCode
                value
            }
            title(lang: $lang)
            defaultOrder
            editableOrder
            identifier
            required
        }
    }
    """
    res = schema.execute(
        query,
        context_value=graphql_request,
        variable_values={"lang": u"en"})
    assert res.errors is None
    assert len(res.data['landingPageModuleTypes']) == MODULES_COUNT
    for module_type in res.data['landingPageModuleTypes']:
        if module_type['identifier'] == 'INTRODUCTION':
            assert module_type['title'] == u'Text & Multimedia'
            assert module_type['defaultOrder'] == 2.0
            assert module_type['editableOrder'] is True
            assert module_type['required'] is False
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_create_text_field(graphql_request, graphql_registry, test_session):
    from assembl.models.configurable_fields import TextField
    res = schema.execute(
        graphql_registry['createTextField'],
        context_value=graphql_request,
        variable_values={
            "lang": u"en",
            "titleEntries": [
                { "localeCode": "en", "value": u"My new field" }
            ],
            "order": 4.0,
            "required": False,
            "hidden": False
        })
    assert res.errors is None
    assert 'createTextField' in res.data
    new_field = res.data['createTextField']['field']
    assert new_field[u'required'] is False
    assert new_field[u'hidden'] is False
    assert new_field[u'order'] == 4.0
    title_entries = new_field['titleEntries']
    assert title_entries[0]['localeCode'] == u'en'
    assert title_entries[0]['value'] == u'My new field'
    saobj = TextField.get(from_global_id(new_field[u'id'])[1])
    test_session.delete(saobj)
def test_query_profile_fields(graphql_request, graphql_registry, text_field2, profile_field):
    from assembl.models.configurable_fields import TextFieldsTypesEnum
    res = schema.execute(
        graphql_registry['ProfileFields'],
        context_value=graphql_request,
        variable_values={"lang": u"en"})
    assert res.errors is None
    assert len(res.data['profileFields']) == 2

    tf_with_value = res.data['profileFields'][0]
    assert int(from_global_id(tf_with_value['id'])[1]) == profile_field.id
    assert tf_with_value['configurableField']['title'] == u'My text field'
    assert tf_with_value['configurableField']['fieldType'] == TextFieldsTypesEnum.TEXT.value
    assert tf_with_value['configurableField']['order'] == 1.0
    assert tf_with_value['configurableField']['required'] is True
    assert tf_with_value['configurableField']['hidden'] is False
    assert tf_with_value['valueData'][u'value'] == u'*****@*****.**'

    generated_tf = res.data['profileFields'][1]
    assert int(from_global_id(generated_tf['id'])[1]) < 0
    assert generated_tf['configurableField']['fieldType'] == TextFieldsTypesEnum.EMAIL.value
    assert generated_tf['configurableField']['title'] == u'My other custom text field'
    assert generated_tf['configurableField']['order'] == 2.0
    assert generated_tf['configurableField']['required'] is False
    assert generated_tf['configurableField']['hidden'] is False
    assert generated_tf['valueData'][u'value'] is None
Beispiel #10
0
def test_mutation_add_extract_comment(admin_user, graphql_request, idea_in_thread_phase, top_post_in_thread_phase, extract_post_1_to_subidea_1_1):
    from graphene.relay import Node
    raw_id = int(Node.from_global_id(top_post_in_thread_phase)[1])
    from assembl.models import Post
    post = Post.get(raw_id)
    post.extracts.append(extract_post_1_to_subidea_1_1)
    post.db.flush()

    extract_id = extract_post_1_to_subidea_1_1.graphene_id()

    idea_id = idea_in_thread_phase
    res = schema.execute(u"""
        mutation createPost {
            createPost(
                ideaId:"%s",
                extractId:"%s",
                subject:"Manger des choux à la crème",
                body:"Je recommande de manger des choux à la crème, c'est très bon, et ça permet de maintenir l'industrie de la patisserie française."
            ) {
                post {
                    ... on Post {
                        parentExtractId
                    }
                }
            }
        }
        """ % (idea_id, extract_id), context_value=graphql_request)

    assert res.data['createPost']['post']['parentExtractId'] == extract_id
Beispiel #11
0
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
Beispiel #12
0
def thematic_with_question(phases, graphql_request):
    from assembl.graphql.schema import Schema as schema
    res = schema.execute(u"""
mutation myMutation {
    createThematic(
        messageViewOverride: "survey",
        titleEntries:[
            {value:"Comprendre les dynamiques et les enjeux", localeCode:"fr"},
            {value:"Understanding the dynamics and issues", localeCode:"en"}
        ],
        questions:[
            {titleEntries:[
                {value:"Comment qualifiez-vous l'emergence de l'Intelligence Artificielle dans notre société ?", localeCode:"fr"}
            ]},
        ],
        discussionPhaseId: """+unicode(phases['survey'].id)+u""",
    ) {
        thematic {
            ... on Idea {
                id,
                titleEntries { localeCode value },
                questions { id, titleEntries { localeCode value } }
            }
        }
    }
}
""", context_value=graphql_request)
    thematic_id = res.data['createThematic']['thematic']['id']
    first_question_id = res.data['createThematic']['thematic']['questions'][0]['id']
    return thematic_id, first_question_id
def test_mutation_create_discussion_phase(graphql_request, discussion_with_2_phase_interface_v2, graphql_registry):
    res = schema.execute(
        graphql_registry['createDiscussionPhase'],
        context_value=graphql_request,
        variable_values={
            "lang": u"en",
            "identifier": u"voteSession",
            "titleEntries": [
                { "localeCode": "en", "value": u"My new phase" }
            ],
            "start": '2018-01-20T09:01:00.000001Z',
            "end": '2018-05-20T00:00:00.100001Z',
            "order": 1.0
        }
    )
    assert res.errors is None
    phase = res.data['createDiscussionPhase']['discussionPhase']
    assert phase['id']
    assert phase['identifier'] == u'voteSession'
    assert phase['title'] == u'My new phase'
    assert phase['titleEntries'][0]['localeCode'] == u'en'
    assert phase['titleEntries'][0]['value'] == u'My new phase'
    assert phase['start'] == u'2018-01-20T09:01:00.000001+00:00'
    assert phase['end'] == u'2018-05-20T00:00:00.100001+00:00'
    assert phase['order'] == 1.0
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_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)'}]
        }}}
Beispiel #16
0
def thematic_with_image(phases, graphql_request):
    from assembl.graphql.schema import Schema as schema
    import os
    from io import BytesIO

    class FieldStorage(object):
        file = BytesIO(os.urandom(16))
        filename = u'path/to/image.png'
        type = 'image/png'

    graphql_request.POST['variables.file'] = FieldStorage()
    res = schema.execute(u"""
mutation createThematicWithImage($file: String!) {
    createThematic(
        messageViewOverride: "survey",
        titleEntries:[
            {value:"You can't program the card without transmitting the wireless AGP card!", localeCode:"en"}
        ],
        discussionPhaseId: """+unicode(phases['survey'].id)+u""",
        image: $file
    ) {
        thematic {
            ... on Idea {
                id,
                img { externalUrl }
            }
        }
    }
}
""", context_value=graphql_request, variable_values={ "file": "variables.file" })
    thematic_id = res.data['createThematic']['thematic']['id']
    return thematic_id
Beispiel #17
0
def create_proposal_x(graphql_request, first_question_id, idx, publication_state):
    from assembl.graphql.schema import Schema as schema
    from assembl.models import PublicationStates
    body = "une proposition {}".format(idx)
    if publication_state == PublicationStates.SUBMITTED_AWAITING_MODERATION.value:
        body = "une proposition en attente de validation {}".format(idx)

    res = schema.execute(u"""
mutation myFirstMutation {
    createPost(
        ideaId:"%s",
        body:"%s"
        publicationState:%s
    ) {
        post {
            ... on Post {
                id,
                body,
                creator { name },
            }
        }
    }
}
""" % (first_question_id, body, publication_state),
        context_value=graphql_request)
    return res.data['createPost']['post']['id']
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_query_resources(graphql_registry, discussion, resource, resource_with_image_and_doc, graphql_request):
    res = schema.execute(
        graphql_registry['ResourcesQuery'],
        variable_values={
            "lang": u"en"
        },
        context_value=graphql_request)
    assert res.data['resources'][0]['order'] == 1.0
    assert res.data['resources'][1]['order'] == 2.0

    first_resource = res.data['resources'][0]
    second_resource = res.data['resources'][1]

    assert first_resource['title'] == u'another resource'
    assert second_resource['title'] == u'a resource'

    assert second_resource['text'] == u'Lorem ipsum dolor sit amet'
    assert second_resource['embedCode'] == u'<iframe ...>'
    assert second_resource['doc'] == None
    assert second_resource['image'] == None

    assert '/documents/' in first_resource['image']['externalUrl']
    assert '/documents/' in first_resource['doc']['externalUrl']
    # this is the title of the File object, not the title of the ResourceAttachment object
    assert first_resource['doc']['title'] == "mydocument.pdf"
def test_graphql_get_synthesis(graphql_request,
                               user_language_preference_en_cookie,
                               synthesis_in_syntheses):
    synthesis_id = synthesis_in_syntheses.data['syntheses'][0]['id']
    res = schema.execute(
        u"""query SynthesisQuery($id: ID!, $lang: String) {
            synthesis: node(id: $id) {
              ... on Synthesis {
                id
                subject(lang: $lang)
                ideas {
                  ... on Idea {
                    id
                    live {
                      ... on Idea {
                        id
                        img { externalUrl }
                      }
                    }
                  }
                }
              }
            }
          }
        """,
        context_value=graphql_request,
        variable_values={
             "id": synthesis_id,
            "lang": "en"
        })
    assert len(res.data) == 1
    synthesis = res.data['synthesis']
    assert synthesis['subject'] == 'subject EN'
    assert len(synthesis['ideas']) == 2
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
Beispiel #22
0
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']
Beispiel #23
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_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_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 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 assert_vote_session_not_created(vote_session, graphql_request, graphql_registry):
    response = schema.execute(
        graphql_registry['VoteSession'],
        context_value=graphql_request,
        variable_values={"ideaId": vote_session, "lang": "en"}
    )
    assert response.errors is None
    assert response.data['voteSession'] is None
def assert_vote_session_not_created(vote_session, graphql_request, graphql_registry):
    response = schema.execute(
        graphql_registry['VoteSession'],
        context_value=graphql_request,
        variable_values={"ideaId": vote_session, "lang": "en"}
    )
    assert response.errors is None
    assert response.data['voteSession'] is None
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_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_query_has_resources_center(discussion, resource,
                                    resource_with_image_and_doc,
                                    graphql_request):
    query = u"""
query { hasResourcesCenter }
"""
    res = schema.execute(query, context_value=graphql_request)
    assert res.data['hasResourcesCenter'] is True
Beispiel #32
0
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']
Beispiel #34
0
def test_mutation_create_resource(graphql_registry, graphql_request):
    title_entries = [{
        "value": u"Première ressource",
        "localeCode": u"fr"
    }, {
        "value": u"First resource",
        "localeCode": u"en"
    }]
    text_entries = [{
        "value": u"Lorem ipsum dolor sit amet, consectetur adipisicing elit.",
        "localeCode": u"fr"
    }, {
        "value": u"Foobar",
        "localeCode": u"en"
    }]
    embed_code = u'iframe foobar'

    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/img.png', 'image/png')
    graphql_request.POST['variables.doc'] = FieldStorage(
        u'path/to/mydoc.pdf', 'application/pdf')

    res = schema.execute(graphql_registry['createResource'],
                         context_value=graphql_request,
                         variable_values={
                             "image": u"variables.img",
                             "doc": u"variables.doc",
                             "lang": u"fr",
                             "titleEntries": title_entries,
                             "textEntries": text_entries,
                             "embedCode": embed_code,
                             "order": 5.0
                         })
    result = res.data
    assert result is not None
    assert result['createResource'] is not None
    resource = result['createResource']['resource']
    assert resource['title'] == u'Première ressource'
    assert resource[
        'text'] == u'Lorem ipsum dolor sit amet, consectetur adipisicing elit.'
    assert resource['embedCode'] == u'iframe foobar'
    assert resource['order'] == 5.0

    assert '/documents/' in resource['image']['externalUrl']
    assert resource['image']['title'] == 'img.png'

    assert '/documents/' in resource['doc']['externalUrl']
    assert resource['doc']['title'] == 'mydoc.pdf'
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_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()
Beispiel #37
0
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
Beispiel #38
0
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
Beispiel #39
0
def test_graphql_has_syntheses(graphql_request,
                               user_language_preference_en_cookie,
                               synthesis_post_1):
    res = schema.execute(u"""query HasSynthesesQuery {
              hasSyntheses
            }
        """,
                         context_value=graphql_request)
    assert res.data['hasSyntheses']
Beispiel #40
0
def test_graphql_get_bright_mirror_noresult(phases, graphql_request,
                                            graphql_registry):
    res = schema.execute(
        graphql_registry['ThematicsQuery'],
        context_value=graphql_request,
        variable_values={'discussionPhaseId': phases['brightMirror'].id})

    assert res.errors is None
    assert len(res.data['thematics']) == 0
Beispiel #41
0
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
Beispiel #42
0
def bright_mirror(phases, graphql_request, graphql_registry, test_session):
    import os
    from io import BytesIO
    from assembl.graphql.schema import Schema as schema

    class FieldStorage(object):
        file = BytesIO(os.urandom(16))
        filename = u'path/to/img.png'
        type = 'image/png'

    graphql_request.POST['variables.img'] = FieldStorage()

    res = schema.execute(graphql_registry['createThematic'],
                         context_value=graphql_request,
                         variable_values={
                             'discussionPhaseId':
                             phases['brightMirror'].id,
                             'messageViewOverride':
                             'brightMirror',
                             'titleEntries': [{
                                 'value':
                                 u"Comprendre les dynamiques et les enjeux",
                                 'localeCode': u"fr"
                             }, {
                                 'value':
                                 u"Understanding the dynamics and issues",
                                 'localeCode': u"en"
                             }],
                             'descriptionEntries': [{
                                 'value': u"Desc FR",
                                 'localeCode': u"fr"
                             }, {
                                 'value': u"Desc EN",
                                 'localeCode': u"en"
                             }],
                             'image':
                             u'variables.img',
                             'announcement': {
                                 'titleEntries': [{
                                     'value': u"Title FR announce",
                                     'localeCode': u"fr"
                                 }, {
                                     'value': u"Title EN announce",
                                     'localeCode': u"en"
                                 }],
                                 'bodyEntries': [{
                                     'value': u"Body FR announce",
                                     'localeCode': u"fr"
                                 }, {
                                     'value': u"Body EN announce",
                                     'localeCode': u"en"
                                 }]
                             }
                         })

    bright_mirror_id = res.data['createThematic']['thematic']['id']
    return bright_mirror_id
Beispiel #43
0
def test_graphql_get_all_ideas_multiColumns_phase(
        graphql_request, user_language_preference_en_cookie, subidea_1,
        subidea_1_1_1, idea_message_column_positive,
        idea_message_column_negative,
        idea_message_column_positive_on_subidea_1_1):
    subidea_1.message_view_override = 'messageColumns'
    subidea_1.db.flush()
    # idea_message_column_positive/negative fixtures add columns on subidea_1
    # the ideas query should return only subidea_1
    # We have a column on subidea_1_1, but messageColumns is not enabled on it.
    res = schema.execute(
        u"""query AllIdeasQuery($lang: String!, $identifier: String!) {
            ideas(identifier: $identifier) {
              ... on Idea {
                id
                title(lang: $lang)
                titleEntries { value, localeCode }
                messageViewOverride
                numPosts
                numContributors
                numChildren(identifier: $identifier)
                parentId
                order
                posts(first:10) {
                  edges {
                    node {
                      ... on Post { subject body }
                    }
                  }
                }
              }
            }
            rootIdea {
              ... on Idea {
                id
              }
            }
        }
        """,
        context_value=graphql_request,
        variable_values={
            "identifier": u"multiColumns",
            "lang": u"en"
        })
    root_idea = res.data['rootIdea']
    assert root_idea['id'] is not None
    assert len(res.data['ideas']) == 1
    first_idea = res.data['ideas'][0]
    assert first_idea['title'] == u'Favor economic growth'
    assert first_idea['parentId'] == root_idea['id']
    assert first_idea['order'] == 0.0
    assert first_idea['numChildren'] == 0
    assert first_idea['messageViewOverride'] == 'messageColumns'
    assert res.errors is None
    # revert the changes for tests isolation
    subidea_1.message_view_override = None
    subidea_1.db.flush()
def test_mutation_update_discussion_phase(graphql_request,
                                          discussion_with_2_phase_interface_v2,
                                          timeline_phase2_interface_v2,
                                          graphql_registry):
    import os
    from io import BytesIO

    class FieldStorage(object):
        file = BytesIO(os.urandom(16))
        filename = u'path/to/img.png'
        type = 'image/png'

    graphql_request.POST['variables.image'] = FieldStorage()
    phase1 = discussion_with_2_phase_interface_v2.timeline_events[0]
    phase1_id = phase1.graphene_id()
    res = schema.execute(graphql_registry['updateDiscussionPhase'],
                         context_value=graphql_request,
                         variable_values={
                             "id":
                             phase1_id,
                             "lang":
                             u"en",
                             "identifier":
                             u"multiColumns",
                             "titleEntries": [{
                                 "localeCode": "en",
                                 "value": u"My new title"
                             }],
                             "descriptionEntries": [{
                                 "localeCode":
                                 "en",
                                 "value":
                                 u"My new description"
                             }],
                             "start":
                             '2018-01-20T09:01:00.000001Z',
                             "end":
                             '2018-05-20T00:00:00.100001Z',
                             "image":
                             u"variables.image",
                             "order":
                             1.0
                         })
    assert res.errors is None
    phase1_updated = res.data['updateDiscussionPhase']['discussionPhase']
    assert phase1_updated['id'] == phase1_id
    assert phase1_updated['identifier'] == 'multiColumns'
    assert phase1_updated['title'] == u'My new title'
    assert phase1_updated['titleEntries'][0]['localeCode'] == u'en'
    assert phase1_updated['titleEntries'][0]['value'] == u'My new title'
    assert phase1_updated['descriptionEntries'][0][
        'value'] == u'My new description'
    assert phase1_updated['start'] == u'2018-01-20T09:01:00.000001+00:00'
    assert phase1_updated['end'] == u'2018-05-20T00:00:00.100001+00:00'
    assert '/documents/' in phase1_updated['image']['externalUrl']
    assert phase1_updated['image']['mimeType'] == 'image/png'
    assert phase1_updated['order'] == 1.0
Beispiel #45
0
def second_thematic_with_questions(request, test_session, phases,
                                   graphql_request):
    from assembl.graphql.schema import Schema as schema
    res = schema.execute(u"""
mutation myMutation {
    createThematic(
        messageViewOverride: "survey",
        titleEntries:[
            {value:"AI revolution", localeCode:"en"}
        ],
        questions:[
            {titleEntries:[
                {value:"How does AI already impact us?", localeCode:"en"}
            ]},
            {titleEntries:[
                {value:"What are the most promising AI applications in the short term?", localeCode:"en"}
            ]},
            {titleEntries:[
                {value:"How would you explain algorithmic biases to a kid?", localeCode:"en"}
            ]},
            {titleEntries:[
                {value:"What sectors will be the most affected by AI?", localeCode:"en"}
            ]},
        ],
        discussionPhaseId: """ + unicode(phases['survey'].id) + u""",
    ) {
        thematic {
            ... on Idea {
                id
                order,
                titleEntries { localeCode value },
                questions { id, titleEntries { localeCode value } }
            }
        }
    }
}
""",
                         context_value=graphql_request)
    thematic_id = res.data['createThematic']['thematic']['id']
    question_ids = [
        question['id']
        for question in res.data['createThematic']['thematic']['questions']
    ]

    def fin():
        from assembl.models import Idea, Question
        idea = test_session.query(Idea).get(int(
            from_global_id(thematic_id)[1]))
        test_session.delete(idea)
        for question_id in question_ids:
            question = test_session.query(Question).get(
                int(from_global_id(question_id)[1]))
            test_session.delete(question)
        test_session.flush()

    request.addfinalizer(fin)
    return thematic_id, question_ids
Beispiel #46
0
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')

    user_id = to_global_id('AgentProfile', participant1_user.id)
    res = schema.execute(graphql_registry["updateUser"],
                         context_value=graphql_request, variable_values={
        "id": 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']

    # update only the user name
    res = schema.execute(graphql_registry["updateUser"],
                         context_value=graphql_request, variable_values={
        "id": user_id,
        "name": u"M. Barking Moon"
    })
    assert res.errors is None
    assert res.data['updateUser']['user']['name'] == u'M. Barking Moon'
    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
Beispiel #47
0
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
Beispiel #48
0
def create_proposal_x(graphql_request, first_question_id, idx):
    from assembl.graphql.schema import Schema as schema
    schema.execute(u"""
mutation myFirstMutation {
    createPost(
        ideaId:"%s",
        body:"une proposition %s"
    ) {
        post {
            ... on PropositionPost {
                id,
                body,
                creator { name },
            }
        }
    }
}
""" % (first_question_id, idx),
                   context_value=graphql_request)
Beispiel #49
0
def proposals_with_sentiments(graphql_request, proposals, admin_user):
    from assembl.graphql.schema import Schema as schema
    # add a sentiment to the first post
    proposal_id = proposals[0]
    mutation = u"""
mutation myFirstMutation {
    addSentiment(
        postId:"%s",
        type:%s
    ) {
      post {
        ... on Post {
          mySentiment
        }
      }
    }
}
""" % (proposal_id, 'LIKE')
    schema.execute(mutation, context_value=graphql_request)
def test_graphql_delete_synthesis(graphql_registry, graphql_request,
                                  fulltext_synthesis_post):
    fulltext_synthesis_post_id = to_global_id('Post',
                                              fulltext_synthesis_post.id)
    res = schema.execute(graphql_registry['deleteSynthesis'],
                         variable_values={"id": fulltext_synthesis_post_id},
                         context_value=graphql_request)
    assert res.errors is None
    assert res.data['deleteSynthesis']['success'] is True
    assert SynthesisPost.get(fulltext_synthesis_post.id) is None
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)
Beispiel #52
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):
    response = schema.execute(
        graphql_registry['VoteSession'],
        context_value=graphql_unauthenticated_request,
        variable_values={
            "discussionPhaseId": vote_session.discussion_phase_id,
            "lang": "en"
        }
    )
    assert_graphql_unauthorized(response)
Beispiel #54
0
def test_update_resource(graphql_registry, graphql_request, resource_with_image_and_doc):
    resource = resource_with_image_and_doc
    resource_id = to_global_id('Resource', resource.id)

    graphql_request.POST['variables.img'] = FakeUploadedFile(
        u'path/to/new-img.png', 'image/png')
    graphql_request.POST['variables.doc'] = FakeUploadedFile(
        u'path/to/new-doc.pdf', 'application/pdf')

    res = schema.execute(
        graphql_registry['updateResource'],
        context_value=graphql_request,
        variable_values={
            "id": resource_id,
            "image": u"variables.img",
            "doc": u"variables.doc",
            "embedCode": u"nothing",
            "lang": u"fr",
            "order": 42.0,
            "titleEntries": [
                {
                    "value": u"My resource",
                    "localeCode": u"en"
                },
                {
                    "value": u"Ma ressource",
                    "localeCode": u"fr"
                }
            ],
            "textEntries": [
                {
                    "value": u"Text in english",
                    "localeCode": u"en"
                },
                {
                    "value": u"Texte en français",
                    "localeCode": u"fr"
                }
            ],
        }
    )
    assert res.data is not None
    assert res.data['updateResource'] is not None
    assert res.data['updateResource']['resource'] is not None
    resource = res.data['updateResource']['resource']
    assert resource[u'title'] == u'Ma ressource'
    assert resource[u'text'] == u'Texte en français'
    assert resource[u'embedCode'] == u'nothing'
    assert resource[u'order'] == 42.0

    assert '/documents/' in resource['image']['externalUrl']
    assert resource['image']['title'] == 'new-img.png'

    assert '/documents/' in resource['doc']['externalUrl']
    assert resource['doc']['title'] == 'new-doc.pdf'
Beispiel #55
0
def test_mutation_create_resource(graphql_registry, graphql_request):
    title_entries = [
        {
            "value": u"Première ressource",
            "localeCode": u"fr"
        },
        {
            "value": u"First resource",
            "localeCode": u"en"
        }
    ]
    text_entries = [
        {
            "value": u"Lorem ipsum dolor sit amet, consectetur adipisicing elit.",
            "localeCode": u"fr"
        },
        {
            "value": u"Foobar",
            "localeCode": u"en"
        }
    ]
    embed_code = u'iframe foobar'

    graphql_request.POST['variables.img'] = FakeUploadedFile(
        u'path/to/img.png', 'image/png')
    graphql_request.POST['variables.doc'] = FakeUploadedFile(
        u'path/to/mydoc.pdf', 'application/pdf')

    res = schema.execute(
        graphql_registry['createResource'],
        context_value=graphql_request,
        variable_values={
            "image": u"variables.img",
            "doc": u"variables.doc",
            "lang": u"fr",
            "titleEntries": title_entries,
            "textEntries": text_entries,
            "embedCode": embed_code,
            "order": 5.0
        }
    )
    result = res.data
    assert result is not None
    assert result['createResource'] is not None
    resource = result['createResource']['resource']
    assert resource['title'] == u'Première ressource'
    assert resource['text'] == u'Lorem ipsum dolor sit amet, consectetur adipisicing elit.'
    assert resource['embedCode'] == u'iframe foobar'
    assert resource['order'] == 5.0

    assert '/documents/' in resource['image']['externalUrl']
    assert resource['image']['title'] == 'img.png'

    assert '/documents/' in resource['doc']['externalUrl']
    assert resource['doc']['title'] == 'mydoc.pdf'
Beispiel #56
0
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_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}}}
Beispiel #58
0
def test_mutation_add_sentiment_like_then_disagree(graphql_request,
                                                   proposition_id):
    res = schema.execute(u"""
mutation myFirstMutation {
    addSentiment(
        postId:"%s",
        type:LIKE
    ) {
    }
}
""" % proposition_id,
                         context_value=graphql_request)
    res = schema.execute(u"""
mutation myFirstMutation {
    addSentiment(
        postId:"%s",
        type:DISAGREE
    ) {
      post {
        ... on Post {
          sentimentCounts {
            like
            disagree
          }
          mySentiment
        }
      }
    }
}
""" % proposition_id,
                         context_value=graphql_request)
    assert json.loads(json.dumps(res.data)) == {
        u'addSentiment': {
            u'post': {
                u'sentimentCounts': {
                    u'like': 0,
                    u'disagree': 1,
                },
                u'mySentiment': u"DISAGREE"
            }
        }
    }
Beispiel #59
0
def test_mutation_create_select_field(graphql_request, graphql_registry,
                                      test_session):
    from assembl.models.configurable_fields import SelectField
    res = schema.execute(graphql_registry['createTextField'],
                         context_value=graphql_request,
                         variable_values={
                             "lang":
                             u"en",
                             "titleEntries": [{
                                 "localeCode": "en",
                                 "value": u"My new field"
                             }],
                             "order":
                             4.0,
                             "required":
                             False,
                             "hidden":
                             False,
                             "options": [{
                                 "labelEntries": [{
                                     "value": u"Option un",
                                     "localeCode": "fr"
                                 }, {
                                     "value": u"Option one",
                                     "localeCode": "en"
                                 }],
                                 "order":
                                 1.0,
                             }, {
                                 "labelEntries": [{
                                     "value": u"Option deux",
                                     "localeCode": "fr"
                                 }, {
                                     "value": u"Option two",
                                     "localeCode": "en"
                                 }],
                                 "order":
                                 2.0,
                             }]
                         })
    assert res.errors is None
    assert 'createTextField' in res.data
    new_field = res.data['createTextField']['field']
    assert new_field[u'required'] is False
    assert new_field[u'hidden'] is False
    assert new_field[u'order'] == 4.0
    assert len(new_field[u'options']) == 2
    assert new_field[u'options'][0]['label'] == u'Option one'
    assert new_field[u'options'][1]['label'] == u'Option two'
    title_entries = new_field['titleEntries']
    assert title_entries[0]['localeCode'] == u'en'
    assert title_entries[0]['value'] == u'My new field'
    saobj = SelectField.get(from_global_id(new_field[u'id'])[1])
    test_session.delete(saobj)
Beispiel #60
0
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