Python เบื้องต้นสำหรับการทดสอบโค้ด
Alexander Levin
Data Scientist
autouse=True ฟังก์ชัน fixture จะทำงานโดยไม่ต้องรอการร้องขอใช้เมื่อต้องการเตรียมหรือปรับแต่งสภาพแวดล้อม สำหรับทุกการทดสอบ
ตัวอย่างเช่น เมื่อต้องการให้ทุกการทดสอบ:
กรณีเหล่านี้ควรใช้ "autouse" argument
ตัวอย่าง fixture แบบ "autoused":
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
ตัวอย่าง fixture แบบ "autoused" ที่ ไม่ถูกต้อง:
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
ตัวอย่าง fixture ที่ แก้ไขแล้ว:
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
ผลลัพธ์ของตัวอย่าง:

autouse: อาร์กิวเมนต์บูลีนเสริมของ fixture decorator@pytest.fixture(autouse=True)autouse=True ทำให้ฟังก์ชัน fixture ทำงานโดยอัตโนมัติโดยไม่ต้องรอการร้องขอPython เบื้องต้นสำหรับการทดสอบโค้ด