**Answer**
A good way to write a test‑case for a `while` loop that reads a file is to
1. **Create a temporary file** that contains the data you want to test.
2. **Pass the file name to the program** (or redirect the file into the program).
3. **Run the program** and capture its output.
4. **Assert that the output is what you expect**.
Below is a concrete example that uses the `tempfile` module to create a temporary file, writes some test data to it, runs the program that contains the `while` loop, and checks that the output is correct. The example uses `pytest` and `subprocess` to execute the program.
```python
# test_read_file.py
import subprocess
import tempfile
import os
def test_read_file_loop(tmp_path):
"""
Test that the program correctly reads a file line by line
and processes each line.
"""
# ------------------------------------------------------------------
# 1. Create a temporary file with known content
# ------------------------------------------------------------------
tmp_file = tmp_path / "input.txt"
tmp_file.write_text(
"first line\n"
"second line\n"
"third line\n"
)
# ------------------------------------------------------------------
# 2. Run the program that contains the while loop
# ------------------------------------------------------------------
# Assume the program is called read_file.py and is in the same
# directory as this test. The program should read the file
# whose name is given as the first command‑line argument.
#
# Example content of read_file.py:
#
# import sys
# def main():
# with open(sys.argv[1], 'r') as f:
# while True:
# line = f.readline()
# if not line:
# break
# # For demonstration we just print the line
# print(line.rstrip())
# if __name__ == "__main__":
# main()
#
# The test below will run that script.
#
cmd = ["python", "read_file.py", str(tmp_file)]
result = subprocess.run(
cmd,
capture_output=True,
text=True, # decode bytes -> str
check=True # raise CalledProcessError on non‑zero exit
)
# ------------------------------------------------------------------
# 3. Verify the output
# ------------------------------------------------------------------
expected_output = "first line\nsecond line\nthird line\n"
assert result.stdout == expected_output, (
f"Unexpected output.\n"
f"Expected:\n{expected_output!r}\n"
f"Got:\n{result.stdout!r}"
)
```
### How the test works
| Step | What happens | Why it matters |
|------|--------------|----------------|
| 1 | `tmp_path / "input.txt"` creates a *temporary* file that is automatically deleted after the test. | Keeps the test isolated from the real filesystem. |
| 2 | The file is written with three lines. | These are the data that the `while` loop will read. |
| 3 | `subprocess.run()` executes the program that contains the `while` loop, passing the temporary file name as an argument. | The program reads the file line by line and prints each line. |
| 4 | The test captures the program’s standard output (`stdout`). | We can compare it to the expected result. |
| 5 | `assert` checks that the output matches the three lines we wrote. | If the loop fails (e.g., it stops early, skips a line, or mis‑parses the file), the assertion will fail. |
### Adapting the test
* **Different processing logic** – If the program does something other than printing each line (e.g., counts words, transforms the text, or writes to another file), change the `expected_output` accordingly or read the output file and compare its contents.
* **Multiple files or edge cases** – Create additional temporary files (empty file, very large file, file with special characters) and repeat the test to cover more scenarios.
* **Unit‑testing the loop directly** – If the loop is inside a function, you can import that function and call it directly from the test, passing a file‑like object created with `io.StringIO`. That way you avoid launching a separate process.
This pattern gives you a clean, repeatable way to test any `while` loop that reads a file, ensuring that the loop behaves correctly for the data you provide.
mai mult


România
Disponibil și pe platforma B2B ›
















