How to write testcases to replace a string in file

def replace_string(file_name, original_string, to_replace, username, password):
    with open(file_name, 'r') as file:
        data =
        data = data.replace(original_string, to_replace)
        data = data.replace("uusername", username)
        if password != "":
            data = data.replace("ppassword", password)
            data = data.replace("password: ppassword", "password: ")
    with open(file_name, 'w') as file:

  1. Create a file containing some example data.
  2. Call replace_string on the example file, and replace some of the original data with new data.
  3. Assert that the example file no longer contains the original data, and that it does contain the new data.

In pytest this would look something like this:

import os
import pytest

EXAMPLE_FILE_NAME = "testfile.txt"

def example_file():
    example_data = "original\nusername: uusername\npassword: ppassword\n"
    with open(EXAMPLE_FILE_NAME, "w") as testfile:
    os.remove(EXAMPLE_FILE_NAME)  # Cleanup

def test_replace_string(example_file):
    replace_string(EXAMPLE_FILE_NAME, "original", "replaced", "", "")
    with open(EXAMPLE_FILE_NAME, "r") as ef:
        data =
    assert "original" not in data
    assert "replaced" in data

This test only covers part of what the function does. Using this as a foundation, you should be able to write additional test cases to cover remaining functionality yourself.

1 Like

I try to avoid reading and writing to real files if possible; it tends to keep tests simpler in the long-run. Therefore, I would use unittest.mock_open, to mock out the open function with a test double.

import unittest
from unittest.mock import MagicMock, mock_open, patch

class TestReplaceString(unittest.TestCase):
    def test(self):
        read_data = 'here is something original, and ppassword, and uusername!'
        with patch('', mock_open(read_data=read_data)) as open_mock:
            replace_string('file name', 'original', 'new', 'user', 'pass')
        write = open_mock.__call__().write
        write.assert_called_once_with('here is something new, and pass, and user!')

Thank You!

Thank you!