snyk-labs / pysnyk

A Python client for the Snyk API.
https://snyk.docs.apiary.io/
MIT License
88 stars 117 forks source link

[BUG]: Nested objects not decoded with to_dict() or to_json() #168

Open bmmcwhirt opened 1 year ago

bmmcwhirt commented 1 year ago

Is there an existing issue for this?

Description of the bug

When using the to_dict() or to_json() of the DataClassJSONMixin object you get a bound method error unless you are at the very bottom level.

Each class that is inheriting DataClassJSONMixin needs to implement to_dict() and to_json() and decode the subsequent classes. This needs to be done for every object type that contains other objects of type DataClassJSONMixin so that the bottom level all the way to the top can be serialized.

Currently what happens is you are returning a dict or json that contains a SnyKClient object.

Steps To Reproduce

import json

from snyk import SnykClient
from snyk.models import Organization, Project

from utils import get_default_token_path, get_token

def get_client() -> SnykClient:
    snyk_token_path = get_default_token_path()
    snyk_token = get_token(snyk_token_path)
    client = SnykClient(token=snyk_token)
    return client

def demo_bug(snyk_client: SnykClient, org_id: str, project_id: str):
    organization: Organization = snyk_client.organizations.get(org_id)
    project: Project = organization.projects.get(project_id)
    with open(file='organization_output.json',
              mode='w', encoding='utf-8') as file:
        file.write(json.dumps(organization.to_dict(), indent=4))
        file.close()
    with open(file='project_output.json', mode='w', encoding='utf-8') as file:
        file.write(json.dumps(project.to_json(), indent=4))
        file.close()

def run(function):
    function(snyk_client=get_client(),
             org_id='',
             project_id='')

if __name__ == '__main__':
    run(demo_bug)

Additional Information

[updated with correct error message]

Exception has occurred: TypeError
Object of type SnykClient is not JSON serializable
  File "/Users/cn263376/gitrepos-local/DSOSNYK/src/DSOSNYK/bug_report.py", line 21, in demo_bug
    file.write(json.dumps(organization.to_dict(), indent=4))
  File "/Users/cn263376/gitrepos-local/DSOSNYK/src/DSOSNYK/bug_report.py", line 29, in run
    function(snyk_client=get_client(),
  File "/Users/cn263376/gitrepos-local/DSOSNYK/src/DSOSNYK/bug_report.py", line 35, in <module>
    run(demo_bug)
TypeError: Object of type SnykClient is not JSON serializable