Verify PyTest installation and basic test execution
Preconditions (2)
✅ Expected Result: PyTest installs successfully, 'pytest --version' shows the installed version, and running 'pytest' executes the test with a passing result.
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:
pip install pytest via subprocess and checks the command succeeded.pytest --version to confirm pytest is installed and captures the output.test_sample.py with one test function asserting 1 + 1 equals 2.This approach uses subprocess to run shell commands and assert statements to verify each step, following best practices for clarity and reliability.
Now add data-driven testing by creating multiple test files with different simple assertions and verify all pass.
pip install package_name.package_name with pytest, so the command is pip install pytest.pytest. Using py.test is incorrect as it is not a package name for pip.pip install pytest successfully, what command should you use to run your tests?pytest in the terminal, not prefixed by python or pip.pip install pytest but got an error saying 'command not found'. What is the most likely cause?pip install --upgrade package_name.package_name with pytest, so the command is pip install --upgrade pytest.pip install pytest) installs but does not upgrade if already installed; B and C are invalid commands.Pass the test and this pattern moves unknown