Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Struct import fails in pytest - Missing requirement argument 'attribute x' or unhashable type: 'StructClass' #660

Open
neotechmonk opened this issue Mar 23, 2024 · 0 comments

Comments

@neotechmonk
Copy link

Description

Setup
Struct based class

from typing import Annotated
import msgspec

class TestModel(msgspec.Struct):
    key: Annotated[str, msgspec.Meta(max_length=6)] 

Importing the TestModel for further unit testing

from tests.model import TestModel

When I run pytest on the unittest module I get this error

.venv/lib/python3.11/site-packages/_pytest/runner.py:340: in from_call
    result: Optional[TResult] = func()
.venv/lib/python3.11/site-packages/_pytest/runner.py:388: in collect
    return list(collector.collect())
.venv/lib/python3.11/site-packages/_pytest/python.py:794: in collect
    self.session._fixturemanager.parsefactories(self.newinstance(), self.nodeid)
.venv/lib/python3.11/site-packages/_pytest/python.py:767: in newinstance
    return self.obj()
E   TypeError: Missing required argument 'key'

The above error is addressed by assigning a default value
key: Annotated[str, msgspec.Meta(max_length=6)] = "test"

However running pytest again leads to this error

.venv/lib/python3.11/site-packages/_pytest/runner.py:340: in from_call
    result: Optional[TResult] = func()
.venv/lib/python3.11/site-packages/_pytest/runner.py:388: in collect
    return list(collector.collect())
.venv/lib/python3.11/site-packages/_pytest/python.py:794: in collect
    self.session._fixturemanager.parsefactories(self.newinstance(), self.nodeid)
.venv/lib/python3.11/site-packages/_pytest/fixtures.py:1713: in parsefactories
    if holderobj in self._holderobjseen:
E   TypeError: unhashable type: 'TestModel

When I implement __hash__() like the below both errors are resolved

class TestModel(msgspec.Struct):
    key: Annotated[str, msgspec.Meta(max_length=6)] = "test"


    def __hash__(self):
        return hash((self.key,))

Is this is an issue or am I using the library in a wrong way?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant