Random File Content Generator Test

  • Share this:

Code introduction


This function generates a random file content and writes it to the specified file path. The test function uses the Freezegun library to ensure that the same content is generated at different time points by freezing time.


Technology Stack : Freezegun, os, random

Code Type : Function

Code Difficulty : Intermediate


                
                    
import random
from freezegun import freeze_time
import datetime
import os

def random_file_content(file_path):
    """
    This function generates a random file content and writes it to the specified file path.
    """
    content = ''.join(random.choices('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', k=100))
    with open(file_path, 'w') as file:
        file.write(content)

def test_random_file_content():
    """
    This function tests the random_file_content function by freezing the time and checking if the file size is consistent.
    """
    test_file_path = 'test_random_file_content.txt'
    with freeze_time("2023-01-01 00:00:00"):
        random_file_content(test_file_path)
        file_size = os.path.getsize(test_file_path)
    
    assert file_size == 100, "File size is not as expected"