Exemplo n.º 1
0
def test_invalid_graphql_schema_string_causes_syntax_error():
    with pytest.raises(GraphQLSyntaxError):
        gql("""
                type User {
                    username String!
                }
            """)
Exemplo n.º 2
0
    def test_status_operator_success_t3(self):
        time_min = MDSTimeZone(
            date_time_now=datetime(2020, 1, 1, 0),
            offset=0,  # Not Needed
            time_zone="US/Central",  # US/Central
        )

        time_max = MDSTimeZone(
            date_time_now=datetime(2020, 1, 1, 17),
            offset=0,  # Not needed
            time_zone="US/Central",  # US/Central
        )

        mds_schedule = MDSSchedule(
            mds_config=mds_config,
            mds_gql=mds_gql,
            provider_name="jump",
            time_min=time_min.get_time_end(),
            time_max=time_max.get_time_end(),
        )

        query = mds_schedule.get_query()
        print("My good sir, query: " + query)
        assert isinstance(gql(query), str) \
               and "status_id: {_eq: 0}" in gql(query)
Exemplo n.º 3
0
def test_invalid_graphql_query_string_causes_syntax_error():
    with pytest.raises(GraphQLSyntaxError):
        gql("""
                query TestQuery {
                    auth
                    users
                        id
                        username
                    }
                }
            """)
Exemplo n.º 4
0
def test_non_null():
    schema = gql(
        """
    scalar Date
    scalar DateTime
    scalar JSON
    directive @policy on FIELD_DEFINITION

    type Query {
    _: Boolean
    }

    type Mutation {
    _: Boolean
    }

    type GraphQLTypes {
        nonNull: Int! @policy
    }
    """
    )

    from turbulette.apps.auth.directives import PolicyDirective

    with pytest.raises(SchemaError):
        make_executable_schema(
            schema,
            base_scalars_resolvers,
            snake_case_fallback_resolvers,
            directives={"policy": PolicyDirective},
        )
Exemplo n.º 5
0
def test_valid_graphql_schema_string_is_returned_unchanged():
    sdl = """
        type User {
            username: String!
        }
    """
    result = gql(sdl)
    assert sdl == result
Exemplo n.º 6
0
    def _load_schema(self) -> str:
        script_directory_path = os.path.dirname(os.path.realpath(__file__))
        schema_path = os.path.join(script_directory_path, "schema",
                                   "main.graphql")
        with io.open(schema_path) as file_pointer:
            schema_content = gql(file_pointer.read())

        return schema_content
Exemplo n.º 7
0
 def test_update_status_query_addtl_args_success_t1(self):
     query = mds_schedule_tester.get_schedule_update_status_query(
         schedule_id=-1,
         status_id=-1,
         payload="https://bucket.s3.aws.com/payload.json",
         message='{"message":"Success"}',
     )
     print("Update Mutation Query: " + query)
     assert isinstance(gql(query), str)
Exemplo n.º 8
0
async def test_date():
    schema = gql("""
        scalar Date
        scalar DateTime
        scalar JSON

        type Query {
            event: Event!
        }
        type Mutation {
            createEvent(date: Date!): Boolean!
        }
        type Event {
            date: Date!
        }
    """)

    query_event = """
    query {
        event {
            date
        }
    }
    """

    mutation_event = """
    mutation createEvent($date: Date!) {
        createEvent(date: $date)
    }
    """

    query_type = QueryType()
    mutation_type = MutationType()

    @mutation_type.field("createEvent")
    async def createEvent(obj, parent, **kwargs):
        return True

    @query_type.field("event")
    async def event(obj, parent, **kwargs):
        return {"date": datetime.now()}

    schema = make_executable_schema(schema, query_type, base_scalars_resolvers,
                                    snake_case_fallback_resolvers)

    await graphql(schema=schema, data={"query": query_event})
    await graphql(
        schema=schema,
        data={
            "query": mutation_event,
            "variables": {
                "date": "1789-07-07T12:00:00+02:00"
            },  # ISO 8601 datetime string
        },
    )
Exemplo n.º 9
0
    def test_login_required_decorator_with_valid_token(self):
        """Tests the login required decorator called with valid token"""
        type_definitions = ariadne.gql("""
            type Query {
                test: String!
            }
        """)

        query_type = ariadne.QueryType()

        def resolve_test(_, info):
            request = info.context
            self.assertTrue(hasattr(request, "user"))
            self.assertEqual(request.user, self.user)

            return "Test!"

        resolve_test = Mock(wraps=resolve_test)
        decorated_resolve_test = Mock(wraps=login_required(resolve_test))
        query_type.set_field("test", decorated_resolve_test)

        schema = ariadne.make_executable_schema([type_definitions],
                                                [query_type])

        middleware = [JSONWebTokenMiddleware()]

        token = JSONWebTokenBackend().create(self.user)

        request = HttpRequest()
        request.META[HTTP_AUTHORIZATION_HEADER] = f"Token {token}"

        settings = {
            "AUTHENTICATION_BACKENDS": (
                "django_ariadne_jwt.backends.JSONWebTokenBackend",
                "django.contrib.auth.backends.ModelBackend",
            )
        }

        with self.settings(**settings):
            ariadne.graphql_sync(
                schema,
                {
                    "query":
                    """
                    query {
                        test
                    }
                    """
                },
                context_value=request,
                middleware=middleware,
            )

            self.assertTrue(resolve_test.called)
Exemplo n.º 10
0
    def test_generate_gql_insert_success_t1(self):
        with open("tests/trip_sample_data_valid.json") as f:
            trip_data = json.load(f)

        mds_trip = MDSTrip(
            mds_config=mds_config, mds_pip=mds_pip, mds_gql=mds_gql, trip_data=trip_data
        )
        query = mds_trip.generate_gql_insert()
        print("GQL: ")
        print(query)
        assert isinstance(gql(query), str)
Exemplo n.º 11
0
def test_valid_graphql_query_string_is_returned_unchanged():
    query = """
        query TestQuery {
            auth
            users {
                id
                username
            }
        }
    """
    result = gql(query)
    assert query == result
Exemplo n.º 12
0
    def test_status_operator_t3(self):
        mds_cli = MDSCli(
            mds_config=mds_config,
            mds_gql=mds_gql,
            provider="veoride",
            interval=2,
            time_max="2020-1-1-2",
            time_min=None,
        )

        s = mds_cli.initialize_schedule()
        query = s.get_query()
        print("Query: " + str(query))
        assert isinstance(gql(query), str) \
            and "status_id: {_eq: 0}" in query
Exemplo n.º 13
0
    async def dummy_client(self, ):
        """
        Client for a dummy server
        """
        type_defs = ariadne.gql("""
            scalar JSON

            type Query {
                headers: JSON
                hello: String
                value_error_required: String!
                value_error: String
                type_error: String
                unauthenticated_error: String
                unauthorized_error: String
            }

            """)
        query = ariadne.QueryType()

        @query.field("hello")
        def hello(parent: Any, info: GraphQLResolveInfo):
            return "👋"

        @query.field("value_error")
        @query.field("value_error_required")
        def value_error(parent: Any, info: GraphQLResolveInfo):
            raise ValueError("this is a value error")

        @query.field("type_error")
        def type_error(parent: Any, info: GraphQLResolveInfo):
            raise TypeError("this is a type error")

        @query.field("unauthenticated_error")
        def unauthenticated_error(parent: Any, info: GraphQLResolveInfo):
            raise Unauthenticated("this is an unauthenticated error")

        @query.field("unauthorized_error")
        def unauthorized_error(parent: Any, info: GraphQLResolveInfo):
            raise Unauthorized("this is an unauthorized error")

        schema = make_executable_schema(type_defs, query)
        app = Starlette()
        app.mount("/", GraphQL(schema))
        async with httpx.Client(app=app,
                                base_url="http://prefect.io") as dummy_client:
            yield dummy_client
Exemplo n.º 14
0
    def test_no_time_min(self):

        time_max = MDSTimeZone(
            date_time_now=datetime(2020, 1, 1, 17),
            offset=0,  # One hour
            time_zone="US/Central",  # US/Central
        )

        mds_schedule = MDSSchedule(
            mds_config=mds_config,
            mds_gql=mds_gql,
            provider_name="jump",
            time_max=time_max.get_time_end(),
        )

        query = mds_schedule.get_query()
        print("Query: " + query)
        assert isinstance(gql(query), str)
Exemplo n.º 15
0
    def test_gql_catches_error(self):
        try:
            # This should crash regardless, causing the exception block to execute
            error_caught = isinstance(
                gql("""
                        {
                            NOT A GraphQL Query, this should be False!
                        }
                    """),
                str,
            )
            # If gql does not raise an exception, then the test failed
            error_caught = False
        except:
            # This block should always run
            error_caught = True

        assert error_caught
Exemplo n.º 16
0
 def test_gql_parses_graphql(self):
     assert isinstance(
         gql("""
                 query fetchPendingSchedules {
                     api_schedule(
                         limit: 1
                     ) {
                         provider_id
                         schedule_id
                         year
                         month
                         day
                         hour
                         status_id
                     }
                 }
             """),
         str,
     )
Exemplo n.º 17
0
type_defs = gql("""
    type Query {
        solve(problem: Problem!): [Result!]!
    }

    input IndepVarComp {
        id: ID!
        value: Float!
    }

    input ExecComp {
        id: ID!
        type: String!
        eq: String!
    }

    input Driver {
        id: ID!
        optimizer: String!
    }

    input DesignVar {
        id: ID!
        lower: Float!
        upper: Float!
    }

    input Objective {
        id: ID!
    }

    input Problem {
        id: ID!
        driver: Driver!
        indeps: [IndepVarComp!]!
        exdep: ExecComp!
        designVars: [DesignVar!]!
        objective: Objective!
    }

    type Result {
        id: ID!
        value: Float!
    }
""")
Exemplo n.º 18
0
    async def execute(
        self,
        query: Union[str, Dict[str, Any]],
        variables: Dict[str, Any] = None,
        headers: dict = None,
        raise_on_error: bool = True,
        as_box=True,
    ) -> dict:
        """
        Args:
            - query (Union[str, dict]): either a GraphQL query string or objects that are compatible
                with prefect.utilities.graphql.parse_graphql().
            - variables (dict): GraphQL variables
            - headers (dict): Headers to include with the GraphQL request
            - raise_on_error (bool): if True, a `ValueError` is raised whenever the GraphQL
                result contains an `errors` field.
            - as_box (bool): if True, a `box.Box` object is returned, which behaves like a dict
                but allows "dot" access in addition to key access.

        Returns:
            - dict: a dictionary of GraphQL info. If `as_box` is True, it will be a Box (dict subclass)

        Raises:
            - GraphQLSyntaxError: if the provided query is not a valid GraphQL query
            - ValueError: if `raise_on_error=True` and there are any errors during execution.
        """
        if not isinstance(query, str):
            query = parse_graphql(query)

        # validate query
        if prefect_server.config.debug:
            ariadne.gql(query)

        # timeout of 30 seconds
        response = await httpx.post(
            self.url,
            json=dict(query=query, variables=variables or {}),
            headers=headers or self.headers,
            timeout=30,
        )
        try:
            result = response.json()
        except json.decoder.JSONDecodeError as exc:
            self.logger.error("JSON Decode Error on {}".format(
                response.content.decode()))
            self.logger.error(exc)
            raise exc

        if raise_on_error and "errors" in result:
            if prefect_server.config.debug:
                self.log_query_debug_info(
                    query=query,
                    variables=variables or {},
                    errors=result["errors"],
                    headers=headers or self.headers,
                )
            raise ValueError(result["errors"])

        # convert to box
        if as_box:
            result = Box(result)

        return result
Exemplo n.º 19
0
        return None
    else:
        # Build as closure to keep scope clean.
        def buildClient(client=qClient):
            # Cached in regular use cases.
            if (client is None):
                logging.info('Building graphql client...')
                client = QClient(os.getenv('MAANA_ENDPOINT_URL'))
            return client

        return buildClient()


# Define types using Schema Definition Language (https://graphql.org/learn/schema/)
# Wrapping string in gql function provides validation and better error traceback
type_defs = gql(dsp_types)

# Map resolver functions to Query fields using QueryType
query = QueryType()
# Resolvers are simple python functions
resolver_compute_resultant(query)
resolver_make_butterwork_filter_mapper(query)
resolver_lfilter_1D_mapper(query)
resolver_compute_intensity(query)
resolver_compute_impact(query)
resolver_compute_1D_DFT(query)
resolver_create_data(query)
resolver_project_data(query)

# Create executable GraphQL schema
schema = make_executable_schema(type_defs, [query])
Exemplo n.º 20
0
from flask import Flask, json, request, jsonify
from ariadne import graphql_sync, make_executable_schema, gql, load_schema_from_path
from ariadne.constants import PLAYGROUND_HTML
from mongoengine import connect

type_defs = gql(load_schema_from_path("./dev/schema/"))
# schema = make_executable_schema(type_defs, query, mutation)
connect("blog")

app = Flask(__name__)


@app.route('/')
def hello_world():
    return 'Hello, world!'


@app.route('/graphql', methods=["GET"])
def graphql_playground():
    return PLAYGROUND_HTML, 200


@app.route("/graphql", methods=["POST"])
def graphql_server():
    data = request.get_json()
    success, result = graphql_sync(schema,
                                   data,
                                   context_value=request,
                                   debug=app.debug)
    status_code = 200 if success else 400
    return jsonify(result), status_code
Exemplo n.º 21
0

test_query = gql(
    """
        query getAnalytics($span: Int!) {
            analytics(span: $span) {
                users {
                    current
                    previous
                }
                threads {
                    current
                    previous
                }
                posts {
                    current
                    previous
                }
                attachments {
                    current
                    previous
                }
                dataDownloads {
                    current
                    previous
                }
            }
        }
    """
)

Exemplo n.º 22
0
from ariadne import gql, make_executable_schema

from core.schema.queries import query
from core.schema.mutations import mutation

type_defs = gql("""
    type Query {
        hello: String!
        url(hash: String!): Url!
    }

    type Mutation {
        createUrl(url: String!): Url!
    }

    type Url {
        id: ID!
        url: String!
        hash: String!
    }
""")

schema = make_executable_schema(type_defs, query, mutation)
Exemplo n.º 23
0
"""Example 02: Object Types.

Run with::

    $ uvicorn example:app
"""
from ariadne import ObjectType, QueryType, gql, make_executable_schema
from ariadne.asgi import GraphQL

# This is our schema
type_defs = gql(
    """
    type Book {
        title: String!
        year: Int!
    }

    type Query {
        books: [Book!]!
    }
"""
)

query = QueryType()  # our Query type


@query.field("books")  # Query.books
def resolve_books(*_):
    return [
        {"title": "The Color of Magic", "year": 1983},
        {"title": "The Light Fantastic", "year": 1986},
        {"title": "Equal Rites", "year": 1987},
Exemplo n.º 24
0
 def __init__(self, schema_str, engine_config):
     self._schema_str = gql(schema_str)
     self._table = CashGameTableAdapter(host=engine_config['host'],
                                        port=engine_config['port'])
     self._app = None
     self._players = {}
Exemplo n.º 25
0
from flask import Flask, request, jsonify
from ariadne import graphql_sync, make_executable_schema, gql, load_schema_from_path
from ariadne.constants import PLAYGROUND_HTML
# The model is where we'll define our resolvers
from model import query

# We'll create this schema soon
type_defs = gql(load_schema_from_path("./schema.graphql"))
schema = make_executable_schema(type_defs, query)

app = Flask(__name__)

@app.route("/graphql", methods=["GET"])
def graphql_playground():
    """Serve GraphiQL playground"""
    return PLAYGROUND_HTML, 200


@app.route("/graphql", methods=["POST"])
def graphql_server():
    data = request.get_json()

    success, result = graphql_sync(
        schema,
        data,
        context_value=request,
        debug=app.debug
    )

    status_code = 200 if success else 400
    return jsonify(result), status_code
Exemplo n.º 26
0
def load_typedef_from_schema():
    type_def = load_schema_from_path(join(dirname(dirname(__file__)), "./gql"))
    type_defs = gql(type_def)
    return type_defs
Exemplo n.º 27
0
from unittest.mock import ANY, Mock

import pytest
from ariadne import gql
from requests.exceptions import RequestException

from .... import __version__
from ..versioncheck import CACHE_KEY, CACHE_LENGTH, resolve_version

test_query = gql("{ version { status message description } }")


def mock_requests_get(mocker, mock):
    return mocker.patch("requests.get", return_value=Mock(json=mock))


def test_version_check_query_returns_error_if_misago_version_is_unreleased(
    admin_graphql_client, mocker
):
    mocker.patch("misago.graphql.admin.versioncheck.__released__", False)
    mock_requests_get(mocker, Mock(return_value={"info": {"version": "outdated"}}))
    result = admin_graphql_client.query(test_query)
    assert result["version"]["status"] == "ERROR"


def test_version_check_query_returns_success_if_site_is_updated(
    admin_graphql_client, mocker
):
    mocker.patch("misago.graphql.admin.versioncheck.__released__", True)
    mock_requests_get(mocker, Mock(return_value={"info": {"version": __version__}}))
    result = admin_graphql_client.query(test_query)
Exemplo n.º 28
0
    def test_login_required_decorator_without_valid_token(self):
        """Tests the login required decorator called without valid token"""
        type_definitions = ariadne.gql("""
            type Query {
                me: String!
                mustfail: String!
            }
        """)

        query_type = ariadne.QueryType()

        resolve_me = Mock(return_value="Me!")
        query_type.set_field("me", resolve_me)

        resolve_mustfail = Mock(return_value="FAIL!")
        decorated_resolve_mustfail = Mock(
            wraps=login_required(resolve_mustfail))
        query_type.set_field("mustfail", decorated_resolve_mustfail)

        schema = ariadne.make_executable_schema([type_definitions],
                                                [query_type])

        middleware = [JSONWebTokenMiddleware()]

        request = HttpRequest()

        settings = {
            "AUTHENTICATION_BACKENDS": (
                "django_ariadne_jwt.backends.JSONWebTokenBackend",
                "django.contrib.auth.backends.ModelBackend",
            )
        }

        with self.settings(**settings):
            success, result = ariadne.graphql_sync(
                schema,
                {
                    "query":
                    """
                    query {
                        me
                        mustfail
                    }
                    """
                },
                context_value=request,
                middleware=middleware,
            )

            self.assertTrue(resolve_me.called)
            self.assertFalse(resolve_mustfail.called)

            self.assertIsNotNone(result)
            self.assertIn("errors", result)

            test_field_error_found = False

            for error_data in result["errors"]:
                if "mustfail" in error_data["path"]:
                    test_field_error_found = True

            self.assertTrue(test_field_error_found)
Exemplo n.º 29
0
from ariadne import ObjectType, QueryType, gql, snake_case_fallback_resolvers, make_executable_schema
from ariadne.asgi import GraphQL

from models.person import Person

# Define types using Schema Definition Language (https://graphql.org/learn/schema/)
# Wrapping string in gql function provides validation and better error traceback
type_defs = gql("""
    type Query {
        people: [Person!]!
    }

    type Person {
        firstName: String
        lastName: String
        age: Int
        fullName: String
    }
""")

# Map resolver functions to Query fields using QueryType
query = QueryType()

# Resolvers are simple python functions
@query.field("people")
def resolve_people(*_):
    return [
        Person(first_name="John", last_name="Doe", age=21),
        Person(first_name="Bob", last_name="Boberson", age=24),
    ]
Exemplo n.º 30
0
from ariadne import ObjectType, make_executable_schema, gql
from ariadne.asgi import GraphQL
import json, os, uuid, requests, threading, time, copy

# load schema
schemaPath =  r"https://raw.githubusercontent.com/" \
              r"coordinated-systems-lab/cube-sat/" \
              r"main/graphql/mbse-metamodel.graphql"
schemaString = requests.get(schemaPath).text
type_defs = gql(schemaString)

# load system model
modelPath = r"https://raw.githubusercontent.com/" \
            r"coordinated-systems-lab/cube-sat/" \
            r"main/graphql/fire-sensing.json"
systemModel = json.loads(requests.get(modelPath).text)

# create storage for status response
status = {}
status['code'] = ""
status['message'] = ""

# create response templates
projectResponse = {}
projectResponse['status'] = status
systemModelResponse = {}
systemModelResponse['status'] = status

# create local storage for projects
projectList = []
projectList.append(systemModel['data']['cpsSystemModel']['project'])
        self.value = value


type_defs = ariadne.gql("""
    scalar JSON
    scalar DateTime
    scalar UUID

    type Query {
        json_input(json: JSON!): Int!
        json_output: JSON!

        datetime_input(dt: DateTime): Int!
        datetime_output: DateTime!

        uuid_input(uuid: UUID): String!
        uuid_output: UUID!
    }

    type Mutation {
        hello_mutation(input: InputType): JSON!
    }

    input InputType {
        u: UUID!
        j: JSON!
    }
    """)

query = ariadne.QueryType()
mutation = ariadne.MutationType()
Exemplo n.º 32
0
type_defs = gql("""
    type Event {
        name: String
        time: String
        state: String
        attendee: String
        links: String
        category: String
        date: String
        groupname: String
    }
    input EventInput {
        name: String!
        time: String!
        state: String!
        attendee: String!
        links: String!
        category: String!
        date: String!
        groupname: String!
    }
    type Query {
        events(name: String, state: String, date: String): [Event!]
    }
    type Mutation {
        add(event: EventInput!): Boolean!
        delete(id: String!): Boolean!
    }
""")