0

I have a file conftest.py in directory A. I have some test files in directory B which is in A. I run all of them using py.test -sv B/. However sometime I want to pass argument -val="Hello" and store in a file.

I am trying to do it as following:

import argparse
parser=argparse.ArgumentParser()
parser.add_argument("val",help="value")
args=parser.parse_args()
print(args.val)
a_file=open("file_val","w")
a_file.write(args.val)
a.file.close()
def pytest_addoption(parser):
    parser.addoption("--name", action="store", default="default name")

However it doesn't write anything and gives error: unrecognized arguments: -sv —val=hello, when I run py.test -sv B/ —val=Hello

so I tried following :

import argparse

def pytest_addoption(parser):
    parser.addoption("--name", action="store", default="default name")
    parser.add_argument("val",help="value")
    args=parser.parse_args()
    print(args.val)
    a_file=open("file_val","w")
    a_file.write(args.val)
    a.file.close()

But it gives error : No method add_argument when I run py.test -sv B/ —val=Hello

1 Answers1

0

read command line argument while running pytest -sv B/

It should work for you:

First of all you need to pass the argument using addoption and fixture that will read the option.

For that you should create a separate file and name it conftest.py in your test folder.

The content of the conftest.py file:

import pytest


def pytest_addoption(parser):
    parser.addoption("--name", action="store", default="default name")


@pytest.fixture
def name(request):
    return request.config.getoption("--name")

Then you need to create a test function with an argument which named after the fixture in the separate file, or like in your case, even in a separate folder.

Content of B/test_write_file.py:

def test_write_file(name):
    print(name)
    a_file = open("file_val.txt", "w")
    a_file.write(name)
    a_file.close()
    assert 0 # or whatever you want

After that you can freely run your test from the test root folder: pytest -sv B/ --name=Hello

Output:

________________ test_write_file _________________
name = 'Hello'

    def test_write_file(name):
        print(name)
        a_file = open("file_val.txt", "w")
        a_file.write(name)
        a_file.close()
>       assert 0
E       assert 0

B\test_write_file.py:8: AssertionError

You don't need to use argparse, pytest does everything for you.

The structure of the test folder:

enter image description here

Just like in this example:

https://docs.pytest.org/en/6.2.x/example/simple.html

Cheers!