Skip to content

Commit 7ec79f7

Browse files
authoredJul 21, 2021
Merge pull request #44 from dbluhm/feat/full-parsing-dereference-as
feat: perform full parsing on dereference as
2 parents e2bb9f5 + 7ca75ba commit 7ec79f7

File tree

2 files changed

+29
-12
lines changed

2 files changed

+29
-12
lines changed
 

‎pydid/resource.py

+9-11
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
"""Resource class that forms the base of all DID Document components."""
22
from abc import ABC, abstractmethod
33
import json
4-
from typing import Any, Dict, Type, TypeVar, cast
4+
from typing import Any, Dict, Type, TypeVar
55

66
from inflection import camelize
77
from pydantic import BaseModel, Extra, parse_obj_as
@@ -126,16 +126,14 @@ def dereference(self, reference: str) -> Resource:
126126
def dereference_as(self, typ: Type[ResourceType], reference: str) -> ResourceType:
127127
"""Dereference a resource to a specific type."""
128128
resource = self.dereference(reference)
129-
if not isinstance(resource, typ):
130-
try:
131-
resource = typ(**resource.dict())
132-
except ValueError as error:
133-
raise ValueError(
134-
"Dereferenced resource {} could not be parsed as {}".format(
135-
resource, typ.__name__
136-
)
137-
) from error
138-
return cast(typ, resource)
129+
try:
130+
return parse_obj_as(typ, resource.dict())
131+
except ValueError as error:
132+
raise ValueError(
133+
"Dereferenced resource {} could not be parsed as {}".format(
134+
resource, typ.__name__
135+
)
136+
) from error
139137

140138
@classmethod
141139
def construct(cls, **data):

‎tests/test_resource.py

+20-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,10 @@
11
"""Test Resource."""
22

3-
from pydid.verification_method import VerificationMethod
3+
from pydid.verification_method import (
4+
Ed25519VerificationKey2018,
5+
KnownVerificationMethods,
6+
VerificationMethod,
7+
)
48
from typing import Optional
59
import pytest
610
from pydid.resource import Resource, IndexedResource
@@ -74,3 +78,18 @@ def test_dereference_as_vmethod_x(mock_indexed_resource):
7478
test = mock_indexed_resource(resource)
7579
with pytest.raises(ValueError):
7680
test.dereference_as(VerificationMethod, "test")
81+
82+
83+
def test_dereference_as_vmethod_using_known_methods(mock_indexed_resource):
84+
resource = Resource(
85+
id="did:example:123#key-1",
86+
controller="did:example:123",
87+
type="Ed25519VerificationKey2018",
88+
public_key_base58="testing",
89+
)
90+
test = mock_indexed_resource(resource)
91+
result = test.dereference_as(KnownVerificationMethods, "test")
92+
assert isinstance(result, VerificationMethod)
93+
assert isinstance(result, Ed25519VerificationKey2018)
94+
assert result.public_key_base58 == "testing"
95+
assert result.material == "testing"

0 commit comments

Comments
 (0)
Please sign in to comment.