Feature: Test Log FileScenario: Check log file for specific content Given I have a log file "<log_file>"When I search for "<search_term>" in the log fileThen I should see "<expected_content>" in the log fileExamples: | log_file | search_term | expected_content | | myapp.log | ERROR | Database failure | | myapp.log | WARNING | Out of memory | | myapp2.log | INFO | Successful login |
steps.py
importosimportrefrombehaveimportgiven,when,then@given('I have a log file "{log_file}"')defstep_impl(context,log_file):log_path=os.path.join(os.getcwd(),'logs',log_file)context.log_path=log_path@when('I search for "{search_term}" in the log file')defstep_impl(context,search_term):withopen(context.log_path,'r')asf:context.log_contents=f.read()context.search_results=re.findall(search_term,context.log_contents)@then('I should see "{expected_content}" in the log file')defstep_impl(context,expected_content):assertexpected_contentincontext.search_results
environment.py
defbefore_feature(context,feature):os.makedirs('logs',exist_ok=True)context.log_file='myapp.log'withopen(os.path.join(os.getcwd(),'logs',context.log_file),'w')asf:f.write('INFO: Successful login\nWARNING: Out of memory\nERROR: Database failure\n')
Feature: Log VerificationScenario: Verify logs for specific content using regex Given I have a log file "file1.txt"When I search for regex pattern "regex_pattern"Then I should see content "expected_content"
importrefrombehaveimportgiven,when,then@given('I have a log file "{filename}"')defstep_impl(context,filename):context.log_file=f'support/test_data/{filename}'@when('I search for regex pattern "{regex_pattern}"')defstep_impl(context,regex_pattern):withopen(context.log_file,'r')asf:context.log_content=f.read()context.matches=re.findall(regex_pattern,context.log_content)@then('I should see content "{expected_content}"')defstep_impl(context,expected_content):assertexpected_contentincontext.matches,f"Expected {expected_content} but found {context.matches}"
fromseleniumimportwebdriverdefbefore_scenario(context,scenario):# This code will be executed before each scenario is runcontext.driver=webdriver.Chrome()defafter_scenario(context,scenario):# This code will be executed after each scenario is runcontext.driver.quit()
stages:
- test
behave_test:
image: python:3.9
stage: test
before_script:
- pip install selenium
- pip install behave
script:
- behave