Example #1
0
    def initialize(
        self,
        schema=None,  # type: 
        executor=None,
        middleware=None,  # type: Optional[Any]
        root_value=None,  # type: Any
        graphiql=False,  # type: bool
        pretty=False,  # type: bool
        batch=False,  # type: bool
        backend=None,  # type: GraphQLBackend
        extensions=None  # type: List[Union[Callable[[], GraphQLExtension], GraphQLExtension]]
    ):
        super(TornadoGraphQLHandler, self).initialize()

        self.schema = schema

        middlewares = []
        if extensions:
            self.extension_stack = GraphQLExtensionStack(extensions)
            middlewares.extend([self.extension_stack.as_middleware()])

        if middleware is not None:
            middlewares.extend(list(self.instantiate_middleware(middleware)))

        if len(middlewares) > 0:
            self.middleware = middlewares

        self.executor = executor
        self.root_value = root_value
        self.pretty = pretty
        self.graphiql = graphiql
        self.batch = batch
        self.backend = backend or get_default_backend()
Example #2
0
def execute_query(query, variables=None, request=None, user=None):
    """Execute a query from the ORM.

    Args:
        - query (str): String with GraphQL query.
        - variables (dict, optional): If the query has variables they need to be passed in as a dictionary.
        - request (django.test.client.RequestFactory, optional): Used to authenticate.
        - user (django.contrib.auth.models.User, optional): Used to authenticate.

    Returns:
        GraphQL Object: Result for query
    """
    if not request and not user:
        raise ValueError("Either request or username should be provided")
    if not request:
        request = RequestFactory().post("/graphql/")
        request.user = user
    backend = get_default_backend()
    schema = graphene_settings.SCHEMA
    document = backend.document_from_string(schema, query)
    if variables:
        return document.execute(context_value=request,
                                variable_values=variables)
    else:
        return document.execute(context_value=request)
Example #3
0
def execute_graphql_request(
        schema,  # type: GraphQLSchema
        params,  # type: GraphQLParams
        allow_only_query=False,  # type: bool
        backend=None,  # type: GraphQLBackend
        **kwargs  # type: Dict
):
    if not params.query:
        raise HttpQueryError(400, "Must provide query string.")

    try:
        if not backend:
            backend = get_default_backend()
        document = backend.document_from_string(schema, params.query)
    except Exception as e:
        return ExecutionResult(errors=[e], invalid=True)

    if allow_only_query:
        operation_type = document.get_operation_type(params.operation_name)
        if operation_type and operation_type != "query":
            raise HttpQueryError(
                405,
                "Can only perform a {} operation from a POST request.".format(
                    operation_type),
                headers={"Allow": "POST"},
            )

    try:
        return document.execute(operation_name=params.operation_name,
                                variables=params.variables,
                                **kwargs)
    except Exception as e:
        return ExecutionResult(errors=[e], invalid=True)
Example #4
0
    def initialize(self,
                   schema=None,
                   executor=None,
                   middleware=None,
                   root_value=None,
                   graphiql=False,
                   pretty=False,
                   batch=False,
                   backend=None,
                   auth=None,
                   **kwargs):
        super(TornadoGraphQLHandler, self).initialize()
        self.auth = auth
        self.schema = schema

        if middleware is not None:
            self.middleware = list(self.instantiate_middleware(middleware))
        # Make authorization info available to auth middleware
        for mw in self.middleware:
            if isinstance(mw, AuthorizationMiddleware):
                mw.auth = self.auth
        self.executor = executor
        self.root_value = root_value
        self.pretty = pretty
        self.graphiql = graphiql
        self.batch = batch
        self.backend = backend or get_default_backend()
        # Set extra attributes
        for key, value in kwargs.items():
            if hasattr(self, key):
                setattr(self, key, value)
Example #5
0
    def __init__(self,
                 schema=None,
                 executor=None,
                 middleware=None,
                 root_value=None,
                 backend=None):
        if not schema:
            schema = graphene_settings.SCHEMA

        if backend is None:
            backend = get_default_backend()

        if middleware is None:
            middleware = graphene_settings.MIDDLEWARE

        self.graphql_schema = self.graphql_schema or schema

        if middleware is not None:
            if isinstance(middleware, MiddlewareManager):
                self.middleware = middleware
            else:
                self.middleware = list(instantiate_middleware(middleware))

        self.executor = executor
        self.root_value = root_value
        self.backend = backend

        assert isinstance(
            self.graphql_schema, GraphQLSchema
        ), "A Schema is required to be provided to GraphQLAPIView."
Example #6
0
    def initialize(self,
                   schema=None,
                   executor=None,
                   middleware=None,
                   root_value=None,
                   graphiql=False,
                   pretty=False,
                   batch=False,
                   backend=None,
                   **kwargs):
        super(TornadoGraphQLHandler, self).initialize()

        self.schema = schema
        if middleware is not None:
            self.middleware = list(self.instantiate_middleware(middleware))
        self.executor = executor
        self.root_value = root_value
        self.pretty = pretty
        self.graphiql = graphiql
        self.batch = batch
        self.backend = backend or get_default_backend()
        # Set extra attributes
        for key, value in kwargs.items():
            if hasattr(self, key):
                setattr(self, key, value)
Example #7
0
def graph_ql_query(request, device, query):
    """Function to run graphql and transposer command."""
    LOGGER.debug("GraphQL - request for `%s`", str(device))
    backend = get_default_backend()
    schema = graphene_settings.SCHEMA

    LOGGER.debug("GraphQL - set query variable to device.")
    variables = {"device_id": str(device.pk)}
    try:
        LOGGER.debug("GraphQL - test query: `%s`", str(query))
        document = backend.document_from_string(schema, query)

    except GraphQLSyntaxError as error:
        LOGGER.warning("GraphQL - test query Failed: `%s`", str(query))
        return (400, {"error": str(error)})

    LOGGER.debug("GraphQL - execute query with variables")
    result = document.execute(context_value=request, variable_values=variables)
    if result.invalid:
        LOGGER.warning("GraphQL - query executed unsuccessfully")
        return (400, result.to_dict())
    data = result.data

    data = data.get("device", {})

    if PLUGIN_CFG.get("sot_agg_transposer"):
        LOGGER.debug("GraphQL - tansform data with function: `%s`", str(PLUGIN_CFG.get("sot_agg_transposer")))
        try:
            data = import_string(PLUGIN_CFG.get("sot_agg_transposer"))(data)
        except Exception as error:  # pylint: disable=broad-except
            return (400, {"error": str(error)})

    LOGGER.debug("GraphQL - request successful")
    return (200, data)
def execute_graphql_request(schema,
                            params,
                            allow_only_query=False,
                            backend=None,
                            **kwargs):
    if not params.query:
        raise HttpQueryError(400, 'Must provide query string.')

    try:
        if not backend:
            backend = get_default_backend()
        document = backend.document_from_string(schema, params.query)
    except Exception as e:
        return ExecutionResult(errors=[e], invalid=True)

    if allow_only_query:
        operation_type = document.get_operation_type(params.operation_name)
        if operation_type and operation_type != 'query':
            raise HttpQueryError(
                405,
                'Can only perform a {} operation from a POST request.'.format(
                    operation_type),
                headers={
                    'Allow': 'POST',
                })

    try:
        return document.execute(operation_name=params.operation_name,
                                variables=params.variables,
                                **kwargs)
    except Exception as e:
        return ExecutionResult(errors=[e], invalid=True)
Example #9
0
    def __init__(self,
                 schema=None,
                 executor=None,
                 middleware=None,
                 root_value=None,
                 graphiql=False,
                 pretty=False,
                 batch=False,
                 backend=None):
        if not schema:
            schema = graphene_settings.SCHEMA

        if backend is None:
            backend = get_default_backend()

        if middleware is None:
            middleware = graphene_settings.MIDDLEWARE

        self.schema = self.schema or schema
        if middleware is not None:
            self.middleware = list(instantiate_middleware(middleware))
        self.executor = executor
        self.root_value = root_value
        self.pretty = self.pretty or pretty
        self.graphiql = self.graphiql or graphiql
        self.batch = self.batch or batch
        self.backend = backend

        assert isinstance(
            self.schema, GraphQLSchema
        ), 'A Schema is required to be provided to GraphQLView.'
        assert not all(
            (graphiql, batch)), 'Use either graphiql or batch processing'
Example #10
0
 def clean(self):
     super().clean()
     schema = graphene_settings.SCHEMA
     backend = get_default_backend()
     try:
         backend.document_from_string(schema, self.query)
     except GraphQLSyntaxError as error:
         raise ValidationError({"query": error})
Example #11
0
def validate_subscription_query(query: str) -> bool:
    from ..api import schema

    graphql_backend = get_default_backend()
    try:
        document = graphql_backend.document_from_string(schema, query)
    except (ValueError, GraphQLSyntaxError):
        return False
    if not check_document_is_single_subscription(document):
        return False
    return True
Example #12
0
 def __init__(
     self, schema=None, executor=None, middleware=None, root_value=None, backend=None
 ):
     super().__init__()
     if backend is None:
         backend = get_default_backend()
     if middleware is None:
         if middleware := settings.GRAPHENE.get("MIDDLEWARE"):
             middleware = [
                 self.import_middleware(middleware_name)
                 for middleware_name in middleware
             ]
Example #13
0
def anonymize_event_payload(
    subscription_query: Optional[str],
    event_type: str,  # pylint: disable=unused-argument
    payload: Any,
    sensitive_fields: SensitiveFieldsMap,
) -> Any:
    if not subscription_query:
        return payload
    graphql_backend = get_default_backend()
    document = graphql_backend.document_from_string(schema, subscription_query)
    if _contain_sensitive_field(document, sensitive_fields):
        return MASK
    return payload
Example #14
0
    def __init__(
        self,
        graphene_schema=None,
        graphene_executor=None,
        graphene_middleware=None,
        graphene_root_value=None,
        graphiql=False,
        graphene_pretty=False,
        graphene_batch=False,
        graphene_backend=None,
        graphene_validation_classes=None,
        graphene_subscription_path=None,
    ):
        if not graphene_schema:
            graphene_schema = graphene_settings.SCHEMA

        if graphene_backend is None:
            graphene_backend = get_default_backend()

        if graphene_subscription_path is None:
            self.graphene_subscription_path = graphene_settings.SUBSCRIPTION_PATH

        if graphene_middleware is None:
            graphene_middleware = graphene_settings.MIDDLEWARE

        if graphene_validation_classes is None:
            graphene_validation_classes = self.graphene_validation_classes

        self.graphene_schema = self.graphene_schema or graphene_schema
        if graphene_middleware is not None:
            if isinstance(graphene_middleware, MiddlewareManager):
                self.graphene_middleware = graphene_middleware
            else:
                self.graphene_middleware = list(
                    instantiate_middleware(graphene_middleware))
        self.graphene_executor = graphene_executor
        self.graphene_root_value = graphene_root_value
        self.graphene_pretty = self.graphene_pretty or graphene_pretty
        self.graphiql = self.graphiql or graphiql
        self.graphene_batch = self.graphene_batch or graphene_batch
        self.graphene_backend = graphene_backend
        self.graphene_validation_classes = graphene_validation_classes

        assert isinstance(
            self.graphene_schema, GraphQLSchema
        ), "A Schema is required to be provided to GraphQLView."
        assert not all(
            (graphiql,
             graphene_batch)), "Use either graphiql or batch processing"

        super().__init__()
Example #15
0
File: views.py Project: vonq/saleor
 def __init__(self,
              schema=None,
              executor=None,
              middleware=None,
              root_value=None,
              backend=None):
     super().__init__()
     if backend is None:
         backend = get_default_backend()
     self.schema = self.schema or schema
     if middleware is not None:
         self.middleware = list()
     self.executor = executor
     self.root_value = root_value
     self.backend = backend
Example #16
0
 def __init__(
     self, schema=None, executor=None, middleware=None, root_value=None, backend=None
 ):
     super().__init__()
     if schema is None:
         schema = graphene_settings.SCHEMA
     if backend is None:
         backend = get_default_backend()
     if middleware is None:
         middleware = graphene_settings.MIDDLEWARE
     self.schema = self.schema or schema
     if middleware is not None:
         self.middleware = list(instantiate_middleware(middleware))
     self.executor = executor
     self.root_value = root_value
     self.backend = backend
Example #17
0
 def __init__(
     self, schema=None, executor=None, middleware=None, root_value=None, backend=None
 ):
     super().__init__()
     if schema is None:
         schema = graphene_settings.SCHEMA
     if backend is None:
         backend = get_default_backend()
     if middleware is None:
         middleware = graphene_settings.MIDDLEWARE
     self.schema = self.schema or schema
     if middleware is not None:
         self.middleware = list(instantiate_middleware(middleware))
     self.executor = executor
     self.root_value = root_value
     self.backend = backend
Example #18
0
def execute_graphql_request(request, data, query, variables, operation_name):
    backend = get_default_backend()
    try:
        document = backend.document_from_string(schema, query)
    except Exception:
        raise

    try:
        return document.execute(
            root=None,
            variables=variables,
            operation_name=operation_name,
            context=request,
        )
    except Exception:
        raise
Example #19
0
def execute_graphql_request(
    schema,  # type: GraphQLSchema
    params,  # type: RequestParams
    allow_only_query=False,  # type: bool
    backend=None,  # type: GraphQLBackend
    **kwargs  # type: Any
):
    """Execute a GraphQL request and return an ExecutionResult.

    You need to pass the GraphQL schema and the GraphQLParams that you can get
    with the get_graphql_params() function. If you only want to allow GraphQL query
    operations, then set allow_only_query=True. You can also specify a custom
    GraphQLBackend instance that shall be used by GraphQL-Core instead of the
    default one. All other keyword arguments are passed on to the GraphQL-Core
    function for executing GraphQL queries.
    """
    if not params.query:
        raise HttpQueryError(400, "Must provide query string.")

    try:
        if not backend:
            backend = get_default_backend()
        document = backend.document_from_string(schema, params.query)
    except Exception as e:
        return ExecutionResult(errors=[e], invalid=True)

    if allow_only_query:
        operation_type = document.get_operation_type(params.operation_name)
        if operation_type and operation_type != "query":
            raise HttpQueryError(
                405,
                "Can only perform a {} operation from a POST request.".format(
                    operation_type
                ),
                headers={"Allow": "POST"},
            )

    try:
        return document.execute(
            operation_name=params.operation_name, variables=params.variables, **kwargs
        )
    except Exception as e:
        return ExecutionResult(errors=[e], invalid=True)
    def initialize(self,
                   schema=None,
                   executor=None,
                   middleware=None,
                   root_value=None,
                   graphiql=False,
                   pretty=False,
                   batch=False,
                   backend=None):
        super(TornadoGraphQLHandler, self).initialize()

        self.schema = schema
        if middleware is not None:
            self.middleware = list(self.instantiate_middleware(middleware))
        self.executor = executor
        self.root_value = root_value
        self.pretty = pretty
        self.graphiql = graphiql
        self.batch = batch
        self.backend = backend or get_default_backend()
Example #21
0
    def __init__(
        self,
        schema=None,
        executor=None,
        middleware=None,
        root_value=None,
        graphiql=False,
        pretty=False,
        batch=False,
        backend=None,
        subscription_path=None,
    ):
        if not schema:
            schema = graphene_settings.SCHEMA

        if backend is None:
            backend = get_default_backend()

        if middleware is None:
            middleware = graphene_settings.MIDDLEWARE

        self.schema = self.schema or schema
        if middleware is not None:
            if isinstance(middleware, MiddlewareManager):
                self.middleware = middleware
            else:
                self.middleware = list(instantiate_middleware(middleware))
        self.executor = executor
        self.root_value = root_value
        self.pretty = self.pretty or pretty
        self.graphiql = self.graphiql or graphiql
        self.batch = self.batch or batch
        self.backend = backend
        if subscription_path is None:
            self.subscription_path = graphene_settings.SUBSCRIPTION_PATH

        assert isinstance(
            self.schema, GraphQLSchema
        ), "A Schema is required to be provided to GraphQLView."
        assert not all(
            (graphiql, batch)), "Use either graphiql or batch processing"
Example #22
0
    def save(self, *args, **kwargs):
        variables = {}
        schema = graphene_settings.SCHEMA
        backend = get_default_backend()
        # Load query into GraphQL backend
        document = backend.document_from_string(schema, self.query)

        # Inspect the parsed document tree (document.document_ast) to retrieve the query (operation) definition(s)
        # that define one or more variables. For each operation and variable definition, store the variable's
        # default value (if any) into our own "variables" dict.
        definitions = [
            d for d in document.document_ast.definitions
            if isinstance(d, OperationDefinition) and d.variable_definitions
        ]
        for definition in definitions:
            for variable_definition in definition.variable_definitions:
                default = variable_definition.default_value.value if variable_definition.default_value else ""
                variables[variable_definition.variable.name.value] = default

        self.variables = variables
        return super().save(*args, **kwargs)
    def clean(self):
        """Validate there is only one model and if there is a GraphQL query, that it is valid."""
        if str(self.pk) != "aaaaaaaa-0000-0000-0000-000000000001":
            raise ValidationError(
                "Only one entry with pk aaaaaaaa-0000-0000-0000-000000000001 is permitted"
            )

        if self.sot_agg_query:
            try:
                LOGGER.debug("GraphQL - test query: `%s`",
                             str(self.sot_agg_query))
                backend = get_default_backend()
                schema = graphene_settings.SCHEMA
                backend.document_from_string(schema, str(self.sot_agg_query))
            except GraphQLSyntaxError as error:
                raise ValidationError(str(error))  # pylint: disable=raise-missing-from
            graphql_start = "query ($device: String!)"
            if not str(self.sot_agg_query).startswith(graphql_start):
                raise ValidationError(
                    f"The GraphQL query must start with exactly `{graphql_start}`"
                )
    def clean(self):
        """Validate there is only one model and if there is a GraphQL query, that it is valid."""
        super().clean()

        if self.sot_agg_query:
            try:
                LOGGER.debug("GraphQL - test query: `%s`",
                             str(self.sot_agg_query))
                backend = get_default_backend()
                schema = graphene_settings.SCHEMA
                backend.document_from_string(schema, str(self.sot_agg_query))
            except GraphQLSyntaxError as error:
                raise ValidationError(str(error))  # pylint: disable=raise-missing-from

            LOGGER.debug("GraphQL - test  query start with: `%s`",
                         GRAPHQL_STR_START)
            if not str(self.sot_agg_query).startswith(GRAPHQL_STR_START):
                raise ValidationError(
                    f"The GraphQL query must start with exactly `{GRAPHQL_STR_START}`"
                )

        if self.scope:
            filterset_class = get_filterset_for_model(Device)
            filterset = filterset_class(self.scope, Device.objects.all())

            if filterset.errors:
                for key in filterset.errors:
                    error_message = ", ".join(filterset.errors[key])
                    raise ValidationError({"scope": f"{key}: {error_message}"})

            filterset_params = set(filterset.get_filters().keys())
            for key in self.scope.keys():
                if key not in filterset_params:
                    raise ValidationError({
                        "scope":
                        f"'{key}' is not a valid filter parameter for Device object"
                    })
Example #25
0
    def __init__(
        self,
        graphene_schema=None,
        graphene_executor=None,
        graphene_middleware=None,
        graphene_root_value=None,
        graphiql=False,
        graphene_pretty=False,
        graphene_batch=False,
        graphene_backend=None,
    ):
        if not graphene_schema:
            graphene_schema = graphene_settings.SCHEMA

        if graphene_backend is None:
            graphene_backend = get_default_backend()

        if graphene_middleware is None:
            graphene_middleware = graphene_settings.MIDDLEWARE

        self.graphene_schema = self.graphene_schema or graphene_schema
        if graphene_middleware is not None:
            self.graphene_middleware = list(
                instantiate_middleware(graphene_middleware))
        self.graphene_executor = graphene_executor
        self.graphene_root_value = graphene_root_value
        self.graphene_pretty = self.graphene_pretty or graphene_pretty
        self.graphiql = self.graphiql or graphiql
        self.graphene_batch = self.graphene_batch or graphene_batch
        self.graphene_backend = graphene_backend

        assert isinstance(
            self.graphene_schema, GraphQLSchema
        ), "A Schema is required to be provided to GraphQLView."
        assert not all(
            (graphiql,
             graphene_batch)), "Use either graphiql or batch processing"
Example #26
0
def generate_payload_from_subscription(
    event_type: str,
    subscribable_object,
    subscription_query: Optional[str],
    context: HttpRequest,
    app: Optional[App] = None,
) -> Optional[Dict[str, Any]]:
    """Generate webhook payload from subscription query.

    It uses a graphql's engine to build payload by using the same logic as response.
    As an input it expects given event type and object and the query which will be
    used to resolve a payload.
    event_type: is a event which will be triggered.
    subscribable_object: is a object which have a dedicated own type in Subscription
    definition.
    subscription_query: query used to prepare a payload via graphql engine.
    context: A dummy request used to share context between apps in order to use
    dataloaders benefits.
    app: the owner of the given payload. Required in case when webhook contains
    protected fields.
    return: A payload ready to send via webhook. None if the function was not able to
    generate a payload
    """
    from ..api import schema
    from ..context import get_context_value

    graphql_backend = get_default_backend()
    ast = parse(subscription_query)  # type: ignore
    document = graphql_backend.document_from_string(
        schema,
        ast,
    )
    app_id = app.pk if app else None

    context.app = app  # type: ignore

    results = document.execute(
        allow_subscriptions=True,
        root=(event_type, subscribable_object),
        context=get_context_value(context),
    )
    if hasattr(results, "errors"):
        logger.warning(
            "Unable to build a payload for subscription. \n"
            "error: %s" % str(results.errors),
            extra={
                "query": subscription_query,
                "app": app_id
            },
        )
        return None
    payload = []  # type: ignore
    results.subscribe(payload.append)

    if not payload:
        logger.warning(
            "Subscription did not return a payload.",
            extra={
                "query": subscription_query,
                "app": app_id
            },
        )
        return None

    payload_instance = payload[0]
    event_payload = payload_instance.data.get("event")

    # Queries that use dataloaders return Promise object for the "event" field. In that
    # case, we need to resolve them first.
    if isinstance(event_payload, Promise):
        return event_payload.get()

    return event_payload
Example #27
0
    def setUp(self):
        """Initialize the Database with some datas."""
        super().setUp()
        self.user = User.objects.create(username="******",
                                        is_active=True,
                                        is_superuser=True)

        # Initialize fake request that will be required to execute GraphQL query
        self.request = RequestFactory().request(
            SERVER_NAME="WebRequestContext")
        self.request.id = uuid.uuid4()
        self.request.user = self.user

        self.backend = get_default_backend()
        self.schema = graphene_settings.SCHEMA

        # Populate Data
        manufacturer = Manufacturer.objects.create(name="Manufacturer 1",
                                                   slug="manufacturer-1")
        self.devicetype = DeviceType.objects.create(manufacturer=manufacturer,
                                                    model="Device Type 1",
                                                    slug="device-type-1")
        self.devicerole1 = DeviceRole.objects.create(name="Device Role 1",
                                                     slug="device-role-1")
        self.devicerole2 = DeviceRole.objects.create(name="Device Role 2",
                                                     slug="device-role-2")
        self.status1 = Status.objects.create(name="status1", slug="status1")
        self.status2 = Status.objects.create(name="status2", slug="status2")
        self.region1 = Region.objects.create(name="Region1", slug="region1")
        self.region2 = Region.objects.create(name="Region2", slug="region2")
        self.site1 = Site.objects.create(name="Site-1",
                                         slug="site-1",
                                         asn=65000,
                                         status=self.status1,
                                         region=self.region1)
        self.site2 = Site.objects.create(name="Site-2",
                                         slug="site-2",
                                         asn=65099,
                                         status=self.status2,
                                         region=self.region2)
        self.rack1 = Rack.objects.create(name="Rack 1", site=self.site1)
        self.rack2 = Rack.objects.create(name="Rack 2", site=self.site2)
        self.tenant1 = Tenant.objects.create(name="Tenant 1", slug="tenant-1")
        self.tenant2 = Tenant.objects.create(name="Tenant 2", slug="tenant-2")

        self.vlan1 = VLAN.objects.create(name="VLAN 1",
                                         vid=100,
                                         site=self.site1)
        self.vlan2 = VLAN.objects.create(name="VLAN 2",
                                         vid=200,
                                         site=self.site2)

        self.device1 = Device.objects.create(
            name="Device 1",
            device_type=self.devicetype,
            device_role=self.devicerole1,
            site=self.site1,
            status=self.status1,
            rack=self.rack1,
            tenant=self.tenant1,
            face="front",
            comments="First Device",
        )

        self.interface11 = Interface.objects.create(
            name="Int1",
            type=InterfaceTypeChoices.TYPE_VIRTUAL,
            device=self.device1,
            mac_address="00:11:11:11:11:11",
            mode=InterfaceModeChoices.MODE_ACCESS,
            untagged_vlan=self.vlan1,
        )
        self.interface12 = Interface.objects.create(
            name="Int2",
            type=InterfaceTypeChoices.TYPE_VIRTUAL,
            device=self.device1,
        )
        self.ipaddr1 = IPAddress.objects.create(
            address="10.0.1.1/24",
            status=self.status1,
            assigned_object=self.interface11)

        self.device2 = Device.objects.create(
            name="Device 2",
            device_type=self.devicetype,
            device_role=self.devicerole2,
            site=self.site1,
            status=self.status2,
            rack=self.rack2,
            tenant=self.tenant2,
            face="rear",
        )

        self.interface21 = Interface.objects.create(
            name="Int1",
            type=InterfaceTypeChoices.TYPE_VIRTUAL,
            device=self.device2,
            untagged_vlan=self.vlan2,
            mode=InterfaceModeChoices.MODE_ACCESS,
        )
        self.interface22 = Interface.objects.create(
            name="Int2",
            type=InterfaceTypeChoices.TYPE_1GE_FIXED,
            device=self.device2,
            mac_address="00:12:12:12:12:12")
        self.ipaddr2 = IPAddress.objects.create(
            address="10.0.2.1/30",
            status=self.status2,
            assigned_object=self.interface12)

        self.device3 = Device.objects.create(
            name="Device 3",
            device_type=self.devicetype,
            device_role=self.devicerole1,
            site=self.site2,
            status=self.status1,
        )

        self.interface31 = Interface.objects.create(
            name="Int1",
            type=InterfaceTypeChoices.TYPE_VIRTUAL,
            device=self.device3)
        self.interface31 = Interface.objects.create(
            name="Mgmt1",
            type=InterfaceTypeChoices.TYPE_VIRTUAL,
            device=self.device3,
            mgmt_only=True,
            enabled=False,
        )

        self.cable1 = Cable.objects.create(
            termination_a=self.interface11,
            termination_b=self.interface12,
            status=self.status1,
        )
        self.cable2 = Cable.objects.create(
            termination_a=self.interface31,
            termination_b=self.interface21,
            status=self.status2,
        )

        context1 = ConfigContext.objects.create(name="context 1",
                                                weight=101,
                                                data={
                                                    "a": 123,
                                                    "b": 456,
                                                    "c": 777
                                                })
        context1.regions.add(self.region1)

        Provider.objects.create(name="provider 1", slug="provider-1", asn=1)
        Provider.objects.create(name="provider 2",
                                slug="provider-2",
                                asn=4294967295)

        webhook1 = Webhook.objects.create(name="webhook 1",
                                          type_delete=True,
                                          enabled=False)
        webhook1.content_types.add(ContentType.objects.get_for_model(Device))
        webhook2 = Webhook.objects.create(name="webhook 2",
                                          type_update=True,
                                          enabled=False)
        webhook2.content_types.add(
            ContentType.objects.get_for_model(Interface))

        clustertype = ClusterType.objects.create(name="Cluster Type 1",
                                                 slug="cluster-type-1")
        cluster = Cluster.objects.create(name="Cluster 1", type=clustertype)
        self.virtualmachine = VirtualMachine.objects.create(
            name="Virtual Machine 1",
            cluster=cluster,
            status=self.status1,
        )
        self.vminterface = VMInterface.objects.create(
            virtual_machine=self.virtualmachine,
            name="eth0",
        )
        self.vmipaddr = IPAddress.objects.create(
            address="1.1.1.1/32",
            status=self.status1,
            assigned_object=self.vminterface)
    def setUp(self):
        """Setup request and create test data to validate GraphQL."""
        super().setUp()
        self.user = User.objects.create(username="******",
                                        is_active=True,
                                        is_superuser=True)

        # Initialize fake request that will be required to execute GraphQL query
        self.request = RequestFactory().request(
            SERVER_NAME="WebRequestContext")
        self.request.id = uuid.uuid4()
        self.request.user = self.user

        self.backend = get_default_backend()
        self.schema = graphene_settings.SCHEMA

        manufacturer = Manufacturer.objects.create(name="Manufacturer 1",
                                                   slug="manufacturer-1")
        self.devicetype = DeviceType.objects.create(manufacturer=manufacturer,
                                                    model="Device Type 1",
                                                    slug="device-type-1")
        self.devicerole1 = DeviceRole.objects.create(name="Device Role 1",
                                                     slug="device-role-1")

        self.site1 = Site.objects.create(name="Site-1",
                                         slug="site-1",
                                         asn=65000)
        self.platform1 = Platform.objects.create(
            name="Platform1",
            slug="platform1",
        )

        self.device1 = Device.objects.create(
            name="Device 1",
            device_type=self.devicetype,
            device_role=self.devicerole1,
            platform=self.platform1,
            site=self.site1,
            comments="First Device",
        )

        for item in GIT_DATA:
            git_obj = GitRepository.objects.create(**item)
            git_obj.save()

        backup_repo_list = GitRepository.objects.filter(
            provided_contents__contains="nautobot_golden_config.backupconfigs")
        intended_repo_list = GitRepository.objects.filter(
            provided_contents__contains="nautobot_golden_config.intendedconfigs"
        )

        GoldenConfigSetting.objects.update(
            backup_path_template="test/backup",
            intended_path_template="test/intended",
            jinja_repository=GitRepository.objects.get(
                provided_contents__contains=
                "nautobot_golden_config.jinjatemplate"),
            jinja_path_template="{{jinja_path}}",
            backup_test_connectivity=True,
            scope={"platform": ["platform1"]},
            sot_agg_query="{test_model}",
        )
        GoldenConfigSetting.objects.first().backup_repository.set(
            backup_repo_list)
        GoldenConfigSetting.objects.first().intended_repository.set(
            intended_repo_list)

        self.feature1 = ComplianceFeature.objects.create(
            name="aaa",
            description="Test Desc",
        )

        self.rule1 = ComplianceRule.objects.create(
            feature=self.feature1,
            platform=self.platform1,
            description="Test Desc",
            config_ordered=True,
            match_config="aaa ",
        )

        ConfigCompliance.objects.create(
            device=self.device1,
            rule=self.rule1,
            compliance=True,
            actual="aaa test",
            intended="aaa test",
            missing="",
            extra="",
            ordered=False,
        )

        GoldenConfig.objects.create(
            device=self.device1,
            backup_config="interface Eth1/1\ndescription test",
            intended_config="interface Ethernet1/1\ndescription test",
            compliance_config="interface Ethernet1/1\ndescription test",
        )

        ConfigRemove.objects.create(name="Test Removal",
                                    platform=self.platform1,
                                    description="Test Desc",
                                    regex="^.Test.*")

        ConfigReplace.objects.create(
            name="Test Replace",
            platform=self.platform1,
            description="Test Desc",
            regex="username\\s+(\\S+)",
            replace="<redacted>",
        )
Example #29
0
class SeriailizerMixin:

    backend = get_default_backend()

    def get_schema(self):
        return get_class("cabins.api.schema:schema")

    serialize_attrs = """
        id
        title
        description
        heroImage{
            jpeg400
            jpeg800
            jpeg1960
        }
        ogImage{
            jpeg400
            jpeg800
            jpeg1960
        }
    """

    def get_query(self):
        return f"""query {{
            {self.serializer_request_string()} (id: {self.id}) {{
                {self.serialize_attrs}
            }}
        }}
        """

    def get_all_query(self):
        return f"""query {{
            {self.serializer_all_request_string()} {{
                {self.serialize_attrs}
            }}
        }}
        """

    def serializer_request_string(self):
        return f"get{self.__class__.__name__}ById"

    def serializer_all_request_string(self):
        return f"all{self.__class__.__name__}s"

    def create_document_data(self, query):
        return self.get_schema().execute(query).data

    def base_serializer(self, string, query):
        data = self.create_document_data(query)
        serialization = data.get(string)
        if serialization:
            return serialization
        else:
            raise SerializerError(
                f"{string} is not a valid key in the serialization dictionary")

    def serialize(self):
        return self.base_serializer(self.serializer_request_string(),
                                    self.get_query())

    def serialize_all(self):
        return self.base_serializer(self.serializer_all_request_string(),
                                    self.get_all_query())
Example #30
0
from typing import Dict, Optional
from unittest.mock import patch

import fakeredis
import pytest
from django.core.cache import cache
from graphql import get_default_backend
from redis import ConnectionPool

from ....graphql.api import schema
from ..buffers import RedisBuffer
from ..utils import GraphQLOperationResponse, get_buffer_name

backend = get_default_backend()

BROKER_URL_HOST = "fake-redis"
BROKER_URL = f"redis://{BROKER_URL_HOST}"
KEY, MAX_SIZE, BATCH_SIZE = get_buffer_name(), 10, 5


@pytest.fixture
def gql_operation_factory():
    def factory(
        query_string: str,
        operation_name: Optional[str] = None,
        variables: Optional[Dict] = None,
        result: Optional[Dict] = None,
        result_invalid=False,
    ) -> GraphQLOperationResponse:
        query = backend.document_from_string(schema, query_string)
        return GraphQLOperationResponse(