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

Annotation based fixtures #7690

Closed
jarovo opened this issue Aug 26, 2020 · 1 comment
Closed

Annotation based fixtures #7690

jarovo opened this issue Aug 26, 2020 · 1 comment

Comments

@jarovo
Copy link

jarovo commented Aug 26, 2020

There is a possibility to leverage the python annotation system to implement very modular and structured fixtures. I hope the following illustrates the draft of the idea.

from typing import Callable
from dataclasses import dataclass

## Somewhere in the pytest internals would be:

def satisfy_the_annotations(f: Callable):
    sig = inspect.signature(f)
    params = sig.bind(**{n: satisfy_the_annotations(p.annotation)
                         for n, p in sig.parameters.items()})
    return f(*params.args, **params.kwargs)

def run_test(f: Callable):
    retval = satisfy_the_annotations(f)
    return "PASSED"


## In the file with the tests:        
@dataclass
class Name:
    val: int = 0
    def __init__(self):
        self.__class__.val += 1
        self.val = self.__class__.val

@dataclass
class Surname:
    pass

@dataclass
class Fixture:
    name: Name
        
@dataclass
class ExtendedFixture(Fixture):
    surname: Surname
    pass
    
def test_function_with_annotations(somefixture: Fixture,
                                   otherfixture: Fixture,
                                   extended: ExtendedFixture,
                                   aaa="ddd"):
    print(somefixture, otherfixture, extended, aaa)
    assert isinstance(somefixture.name, Name)

    
run_test(test_function_with_annotations)
@graingert
Copy link
Member

@JaryN I definitely want FastAPI or similar DI based fixtures!

Closing as duplicate of #3834 (comment)

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

2 participants