1

I wrote a testcase like this, but it doesn't work.

import pytest


@pytest.fixture()
def my_fixture():
    print('begin')
    print('#####################################')


class TestA():

    # @pytest.mark.usefixtures('my_fixture')
    def test_a(self, my_fixture, a):
        print("{}".format(a))


if __name__ == '__main__':
    pytest.main()

the raise error:

E       fixture 'a' not found
>       available fixtures: cache, capfd, capfdbinary, caplog, capsys, capsysbinary, doctest_namespace, extra, include_metadata_in_junit_xml, login_and_exit, metadata, monkeypatch, my_fixture, pytestconfig, record_property, record_testsuite_property, record_xml_attribute, recwarn, tmp_path, tmp_path_factory, tmpdir, tmpdir_factory
>       use 'pytest --fixtures [testpath]' for help on them.

I don't know why......

gaoHang
  • 11
  • 3
  • 1
    Where is `a` defined? You need to define all fixtures you want to use. You define my_fixture but never a – Michael Delgado Jun 08 '22 at 05:30
  • Does this mean that function test_a can only use fixtures as parameters – gaoHang Jun 08 '22 at 06:00
  • If it’s going to be auto discovered and invoked by pytest, then yeah you need to specify all inputs as e.g. fixtures or parameters with [`pytest.mark.parametrize`](https://docs.pytest.org/en/6.2.x/parametrize.html), etc. Where were you expecting that input to come from? – Michael Delgado Jun 08 '22 at 14:41

1 Answers1

2

If you uncomment decorator above test_a and remove parameters it will work. Also you can remove redundant parentheses from class definition and fixture decorator:

import pytest


@pytest.fixture
def my_fixture():
    print('Inside fixture my_fixture.')


@pytest.fixture
def a():
    print('Inside fixture a . Returning value 3 for a')
    return 3


class Test:

    @pytest.mark.usefixtures('my_fixture', 'a')
    def test_a(self, a):
        print("Inside test. Argument has value: {}".format(a))


if __name__ == '__main__':
    pytest.main()
Dan Constantinescu
  • 1,426
  • 1
  • 7
  • 11
  • 1
    Thanks. If i need to use parameters in function test_a, what can i do? – gaoHang Jun 08 '22 at 06:07
  • Hi @gaoHang. I have updated the response to include also a parameter. Have a look also at this post, on how to pass arguments from command line: https://stackoverflow.com/questions/40880259/how-to-pass-arguments-in-pytest-by-command-line – Dan Constantinescu Jun 08 '22 at 07:48
  • 1
    Thanks @Dan, this should solve my problem. – gaoHang Jun 08 '22 at 08:08