def test_enum_input_value_resolution(mocker): class ClownTypes(Enum): SAD = "Sad Clown" HAPPY = "Happy Clown" class ClownEmotionResolver(InputMixin, Resolver): def retrieve(self, *args, **kwargs): """Get sad, return happy""" assert self.get_input_data().get("type") == "Sad Clown" return ClownTypes.HAPPY class ClownEmotionResolverOff(InputMixin, Resolver): convert_enums = False def retrieve(self, *args, **kwargs): """Get sad enum, return happy enum""" assert self.get_input_data().get("type") == ClownTypes.SAD return ClownTypes.HAPPY type_defs = """ enum ClownTypes { "Sad Clown" SAD "Happy Clown" HAPPY } input ClownInput { type: ClownTypes } type Query { clownEmotion(input: ClownInput!): ClownTypes clownEmotionOff(input: ClownInput!): ClownTypes } """ query = QueryType() clown_types = EnumType("ClownTypes", ClownTypes) query.set_field("clownEmotion", ClownEmotionResolver.as_resolver()) query.set_field("clownEmotionOff", ClownEmotionResolverOff.as_resolver()) resolvers = [query, clown_types] schema = make_executable_schema(type_defs, resolvers) result = graphql_sync( schema, """ query { on: clownEmotion(input: {type: SAD}) off: clownEmotionOff(input: {type: SAD}) } """, ) assert result.errors is None assert glom(result.data, "on") == "HAPPY" assert glom(result.data, "off") == "HAPPY"
def test_enum_type_is_able_to_represent_enum_default_value_in_schema(): # regression test for: https://github.com/mirumee/ariadne/issues/293 type_defs = """ enum Role { ADMIN USER } type Query { hello(r: Role = USER): String } """ class Role(Enum): ADMIN = "admin" USER = "******" def resolve_test_enum(*_, r): return r == Role.USER RoleGraphQLType = EnumType("Role", Role) QueryGraphQLType = QueryType() QueryGraphQLType.set_field("hello", resolve_test_enum) schema = make_executable_schema( type_defs, QueryGraphQLType, RoleGraphQLType, ) query = "{__schema{types{name,fields{name,args{name,defaultValue}}}}}" _, result = ariadne_graphql_sync(schema, {"query": query}, debug=True) types_map = { result_type["name"]: result_type for result_type in result["data"]["__schema"]["types"] } assert schema.type_map["Query"].fields["hello"].args[ "r"].default_value == Role.USER result_hello_query = graphql_sync(schema, "{hello}") assert types_map["Query"]["fields"][0]["args"][0]["defaultValue"] == "USER" assert result_hello_query.data["hello"] assert result_hello_query.errors is None
from ariadne import EnumType from src.enums import ( ArtistRole, CollectionType, PlaylistType, ReleaseSort, ReleaseType, TrackSort, ) artist_role_enum = EnumType("ArtistRole", ArtistRole) collection_type_enum = EnumType("CollectionType", CollectionType) playlist_type_enum = EnumType("PlaylistType", PlaylistType) release_type_enum = EnumType("ReleaseType", ReleaseType) release_sort_enum = EnumType("ReleaseSort", ReleaseSort) track_sort_enum = EnumType("TrackSort", TrackSort)
from enum import IntEnum from ariadne import EnumType class RequestStatus(IntEnum): SUCCESS = 1 FALIURE = 0 status_enum = EnumType("RequestStatus", RequestStatus) bindables = [status_enum]
self.get_updated() def update_class(self, kwargs): for k, v in kwargs.items(): if not hasattr(self, k): setattr(self, k, v) def get_updated(self): return self class Bundle_Enum_schema(enum.IntEnum): Bundle = 1 bundle_enum_schema = EnumType("Bundle_Enum_schema", Bundle_Enum_schema) """ Dataclasses, These need to be defined for Boundry Types (A GraphQL type from another server that you are Extending """ @dataclass class User(BoundaryGeneric): def __init__(self, **kwargs): super().__init__(self.__class__.__name__, kwargs) @dataclass class Account(BoundaryGeneric): def __init__(self, **kwargs): super().__init__(self.__class__.__name__, kwargs) @dataclass
from ariadne import EnumType rarity = EnumType( "Rarity", { "ONE_STAR": 1, "TWO_STAR": 2, "THREE_STAR": 3, "FOUR_STAR": 4, "FIVE_STAR": 5 }, )
from hexa.user_management.countries import get_who_info from hexa.user_management.models import Team, User accessmod_type_defs = load_schema_from_path( f"{pathlib.Path(__file__).parent.resolve()}/graphql/schema.graphql") accessmod_query = QueryType() accessmod_mutations = MutationType() # Projects project_object = ObjectType("AccessmodProject") project_order_by = EnumType( "AccessmodProjectOrder", { "UPDATED_AT_DESC": "-updated_at", "UPDATED_AT_ASC": "updated_at", "NAME_DESC": "-name", "NAME_ASC": "name", }, ) owner_union = UnionType("AccessmodOwner") @owner_union.type_resolver def resolve_accessmod_owner_type(obj, *_): if isinstance(obj, Team): return "Team" elif isinstance(obj, User): return "User"
def test_attempt_bind_custom_enum_to_wrong_schema_type_raises_error( schema_with_enum): graphql_enum = EnumType("Query", {}) with pytest.raises(ValueError): graphql_enum.bind_to_schema(schema_with_enum)
def test_attempt_bind_custom_enum_to_schema_enum_missing_value_raises_error( schema_with_enum): graphql_enum = EnumType("Episode", {"JARJAR": 1999}) with pytest.raises(ValueError): graphql_enum.bind_to_schema(schema_with_enum) # pylint: disable=no-member
snake_case_fallback_resolvers, ) from ariadne_django.scalars import datetime_scalar from graphql import GraphQLError, GraphQLResolveInfo from gentoo_build_publisher.publisher import MachineInfo, get_publisher from gentoo_build_publisher.records import BuildRecord from gentoo_build_publisher.tasks import publish_build, pull_build from gentoo_build_publisher.types import Build, Package, Status from gentoo_build_publisher.utils import get_version Object = dict[str, Any] type_defs = gql(resources.read_text("gentoo_build_publisher", "schema.graphql")) resolvers = [ EnumType("StatusEnum", Status), datetime_scalar, ObjectType("Build"), ObjectType("MachineSummary"), mutation := ObjectType("Mutation"), query := ObjectType("Query"), ] class BuildType: """Build Type resolvers""" def __init__(self, build: Build): self.build = build self._record = build if isinstance(build, BuildRecord) else None
from ariadne import EnumType weapon_type = EnumType( "WeaponType", { "BLUE_BEAST": "Blue Beast", "BLUE_BOW": "Blue Bow", "BLUE_BREATH": "Blue Breath", "BLUE_DAGGER": "Blue Dagger", "BLUE_LANCE": "Blue Lance", "BLUE_TOME": "Blue Tome", "COLORLESS_BEAST": "Colorless Beast", "COLORLESS_BOW": "Colorless Bow", "COLORLESS_BREATH": "Colorless Breath", "COLORLESS_DAGGER": "Colorless Dagger", "COLORLESS_STAFF": "Colorless Staff", "GREEN_AXE": "Green Axe", "GREEN_BEAST": "Green Beast", "GREEN_BOW": "Green Bow", "GREEN_BREATH": "Green Breath", "GREEN_DAGGER": "Green Dagger", "GREEN_TOME": "Green Tome", "RED_BEAST": "Red Beast", "RED_BOW": "Red Bow", "RED_BREATH": "Red Breath", "RED_DAGGER": "Red Dagger", "RED_SWORD": "Red Sword", "RED_TOME": "Red Tome", }, )
from ariadne import ObjectType, EnumType ALERT = ObjectType('Alert') EVENT = ObjectType('Event') FINDING = ObjectType('Finding') FORCES_EXECUTIONS = ObjectType('ForcesExecutions') INTERNAL_PROJECT_NAME = ObjectType('InternalProject') ME = ObjectType('Me') PROJECT = ObjectType('Project') RESOURCE = ObjectType('Resource') USER = ObjectType('User') DELETE_VULNERABILITY_JUSTIFICATION = EnumType( 'DeleteVulnerabilityJustification', { 'DUPLICATED': 'DUPLICATED', 'FALSE_POSITIVE': 'FALSE_POSITIVE', 'REPORTING_ERROR': 'REPORTING_ERROR', }) EVIDENCE_TYPE = EnumType( 'EvidenceType', { 'ANIMATION': 'animation', 'EVIDENCE1': 'evidence_route_1', 'EVIDENCE2': 'evidence_route_2', 'EVIDENCE3': 'evidence_route_3', 'EVIDENCE4': 'evidence_route_4', 'EVIDENCE5': 'evidence_route_5', 'EXPLOIT': 'exploit', 'EXPLOITATION': 'exploitation', 'RECORDS': 'fileRecords' }) EVIDENCE_DESCRIPTION_TYPE = EnumType(
SIZE_CHOICES = [(PanelSize.SMALL.value, 'small'), (PanelSize.MEDIUM.value, 'medium'), (PanelSize.LARGE.value, 'large'), (PanelSize.VERY_LARGE.value, 'very large')] # utilizes an enum, but stores in string size = models.CharField(max_length=2, choices=SIZE_CHOICES, default=PanelSize.MEDIUM.value) admin.site.register(Panel) """ GraphQL Resolvers """ resolver_panel = ObjectType('Panel') @resolver_panel.field('embed_url') def resolve_panel_embed_url(obj, *_) -> str: return obj.embed_url @resolver_panel.field('size') def resolve_panel_size(obj, *_) -> PanelSize: return PanelSize(obj.size) resolver_panel_size = EnumType('PanelSize', PanelSize)
from ariadne import EnumType move_type = EnumType( "MoveType", { "ARMORED": "Armored", "CAVALRY": "Cavalry", "FLYING": "Flying", "INFANTRY": "Infantry", }, )
from enum import IntEnum from ariadne import EnumType class Status(IntEnum): ERROR = 0 WARNING = 1 SUCCESS = 2 status = EnumType("Status", Status)
schema_with_enum): graphql_enum = EnumType("Query", {}) with pytest.raises(ValueError): graphql_enum.bind_to_schema(schema_with_enum) def test_attempt_bind_custom_enum_to_schema_enum_missing_value_raises_error( schema_with_enum): graphql_enum = EnumType("Episode", {"JARJAR": 1999}) with pytest.raises(ValueError): graphql_enum.bind_to_schema(schema_with_enum) # pylint: disable=no-member dict_enum = EnumType("Episode", { "NEWHOPE": 1977, "EMPIRE": 1980, "JEDI": 1983 }) TEST_INTERNAL_VALUE = 1977 def test_dict_enum_is_resolved_from_internal_value(): query = QueryType() query.set_field("testEnum", lambda *_: TEST_INTERNAL_VALUE) schema = make_executable_schema([enum_definition, enum_field], [query, dict_enum]) result = graphql_sync(schema, "{ testEnum }") assert result.data["testEnum"] == TEST_VALUE
# "TAMIL" : sanscript.TAMIL, # "KANNADA" : sanscript.KANNADA # }) class SanscriptScheme(enum.Enum): DEVANAGARI = sanscript.DEVANAGARI IAST = sanscript.IAST ITRANS = sanscript.ITRANS SLP1 = sanscript.SLP1 TELUGU = sanscript.TELUGU TAMIL = sanscript.TAMIL KANNADA = sanscript.KANNADA sanscriptSchemesEnum = EnumType("SanscriptScheme", SanscriptScheme) class Dictionaries(enum.Enum): VCP = 'vcp' DHATU_PATA = 'Dhātu-pāṭha' MW = 'mw' MWE = 'mwe' SKD = 'skd' dictionaryEnum = EnumType("Dictionary", Dictionaries) @query.field("transliterate") def res_q_transliterate(_,
def test_attempt_bind_custom_enum_to_undefined_type_raises_error( schema_with_enum): graphql_enum = EnumType("Undefined", {}) with pytest.raises(ValueError): graphql_enum.bind_to_schema(schema_with_enum)
from ariadne import EnumType from graph.graphql import Resolver # 一般不需要在绑定达到另一个value了 user_status = EnumType( "UserStatus", { "STANDARD": 1, "PINNED": 2, "PROMOTED": 3, }, ) Resolver(user_status)
from ariadne import QueryType, ObjectType, EnumType from random import randint from models import Skill, Person from data import session from datetime import datetime query = QueryType() # Type definitions skill = ObjectType("Skill") person = ObjectType("Person") eye_color = EnumType( "EyeColor", { 'BLUE': 'blue', 'GREEN': 'green', 'BROWN': 'brown', 'BLACK': 'black', }, ) # Top level resolvers @query.field("randomSkill") def resolve_random_skill(_, info): records = session.query(Skill).count() random_id = str(randint(1, records)) return session.query(Skill).get(random_id) @query.field("randomPerson")
from ariadne import EnumType from ..enums import ( BoxState, HumanGender, Language, ProductGender, ShipmentState, TransferAgreementState, TransferAgreementType, ) enum_types = [ EnumType("ProductGender", ProductGender), EnumType("BoxState", BoxState), EnumType("HumanGender", HumanGender), EnumType("Language", Language), EnumType("ShipmentState", ShipmentState), EnumType("TransferAgreementState", TransferAgreementState), EnumType("TransferAgreementType", TransferAgreementType), ]