Fixture autouse

Nhập môn Kiểm thử trong Python

Alexander Levin

Data Scientist

Tham số autouse

  • Tham số boolean tùy chọn của fixture
  • Có thể truyền vào decorator fixture
  • Khi autouse=True, fixture chạy dù không có request
  • Giúp giảm số lần gọi fixture dư thừa
Nhập môn Kiểm thử trong Python

Khi nào dùng

Dùng khi cần chuẩn bị/điều chỉnh môi trường cho tất cả các test.

Ví dụ, khi muốn đảm bảo tất cả test:

  • Có cùng dữ liệu
  • Có cùng kết nối (data, API, v.v.)
  • Có cùng cấu hình môi trường
  • Có monitor, logging, hoặc profiling

Các trường hợp này nên dùng tham số "autouse".

Nhập môn Kiểm thử trong Python

Ví dụ autouse

Ví dụ fixture "autouse":

import pytest
import pandas as pd

# Autoused fixture
@pytest.fixture(autouse=True)
def set_pd_options():
    pd.set_option('display.max_columns', 5000)

# Test function
def test_pd_options():
    assert pd.get_option('display.max_columns') == 5000
Nhập môn Kiểm thử trong Python

Ví dụ autouse không đúng

Ví dụ không đúng về fixture "autouse":

import pytest
import pandas as pd

# Wrong autoused fixture
@pytest.fixture(autouse=True)
def wrong_fixture():
    return [1,2,3,4,5]

# Test function
def test_type():
    assert type(wrong_fixture) == list

Ví dụ đã sửa đúng:

import pytest
import pandas as pd

# Wrong autoused fixture
@pytest.fixture
def correct_fixture():
    return [1,2,3,4,5]

# Test function
def test_type(correct_fixture):
    assert type(correct_fixture) == list
Nhập môn Kiểm thử trong Python

Ví dụ autouse: kết quả

Kết quả ví dụ:

kết quả ví dụ autouse

Nhập môn Kiểm thử trong Python

Tóm tắt

  • Định nghĩa autouse: Tham số boolean tùy chọn của decorator fixture
  • Cách dùng: @pytest.fixture(autouse=True)
  • Lợi ích: Giảm lời gọi fixture dư thừa, giúp mã gọn hơn
  • Đặc điểm: Với autouse=True, fixture luôn chạy dù không được yêu cầu
  • Khi dùng: Khi cần chuẩn bị/điều chỉnh môi trường
  • Ví dụ trường hợp dùng:
    • Đọc và chuẩn bị dữ liệu cho mọi test
    • Cấu hình kết nối và tham số môi trường
    • Thiết lập monitor, logger, hoặc profiler
Nhập môn Kiểm thử trong Python

Ayo berlatih!

Nhập môn Kiểm thử trong Python

Preparing Video For Download...