2016-11-30 16 views
9

Tôi có một mã và tôi cần chuyển các đối số như tên từ thiết bị đầu cuối. Đây là mã của tôi và cách chuyển đối số. Tôi đang gặp lỗi. Tập tin không tìm thấy loại điều. Tôi không thể hiểu được.Làm thế nào để chuyển đối số trong pytest bằng dòng lệnh

Tôi đã thử lệnh trong terminal: pytest <filename>.py -almonds tôi nên tên in như "hạnh nhân"

@pytest.mark.parametrize("name") 
def print_name(name): 
    print ("Displaying name: %s" % name) 

Trả lời

2

Theo official document, các trang trí dấu sẽ giống như dưới đây.

@pytest.mark.parametrize("arg1", ["StackOverflow"]) 
def test_mark_arg1(arg1): 
    assert arg1 == "StackOverflow" #Success 
    assert arg1 == "ServerFault" #Failed 

Run

python -m pytest <filename>.py 
  • Note1: tên hàm phải bắt đầu với test_
  • Note2: pytest sẽ chuyển hướng stdout (print), do đó trực tiếp chạy stdout sẽ không thể hiển thị bất kỳ kết quả trên màn. Ngoài ra, không cần in kết quả trong hàm của bạn trong các trường hợp thử nghiệm.
  • Note3: pytest là một module chạy bằng python, mà không phải là có thể nhận được sys.argv trực tiếp

Nếu bạn thực sự muốn có được tranh cãi bên ngoài cấu hình, bạn nên bạn thực hiện điều đó trong kịch bản của bạn . (Ví dụ, tải nội dung của tập tin)

with open("arguments.txt") as f: 
    args = f.read().splitlines() 
... 
@pytest.mark.parametrize("arg1", args) 
... 
6

Trong thử nghiệm pytest của bạn, không sử dụng @pytest.mark.parametrize:

@pytest.mark.unit 
def test_print_name(name): 
    print ("Displaying name: %s" % name) 

Trong conftest.py:

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


def pytest_generate_tests(metafunc): 
    # This is called for every test. Only get/set command line arguments 
    # if the argument is specified in the list of test "fixturenames". 
    option_value = metafunc.config.option.name 
    if 'name' in metafunc.fixturenames and option_value is not None: 
     metafunc.parametrize("name", [option_value]) 

Sau đó, bạn có thể chạy từ dòng lệnh có đối số dòng lệnh:

pytest -s tests/my_test_module.py --name abc 
Các vấn đề liên quan