Skip to content

Commit

Permalink
fix: package update related fixes and formatting
Browse files Browse the repository at this point in the history
Refs: HP-2082
  • Loading branch information
charn committed Feb 2, 2024
1 parent 8aea85a commit a4bb163
Show file tree
Hide file tree
Showing 26 changed files with 76 additions and 60 deletions.
4 changes: 2 additions & 2 deletions open_city_profile/decorators.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

from django.core.exceptions import PermissionDenied
from django.utils.translation import gettext_lazy as _
from graphql.execution.base import ResolveInfo
from graphql.type import GraphQLResolveInfo

from open_city_profile.exceptions import ServiceNotIdentifiedError

Expand All @@ -13,7 +13,7 @@ def decorator(decorator_function):
def wrapper(function):
@wraps(function)
def context_tester(*args, **kwargs):
info = next(arg for arg in args if isinstance(arg, ResolveInfo))
info = next(arg for arg in args if isinstance(arg, GraphQLResolveInfo))
context = info.context

for test_func in test_funcs:
Expand Down
4 changes: 2 additions & 2 deletions open_city_profile/graphene.py
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,7 @@ def __init_subclass_with_meta__(
interfaces=(),
convert_choices_to_enum=True,
_meta=None,
**options
**options,
):
assert issubclass(model, TranslatableModel), (
'You need to pass a valid Django Parler Model in {}.Meta, received "{}".'
Expand All @@ -176,5 +176,5 @@ def __init_subclass_with_meta__(
interfaces=interfaces,
convert_choices_to_enum=convert_choices_to_enum,
_meta=_meta,
**options
**options,
)
10 changes: 6 additions & 4 deletions open_city_profile/tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
from graphene.test import Client as GrapheneClient
from graphene_django.settings import graphene_settings
from graphene_django.views import instantiate_middleware
from graphql import build_client_schema, introspection_query
from graphql import build_client_schema, get_introspection_query
from helusers.authz import UserAuthorization

from open_city_profile.schema import schema
Expand All @@ -33,7 +33,7 @@ def execute(
auth_token_payload=None,
service=_not_provided,
context=None,
**kwargs
**kwargs,
):
"""
Custom execute method which adds all of the middlewares defined in the
Expand Down Expand Up @@ -70,7 +70,7 @@ def execute(
*args,
context=context,
middleware=list(instantiate_middleware(graphene_settings.MIDDLEWARE)),
**kwargs
**kwargs,
)


Expand Down Expand Up @@ -179,7 +179,9 @@ def superuser_gql_client():

@pytest.fixture
def gql_schema(anon_user_gql_client):
introspection = anon_user_gql_client.execute(introspection_query)
introspection = anon_user_gql_client.execute(
get_introspection_query(descriptions=False)
)
return build_client_schema(introspection["data"])


Expand Down
2 changes: 1 addition & 1 deletion open_city_profile/tests/graphql_test_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ def generate_jwt_token(extra_claims=None):
"iat": get_unix_timestamp_now() - 10,
"aud": AUDIENCE,
"sub": str(uuid.uuid4()),
"sid": get_random_string(),
"sid": get_random_string(12),
"exp": get_unix_timestamp_now() + 120,
}
jwt_data.update(extra_claims)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@

from snapshottest import Snapshot


snapshots = Snapshot()

snapshots['test_graphql_schema_matches_the_reference 1'] = '''type Query {
Expand Down
4 changes: 2 additions & 2 deletions open_city_profile/tests/test_graphql_authentication.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ def test_presenting_an_expired_access_token_with_any_operation_returns_jwt_authe
assert len(errors) == 2

for path in ["myProfile", "_service"]:
assert data[path] is None
assert data is None

error = next(err for err in errors if err["path"] == [path])
assert error["extensions"]["code"] == "JWT_AUTHENTICATION_ERROR"
Expand All @@ -51,7 +51,7 @@ def test_presenting_a_logged_out_token_returns_jwt_authentication_error(live_ser
assert len(errors) == 2

for path in ["myProfile", "_service"]:
assert data[path] is None
assert data is None

error = next(err for err in errors if err["path"] == [path])
assert error["extensions"]["code"] == "JWT_AUTHENTICATION_ERROR"
3 changes: 1 addition & 2 deletions open_city_profile/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,8 +93,7 @@ class GraphQLView(BaseGraphQLView):
def execute_graphql_request(self, request, data, query, *args, **kwargs):
"""Extract any exceptions and send some of them to Sentry"""
result = super().execute_graphql_request(request, data, query, *args, **kwargs)
# If 'invalid' is set, it's a bad request
if result and result.errors and not result.invalid:
if result and result.errors:
errors = [
e
for e in result.errors
Expand Down
5 changes: 5 additions & 0 deletions profiles/helpers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
from graphql_relay import to_global_id as relay_to_global_id


def to_global_id(type, id):
return relay_to_global_id(type_=type, id_=id)
24 changes: 12 additions & 12 deletions profiles/schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@
profile_updated = django.dispatch.Signal()


def get_claimable_profile(token=None):
def get_claimable_profile(token=None) -> Profile:
claim_token = ClaimToken.objects.get(token=token)
if claim_token.expires_at and claim_token.expires_at < timezone.now():
raise TokenExpiredError("Token for claiming this profile has expired")
Expand Down Expand Up @@ -206,7 +206,7 @@ def update_sensitivedata(profile, sensitive_data):

with override("en"):
Language = graphene.Enum(
"Language", [(l[1].upper(), l[0]) for l in settings.LANGUAGES]
"Language", [(lang[1].upper(), lang[0]) for lang in settings.LANGUAGES]
)
ContactMethod = graphene.Enum(
"ContactMethod", [(cm[1].upper(), cm[0]) for cm in settings.CONTACT_METHODS]
Expand Down Expand Up @@ -537,22 +537,22 @@ class Meta:
language = Language()
contact_method = ContactMethod()

def resolve_primary_email(self, info, **kwargs):
def resolve_primary_email(self: Profile, info, **kwargs):
return info.context.primary_email_for_profile_loader.load(self.id)

def resolve_primary_phone(self, info, **kwargs):
def resolve_primary_phone(self: Profile, info, **kwargs):
return info.context.primary_phone_for_profile_loader.load(self.id)

def resolve_primary_address(self, info, **kwargs):
def resolve_primary_address(self: Profile, info, **kwargs):
return info.context.primary_address_for_profile_loader.load(self.id)

def resolve_emails(self, info, **kwargs):
def resolve_emails(self: Profile, info, **kwargs):
return info.context.emails_by_profile_id_loader.load(self.id)

def resolve_phones(self, info, **kwargs):
def resolve_phones(self: Profile, info, **kwargs):
return info.context.phones_by_profile_id_loader.load(self.id)

def resolve_addresses(self, info, **kwargs):
def resolve_addresses(self: Profile, info, **kwargs):
return info.context.addresses_by_profile_id_loader.load(self.id)


Expand All @@ -579,10 +579,10 @@ class Meta:
"privileges to access this information.",
)

def resolve_service_connections(self, info, **kwargs):
def resolve_service_connections(self: Profile, info, **kwargs):
return self.effective_service_connections_qs()

def resolve_sensitivedata(self, info, **kwargs):
def resolve_sensitivedata(self: Profile, info, **kwargs):
service = info.context.service

if info.context.user == self.user or info.context.user.has_perm(
Expand All @@ -593,7 +593,7 @@ def resolve_sensitivedata(self, info, **kwargs):
# TODO: We should return PermissionDenied as a partial error here.
return None

def resolve_verified_personal_information(self, info, **kwargs):
def resolve_verified_personal_information(self: Profile, info, **kwargs):
loa = info.context.user_auth.data.get("loa")
if (
info.context.user == self.user and loa in ["substantial", "high"]
Expand All @@ -608,7 +608,7 @@ def resolve_verified_personal_information(self, info, **kwargs):
)

@login_and_service_required
def __resolve_reference(self, info, **kwargs):
def __resolve_reference(self: Profile, info, **kwargs):
profile = graphene.Node.get_node_from_global_id(
info, self.id, only_type=ProfileNode
)
Expand Down
6 changes: 3 additions & 3 deletions profiles/tests/gdpr/test_gdpr_functions_with_multiple_idps.py
Original file line number Diff line number Diff line change
Expand Up @@ -128,9 +128,9 @@ def get_keycloak_token_response(token_request, context):
for tunnistamo_service in tunnistamo_services:
scope = tunnistamo_service.gdpr_query_scope
api_audience = scope[: scope.rfind(".")]
tunnistamo_api_tokens[
api_audience
] = f"{tunnistamo_service.name}-{TUNNISTAMO_API_TOKEN_MARKER}"
tunnistamo_api_tokens[api_audience] = (
f"{tunnistamo_service.name}-{TUNNISTAMO_API_TOKEN_MARKER}"
)

requests_mock.get(
settings.TUNNISTAMO_API_TOKENS_URL,
Expand Down
5 changes: 4 additions & 1 deletion profiles/tests/gdpr/test_gql_delete_my_profile_mutation.py
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,10 @@ def test_user_can_delete_their_profile(
assert Profile.objects.filter(pk=profile.pk).exists()


@pytest.mark.parametrize("should_fail", [False, True])
@pytest.mark.parametrize(
"should_fail",
[pytest.param(False, id="should_not_fail"), pytest.param(True, id="should_fail")],
)
def test_user_can_dry_run_profile_deletion(
user_gql_client,
service_1,
Expand Down
2 changes: 1 addition & 1 deletion profiles/tests/profile_input_validation.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import pytest
from graphql_relay import to_global_id

from open_city_profile.tests import to_graphql_name, to_graphql_object
from open_city_profile.tests.asserts import assert_match_error_code
from profiles.models import Profile

from ..helpers import to_global_id
from .factories import AddressFactory, EmailFactory, PhoneFactory


Expand Down
2 changes: 1 addition & 1 deletion profiles/tests/test_audit_log_to_db.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
from typing import Any, List, Optional

import pytest
from graphql_relay import to_global_id
from guardian.shortcuts import assign_perm

from audit_log.models import LogEntry
Expand All @@ -22,6 +21,7 @@
)
from services.tests.factories import ServiceConnectionFactory

from ..helpers import to_global_id
from .factories import (
AddressFactory,
EmailFactory,
Expand Down
2 changes: 1 addition & 1 deletion profiles/tests/test_audit_log_to_logger.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
from typing import Any, List, Optional

import pytest
from graphql_relay import to_global_id
from guardian.shortcuts import assign_perm

from open_city_profile.tests import to_graphql_name
Expand All @@ -23,6 +22,7 @@
)
from services.tests.factories import ServiceConnectionFactory

from ..helpers import to_global_id
from .factories import (
AddressFactory,
EmailFactory,
Expand Down
3 changes: 2 additions & 1 deletion profiles/tests/test_gql_claim_profile_mutation.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,12 @@
from string import Template

from django.utils import timezone
from graphql_relay.node.node import to_global_id

from open_city_profile.consts import API_NOT_IMPLEMENTED_ERROR, TOKEN_EXPIRED_ERROR
from open_city_profile.tests.asserts import assert_match_error_code
from profiles.models import Profile

from ..helpers import to_global_id
from .factories import (
ClaimTokenFactory,
EmailFactory,
Expand Down Expand Up @@ -164,6 +164,7 @@ def test_changing_an_email_address_marks_it_unverified(user_gql_client):
}

executed = user_gql_client.execute(CLAIM_PROFILE_MUTATION, variables=variables)
assert "errors" not in executed
assert executed["data"] == expected_data


Expand Down
2 changes: 1 addition & 1 deletion profiles/tests/test_gql_claimable_profile_query.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@
from string import Template

from django.utils import timezone
from graphql_relay.node.node import to_global_id

from open_city_profile.consts import TOKEN_EXPIRED_ERROR
from open_city_profile.tests.asserts import assert_match_error_code

from ..helpers import to_global_id
from .factories import ClaimTokenFactory, ProfileFactory


Expand Down
22 changes: 12 additions & 10 deletions profiles/tests/test_gql_create_profile_mutation.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,17 +111,19 @@ def test_staff_user_can_create_a_profile(
]
},
"emails": {
"edges": [
{
"node": {
"emailType": email_data["email_type"],
"email": email_data["email"],
"primary": True,
"edges": (
[
{
"node": {
"emailType": email_data["email_type"],
"email": email_data["email"],
"primary": True,
}
}
}
]
if with_email
else []
]
if with_email
else []
)
},
"serviceConnections": {
"edges": [
Expand Down
3 changes: 2 additions & 1 deletion profiles/tests/test_gql_federation.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
import pytest
from graphql_relay import to_global_id
from guardian.shortcuts import assign_perm

from open_city_profile.tests.asserts import assert_match_error_code
from profiles.schema import AddressNode, ProfileNode
from profiles.tests.factories import AddressFactory, ProfileFactory
from services.tests.factories import ServiceConnectionFactory

from ..helpers import to_global_id

GRAPHQL_SDL_QUERY = """
query {
_service {
Expand Down
5 changes: 3 additions & 2 deletions profiles/tests/test_gql_profiles_query.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import pytest
import uuid
from string import Template

import pytest
from django.utils.translation import gettext_lazy as _
from guardian.shortcuts import assign_perm
from string import Template

from open_city_profile.tests import to_graphql_name
from open_city_profile.tests.asserts import assert_match_error_code
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import datetime
import uuid

from graphql_relay import to_global_id
from guardian.shortcuts import assign_perm

from open_city_profile.tests.asserts import assert_match_error_code

from ..helpers import to_global_id

QUERY = """
query ($userId: UUID!, $serviceClientId: String!)
{
Expand Down
2 changes: 1 addition & 1 deletion profiles/tests/test_gql_update_my_profile_mutation.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
from string import Template

import pytest
from graphql_relay.node.node import to_global_id

from open_city_profile.tests.asserts import assert_match_error_code
from profiles.models import Address, Email, Phone, Profile
from profiles.tests.profile_input_validation import ExistingProfileInputValidationBase
from services.tests.factories import ServiceConnectionFactory
from utils import keycloak

from ..helpers import to_global_id
from .factories import (
AddressFactory,
EmailFactory,
Expand Down
Loading

0 comments on commit a4bb163

Please sign in to comment.