Python File Operations Automation with Behave Testing Framework

  • Share this:

Code introduction


代码含义解释[英文]


Technology Stack : 代码所使用到的包和技术栈[英文]

Code Type : The type of code

Code Difficulty : Intermediate


                
                    
import random
from behave import given, when, then, Step
import os
import datetime

def random_file_name():
    """
    Generate a random file name with a .txt extension.
    """
    return datetime.datetime.now().strftime("%Y%m%d%H%M%S") + ".txt"

def write_to_file(content, file_name):
    """
    Write content to a file with the given file name.
    """
    with open(file_name, 'w') as file:
        file.write(content)

def delete_file(file_name):
    """
    Delete a file with the given file name.
    """
    os.remove(file_name)

@given('a file name')
def step_given_file_name(context):
    context.file_name = random_file_name()

@when('the file is written with content')
def step_when_file_written(context):
    write_to_file("Hello, World!", context.file_name)

@then('the file exists')
def step_then_file_exists(context):
    assert os.path.exists(context.file_name)

@then('the file is deleted')
def step_then_file_deleted(context):
    delete_file(context.file_name)
    assert not os.path.exists(context.file_name)