GispoCoding / pytest-qgis

A pytest plugin for testing QGIS python plugins
GNU General Public License v2.0
29 stars 8 forks source link

Clean qgis layer fixtures automatically #25

Closed Joonalai closed 9 months ago

Joonalai commented 2 years ago

Expected behaviour QGIS layer fixtures should be cleaned automatically without the need of using decoration.

Current behaviour A decoration clean_qgis_layer is needed to ensure that the layer is cleared.

Describe alternatives you've considered

Additional context Here is a working hook that cleans the layers. One thing to consider though are fixtures with other than function scope.

@pytest.hookimpl(tryfirst=True)
def pytest_runtest_teardown(item):
    feature_request = item.funcargs["request"]
    for fixture_name in item.fixturenames:
        if "layer" in fixture_name.lower():
            if (
            isinstance(layer, QgsMapLayer)
            and not sip.isdeleted(layer)
            and layer.id() not in QgsProject.instance().mapLayers(True).keys()
        ):
              QgsProject.instance().addMapLayer(layer)
              QgsProject.instance().removeMapLayer(layer)
cefect commented 3 months ago

@Joonalai thank you for implementing this. Does this mean I need to rename all my fixtures to include 'layer'? Or is there some way to flag them as layers like before? see my old code below.

@pytest.fixture(scope='function')
@clean_qgis_layer
def dem(caseName, qproj):
    #retrieve the layer
Joonalai commented 3 months ago

We decided that it is best to do that automatically in version 2.0. The old marker did not follow pytest philosophy in my opinion and I was not completely happy with it.

So in your case it means that you should rename the fixture to for example dem_layer.

Do you think yhat there would be still a need for that kind of marker?

cefect commented 3 months ago

I cannot comment on pytest philosophy, but I do think it would be useful to allow users to manually flag and unflag layer fixtures.... and I'm not sure what the downside would be of this feature.

Joonalai commented 3 months ago

I thought that it would be ugly to import some utility decorator from pytest plugin.

But since you find it handy, I'll re-implement the feature and it should be available to use again in the next release :)