jeudi 26 octobre 2017

Why use fixtures instead of global variables when testing?

I'm new to testing, please bear with me. If I'm lacking fundamental conceptual knowledge, let me know in a comment. I'd like to improve this question (or realize it shouldn't be asked), but I can't tell what's wrong from downvotes alone.

Question

When using pytest, is there a downside to using global variables instead of fixtures?

Code (with a global variable)

DATASET = FlickrPortraitMaskDataset(root=ROOT)

class TestFlickrPortraitMaskDataset(object):

    def test_len(self):
        nb_portraits = len(get_fnames(ROOT + "portraits/"))
        assert len(DATASET) == nb_portraits

    def test_getitem(self):
        idx = random.randint(0, len(DATASET) - 1)
        sample = DATASET[idx]
        assert isinstance(sample, dict)

Output

TestFlickrPortraitMaskDataset::test_len PASSED
TestFlickrPortraitMaskDataset::test_getitem PASSED

Code (with a fixture)

@pytest.fixture(scope="module")
def dataset():
    return FlickrPortraitMaskDataset(root=ROOT)

class TestFlickrPortraitMaskDataset(object):

    def test_len(self, dataset):
        nb_portraits = len(get_fnames(ROOT + "portraits/"))
        assert len(dataset) == nb_portraits

    def test_getitem(self, dataset):
        idx = random.randint(0, len(dataset) - 1)
        sample = dataset[idx]
        assert isinstance(sample, dict)

Output

TestFlickrPortraitMaskDataset::test_len PASSED
TestFlickrPortraitMaskDataset::test_getitem PASSED

The output is the same.


Common

import random

import pytest

from portraitseg.utils import get_fnames
from portraitseg.pytorch_datasets import FlickrPortraitMaskDataset


ROOT = "../data/portraits/flickr/cropped/"

Aucun commentaire:

Enregistrer un commentaire