microsoft / pylance-release

Documentation and issues for Pylance
Creative Commons Attribution 4.0 International
1.72k stars 766 forks source link

pytest fixtures dimmed as unused import despite being used #6458

Open dl-lim opened 1 month ago

dl-lim commented 1 month ago

Environment data

Code Snippet

Given these two files: tests.test_dependencies and tests.test_module

tests.test_dependencies

import pytest

@pytest.fixture(scope="function")
def fixture_function():
    yield 1

tests.test_module

from tests.test_dependencies import fixture_function

def test_number_one(fixture_function):
    assert fixture_function == 1

Repro Steps

  1. Use VSCode's built-in Pylance
  2. pip install pytest
  3. Write above code in a module.
  4. See fixture dimmed, depending on your theme.

Expected behavior

image

Actual behavior

image

Logs

N/A

Comments

I was initially hesitant on posting this after reading #1059 and #684, but I thought I'd post my own discussion here to get to the bottom of this, if that's welcome.

Is this dimming of the unused import something handled by pylint, and not an issue with pylance?

Is this also due to the way pytest calls fixtures which may perhaps be less than pythonic?

Any hints on where the root of this may lie? I'd be glad to look into this.

rchiodo commented 1 month ago

This is because Pyright (the underlying typechecker for Pyright) doesn't see this code as using the fixture:

def test_fixture_function(fixture_function):
    assert fixture_function == 1

From its point of view, the fixture_function parameter is just a named parameter, it is not actually using the import. That you have to import the fixture is really a function of how pytest works at runtime and can't currently be modeled by a static typechecker.

We do however add some dynamic capabilities to Pyright inside of Pylance and usage of fixtures is just something we haven't done yet.

dl-lim commented 1 month ago

Hmm, further digging, I realise this is exactly what conftest.py was made for! Using that means one does not need to perform such imports. Hope this helps anyone else stumbling upon this.

Regardless, the imports also work just fine even if they are declared as in my example above. They'll just be linted wrongly as above. I believe it could still be looked into...

heejaechang commented 1 month ago

if you want to keep the import, you need to write like from tests.test_dependencies import fixture_function as fixture_function

the grey out means the code will work without the import statement. you will get same behavior if you add import os. it won't break your code even if you have unnecessary import, but we are telling you that the code will still work even if you remove the import statement.

...

ah, I think I misunderstood what you are saying. you are saying when you do it without conftest.py.