profusion / sgqlc

Simple GraphQL Client
https://sgqlc.readthedocs.io/
ISC License
513 stars 85 forks source link

datetime.datetime cannot be passed to `non_null` #177

Open jwodder opened 2 years ago

jwodder commented 2 years ago

As of sgqlc v14.1, running the following code:

from datetime import datetime
from sgqlc.types import Type, non_null

class MyType(Type):
    createdAt = non_null(datetime)

fails with:

Traceback (most recent call last):
  File "/home/jwodder/.local/virtualenvwrapper/venvs/tmp-6802b9daf21c10c/lib/python3.8/site-packages/sgqlc/types/__init__.py", line 930, in __ensure__
    return map_python_to_graphql[t]
KeyError: <class 'datetime.datetime'>

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "bug01a.py", line 4, in <module>
    class MyType(Type):
  File "bug01a.py", line 5, in MyType
    createdAt = non_null(datetime)
  File "/home/jwodder/.local/virtualenvwrapper/venvs/tmp-6802b9daf21c10c/lib/python3.8/site-packages/sgqlc/types/__init__.py", line 1128, in non_null
    t = BaseType.__ensure__(t)
  File "/home/jwodder/.local/virtualenvwrapper/venvs/tmp-6802b9daf21c10c/lib/python3.8/site-packages/sgqlc/types/__init__.py", line 932, in __ensure__
    raise TypeError('Not %s or mapped: %s' % (cls, t)) from exc
TypeError: Not BaseType or mapped: <class 'datetime.datetime'>

Using createdAt = non_null(Field(datetime)) fails as well. Only createdAt = non_null(sgqlc.types.datetime.DateTime) works. However, I believe the failure of non_null(datetime) should be considered a bug, as things like non_null(str) work perfectly fine.

barbieri commented 2 years ago

You need to import sgqlc.types.datetime so it will run https://github.com/profusion/sgqlc/blob/master/sgqlc/types/datetime.py#L307-L311

otherwise it doesn't have the mapping. It's not automatic to avoid polluting the conversion with undesired mappings, so you must opt-in by importing that. After that you can use and it should work