import subprocess
import os
import sys
import pytest
def test_pytest_installation_and_basic_test():
# Step 1 & 2: Install pytest
install_result = subprocess.run([sys.executable, '-m', 'pip', 'install', 'pytest'], capture_output=True, text=True)
assert install_result.returncode == 0, f"pip install pytest failed: {install_result.stderr}"
# Step 3: Verify pytest version
version_result = subprocess.run(['pytest', '--version'], capture_output=True, text=True)
assert version_result.returncode == 0, "pytest --version command failed"
assert 'pytest' in version_result.stdout.lower(), "pytest version info not found"
# Step 4 & 5: Create a simple test file
test_file_content = '''def test_addition():\n assert 1 + 1 == 2\n'''
test_file_name = 'test_sample.py'
with open(test_file_name, 'w') as f:
f.write(test_file_content)
# Step 6: Run pytest on the test file
run_result = subprocess.run(['pytest', test_file_name, '--tb=no', '-q'], capture_output=True, text=True)
# Step 7: Check test execution result
assert run_result.returncode == 0, f"pytest run failed:\n{run_result.stdout}\n{run_result.stderr}"
assert '1 passed' in run_result.stdout, "Test did not pass as expected"
# Cleanup
os.remove(test_file_name)
This test function automates the manual test case steps:
- It installs pytest using
pip install pytest via subprocess and checks the command succeeded. - It runs
pytest --version to confirm pytest is installed and captures the output. - It creates a simple test file
test_sample.py with one test function asserting 1 + 1 equals 2. - It runs pytest on that test file and asserts the test passes by checking the output and return code.
- Finally, it cleans up by deleting the test file.
This approach uses subprocess to run shell commands and assert statements to verify each step, following best practices for clarity and reliability.