Handling shared resources in PyTest - Build an Automation Script
import os import pytest @pytest.fixture(scope='module') def shared_file(): filename = 'shared_resource.txt' # Setup: create or clear the file before tests with open(filename, 'w') as f: f.write('') yield filename # Teardown: remove the file after tests if os.path.exists(filename): os.remove(filename) def test_write_test1(shared_file): with open(shared_file, 'w') as f: f.write('Test1') with open(shared_file, 'r') as f: content = f.read() assert content == 'Test1', f"Expected 'Test1' but got '{content}'" def test_append_test2(shared_file): with open(shared_file, 'a') as f: f.write('Test2') with open(shared_file, 'r') as f: content = f.read() assert content == 'Test1Test2', f"Expected 'Test1Test2' but got '{content}'"
This code uses a pytest fixture named shared_file with scope='module' to setup and teardown a shared file resource.
Before any tests run, the fixture creates or clears the file shared_resource.txt. After all tests in the module finish, it deletes the file to clean up.
The first test writes 'Test1' to the file and verifies the content exactly matches 'Test1'.
The second test appends 'Test2' to the same file and verifies the content is 'Test1Test2', confirming the append worked and the shared resource was handled correctly.
This approach avoids interference by ensuring the file starts empty before tests and is removed after, following best practices for shared resource handling.
Now add data-driven testing with 3 different strings to write and append to the shared file