Python graphql_relay.to_global_id() Examples

The following are 30 code examples of graphql_relay.to_global_id(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module graphql_relay , or try the search function .
Example #1
Source File: test_object_identification.py    From graphene-gae with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_correctly_refetches_rebels(self):
        rebels_key = to_global_id('Faction', ndb.Key('Faction', 'rebels').urlsafe())
        query = '''
            query RebelsRefetchQuery {
              node(id: "%s") {
                id
                ... on Faction {
                  name
                }
              }
            }
          ''' % rebels_key

        expected = {
            'node': {
                'id': rebels_key,
                'name': 'Alliance to Restore the Republic'
            }
        }
        result = schema.execute(query)
        self.assertFalse(result.errors, msg=str(result.errors))
        self.assertDictEqual(result.data, expected) 
Example #2
Source File: test_schema.py    From caluma with GNU General Public License v3.0 6 votes vote down vote up
def test_schema_node(db, snapshot, request, node_type):
    """
    Add your model to parametrize for automatic global node testing.

    Requirement is that node and model have the same name
    """
    node_instance = request.getfixturevalue(node_type)
    global_id = to_global_id(node_instance.__class__.__name__, node_instance.pk)

    node_query = """
    query %(name)s($id: ID!) {
      node(id: $id) {
        ... on %(name)s {
          id
        }
      }
    }
    """ % {
        "name": node_instance.__class__.__name__
    }

    result = schema.execute(node_query, variable_values={"id": global_id})
    assert not result.errors
    assert result.data["node"]["id"] == global_id 
Example #3
Source File: test_type.py    From caluma with GNU General Public License v3.0 6 votes vote down vote up
def test_question_types(
    db, question, expected_typename, answer_factory, schema_executor
):
    global_id = to_global_id(expected_typename, question.pk)

    query = """
        query Question($id: ID!) {
            node(id: $id) {
              id
              __typename
            }
        }
    """

    result = schema_executor(query, variable_values={"id": global_id})
    assert not result.errors
    assert result.data["node"]["__typename"] == expected_typename 
Example #4
Source File: test_type.py    From caluma with GNU General Public License v3.0 6 votes vote down vote up
def test_answer_types(
    db, question, expected_typename, success, answer_factory, schema_executor
):
    answer = answer_factory(question=question)
    global_id = to_global_id(expected_typename, answer.pk)

    query = """
        query Answer($id: ID!) {
            node(id: $id) {
              id
              __typename
            }
        }
    """

    result = schema_executor(query, variable_values={"id": global_id})
    assert not result.errors == success
    if success:
        assert result.data["node"]["__typename"] == expected_typename 
Example #5
Source File: test_node.py    From graphql-relay-py with MIT License 6 votes vote down vote up
def describe_convert_global_ids():
    def to_global_id_converts_unicode_strings_correctly():
        my_unicode_id = "ûñö"
        g_id = to_global_id("MyType", my_unicode_id)
        assert g_id == "TXlUeXBlOsO7w7HDtg=="

        my_unicode_id = "\u06ED"
        g_id = to_global_id("MyType", my_unicode_id)
        assert g_id == "TXlUeXBlOtut"

    def from_global_id_converts_unicode_strings_correctly():
        my_unicode_id = "ûñö"
        my_type, my_id = from_global_id("TXlUeXBlOsO7w7HDtg==")
        assert my_type == "MyType"
        assert my_id == my_unicode_id

        my_unicode_id = "\u06ED"
        my_type, my_id = from_global_id("TXlUeXBlOtut")
        assert my_type == "MyType"
        assert my_id == my_unicode_id 
Example #6
Source File: test_types.py    From graphene-django-optimizer with MIT License 6 votes vote down vote up
def test_mutating_should_not_optimize(mocked_optimizer):
    Item.objects.create(id=7)

    info = create_resolve_info(schema, '''
        query {
            items(id: $id) {
                id
                foo
                children {
                    id
                    foo
                }
            }
        }
    ''')

    info.return_type = schema.get_type('SomeOtherItemType')
    result = DummyItemMutation.mutate(info, to_global_id('ItemNode', 7))
    assert result
    assert result.pk == 7
    assert mocked_optimizer.call_count == 0 
Example #7
Source File: test_object_identification.py    From graphene-gae with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_correctly_fetches_id_name_rebels(self):
        query = '''
            query RebelsQuery {
              rebels {
                id,
                name
              }
            }
          '''
        expected = {
            'rebels': {
                'id': to_global_id('Faction', ndb.Key('Faction', 'rebels').urlsafe()),
                'name': 'Alliance to Restore the Republic'
            }
        }
        result = schema.execute(query)
        self.assertFalse(result.errors, msg=str(result.errors))
        self.assertDictEqual(result.data, expected) 
Example #8
Source File: test_object_identification.py    From graphene-gae with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_correctly_fetches_id_name_empire(self):
        empire_key = to_global_id('Faction', ndb.Key('Faction', 'empire').urlsafe())
        query = '''
          query EmpireQuery {
            empire {
              id
              name
            }
          }
        '''
        expected = {
            'empire': {
                'id': empire_key,
                'name': 'Galactic Empire'
            }
        }
        result = schema.execute(query)
        self.assertFalse(result.errors, msg=str(result.errors))
        self.assertDictEqual(result.data, expected) 
Example #9
Source File: test_object_identification.py    From graphene-gae with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_correctly_refetches_id_name_empire(self):
        empire_key = to_global_id('Faction', ndb.Key('Faction', 'empire').urlsafe())
        query = '''
            query EmpireRefetchQuery {
              node(id: "%s") {
                id
                ... on Faction {
                  name
                }
              }
            }
          ''' % empire_key
        expected = {
            'node': {
                'id': empire_key,
                'name': 'Galactic Empire'
            }
        }
        result = schema.execute(query)
        self.assertFalse(result.errors, msg=str(result.errors))
        self.assertDictEqual(result.data, expected) 
Example #10
Source File: test_types.py    From django-graphql-extensions with MIT License 5 votes vote down vote up
def test_global_id(self):
        global_id_type = types.GlobalID()
        random_id = random.randint(1, 10 ** 10)
        global_id = to_global_id('Test', random_id)
        node = ast.StringValue(global_id)

        self.assertEqual(global_id_type.serialize(global_id), global_id)
        self.assertEqual(global_id_type.parse_literal(node), random_id) 
Example #11
Source File: __init__.py    From caluma with GNU General Public License v3.0 5 votes vote down vote up
def extract_global_id_input_fields(instance):
    global_id = to_global_id(type(instance).__name__, instance.pk)
    return {"id": global_id, "clientMutationId": "testid"} 
Example #12
Source File: test_case.py    From caluma with GNU General Public License v3.0 5 votes vote down vote up
def test_family_workitems(schema_executor, db, case_factory, work_item_factory):
    case = case_factory()
    child_case = case_factory(family=case)
    dummy_case = case_factory()
    work_item = work_item_factory(child_case=child_case, case=case)
    sub_work_item = work_item_factory(child_case=None, case=child_case)
    work_item_factory(child_case=None, case=dummy_case)

    query = """
        query CaseNode ($case: ID!) {
          node(id: $case) {
            ...on Case {
              familyWorkItems {
                edges {
                  node {
                    id
                  }
                }
              }
            }
          }
        }
    """

    variables = {"case": to_global_id("Case", case.pk)}
    result = schema_executor(query, variable_values=variables)

    assert not result.errors

    result_ids = [
        extract_global_id(edge["node"]["id"])
        for edge in result.data["node"]["familyWorkItems"]["edges"]
    ]

    assert sorted(result_ids) == sorted([str(work_item.id), str(sub_work_item.id)]) 
Example #13
Source File: test_form.py    From caluma with GNU General Public License v3.0 5 votes vote down vote up
def test_reorder_form_questions_duplicated_question(
    db, form, question, form_question, schema_executor
):

    query = """
        mutation ReorderFormQuestions($input: ReorderFormQuestionsInput!) {
          reorderFormQuestions(input: $input) {
            form {
              questions {
                edges {
                  node {
                    slug
                  }
                }
              }
            }
            clientMutationId
          }
        }
    """

    result = schema_executor(
        query,
        variable_values={
            "input": {
                "form": to_global_id(type(form).__name__, form.pk),
                "questions": [question.slug, question.slug],
            }
        },
    )
    assert result.errors 
Example #14
Source File: test_form.py    From caluma with GNU General Public License v3.0 5 votes vote down vote up
def test_remove_form_question(
    db, form, form_question, question, snapshot, schema_executor
):
    query = """
        mutation RemoveFormQuestion($input: RemoveFormQuestionInput!) {
          removeFormQuestion(input: $input) {
            form {
              questions {
                edges {
                  node {
                    slug
                  }
                }
              }
            }
            clientMutationId
          }
        }
    """

    result = schema_executor(
        query,
        variable_values={
            "input": {
                "form": to_global_id(type(form).__name__, form.pk),
                "question": to_global_id(type(question).__name__, question.pk),
            }
        },
    )

    assert not result.errors
    snapshot.assert_match(result.data) 
Example #15
Source File: test_form.py    From caluma with GNU General Public License v3.0 5 votes vote down vote up
def test_add_form_question(db, form, question, form_question_factory, schema_executor):
    form_questions = form_question_factory.create_batch(5, form=form)

    # initialize sorting keys
    for idx, form_question in enumerate(form_questions):
        form_question.sort = idx + 1
        form_question.save()

    query = """
        mutation AddFormQuestion($input: AddFormQuestionInput!) {
          addFormQuestion(input: $input) {
            form {
              questions {
                edges {
                  node {
                    slug
                  }
                }
              }
            }
            clientMutationId
          }
        }
    """

    result = schema_executor(
        query,
        variable_values={
            "input": {
                "form": to_global_id(type(form).__name__, form.pk),
                "question": to_global_id(type(question).__name__, question.pk),
            }
        },
    )

    assert not result.errors
    questions = result.data["addFormQuestion"]["form"]["questions"]["edges"]
    assert len(questions) == 6
    assert questions[-1]["node"]["slug"] == question.slug 
Example #16
Source File: test_document.py    From caluma with GNU General Public License v3.0 5 votes vote down vote up
def test_query_answer_node(db, answer, schema_executor):
    global_id = to_global_id("FloatAnswer", answer.pk)

    node_query = """
    query AnswerNode($id: ID!) {
      node(id: $id) {
        ... on FloatAnswer {
            value
        }
      }
    }
    """

    result = schema_executor(node_query, variable_values={"id": global_id})
    assert not result.errors 
Example #17
Source File: test_document.py    From caluma with GNU General Public License v3.0 5 votes vote down vote up
def test_save_document_answer_empty(
    db, snapshot, question, answer, schema_executor, delete_answer
):
    query = f"""
        mutation saveDocumentStringAnswer($input: SaveDocumentStringAnswerInput!) {{
          saveDocumentStringAnswer(input: $input) {{
            answer {{
              __typename
              ... on StringAnswer {{
                stringValue: value
              }}
            }}
            clientMutationId
          }}
        }}
    """

    inp = {
        "input": {
            "document": to_global_id("StringAnswer", answer.document.pk),
            "question": to_global_id("StringAnswer", answer.question.pk),
        }
    }

    if delete_answer:
        # delete answer to force create test instead of update
        Answer.objects.filter(pk=answer.pk).delete()

    result = schema_executor(query, variable_values=inp)

    assert not result.errors
    snapshot.assert_match(result.data) 
Example #18
Source File: test_global_id.py    From graphene with MIT License 5 votes vote down vote up
def test_global_id_defaults_to_info_parent_type():
    my_id = "1"
    gid = GlobalID()
    id_resolver = gid.get_resolver(lambda *_: my_id)
    my_global_id = id_resolver(None, Info(User))
    assert my_global_id == to_global_id(User._meta.name, my_id) 
Example #19
Source File: fields.py    From graphene-gae with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def resolve_key_to_string(self, entity, info, ndb=False):
        is_global_id = not ndb
        key_value = self.__ndb_key_prop._get_user_value(entity)
        if not key_value:
            return None

        if isinstance(key_value, list):
            return [to_global_id(self.__graphql_type_name, k.urlsafe()) for k in key_value] if is_global_id else [k.id() for k in key_value]

        return to_global_id(self.__graphql_type_name, key_value.urlsafe()) if is_global_id else key_value.id() 
Example #20
Source File: test_types.py    From graphene-gae with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def testQuery_repeatedKeyProperty(self):
        tk1 = Tag(name="t1").put()
        tk2 = Tag(name="t2").put()
        tk3 = Tag(name="t3").put()
        tk4 = Tag(name="t4").put()
        Article(headline="h1", summary="s1", tags=[tk1, tk2, tk3, tk4]).put()

        result = schema.execute('''
            query ArticleWithAuthorID {
                articles {
                    headline
                    authorId
                    tagIds
                    tags {
                        name
                    }
                }
            }
        ''')

        self.assertEmpty(result.errors)

        article = dict(result.data['articles'][0])
        self.assertListEqual(map(lambda k: to_global_id('TagType', k.urlsafe()), [tk1, tk2, tk3, tk4]), article['tagIds'])

        self.assertLength(article['tags'], 4)
        for i in range(0, 3):
            self.assertEqual(article['tags'][i]['name'], 't%s' % (i + 1)) 
Example #21
Source File: fields.py    From graphql-pynamodb with MIT License 5 votes vote down vote up
def get_edges_from_iterable(cls, iterable, model, info, edge_type=Edge, after=None, page_size=None):
        has_next = False

        key_name = get_key_name(model)
        after_index = 0
        if after:
            after_index = next((i for i, item in enumerate(iterable) if str(getattr(item, key_name)) == after), None)
            if after_index is None:
                return None
            else:
                after_index += 1

        if page_size:
            has_next = len(iterable) - after_index > page_size
            iterable = iterable[after_index:after_index + page_size]
        else:
            iterable = iterable[after_index:]

        # trigger a batch get to speed up query instead of relying on lazy individual gets
        if isinstance(iterable, RelationshipResultList):
            iterable = iterable.resolve()

        edges = [edge_type(node=entity, cursor=to_global_id(model.__name__, getattr(entity, key_name)))
                 for entity in iterable]

        return [has_next, edges] 
Example #22
Source File: node.py    From graphene with MIT License 5 votes vote down vote up
def id_resolver(parent_resolver, node, root, info, parent_type_name=None, **args):
        type_id = parent_resolver(root, info, **args)
        parent_type_name = parent_type_name or info.parent_type.name
        return node.to_global_id(parent_type_name, type_id)  # root._meta.name 
Example #23
Source File: test_node.py    From graphene with MIT License 5 votes vote down vote up
def test_node_field_only_lazy_type_wrong():
    executed = schema.execute(
        '{ onlyNodeLazy(id:"%s") { __typename, name } } '
        % Node.to_global_id("MyOtherNode", 1)
    )
    assert len(executed.errors) == 1
    assert str(executed.errors[0]).startswith("Must receive a MyNode id.")
    assert executed.data == {"onlyNodeLazy": None} 
Example #24
Source File: test_node.py    From graphene with MIT License 5 votes vote down vote up
def test_node_field_only_lazy_type():
    executed = schema.execute(
        '{ onlyNodeLazy(id:"%s") { __typename, name } } '
        % Node.to_global_id("MyNode", 1)
    )
    assert not executed.errors
    assert executed.data == {"onlyNodeLazy": {"__typename": "MyNode", "name": "1"}} 
Example #25
Source File: test_node.py    From graphene with MIT License 5 votes vote down vote up
def test_node_field_only_type_wrong():
    executed = schema.execute(
        '{ onlyNode(id:"%s") { __typename, name } } '
        % Node.to_global_id("MyOtherNode", 1)
    )
    assert len(executed.errors) == 1
    assert str(executed.errors[0]).startswith("Must receive a MyNode id.")
    assert executed.data == {"onlyNode": None} 
Example #26
Source File: test_node.py    From graphene with MIT License 5 votes vote down vote up
def test_node_field_only_type():
    executed = schema.execute(
        '{ onlyNode(id:"%s") { __typename, name } } ' % Node.to_global_id("MyNode", 1)
    )
    assert not executed.errors
    assert executed.data == {"onlyNode": {"__typename": "MyNode", "name": "1"}} 
Example #27
Source File: test_node.py    From graphene with MIT License 5 votes vote down vote up
def test_node_requesting_non_node():
    executed = schema.execute(
        '{ node(id:"%s") { __typename } } ' % Node.to_global_id("RootQuery", 1)
    )
    assert executed.errors
    assert re.match(
        r"ObjectType .* does not implement the .* interface.",
        executed.errors[0].message,
    )
    assert executed.data == {"node": None} 
Example #28
Source File: test_node.py    From graphene with MIT License 5 votes vote down vote up
def test_subclassed_node_query():
    executed = schema.execute(
        '{ node(id:"%s") { ... on MyOtherNode { shared, extraField, somethingElse } } }'
        % to_global_id("MyOtherNode", 1)
    )
    assert not executed.errors
    assert executed.data == {
        "node": {
            "shared": "1",
            "extraField": "extra field info.",
            "somethingElse": "----",
        }
    } 
Example #29
Source File: test_node.py    From graphene with MIT License 5 votes vote down vote up
def test_node_query():
    executed = schema.execute(
        '{ node(id:"%s") { ... on MyNode { name } } }' % Node.to_global_id("MyNode", 1)
    )
    assert not executed.errors
    assert executed.data == {"node": {"name": "1"}} 
Example #30
Source File: test_global_id.py    From graphene with MIT License 5 votes vote down vote up
def test_global_id_allows_setting_customer_parent_type():
    my_id = "1"
    gid = GlobalID(parent_type=User)
    id_resolver = gid.get_resolver(lambda *_: my_id)
    my_global_id = id_resolver(None, None)
    assert my_global_id == to_global_id(User._meta.name, my_id)